Merge pull request #525 from seaweedfs/test/1.0.1-first-cut-known-zero-red

fix: 1.0.1 a fresh store's chunks that its claimed HEAD does not name start known-zero
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-23 22:43:17 -08:00
commit 1720cd49cc
11 files changed
+715 -12

No files matched your search

@@ -0,0 +1,198 @@
package durable_test
// The first cut of a volume. A fresh local store (its first attach not yet
// committed) knows every chunk its claimed HEAD does not name is zero on both
// sides, so its first cut scans only the chunks written since; a
// store that is not fresh (one an earlier release created, or any store
// after its first attach commit) keeps its chunks' state as persisted. Chunks
// HEAD names stay absent and are hydrated from HEAD.
import (
"bytes"
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// fcutChunks is chunkProvider's chunk count: pcBlocks blocks of pcChunkBlocks.
const fcutChunks = pcBlocks / pcChunkBlocks
func fcutProvider(t *testing.T, root string, remote storage.ChunkRemote) *durable.DurableProvider {
return chunkProvider(t, root, remote, v1View(), 0)
}
// fcutCheckpointedPast waits until the store's checkpoint has moved past
// from, so a write made after from has left the WAL's dirty map.
func fcutCheckpointedPast(t *testing.T, st storage.LogicalStorage, from uint64) {
t.Helper()
ws := st.(*storage.WALStore)
waitFor(t, 10*time.Second, "the WAL checkpoint past the write", func() bool { return ws.CheckpointLSN() > from })
}
// fcutStats returns v1's chunk-layer counters.
func fcutStats(t *testing.T, p *durable.DurableProvider) storage.ChunkLayerStats {
t.Helper()
for _, st := range p.DurableStatuses() {
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached {
return st.Chunk.Stats
}
}
t.Fatal("v1 has no attached chunk layer")
return storage.ChunkLayerStats{}
}
func fcutOpen(t *testing.T, ctx context.Context, p *durable.DurableProvider) storage.LogicalStorage {
t.Helper()
st, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
return st
}
func fcutWrite(t *testing.T, ctx context.Context, p *durable.DurableProvider, lba int, fill byte) []byte {
t.Helper()
data := bytes.Repeat([]byte{fill}, 4096)
b := p.Backend("v1")
if n, err := b.Write(ctx, int64(lba)*4096, data); err != nil || n != len(data) {
t.Fatalf("write lba %d: %d %v", lba, n, err)
}
if err := b.Sync(ctx); err != nil {
t.Fatal(err)
}
return data
}
// fcutHeadBlock reads block lba from the published HEAD (zero if its chunk
// is not named).
func fcutHeadBlock(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, lba int) []byte {
t.Helper()
head, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
ref, ok := head.Chunks[uint64(lba/pcChunkBlocks)]
if !ok {
return make([]byte, 4096)
}
c, err := remote.Get(ctx, ref.Key)
if err != nil {
t.Fatal(err)
}
off := (lba % pcChunkBlocks) * 4096
return c[off : off+4096]
}
// TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks: a store created
// empty against a HEAD never claimed, with two chunks written (one of them
// already checkpointed out of the WAL), has two first-cut candidates, and
// its first cut publishes both. Today every chunk of the volume is a
// candidate (all 16 start Unknown).
func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
p := fcutProvider(t, t.TempDir(), remote)
st := fcutOpen(t, ctx, p)
cp0 := st.(*storage.WALStore).CheckpointLSN()
a := fcutWrite(t, ctx, p, pcChunkBlocks*1+1, 0x31) // chunk 1, checkpointed below
fcutCheckpointedPast(t, st, cp0)
b := fcutWrite(t, ctx, p, pcChunkBlocks*9+3, 0x39) // chunk 9, still in the WAL
if got := fcutStats(t, p).DirtyChunks; got != 2 {
t.Errorf("before the first cut: %d candidate chunks; want 2 (the written ones), not all %d", got, fcutChunks)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if got := fcutStats(t, p).LastCut.CandidateChunks; got != 2 {
t.Errorf("first cut: %d candidate chunks; want 2", got)
}
if !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*1+1), a) || !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*9+3), b) {
t.Fatal("the first cut did not publish both written blocks")
}
}
// TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks: a store created
// empty against a HEAD another store already claimed (no data published) is
// fresh too: every chunk that HEAD does not name starts equal to it (both
// zero), so the first cut has no candidates. General form of the rule: the
// premise is the store's fresh marker, not the HEAD's history.
func TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
first := fcutProvider(t, t.TempDir(), remote)
fcutOpen(t, ctx, first)
if err := first.Close(); err != nil {
t.Fatal(err)
}
if head, err := remote.GetHead(ctx); err != nil || head.Gen == 0 || len(head.Chunks) != 0 {
t.Fatalf("setup: HEAD %+v %v; want a claimed HEAD naming no chunk", head, err)
}
p := fcutProvider(t, t.TempDir(), remote)
fcutOpen(t, ctx, p)
if got := fcutStats(t, p).DirtyChunks; got != 0 {
t.Fatalf("fresh store against a claimed HEAD naming nothing: %d candidate chunks; want 0", got)
}
}
// TestFirstCutOfARestoreTargetKeepsItsHydrationPath: a fresh store against a
// HEAD that names chunks keeps those chunks absent (hydrated from HEAD; a
// read returns HEAD's data, never zeros) and starts every other chunk equal
// to HEAD (zero), so its first cut has no candidates.
func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
first := fcutProvider(t, t.TempDir(), remote)
fcutOpen(t, ctx, first)
a := fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33)
b := 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(), remote)
fcutOpen(t, ctx, p)
if s := fcutStats(t, p); s.AbsentChunks != 2 || s.DirtyChunks != 0 {
t.Fatalf("restore target: %d absent, %d candidate chunks; want 2 absent and 0 candidates", s.AbsentChunks, s.DirtyChunks)
}
got := make([]byte, 4096)
for lba, want := range map[int][]byte{pcChunkBlocks * 3: a, pcChunkBlocks * 7: b} {
if n, err := p.Backend("v1").Read(ctx, int64(lba)*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) {
t.Fatalf("restore target read of HEAD-named block %d: %d %v, data equal %v; want HEAD's data, not zeros", lba, n, err, bytes.Equal(got, want))
}
}
}
// 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
// store whose marker says none ever did.
func TestExplicitWALStoreRefusesAFreshChunkRoot(t *testing.T) {
root := t.TempDir()
p := fcutProvider(t, root, storage.NewMemChunkRemote())
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if err := p.Close(); err != nil {
t.Fatal(err)
}
plain, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = plain.Close() })
if _, err := plain.EnsureStorage("v1"); !errors.Is(err, durable.ErrImplKindMismatch) {
t.Fatalf("explicit walstore on a fresh chunk root: %v; want ErrImplKindMismatch", err)
}
}
@@ -0,0 +1,293 @@
package durable
import (
"bytes"
"context"
"errors"
"os"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// kzProvider is a walstore-chunk provider for v1 (256 blocks, 16 per
// chunk: 16 chunks) over root and remote.
func kzProvider(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider {
t.Helper()
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
p, err := NewDurableProvider(ProviderConfig{
Impl: ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, precopyQueueView{id})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
return p
}
func kzCandidates(t *testing.T, p *DurableProvider) int {
t.Helper()
for _, st := range p.DurableStatuses() {
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Attached {
return st.Chunk.Stats.DirtyChunks
}
}
t.Fatal("v1 has no attached chunk layer")
return -1
}
// The premise of RULE-FRESH-KNOWN-ZERO: until the attach commit retires the
// fresh marker, no write reaches the store. Held at that boundary (after the
// claim and the certification, before the commit), a frontend write is not
// admitted (it may wait; here it is bounded) and appends no WAL record. After
// the commit the store has no candidates: nothing was written.
func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
p := kzProvider(t, t.TempDir(), storage.NewMemChunkRemote())
st, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
ws := st.(*storage.WALStore)
var writeErr error
var nextAtBoundary uint64
held := false
p.testBeforeChunkFreshRetire = func() error {
held = true
wctx, wcancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer wcancel()
_, writeErr = p.Backend("v1").Write(wctx, 0, bytes.Repeat([]byte{0x5a}, 4096))
nextAtBoundary = ws.NextLSN()
return nil
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
p.testBeforeChunkFreshRetire = nil
if !held {
t.Fatal("the attach did not reach its commit boundary")
}
if writeErr == nil || nextAtBoundary != 1 {
t.Fatalf("at the commit boundary a frontend write returned %v and the WAL's next LSN was %d; want refused, 1", writeErr, nextAtBoundary)
}
if got := kzCandidates(t, p); got != 0 {
t.Fatalf("after the commit: %d candidate chunks; want 0 (nothing was written)", got)
}
for _, st := range p.DurableStatuses() {
if st.VolumeID == "v1" && st.Chunk != nil && st.Chunk.Stats.KnownZeroChunks != 16 {
t.Fatalf("status KnownZeroChunks %d; want 16", st.Chunk.Stats.KnownZeroChunks)
}
}
}
// RULE-FRESH-KNOWN-ZERO needs THIS start's create: a first start that
// crashes before its attach commit leaves the fresh marker, but the next
// start did not create the store, so it certifies nothing (one scan: every
// chunk a candidate), and its next cut still publishes a write.
func TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
root, remote := t.TempDir(), storage.NewMemChunkRemote()
p := kzProvider(t, root, remote)
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
crash := errors.New("crash before the attach commit")
p.testBeforeChunkFreshRetire = func() error { return crash }
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, crash) {
t.Fatalf("first start: %v; want the injected crash", err)
}
if err := p.Close(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil {
t.Fatalf("fresh marker after the crash: %v; want it kept", err)
}
p2 := kzProvider(t, root, remote)
if _, err := p2.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if got := kzCandidates(t, p2); got != 16 {
t.Fatalf("second start: %d candidate chunks; want all 16 (it did not create the store)", got)
}
kzWriteAndPublish(t, ctx, p2, remote)
}
// The same after a restart between the create and any attach (test #13).
func TestFreshKnownZeroNotAfterARestartBeforeAnyAttach(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
root, remote := t.TempDir(), storage.NewMemChunkRemote()
p := kzProvider(t, root, remote)
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if err := p.Close(); err != nil {
t.Fatal(err)
}
p2 := kzProvider(t, root, remote)
if _, err := p2.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if got := kzCandidates(t, p2); got != 16 {
t.Fatalf("restart before any attach: %d candidate chunks; want all 16", got)
}
}
// The order: the attach commit retires the marker, THEN the marking is made
// durable, THEN the volume serves. A crash between the first two leaves no
// marker and every chunk UNKNOWN: the next start scans every chunk once, and
// is correct. (Marking before the retirement would leave certified chunks
// behind a marker a later start could trust.)
func TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
root, remote := t.TempDir(), storage.NewMemChunkRemote()
p := kzProvider(t, root, remote)
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
crash := errors.New("crash after the marker retirement, before the marking")
p.testAfterChunkFreshRetire = func() error { return crash }
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, crash) {
t.Fatalf("first start: %v; want the injected crash", err)
}
if err := p.Close(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) {
t.Fatalf("fresh marker after the crash: %v; want it retired", err)
}
p2 := kzProvider(t, root, remote)
if _, err := p2.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if got := kzCandidates(t, p2); got != 16 {
t.Fatalf("restart after a crash between marker retirement and marking: %d candidate chunks; want all 16 (one scan)", got)
}
kzWriteAndPublish(t, ctx, p2, remote)
}
// kzWriteAndPublish writes chunk 5, cuts, and checks HEAD publishes it.
func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, remote *storage.MemChunkRemote) {
t.Helper()
want := bytes.Repeat([]byte{0x6b}, 4096)
if _, err := p.Backend("v1").Write(ctx, 5*16*4096, want); err != nil {
t.Fatal(err)
}
if err := p.Backend("v1").Sync(ctx); err != nil {
t.Fatal(err)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
head, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
ref, ok := head.Chunks[5]
if !ok {
t.Fatal("the cut did not publish chunk 5")
}
chunk, err := remote.Get(ctx, ref.Key)
if err != nil || !bytes.Equal(chunk[:4096], want) {
t.Fatalf("published chunk 5: %v", err)
}
if got := kzCandidates(t, p); got != 0 {
t.Fatalf("after the cut: %d candidate chunks; want 0", got)
}
}
// kzCountingRemote counts chunk reads (Get) of the remote it wraps.
type kzCountingRemote struct {
storage.ChunkRemote
gets atomic.Int64
}
func (r *kzCountingRemote) Get(ctx context.Context, key string) ([]byte, error) {
r.gets.Add(1)
return r.ChunkRemote.Get(ctx, key)
}
// The premise again, for fills (test #12): until the attach commit retires
// the fresh marker, no fetch and no extent write reaches the store. A restore
// target whose HEAD names two chunks is held at the commit boundary; a
// frontend read of a HEAD-named block there is not served (it may wait;
// here it is bounded), the remote serves no chunk read, and after the
// commit both named chunks are still absent with no fetch started: no fill
// wrote the extent. After that the read returns HEAD's data.
func TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
mem := storage.NewMemChunkRemote()
src := kzProvider(t, t.TempDir(), mem)
if _, err := src.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := src.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
want := bytes.Repeat([]byte{0x3c}, 4096)
for _, chunk := range []int64{3, 7} {
if _, err := src.Backend("v1").Write(ctx, chunk*16*4096, want); err != nil {
t.Fatal(err)
}
}
if err := src.Backend("v1").Sync(ctx); err != nil {
t.Fatal(err)
}
if _, err := src.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if err := src.Close(); err != nil {
t.Fatal(err)
}
remote := &kzCountingRemote{ChunkRemote: mem}
p := kzProvider(t, t.TempDir(), remote)
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
var readErr error
var getsAtBoundary int64 = -1
p.testBeforeChunkFreshRetire = func() error {
before := remote.gets.Load()
rctx, rcancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer rcancel()
_, readErr = p.Backend("v1").Read(rctx, 3*16*4096, make([]byte, 4096))
getsAtBoundary = remote.gets.Load() - before
return nil
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
p.testBeforeChunkFreshRetire = nil
if readErr == nil || getsAtBoundary != 0 {
t.Fatalf("at the commit boundary a frontend read of a HEAD-named block returned %v and the remote served %d chunk reads; want refused, 0", readErr, getsAtBoundary)
}
for _, st := range p.DurableStatuses() {
if st.VolumeID == "v1" && st.Chunk != nil {
if h := st.Chunk.Stats.Hydration; st.Chunk.Stats.AbsentChunks != 2 || h.Fetches != 0 || h.Completed != 0 {
t.Fatalf("after the commit: %d absent chunks, %d fetches, %d completed; want 2 absent and no fetch (no fill before the commit)", st.Chunk.Stats.AbsentChunks, h.Fetches, h.Completed)
}
}
}
got := make([]byte, 4096)
if n, err := p.Backend("v1").Read(ctx, 3*16*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) {
t.Fatalf("read after the commit: %d %v, data equal %v; want HEAD's data", n, err, bytes.Equal(got, want))
}
}
@@ -267,6 +267,9 @@ type DurableProvider struct {
// testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary.
testBeforeChunkFreshRetire func() error
// testAfterChunkFreshRetire runs after the attach commit retired the
// fresh marker, before the known-zero marking is made durable.
testAfterChunkFreshRetire func() error
// testWALStoreFactory selects a dark store only in provider caller controls.
// No production option, flag or environment variable installs it.
@@ -297,8 +300,11 @@ type volHandle struct {
// volume file, written before the file is created and removed only
// after the first attach succeeded, so an interrupted initialization
// is still fresh after a restart.
fresh bool
attachMu sync.Mutex // serializes recovery and attach of this volume
fresh bool
// createdThisStart: this process start created the store (in memory,
// never persisted); RULE-FRESH-KNOWN-ZERO needs it with fresh.
createdThisStart bool
attachMu sync.Mutex // serializes recovery and attach of this volume
// recoverGen numbers this volume's RecoverVolume calls (written under
// attachMu and p.mu). waitGen is the generation of the live authority
// wait, 0 if none: a recovered volume whose layer waits for master
@@ -809,17 +815,19 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
if err != nil {
return nil, fmt.Errorf("durable: stat %s: %w", path, err)
}
if p.cfg.Impl == ImplAuto {
if p.cfg.Impl != ImplWALStoreChunk {
// A walstore-chunk volume shares walstore's on-disk format, and its
// authoritative bytes may live only in the remote HEAD. Opened as
// plain walstore it would serve local (possibly absent) extents, so
// auto refuses any root carrying chunk metadata; it never deletes
// or converts it.
// plain walstore it would serve local (possibly absent) extents, and
// a write through it would reach a store whose fresh marker still
// says no write ever did (RULE-FRESH-KNOWN-ZERO). So every other
// implementation, auto or explicit, refuses a root carrying chunk
// metadata; it never deletes or converts it.
if side, err := chunkSidecars(path); err != nil {
return nil, err
} else if len(side) > 0 {
return nil, fmt.Errorf("%w: %s is a chunk-managed volume (%s present); auto cannot open it: set --durable-impl=walstore-chunk with its remote configuration",
ErrImplKindMismatch, path, strings.Join(side, ", "))
return nil, fmt.Errorf("%w: %s is a chunk-managed volume (%s present); %s cannot open it: set --durable-impl=walstore-chunk with its remote configuration",
ErrImplKindMismatch, path, strings.Join(side, ", "), p.cfg.Impl)
}
}
@@ -862,7 +870,7 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) {
}
h, err := p.createFresh(volumeID, path, impl)
if err == nil && p.cfg.Impl == ImplWALStoreChunk {
h.fresh = true
h.fresh, h.createdThisStart = true, true
}
return h, err
}
@@ -321,6 +321,18 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
} else if err := commit(); err != nil {
return err
}
// RULE-FRESH-KNOWN-ZERO order: the marker is retired (above), THEN the
// marking is made durable, THEN the volume serves (after this attach).
if h.fresh {
if hook := p.testAfterChunkFreshRetire; hook != nil {
if err := hook(); err != nil {
return err
}
}
}
if kz, ok := layer.(interface{ ApplyFreshKnownZero() }); ok {
kz.ApplyFreshKnownZero()
}
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
@@ -418,6 +430,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
Epoch: lin.epoch,
Holder: holder,
FreshFromHead: h.fresh,
CreatedThisStart: h.fresh && h.createdThisStart,
ReadMissTimeout: p.cfg.ChunkReadMissTimeout,
HydrationWorkers: p.cfg.ChunkHydrationWorkers,
HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth,
@@ -0,0 +1,78 @@
package storage
import "log"
// RULE-FRESH-KNOWN-ZERO (INV-CUT-FRESH-KNOWN-ZERO-001). A store this process
// start created (CreatedThisStart, in memory) that is still fresh at its
// attach (FreshFromHead: the .chunkfresh marker is present and no BASE is
// installed) has never had a write or a fill reach it: frontend I/O is
// admitted only after the attach commit retires the marker, a chunk volume
// takes no replication apply, no cut or hydration can resolve the layer
// before that commit, and no other implementation opens a root that carries
// chunk metadata. Its extent therefore holds the creation bytes (zeros) in
// every chunk, and a chunk the claimed HEAD does not name is zero there too:
// the two are equal, so the chunk need not be a cut candidate.
//
// freshKnownZeroCandidates samples, under the attach's capture barrier, the
// mutation token of every chunk the claimed HEAD does not name whose owned
// map entry is still its creation value {LSN 0, Unknown}; the entry test is
// an extra exclusion, not the premise. ApplyFreshKnownZero then clears only
// the UNKNOWN bit of those whose token is unchanged, through the cut's own
// persistCapturedMapV3. The order is: the attach commit retires the marker,
// THEN the marking is made durable, THEN the volume serves. A crash between
// the first two leaves no marker and every chunk UNKNOWN (one scan); a
// failed map publication leaves them UNKNOWN on disk (conservative).
func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 {
s := l.s
if s.v3 == nil || s.v3.ownedMap == nil {
return nil
}
s.mu.RLock()
defer s.mu.RUnlock()
out := map[uint64]uint64{}
for idx := uint64(0); idx < l.numChunks && idx < uint64(len(s.v3.mapEntries)); idx++ {
if _, named := head.Chunks[idx]; named {
continue
}
if e := s.v3.mapEntries[idx]; e.LSN != 0 || !e.Unknown {
continue
}
out[idx] = l.chunkVersion(idx)
}
if len(out) == 0 {
return nil
}
return out
}
// ApplyFreshKnownZero makes the fresh attach's certification durable: called
// once, by the provider, after the attach commit retired the fresh marker and
// before the volume serves, outside the capture barrier (as for a cut).
// It counts the chunks it certified in Stats.KnownZeroChunks and logs the
// outcome: a failed map publication or a raced write leaves chunks UNKNOWN,
// and the first cut then scans them (the log says why).
func (l *chunkLayerImpl) ApplyFreshKnownZero() {
tokens := l.freshKnownZero
if tokens == nil {
return
}
l.freshKnownZero = nil
l.persistCapturedMapV3(tokens)
s := l.s
s.mu.RLock()
certified := 0
for idx := range tokens {
if idx < uint64(len(s.v3.mapEntries)) && !s.v3.mapEntries[idx].Unknown {
certified++
}
}
s.mu.RUnlock()
l.stMu.Lock()
l.stats.KnownZeroChunks = uint64(certified)
l.stMu.Unlock()
if certified == len(tokens) {
log.Printf("storage: fresh attach: %d chunks HEAD does not name start known-zero", certified)
} else {
log.Printf("storage: WARNING: fresh attach: %d of %d chunks HEAD does not name start known-zero; the rest stay unknown (map publication failed or a write raced) and the first cut scans them", certified, len(tokens))
}
}
@@ -0,0 +1,98 @@
package storage
import (
"bytes"
"testing"
)
// fkzConfig is a fresh attach's config (FreshFromHead) or an existing
// store's.
func fkzConfig(fresh bool) chunkLayerConfig {
cfg := ctConfig(1)
cfg.FreshFromHead, cfg.CreatedThisStart = fresh, fresh
return cfg
}
// fkzAttach attaches and applies the certification, as the provider does
// after its attach commit.
func fkzAttach(t *testing.T, s *WALStore, r chunkRemote, cfg chunkLayerConfig) chunkLayer {
t.Helper()
l := mustAttach(t, s, r, cfg)
l.(*chunkLayerImpl).ApplyFreshKnownZero()
return l
}
func fkzCandidates(l chunkLayer) int { return l.Stats().DirtyChunks }
// A fresh attach certifies every chunk the claimed HEAD does not name whose
// owned-map entry is still the creation value; a chunk whose entry recorded
// a write (LSN >= 1) is never certified and stays a candidate, even where
// that LSN is not above HEAD's RemoteLSN (so "LSN above HEAD" alone would
// not make it one): here HEAD is at 100 and the write at 1.
func TestFreshKnownZeroNeverCertifiesARecordedWrite(t *testing.T) {
s, _ := newChunkTestStore(t)
if _, err := s.Write(uint32(2*ctChunkBlocks+1), bytes.Repeat([]byte{0x22}, ctBlockSize)); err != nil {
t.Fatal(err)
}
remote := newFakeChunkRemote()
remote.head = chunkHead{Gen: 1, Epoch: 1, RemoteLSN: 100, State: ChunkHeadActive}
l := fkzAttach(t, s, remote, fkzConfig(true))
if got := fkzCandidates(l); got != 1 {
t.Fatalf("fresh attach after a recorded write to chunk 2: %d candidates; want 1 (that chunk only)", got)
}
if got, want := l.Stats().KnownZeroChunks, uint64(l.(*chunkLayerImpl).numChunks-1); got != want {
t.Fatalf("KnownZeroChunks %d; want %d", got, want)
}
}
// Without the fresh premise (an existing store) nothing is certified: every
// chunk keeps its persisted UNKNOWN.
func TestFreshKnownZeroNotWithoutTheFreshPremise(t *testing.T) {
s, _ := newChunkTestStore(t)
l := fkzAttach(t, s, newFakeChunkRemote(), fkzConfig(false))
if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want {
t.Fatalf("existing-store attach: %d candidates; want all %d", got, want)
}
if got := l.Stats().KnownZeroChunks; got != 0 {
t.Fatalf("KnownZeroChunks %d without the fresh premise; want 0", got)
}
}
// The certification clears only chunks whose mutation token is unchanged
// since it was sampled under the attach barrier: a write landing between the
// sample and the clear keeps its chunk a candidate.
func TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample(t *testing.T) {
s, _ := newChunkTestStore(t)
raw, err := attachChunkLayerImpl(s, newFakeChunkRemote(), fkzConfig(true))
if err != nil {
t.Fatal(err)
}
l := raw.(*chunkLayerImpl)
t.Cleanup(func() { _ = l.Close() })
sampled := len(l.freshKnownZero)
if sampled == 0 {
t.Fatal("no chunk sampled for certification")
}
if _, err := s.Write(uint32(3*ctChunkBlocks), bytes.Repeat([]byte{0x33}, ctBlockSize)); err != nil {
t.Fatal(err)
}
l.ApplyFreshKnownZero()
if got := fkzCandidates(l); got != 1 {
t.Fatalf("a write between the sample and the clear: %d candidates; want 1 (the written chunk)", got)
}
if got := l.Stats().KnownZeroChunks; got != uint64(sampled-1) {
t.Fatalf("KnownZeroChunks %d; want %d (every sampled chunk but the written one)", got, sampled-1)
}
}
// A fresh marker alone is not trusted: an attach whose store this start did
// not create (CreatedThisStart false) certifies nothing.
func TestFreshKnownZeroNeedsThisStartsCreate(t *testing.T) {
s, _ := newChunkTestStore(t)
cfg := fkzConfig(true)
cfg.CreatedThisStart = false
l := fkzAttach(t, s, newFakeChunkRemote(), cfg)
if got, want := fkzCandidates(l), int(l.(*chunkLayerImpl).numChunks); got != want {
t.Fatalf("fresh attach of a store this start did not create: %d candidates; want all %d", got, want)
}
}
@@ -62,6 +62,10 @@ type chunkLayerImpl struct {
remote chunkRemote
cfg chunkLayerConfig
// freshKnownZero: the mutation tokens RULE-FRESH-KNOWN-ZERO sampled at a
// fresh attach; applied once by ApplyFreshKnownZero.
freshKnownZero map[uint64]uint64
blockSize int
chunkBlocks uint64
numChunks uint64
@@ -287,6 +291,9 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.absentGen[idx]++
}
l.presenceVer++
if cfg.CreatedThisStart {
l.freshKnownZero = l.freshKnownZeroCandidates(head)
}
} else if err := l.loadPresence(); err != nil {
l.cancel()
return nil, err
+6
View File
@@ -343,6 +343,11 @@ type chunkLayerConfig struct {
// HEAD (every block absent, read lazily). False means an existing local
// volume. Never inferred from the local contents.
FreshFromHead bool
// CreatedThisStart says this process start created the local store (an
// in-memory fact, never persisted). RULE-FRESH-KNOWN-ZERO samples only
// with it and FreshFromHead: a fresh marker left by an earlier start, an
// older binary or another opener is never trusted.
CreatedThisStart bool
// RestoreGuard binds fresh attachment to the HEAD the provider claimed
// and durably seeded. A changed read refuses before hooks/readiness; the
// next recovery must repeat claim and seed. Nil is for direct layer users.
@@ -519,6 +524,7 @@ type chunkLayerStats struct {
PendingUnresolved bool // an unresolved HEAD proposal is held now
DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress
StagedChunks uint64 // chunks staged by every cut attempt, failed ones included (in-process)
KnownZeroChunks uint64 // chunks this layer's fresh attach certified known-zero (RULE-FRESH-KNOWN-ZERO); 0 otherwise
Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile
ReconcileDone int // chunks compared so far
ReconcileTotal int // chunks to compare
+3 -2
View File
@@ -497,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
322 rows: 252 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 307 new.
323 rows: 253 ACTIVE, 67 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 308 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -822,7 +822,8 @@ Notes:
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE |
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE |
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
| `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE |
| `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE |
+1 -1
View File
@@ -202,7 +202,7 @@ with `move target node "s2" is not registered`.
| `SWB_HEARTBEAT_INTERVAL` | `--heartbeat-interval` | `2s` | Heartbeat interval |
| `SWB_RECOVER_TIMEOUT` | `--recover-timeout` | `30s` | Time to become promotion-ready before reporting `recovery_timeout` |
| `SWB_DURABLE_ROOT` | `--durable-root` | empty (in memory, not durable) | Storage directory; writable by the service user |
| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root. Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. |
| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root; so does every explicit value other than `walstore-chunk` (a chunk root holds data that may live only in the remote HEAD: open it with `--durable-impl=walstore-chunk` and its remote configuration). Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. |
| `SWB_DURABLE_BLOCKS` | `--durable-blocks` | `2048` | Blocks on first create |
| `SWB_DURABLE_BLOCKSIZE` | `--durable-blocksize` | `4096` | Block size on first create |
| `SWB_NVME_LISTEN` | `--nvme-listen` | empty (off) | NVMe/TCP target; loopback only, no authentication |
+1
View File
@@ -229,6 +229,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now |
| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress |
| `Volumes[].Chunk.Stats.StagedChunks` | uint64 | chunks staged by every cut attempt, failed ones included (in-process) |
| `Volumes[].Chunk.Stats.KnownZeroChunks` | uint64 | chunks this layer's fresh attach certified known-zero (RULE-FRESH-KNOWN-ZERO); 0 otherwise |
| `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile |
| `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far |
| `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare |