Merge pull request #689 from seaweedfs/fix/fresh-fill-clean

fix(storage): a chunk filled from HEAD is not a cut candidate while unchanged
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-28 13:59:34 -08:00
commit 79a7801a9d
4 files changed
+333 -2

No files matched your search

@@ -155,6 +155,43 @@ func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) {
}
}
// TestARestoreTargetThatOnlyReadCutsNothing: a restore target whose reads
// filled HEAD's chunks holds HEAD's bytes in them, so its next cut (the final
// cut of a detach included) compares nothing. Comparing every filled chunk
// makes the detach of a fully read target as long as reading the target.
func TestARestoreTargetThatOnlyReadCutsNothing(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks)
first := fcutProvider(t, t.TempDir(), fixture, v1View())
fcutOpen(t, ctx, first)
fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33)
fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37)
if _, err := first.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
p := fcutProvider(t, t.TempDir(), fixture, viewAs("rB", 4))
fcutOpen(t, ctx, p)
got := make([]byte, 4096)
for _, lba := range []int{pcChunkBlocks * 3, pcChunkBlocks * 7} {
if _, err := p.Backend("v1").Read(ctx, int64(lba)*4096, got); err != nil {
t.Fatal(err)
}
}
if s := fcutStats(t, p); s.AbsentChunks != 0 {
t.Fatalf("setup: %d chunks still absent after reading both HEAD-named chunks", s.AbsentChunks)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if got := fcutStats(t, p).LastCut.CandidateChunks; got != 0 {
t.Errorf("the cut after reads only: %d candidate chunks; want 0 (the filled chunks are HEAD's bytes)", got)
}
}
// TestExplicitWALStoreRefusesAFreshChunkRoot: a root carrying chunk metadata
// (here the fresh marker of a store that never attached) is refused by an
// explicitly configured plain walstore as by auto, so no write can reach a
@@ -0,0 +1,265 @@
package storage
import (
"bytes"
"testing"
)
// A volume fresh from HEAD (a restore target) that only READ its blocks back
// has nothing to compare at its next cut: a chunk filled from HEAD holds
// HEAD's bytes by construction. Re-hashing every filled chunk makes the
// final cut of a fully read volume as long as reading the whole volume.
func TestFreshFromHeadReadBackLeavesNoCutCandidates(t *testing.T) {
src := make([]byte, ctNumBlocks*ctBlockSize)
for lba := 0; lba < ctNumBlocks; lba++ {
copy(src[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba)))
}
f := newFakeChunkRemote()
f.seedHead(t, src, 10, 1)
s, _ := newChunkTestStore(t)
if err := s.SeedChunkFrontier(10); err != nil {
t.Fatal(err)
}
cfg := ctConfig(2)
cfg.FreshFromHead = true
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
for lba := uint32(0); lba < ctNumBlocks; lba++ {
got, err := s.Read(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, blockOf(src, lba)) {
t.Fatalf("lba %d read back other bytes", lba)
}
}
l.stMu.Lock()
absent := len(l.absent)
l.stMu.Unlock()
if absent != 0 {
t.Fatalf("setup: %d chunks still absent after reading every block", absent)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks != 0 {
t.Errorf("a read-only fresh volume's cut compared %d of %d chunks (want 0): its final cut re-reads every filled chunk", r.Stats.CandidateChunks, ctNumBlocks/ctChunkBlocks)
}
again, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if again.Stats.CandidateChunks != 0 {
t.Errorf("control: the cut after a finished cut compared %d chunks", again.Stats.CandidateChunks)
}
t.Logf("first cut compared %d chunks, second %d", r.Stats.CandidateChunks, again.Stats.CandidateChunks)
assertNoRemoteMisuse(t, f)
}
// Control: the same volume with nothing read compares nothing.
func TestFreshFromHeadUnreadLeavesNoCutCandidates(t *testing.T) {
src := make([]byte, ctNumBlocks*ctBlockSize)
for lba := 0; lba < ctNumBlocks; lba++ {
copy(src[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba)))
}
f := newFakeChunkRemote()
f.seedHead(t, src, 10, 1)
s, _ := newChunkTestStore(t)
if err := s.SeedChunkFrontier(10); err != nil {
t.Fatal(err)
}
cfg := ctConfig(2)
cfg.FreshFromHead = true
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks != 0 {
t.Errorf("an unread fresh volume compared %d chunks", r.Stats.CandidateChunks)
}
}
// Control: a filled chunk written locally afterwards is a candidate again,
// and its cut publishes the write.
func TestFreshFromHeadFilledThenWrittenIsACandidate(t *testing.T) {
src := make([]byte, ctNumBlocks*ctBlockSize)
for lba := 0; lba < ctNumBlocks; lba++ {
copy(src[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba)))
}
f := newFakeChunkRemote()
f.seedHead(t, src, 10, 1)
s, _ := newChunkTestStore(t)
if err := s.SeedChunkFrontier(10); err != nil {
t.Fatal(err)
}
cfg := ctConfig(2)
cfg.FreshFromHead = true
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
for lba := uint32(0); lba < ctNumBlocks; lba++ {
if _, err := s.Read(lba); err != nil {
t.Fatal(err)
}
}
local := makeBlock(ctBlockSize, 0xEE)
if _, err := s.Write(ctChunkBlocks+1, local); err != nil {
t.Fatal(err)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks != 1 {
t.Errorf("filled, then one chunk written: %d candidates, want 1", r.Stats.CandidateChunks)
}
if !bytes.Equal(blockOf(f.imageOf(t, r.Head), ctChunkBlocks+1), local) {
t.Fatal("the cut lost the write to a filled chunk")
}
}
// filledFreshVolume is a fresh-from-HEAD volume whose every chunk a read has
// filled from HEAD, with its clean-fill records in place.
func filledFreshVolume(t *testing.T) (*WALStore, *chunkLayerImpl, *fakeChunkRemote) {
t.Helper()
src := make([]byte, ctNumBlocks*ctBlockSize)
for lba := 0; lba < ctNumBlocks; lba++ {
copy(src[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba)))
}
f := newFakeChunkRemote()
f.seedHead(t, src, 10, 1)
s, _ := newChunkTestStore(t)
if err := s.SeedChunkFrontier(10); err != nil {
t.Fatal(err)
}
cfg := ctConfig(2)
cfg.FreshFromHead = true
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
for lba := uint32(0); lba < ctNumBlocks; lba++ {
if _, err := s.Read(lba); err != nil {
t.Fatal(err)
}
}
l.stMu.Lock()
marks := len(l.filledClean)
l.stMu.Unlock()
if marks != ctNumBlocks/ctChunkBlocks {
t.Fatalf("setup: %d clean-fill records, want %d", marks, ctNumBlocks/ctChunkBlocks)
}
return s, l, f
}
// Guard enumeration: every path that writes a chunk's local bytes after a
// clean fill bumps that chunk's version, so the fill's record no longer
// holds and the chunk is a cut candidate again. A frontend trim or
// write-zeroes reaches the store as a write.
func TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate(t *testing.T) {
const idx = 1
lba := uint32(idx * ctChunkBlocks)
data := makeBlock(ctBlockSize, 0xA5)
for _, tc := range []struct {
name string
do func(t *testing.T, s *WALStore)
}{
{"write", func(t *testing.T, s *WALStore) {
if _, err := s.Write(lba+1, data); err != nil {
t.Fatal(err)
}
}},
{"write, then flushed to the extent", func(t *testing.T, s *WALStore) {
if _, err := s.Write(lba+1, data); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.flushOnce(); err != nil {
t.Fatal(err)
}
}},
{"batch of one block", func(t *testing.T, s *WALStore) {
if _, err := s.WriteBatch(lba+1, [][]byte{data}); err != nil {
t.Fatal(err)
}
}},
{"batch of several blocks", func(t *testing.T, s *WALStore) {
if _, err := s.WriteBatch(lba, [][]byte{data, data}); err != nil {
t.Fatal(err)
}
}},
{"replicated entry (rebuild, catch-up)", func(t *testing.T, s *WALStore) {
if err := s.ApplyEntry(lba+1, data, s.NextLSN()); err != nil {
t.Fatal(err)
}
}},
{"recovery republishing the WAL", func(t *testing.T, s *WALStore) {
s.noteChunkRecovery()
}},
} {
t.Run(tc.name, func(t *testing.T) {
s, l, _ := filledFreshVolume(t)
before := l.chunkVersion(idx)
if l.captureCandidates()[idx] {
t.Fatal("setup: the clean-filled chunk is already a candidate")
}
tc.do(t, s)
if l.chunkVersion(idx) == before {
t.Errorf("chunk %d's version did not move", idx)
}
if !l.captureCandidates()[idx] {
t.Errorf("chunk %d is not a cut candidate after the local write", idx)
}
})
}
}
// A HEAD that no longer names the ref a chunk was filled from ends the
// fill's record, whatever replaced it: the chunk is a candidate again.
// (While attached, this layer's own cuts change only candidates' refs, and
// another publisher fences the layer; this guards any other path.)
func TestACleanFillRecordEndsWithItsHeadRef(t *testing.T) {
const idx = 2
_, l, _ := filledFreshVolume(t)
if l.captureCandidates()[idx] {
t.Fatal("setup: the clean-filled chunk is already a candidate")
}
l.stMu.Lock()
h := copyHead(l.head)
ref := h.Chunks[idx]
ref.Key += "-replaced"
ref.SHA256[0] ^= 0xFF
h.Chunks[idx] = ref
l.head = h
l.stMu.Unlock()
if !l.captureCandidates()[idx] {
t.Fatal("a chunk whose HEAD ref changed after its fill is not a candidate")
}
}
// Guard enumeration, BASE: a BASE install after clean fills takes local
// authority; its records end and every chunk is a candidate of the next cut.
func TestABaseInstallAfterCleanFillsEndsTheirRecords(t *testing.T) {
s, l, _ := filledFreshVolume(t)
h, err := s.BeginBaseInstall(s.NextLSN()+10, idA)
if err != nil {
t.Fatal(err)
}
if err := h.WriteBase(ctChunkBlocks+1, makeBlock(ctBlockSize, 0xB5)); err != nil {
t.Fatal(err)
}
if err := h.MarkBaseComplete(); err != nil {
t.Fatal(err)
}
l.stMu.Lock()
marks := len(l.filledClean)
l.stMu.Unlock()
if marks != 0 {
t.Errorf("%d clean-fill records survived a BASE install", marks)
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.Stats.CandidateChunks != ctNumBlocks/ctChunkBlocks {
t.Errorf("the cut after a BASE install compared %d chunks, want all %d", r.Stats.CandidateChunks, ctNumBlocks/ctChunkBlocks)
}
}
+30 -1
View File
@@ -154,6 +154,12 @@ type chunkLayerImpl struct {
absent map[uint64]bool
absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation
localBlocks map[uint64]bool
// filledClean: chunks a fill wrote entirely from HEAD, with no local
// block and no mutation during the fill, at that chunk's version and
// HEAD ref. While both are unchanged the local bytes are that HEAD's, so
// an UNKNOWN map entry alone does not make the chunk a cut candidate.
// Memory only: after a restart the next cut compares them once.
filledClean map[uint64]filledMark
presenceVer uint64
savedPresVer uint64
dirtyVer uint64
@@ -236,6 +242,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
absent: map[uint64]bool{},
absentGen: map[uint64]uint64{},
localBlocks: map[uint64]bool{},
filledClean: map[uint64]filledMark{},
closeDone: make(chan struct{}),
syncDirFn: syncDir,
}
@@ -415,12 +422,18 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
absent[idx] = true
}
}
filled := map[uint64]bool{}
for idx, m := range l.filledClean {
if l.chunkVersion(idx) == m.version && l.head.Chunks[idx] == m.ref {
filled[idx] = true
}
}
l.addOwnCandidatesLocked(out)
l.stMu.Unlock()
l.s.mu.RLock()
for idx, e := range l.s.v3.mapEntries {
i := uint64(idx)
if !absent[i] && (e.Unknown || e.LSN > base) {
if !absent[i] && ((e.Unknown && !filled[i]) || e.LSN > base) {
out[i] = true
}
}
@@ -430,6 +443,13 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
return out
}
// filledMark is a clean fill: the chunk's version and the HEAD ref it was
// filled from.
type filledMark struct {
version uint64
ref chunkRef
}
// chunkVersion is chunk idx's mutation count.
func (l *chunkLayerImpl) chunkVersion(idx uint64) uint64 {
return l.chunkMut[idx].Load()
@@ -446,6 +466,7 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error {
l.stMu.Lock()
l.absent = map[uint64]bool{}
l.localBlocks = map[uint64]bool{}
l.filledClean = map[uint64]filledMark{}
l.presenceVer++
l.stMu.Unlock()
}
@@ -478,6 +499,11 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun
current := func() bool {
return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref
}
// Read with the end check's lock: a mutation bumps the version after its
// dirty-map insert, so one that lands during the fill changes it.
l.stMu.Lock()
version := l.chunkVersion(idx)
l.stMu.Unlock()
data, err := l.remote.Get(ctx, ref.Key)
if err != nil {
return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, err)
@@ -505,6 +531,9 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun
if !current() {
return false, nil
}
if !l.chunkHasLocalLocked(idx) && l.chunkVersion(idx) == version {
l.filledClean[idx] = filledMark{version: version, ref: ref}
}
delete(l.absent, idx)
for i := uint64(0); i < l.chunkBlocks; i++ {
delete(l.localBlocks, first+i)
+1 -1
View File
@@ -573,7 +573,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | ACTIVE |
| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE |
| `INV-WAL-V3-WRITE-AHEAD-001` | No extent byte reaches the disk before its WAL record is durable: the flusher writes an extent only from dirty entries at or below the synced (acknowledged) WAL frontier; Recover and the install log fsync their records before raising it. | M1 Serving (flusher extent write) | `core/storage/flusher.go` `flushOnceInternal`; `walstore_v3.go` `recoverV3` (descriptor publish fsync before `wack`); `install_log_v3.go` | `TestRedCrashKeepingAnUnsyncedExtentWriteLeavesLocalAndHEADApart` (`core/storage/chunk_u1_reorder_test.go`); `TestFlusherWriteAheadNeverFlushingGuestReachesExtentAtPressure` (`core/storage/flusher_write_ahead_test.go`) | A checkpoint may pass a synced record superseded by an unsynced newer one only because the cycle's sync covers the whole file, WAL included (one file, one descriptor: `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`); separating WAL and extent, or a range sync, must first change the checkpoint bound | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates; an UNKNOWN chunk a fill wrote wholly from HEAD, with no local block and no mutation since, is not. | M5 candidate selection | `chunk_layer.go` `captureCandidates`, `fillOnce` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing` | Conservative reachability unchanged; narrower redundant work | ACTIVE |
| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | ACTIVE |