storage: cut COW never fetches under a guest write (#216 follow-up P1)

A cut candidate chunk that is lazily absent but has local writes stays a
candidate. Its first writer inside the copy window saved the chunk
synchronously through Read, so every non-local block became a remote fetch
bounded only by ReadMissTimeout (30 s), and every writer queued behind that
chunk waited on it; an abort did not cancel the fetch. The in-window copier
had the same shape: writers to a chunk it was copying waited on its fetch.

The COW save and the in-window copy now read LOCAL blocks only (dirty
map/WAL, the extent of present or locally written blocks, zeros for a chunk
HEAD stores as ZERO) and never call the miss hook. A lazily-absent block's
image at H is HEAD's by definition: it is listed as missing, and the copier
fills it from the cut's base HEAD after it has released the entry, off the
write path (bounded by ReadMissTimeout and the window's end).

Tests: the lazy-HEAD saver test now holds every remote fetch once the window
is open and requires the saving write to finish without one (it asserted the
blocking fetch before); C3 holds the in-window local copy instead of a fetch
and requires the write to complete with the remote held, the copier's HEAD
fetch coming afterwards. Five declared mutants (blocking read, absent block
read as local, no fill, saver drops the missing list, fill under the entry)
each turn exactly their declared tests red.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-18 19:42:43 -08:00
1 parent b6ca5237fd
commit 623c11da4c
5 files changed
+146 -22

No files matched your search

+97 -11
View File
@@ -36,6 +36,10 @@ type cutCOWEntry struct {
slot int64
spilled bool
readingSaved bool
// missing lists the block offsets that were lazily absent when the bytes
// were captured: their image at H is HEAD's, filled by the copier from the
// cut's base HEAD after it released the entry (never under a guest write).
missing []uint64
}
type cutCOWWindow struct {
layer *chunkLayerImpl
@@ -47,6 +51,7 @@ type cutCOWWindow struct {
sideReady chan struct{}
cleanupErr error
entries map[uint64]*cutCOWEntry
head map[uint64]chunkRef // the cut's base HEAD: the source of missing blocks
memory int64
chunkBytes int64
side *os.File
@@ -119,12 +124,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() {
}
// The caller owns captureMu exclusive, so no writer can miss this publication.
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool) (*cutCOWWindow, error) {
func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef) (*cutCOWWindow, error) {
size := uint64(l.blockSize) * l.chunkBlocks
if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size {
return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted)
}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), chunkBytes: int64(size)}
w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, chunkBytes: int64(size)}
var slot int64
for _, idx := range sortedKeys(candidates) {
state := cowPending
@@ -256,9 +261,10 @@ func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) {
break
}
start := time.Now()
data, err := l.readCOWChunk(w, idx)
// Local blocks only: a guest write never waits on SeaweedFS.
data, missing, err := l.readCOWChunk(w, idx)
if err == nil {
err = w.save(e, data)
err = w.save(e, data, missing)
}
if err != nil {
w.abort(err)
@@ -273,7 +279,7 @@ func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) {
}
}
func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte) error {
func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error {
if hook := w.layer.testCOWSave; hook != nil {
if err := hook(); err != nil {
return err
@@ -289,6 +295,7 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte) error {
w.memory += w.chunkBytes
}
w.mu.Unlock()
e.missing = missing
if inMemory {
e.data = data
return nil
@@ -307,25 +314,95 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte) error {
return err
}
func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, error) {
// readCOWChunk reads chunk idx's LOCAL blocks and never fetches: a block that
// is lazily absent (no local version, HEAD names the chunk) is left zero and
// listed in missing; its image at H is HEAD's by definition.
func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, []uint64, error) {
buf := make([]byte, int(w.chunkBytes))
var missing []uint64
for i := uint64(0); i < l.chunkBlocks; i++ {
select {
case <-w.ended:
return nil, errCutCOWAborted
return nil, nil, errCutCOWAborted
default:
}
lba := idx*l.chunkBlocks + i
if lba >= uint64(l.s.NumBlocks()) {
break
}
b, err := l.s.Read(uint32(lba))
b, local, err := l.readLocalBlock(lba)
if err != nil {
return nil, err
return nil, nil, err
}
if !local {
missing = append(missing, i)
continue
}
copy(buf[int(i)*l.blockSize:], b)
}
return buf, nil
return buf, missing, nil
}
// readLocalBlock reads lba unless it is lazily absent (local=false): the dirty
// map/WAL first, then the extent of a present block (or of a block written
// since its chunk became absent), zeros for an absent chunk HEAD stores as
// ZERO. It never calls the miss hook. The order is safe against a concurrent
// flush (dirty map before presence) and fill (HEAD's bytes either way); a new
// write of the block waits for the caller's COW entry.
func (l *chunkLayerImpl) readLocalBlock(lba uint64) ([]byte, bool, error) {
s := l.s
if s.v3 != nil {
if data, handled, err := s.readDirtyV3(uint32(lba)); handled {
return data, err == nil, err
}
} else if walRelOff, dataOffset, _, _, ok := s.dm.get(lba); ok {
data, err := s.readFromWAL(walRelOff, dataOffset)
return data, err == nil, err
}
idx := l.chunkOf(lba)
l.stMu.Lock()
absent := l.absent[idx] && !l.localBlocks[lba]
_, inHead := l.head.Chunks[idx]
l.stMu.Unlock()
if absent && inHead {
return nil, false, nil
}
if absent {
return make([]byte, l.blockSize), true, nil
}
data, err := s.readExtentBlock(uint32(lba))
return data, err == nil, err
}
// fillMissing completes a COW capture: the blocks listed missing get the cut's
// base HEAD bytes. It runs with no entry held (no guest waits on it), bounded
// by ReadMissTimeout and the window's end.
func (l *chunkLayerImpl) fillMissing(w *cutCOWWindow, idx uint64, data []byte, missing []uint64) ([]byte, error) {
ref, ok := w.head[idx]
if !ok {
return nil, fmt.Errorf("storage: cut chunk %d: %d lazily absent block(s) but HEAD has no chunk", idx, len(missing))
}
ctx, cancel := context.WithTimeout(l.ctx, l.cfg.ReadMissTimeout)
defer cancel()
go func() {
select {
case <-w.ended:
cancel()
case <-ctx.Done():
}
}()
head, err := l.remote.Get(ctx, ref.Key)
if err != nil {
return nil, fmt.Errorf("storage: cut chunk %d HEAD fetch: %w", idx, err)
}
if sha256.Sum256(head) != ref.SHA256 || len(head) != int(l.chunkBlocks)*l.blockSize {
return nil, fmt.Errorf("storage: cut chunk %d HEAD fetch: content does not match HEAD", idx)
}
out := append([]byte(nil), data...)
for _, i := range missing {
copy(out[int(i)*l.blockSize:int(i+1)*l.blockSize], head[int(i)*l.blockSize:int(i+1)*l.blockSize])
}
return out, nil
}
func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChunk, bool, error) {
@@ -343,8 +420,10 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun
return capturedChunk{}, false, w.status()
}
var data []byte
var missing []uint64
var err error
if state == cowSaved {
missing = e.missing
if e.spilled {
data = make([]byte, int(w.chunkBytes))
_, err = w.side.ReadAt(data, e.slot*w.chunkBytes)
@@ -352,7 +431,7 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun
data = e.data
}
} else {
data, err = l.readCOWChunk(w, idx)
data, missing, err = l.readCOWChunk(w, idx)
}
if hook := l.testCOWRead; hook != nil {
hook(idx, state == cowSaved)
@@ -367,6 +446,13 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun
if err == nil {
kept = w.finish(e, cowDone)
}
if kept && len(missing) > 0 {
// The entry is released: guests no longer wait on this chunk.
if data, err = l.fillMissing(w, idx, data, missing); err != nil {
w.abort(err)
kept = false
}
}
w.refs.Done()
if !kept {
return capturedChunk{}, false, w.status()
@@ -816,12 +816,21 @@ func TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD(t *testing.T) {
})
go func() { defer close(cutDone); _, cutErr = l.Cut(context.Background()) }()
cowWaitSignal(t, live, "first actual copied chunk")
gets, releaseGet := holdGets(t, f) // only the pending chunk still needs HEAD bytes
// The window is open. No guest write may wait on SeaweedFS (design
// rules 1/2): the lazily-absent chunks with local writes were filled
// BEFORE the window, so from here every HEAD fetch is held and the
// saving write must finish without one.
gets, releaseGet := holdGets(t, f)
t.Cleanup(releaseGet)
writeStarted = true
go func() { defer close(writeDone); _, writeErr = s.Write(6, makeBlock(ctBlockSize, 0x96)) }()
waitKey(t, gets, "saving owner's actual lazy fetch")
cowWaitSignal(t, writeDone, "lazy saving write without a remote fetch")
select {
case k := <-gets:
t.Fatalf("a guest write fetched %s from the remote inside the cut window", k)
default:
}
releaseGet()
cowWaitSignal(t, writeDone, "lazy saving write")
if writeErr != nil {
t.Fatal(writeErr)
}
+1 -1
View File
@@ -898,7 +898,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
copyStart := time.Now()
if l.usesOwnedMapV3() {
var w *cutCOWWindow
w, copyErr = l.installCOWWindow(candidates, useStaged)
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks)
l.s.captureMu.Unlock()
st.BarrierPauseNs = time.Since(barrier).Nanoseconds()
copyStart = time.Now()
@@ -273,6 +273,10 @@ func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) {
// C3 barrier: a write issued while a cut is still copying its chunks does
// not land until the copy is done, so it can never tear the captured image.
// It waits for the LOCAL copy only, never for SeaweedFS (design rules 1/2):
// the copy reads chunk 2's local blocks and releases the chunk; it fetches the
// absent blocks from HEAD afterwards, so the write completes with every remote
// fetch held.
// The copy is held deterministically: on a fresh host the cut's copy of a
// dirty chunk must fetch that chunk's absent blocks, and the fetch is held.
func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) {
@@ -296,12 +300,25 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) {
t.Fatal(err)
}
gEntered, gRelease := holdGets(t, f)
l := layer.(*chunkLayerImpl)
inCopy, releaseCopy := make(chan struct{}), make(chan struct{})
var copyOnce, releaseOnce sync.Once
unblockCopy := func() { releaseOnce.Do(func() { close(releaseCopy) }) }
l.testCOWRead = func(idx uint64, _ bool) {
if idx == 2 {
copyOnce.Do(func() { close(inCopy) })
<-releaseCopy
}
}
late := makeBlock(ctBlockSize, 0xDA)
wrote := make(chan error, 1)
joined := make(chan struct{})
var gRelease func()
t.Cleanup(func() {
gRelease()
unblockCopy()
if gRelease != nil {
gRelease()
}
select {
case <-joined:
case <-time.After(ctLocalBound):
@@ -309,7 +326,9 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) {
}
})
done := startCapture(t, layer)
waitKey(t, gEntered, "the cut's fetch of an absent block in chunk 2")
cowWaitSignal(t, inCopy, "the cut copying chunk 2 inside its window")
var gEntered chan string
gEntered, gRelease = holdGets(t, f) // from here any remote fetch blocks
go func() {
defer close(joined)
_, err := s.Write(10, late)
@@ -318,15 +337,19 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) {
select {
case err := <-wrote:
t.Fatalf("a write landed while the cut was still copying (err %v); the barrier was released before the copy", err)
case <-time.After(200 * time.Millisecond): // the copy is held indefinitely; the write must wait
case <-time.After(200 * time.Millisecond): // the copy is held; the write must wait for it
}
unblockCopy() // the remote stays held: the write may wait only for the local copy
if err := waitErr(t, wrote, "write after the local copy, with the remote held"); err != nil {
t.Fatal(err)
}
// The copier fetches chunk 2's absent blocks from HEAD only now, after it
// released the entry: the write above completed with that fetch held.
waitKey(t, gEntered, "the copier's HEAD fetch of chunk 2's absent blocks, off the write path")
gRelease()
if err := waitErr(t, done, "held cut"); err != nil {
t.Fatalf("held cut: %v", err)
}
if err := waitErr(t, wrote, "write after the cut"); err != nil {
t.Fatal(err)
}
img := f.imageOf(t, f.stats().head)
if !bytes.Equal(blockOf(img, 8), local) {
t.Fatal("the cut's image lacks the write made before its barrier")
+6
View File
@@ -1100,6 +1100,12 @@ func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) {
return s.readFromWAL(walRelOff, dataOffset)
}
}
return s.readExtentBlock(lba)
}
// readExtentBlock reads lba's extent bytes under its extent lock, without the
// chunk layer's miss hook: the caller has resolved the block as local.
func (s *WALStore) readExtentBlock(lba uint32) ([]byte, error) {
lock := &s.extentMu[uint64(lba)%uint64(len(s.extentMu))]
lock.RLock()
defer lock.RUnlock()