storage: a staged chunk is reused only while its mutation count is unchanged; a barrier Sync failure settles staged intents

The chunk's highest write LSN is not a change detector: a replica apply
may land a block at an LSN below another block of the same chunk, so the
maximum does not move and a stale stage could be reused. Each chunk now
has a mutation count, raised after every dirty-map insert (a write, a
batch write, a replica apply at any LSN) and every BASE block; flushing
moves bytes without changing them and never counts. It is an atomic
per-chunk counter on the write path (O(1), lock-free), sampled before the
staging read and compared at the barrier.

A barrier Sync failure after staging is a clean abort: the cut's staging
intents are deleted (a failed delete is kept and retried by the next cut).

Real-caller controls:
- chunk 0 holds a@10 and b@5; after the staging read, ApplyEntry(b, 6)
  through the production apply path, in the WAL and flushed: HEAD at H
  has b@6;
- staged uploads, then the local fsync fails at the barrier: no intent
  is left; with the intent delete failing too, the intent is kept and the
  next cut settles it and publishes the exact image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 11:52:01 -08:00
1 parent 5792d1427b
commit b91b2bf3b3
3 files changed
+151 -28

No files matched your search

+35 -28
View File
@@ -27,6 +27,7 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
@@ -34,6 +35,9 @@ import (
type chunkHooks struct {
sink chunkSink
closer func() error
// mutated runs after every dirty-map insert (a write, a batch write,
// a replica apply) with the LBA: O(1), lock-free, on the write path.
mutated func(lba uint64)
}
const defaultReadMissTimeout = 30 * time.Second
@@ -87,10 +91,11 @@ type chunkLayerImpl struct {
allDirty bool // a BASE block landed: every chunk is dirty
hashMode bool // the dirty set is unknown: compare every chunk by hash
cutLSN uint64 // H of the latest cut taken (in flight or installed)
// chunkVer is the highest LSN flushed into each chunk (under stMu).
// With the WAL's entries it gives a chunk's version (chunkVersion):
// flushing an entry never changes it, any newer write raises it.
chunkVer map[uint64]uint64
// chunkMut counts the mutations of each chunk: every dirty-map insert
// (any LSN, a replica apply's lower LSN included) and every BASE
// block. Flushing moves bytes without changing them and never counts.
// A chunk staged at count n is unchanged while its count is n.
chunkMut []atomic.Uint64
keySeq uint64
// Test-only scheduling hooks; nil in production.
@@ -131,10 +136,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
absent: map[uint64]bool{},
absentGen: map[uint64]uint64{},
localBlocks: map[uint64]bool{},
chunkVer: map[uint64]uint64{},
closeDone: make(chan struct{}),
syncDirFn: syncDir,
}
l.chunkMut = make([]atomic.Uint64, l.numChunks)
var nb8 [8]byte
if _, err := rand.Read(nb8[:]); err != nil {
return nil, err
@@ -218,7 +223,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.cancel()
return nil, err
}
hooks := &chunkHooks{sink: l, closer: l.Close}
hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation}
if !s.chunk.CompareAndSwap(nil, hooks) {
l.cancel()
return nil, errors.New("storage: a chunk layer is already attached")
@@ -277,31 +282,33 @@ func (l *chunkLayerImpl) OnExtentWrite(lba uint64, lsn uint64) {
l.localBlocks[lba] = true
l.presenceVer++
}
if lsn > l.chunkVer[idx] {
l.chunkVer[idx] = lsn
if lsn == 0 { // a BASE block lands in the extent directly
l.noteMutation(lba)
}
l.dirtyVer++
}
// walMaxLSN maps each chunk with entries in the WAL dirty map to its
// highest entry LSN.
func (l *chunkLayerImpl) walMaxLSN() map[uint64]uint64 {
out := map[uint64]uint64{}
// noteMutation counts a mutation of lba's chunk. It runs after the
// mutation is visible to reads, so a staging read that sampled the count
// first either sees the new bytes or a stale count (never reused).
func (l *chunkLayerImpl) noteMutation(lba uint64) {
if idx := l.chunkOf(lba); idx < uint64(len(l.chunkMut)) {
l.chunkMut[idx].Add(1)
}
}
// walChunks returns the chunks with entries in the WAL dirty map.
func (l *chunkLayerImpl) walChunks() map[uint64]bool {
out := map[uint64]bool{}
for _, e := range l.s.dm.snapshot() {
if idx := l.chunkOf(e.LBA); e.LSN > out[idx] {
out[idx] = e.LSN
}
out[l.chunkOf(e.LBA)] = true
}
return out
}
// chunkVersion is chunk idx's highest write LSN, flushed or in the WAL
// (wal from walMaxLSN). Caller holds stMu.
func (l *chunkLayerImpl) chunkVersion(idx uint64, wal map[uint64]uint64) uint64 {
if v := wal[idx]; v > l.chunkVer[idx] {
return v
}
return l.chunkVer[idx]
// chunkVersion is chunk idx's mutation count.
func (l *chunkLayerImpl) chunkVersion(idx uint64) uint64 {
return l.chunkMut[idx].Load()
}
// BeforeCheckpointAdvance runs inside persistCheckpoint and the direct
@@ -669,11 +676,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if err != nil {
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
l.dropIntents(ctx, intents) // a clean abort: staged keys are released
return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err)
}
candidates := map[uint64]bool{}
wal := l.walMaxLSN()
for idx := range wal {
for idx := range l.walChunks() {
candidates[idx] = true
}
l.stMu.Lock()
@@ -697,7 +704,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
var captured []capturedChunk
useStaged := map[uint64]bool{}
for idx := range candidates {
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx, wal) && sc.headGen == l.head.Gen {
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen {
useStaged[idx] = true
captured = append(captured, sc.capturedChunk)
}
@@ -1138,11 +1145,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
staged := map[uint64]stagedChunk{}
var intents []string
for round := 0; round < chunkStageRounds; round++ {
wal := l.walMaxLSN()
wal := l.walChunks()
l.stMu.Lock()
need := map[uint64]bool{}
consider := func(idx uint64) {
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx, wal) && sc.headGen == l.head.Gen {
if sc, ok := staged[idx]; ok && sc.ver == l.chunkVersion(idx) && sc.headGen == l.head.Gen {
return // still current
}
need[idx] = true
@@ -1168,7 +1175,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
batch := sortedKeys(need)[:bound]
vers := make(map[uint64]uint64, len(batch))
for _, idx := range batch {
vers[idx] = l.chunkVersion(idx, wal) // before the read: a later write raises it
vers[idx] = l.chunkVersion(idx) // before the read: a later mutation raises it
}
head := copyHead(l.head)
l.stMu.Unlock()
@@ -6,7 +6,9 @@ package storage
// write reached it since staging, so the image at H stays exact.
import (
"bytes"
"context"
"errors"
"strings"
"testing"
)
@@ -191,3 +193,105 @@ func TestChunkPrecopy_WriteRightAfterStagingReadIsNotLost(t *testing.T) {
}
assertEveryHeadIsPrefixImage(t, f, w)
}
// A replica apply may land a block at an LSN below another block of the
// same chunk (the highest LSN in the chunk does not move). It still makes
// the staged copy stale: the barrier copies the chunk again and HEAD has
// the applied bytes, whether the apply is still in the WAL or flushed.
func TestChunkPrecopy_LowerLSNApplyAfterStagingIsNotLost(t *testing.T) {
for _, flushed := range []bool{false, true} {
name := map[bool]string{true: "flushed", false: "in the WAL"}[flushed]
t.Run(name, func(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
cfg := ctConfig(1)
cfg.FreshFromHead = true
cfg.BarrierBound = 1
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
a, b, b2, c := makeBlock(ctBlockSize, 0xa0), makeBlock(ctBlockSize, 0xb5), makeBlock(ctBlockSize, 0xb6), makeBlock(ctBlockSize, 0xc1)
for _, e := range []struct {
lba uint32
data []byte
lsn uint64
}{{1, b, 5}, {0, a, 10}, {ctChunkBlocks, c, 11}} { // chunk 0 holds a@10 and b@5; chunk 1 c@11
if err := s.ApplyEntry(e.lba, e.data, e.lsn); err != nil {
t.Fatal(err)
}
}
applied := false
l.testAfterStageReadHook = func(idx uint64) {
if idx == 0 && !applied { // chunk 0 is staged with b@5
applied = true
if err := s.ApplyEntry(1, b2, 6); err != nil { // the production apply path
t.Errorf("apply b@6: %v", err)
}
if flushed {
mustSyncFlush(t, s)
}
}
}
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !applied || r.Stats.StagedChunks == 0 {
t.Fatalf("schedule did not run: applied=%v staged=%d", applied, r.Stats.StagedChunks)
}
img := f.imageOf(t, r.Head)
for _, want := range []struct {
lba int
data []byte
}{{0, a}, {1, b2}, {ctChunkBlocks, c}} {
if got := img[want.lba*ctBlockSize : (want.lba+1)*ctBlockSize]; !bytes.Equal(got, want.data) {
t.Fatalf("HEAD at H=%d: LBA %d is %#x..., want %#x... (the b@6 apply after staging lost)", r.H, want.lba, got[0], want.data[0])
}
}
assertNoIntentsLeft(t, f)
})
}
}
// A barrier Sync that fails after staging uploaded keys is a clean abort:
// the cut's staging intents are deleted (a failed delete is kept and
// retried by the next cut), and the next cut publishes the exact image.
func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) {
s, f, l, w := precopyLayer(t, 2, 5)
orig := s.committer.syncFunc
l.testAfterStageHook = func(round int) {
if round == 0 {
s.committer.syncFunc = func() error { return errors.New("injected local fsync failure") }
}
}
before := f.stats()
if _, err := l.Cut(ctTimeout(t)); err == nil || !strings.Contains(err.Error(), "capture sync") {
t.Fatalf("cut with a failing barrier Sync: %v; want a capture sync error", err)
}
if st := f.stats(); st.puts == before.puts {
t.Fatal("schedule did not stage any upload before the barrier")
}
assertNoIntentsLeft(t, f)
// The same abort with the intent delete failing: kept, retried next cut.
w.write(t, s, 2, 0x22)
w.write(t, s, uint32(ctChunkBlocks+2), 0x23)
w.write(t, s, uint32(2*ctChunkBlocks+2), 0x24)
f.mu.Lock()
f.failDeleteIntent = 100
f.mu.Unlock()
if _, err := l.Cut(ctTimeout(t)); err == nil {
t.Fatal("second cut with a failing barrier Sync succeeded")
}
if left := len(liveIntents(t, f)); left == 0 {
t.Fatal("schedule: the failing delete left no intent to retry")
}
f.mu.Lock()
f.failDeleteIntent = 0
f.mu.Unlock()
l.testAfterStageHook = nil
s.committer.syncFunc = orig
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
assertEveryHeadIsPrefixImage(t, f, w)
assertNoIntentsLeft(t, f)
}
+12
View File
@@ -525,6 +525,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
}
dirtyStart := time.Now()
s.dm.put(uint64(lba), walRelOff, lsn, uint32(len(data)))
s.noteChunkMutation(uint64(lba))
s.instr.recordDirtyMapUpdate(1, time.Since(dirtyStart))
s.nextLSN++
@@ -602,6 +603,7 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error
dirtyStart := time.Now()
for i, walRelOff := range offsets {
s.dm.put(uint64(startLBA+uint32(i)), walRelOff, lsns[i], uint32(len(blocks[i])))
s.noteChunkMutation(uint64(startLBA + uint32(i)))
}
s.instr.recordDirtyMapUpdate(len(offsets), time.Since(dirtyStart))
@@ -655,6 +657,7 @@ func (s *WALStore) writeBatchMultiBlockLocked(startLBA uint32, blocks [][]byte,
lsn,
uint32(len(data)),
)
s.noteChunkMutation(uint64(startLBA + uint32(i)))
}
s.instr.recordDirtyMapUpdate(len(blocks), time.Since(dirtyStart))
@@ -999,6 +1002,14 @@ func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error {
// ApplyEntry writes a replicated block with the source's LSN rather
// than allocating a fresh one. Same durability semantics as Write
// (becomes durable on next Sync).
// noteChunkMutation tells an attached chunk layer that lba changed; it
// runs after the dirty-map insert that made the change visible.
func (s *WALStore) noteChunkMutation(lba uint64) {
if h := s.chunk.Load(); h != nil && h.mutated != nil {
h.mutated(lba)
}
}
func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
s.bypassSyncDedup.Store(true)
s.captureMu.RLock()
@@ -1035,6 +1046,7 @@ func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
return fmt.Errorf("storage: WAL append (apply): %w", err)
}
s.dm.put(uint64(lba), walRelOff, lsn, uint32(len(dataCopy)))
s.noteChunkMutation(uint64(lba))
if lsn >= s.nextLSN {
s.nextLSN = lsn + 1