From 623c11da4c174942072637e1bf093b5bc25a2d17 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 19:42:43 -0800 Subject: [PATCH 1/2] 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 --- seaweed-block/core/storage/chunk_cut_cow.go | 108 ++++++++++++++++-- .../storage/chunk_cut_cow_lifetime_test.go | 15 ++- seaweed-block/core/storage/chunk_layer.go | 2 +- .../core/storage/chunk_layer_contract_test.go | 37 ++++-- seaweed-block/core/storage/walstore.go | 6 + 5 files changed, 146 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index 532aa8c681..dce0c18225 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -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() diff --git a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go index 8d03a77b2a..68d8e3471a 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go @@ -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) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 07c6daf783..612b777a9e 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -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() diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index ad2377faba..a4281471d9 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -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") diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index a40558ddde..c148ce5f1f 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -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() From 377ed5fcff4c544b06c81d9ed5869eac50e70a8e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 19:59:25 -0800 Subject: [PATCH 2/2] storage: COW P1 review fold: fill abort/timeout and spill coverage, handshake, comments - Tests: the copier's HEAD fill (after it released the entry) is cancelled by an aborted cut and the window drains; a held fill is bounded by ReadMissTimeout and aborts the cut; a lazily-absent saved chunk that spills keeps its missing list and the image is exact. - C3 waits for an actual writer-entry handshake (the writer parked on the copy entry) instead of a 200 ms non-completion window. - Comments: the happens-before of e.missing (published by finish), and the lazy-HEAD saver test describes the local-only save. Mutants (declared): fill ignores the window's end, fill without ReadMissTimeout, missing list kept only for in-memory saves; the earlier five now also turn the new fill/spill tests red where they should. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_cut_cow.go | 3 + .../core/storage/chunk_cut_cow_fill_test.go | 149 ++++++++++++++++++ .../storage/chunk_cut_cow_lifetime_test.go | 5 +- .../core/storage/chunk_layer_contract_test.go | 6 +- 4 files changed, 160 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_cut_cow_fill_test.go diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index dce0c18225..23debf9367 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -295,6 +295,9 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error w.memory += w.chunkBytes } w.mu.Unlock() + // e.missing (and e.data / the spilled bytes) are published to readers by + // w.finish(e, cowSaved), which takes w.mu and e.mu after these writes: a + // copier reads them only after claiming the entry in state cowSaved. e.missing = missing if inMemory { e.data = data diff --git a/seaweed-block/core/storage/chunk_cut_cow_fill_test.go b/seaweed-block/core/storage/chunk_cut_cow_fill_test.go new file mode 100644 index 0000000000..194f9a4e09 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_fill_test.go @@ -0,0 +1,149 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "testing" + "time" +) + +// lazyChunk2Fixture: HEAD holds chunk 2 (LBA 8-11); the volume is fresh from +// HEAD (every chunk absent) and LBA 8 is written locally, so chunk 2 is a +// partly absent cut candidate. +func lazyChunk2Fixture(t *testing.T, readMiss time.Duration) (*WALStore, *chunkLayerImpl, *fakeChunkRemote, []byte, []byte) { + t.Helper() + src := make([]byte, ctNumBlocks*ctBlockSize) + for lba := uint32(8); lba < 12; lba++ { + copy(src[int(lba)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x80+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 + cfg.ReadMissTimeout = readMiss + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + local := makeBlock(ctBlockSize, 0xD8) + if _, err := s.Write(8, local); err != nil { + t.Fatal(err) + } + return s, l, f, src, local +} + +// The copier's HEAD fill (after it released the entry) is cancelled by an +// aborted cut: the cut returns promptly, the window is drained, and the next +// cut publishes the right image. +func TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained(t *testing.T) { + _, l, f, src, local := lazyChunk2Fixture(t, time.Minute) + gEntered, gRelease := holdGets(t, f) + t.Cleanup(gRelease) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { _, err := l.Cut(ctx); done <- err }() + waitKey(t, gEntered, "the copier's HEAD fill of chunk 2") + cancel() + err := waitErr(t, done, "aborted cut with a held fill") + if err == nil || !(errors.Is(err, context.Canceled) || errors.Is(err, errCutCOWAborted)) { + t.Fatalf("cut aborted during a held fill: %v, want cancellation", err) + } + if w := l.cowActive.Load(); w != nil { + t.Fatal("copy window not drained after the abort") + } + gRelease() + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal("next cut:", err) + } + img := f.imageOf(t, r.Head) + if !bytes.Equal(blockOf(img, 8), local) || !bytes.Equal(blockOf(img, 9), blockOf(src, 9)) { + t.Fatal("next cut lost the local block or HEAD's bytes for the absent ones") + } +} + +// A held fill is bounded by ReadMissTimeout: the cut aborts (retryable) instead +// of waiting, and the window is drained. +func TestCutCOWV3_HeldFillTimesOutAndAborts(t *testing.T) { + _, l, f, _, _ := lazyChunk2Fixture(t, 200*time.Millisecond) + _, gRelease := holdGets(t, f) + t.Cleanup(gRelease) + done := make(chan error, 1) + go func() { _, err := l.Cut(context.Background()); done <- err }() + err := waitErr(t, done, "cut with a held fill past ReadMissTimeout") + if !errors.Is(err, errCutCOWAborted) || !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "HEAD fetch") { + t.Fatalf("cut with a timed-out fill: %v, want an aborted cut naming the HEAD fetch deadline", err) + } + if w := l.cowActive.Load(); w != nil { + t.Fatal("copy window not drained after the fill timeout") + } +} + +// Image control for the spill path: a saved chunk with lazily-absent blocks +// spills its local bytes and its missing list; the copier fills the missing +// blocks from HEAD, and the image is exact. +func TestCutCOWV3_LazySaverSpillImageIsExact(t *testing.T) { + s, _ := newChunkTestStore(t) + source := make([]byte, ctNumBlocks*ctBlockSize) + for lba := 0; lba < 8; lba++ { + copy(source[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x30+lba))) + } + f := newFakeChunkRemote() + f.seedHead(t, source, 0, 1) + cfg := ctConfig(2) + cfg.Bitmap = nil + cfg.FreshFromHead = true + cfg.BarrierBound = 0 + cfg.UploadConcurrency = 1 + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := s.Write(1, makeBlock(ctBlockSize, 0x51)); err != nil { + t.Fatal(err) + } + if _, err := s.WriteBatch(4, [][]byte{makeBlock(ctBlockSize, 0x54), makeBlock(ctBlockSize, 0x55)}); err != nil { + t.Fatal(err) + } + live, releaseLive := make(chan struct{}), make(chan struct{}) + var once, relOnce sync.Once + unblock := func() { relOnce.Do(func() { close(releaseLive) }) } + var w *cutCOWWindow + l.testCOWRead = func(idx uint64, _ bool) { + if idx == 0 { + once.Do(func() { + w = l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the next save spills + w.mu.Unlock() + close(live) + }) + <-releaseLive + } + } + cutDone := make(chan error, 1) + t.Cleanup(unblock) + go func() { _, err := l.Cut(context.Background()); cutDone <- err }() + cowWaitSignal(t, live, "the window open, chunk 0 held") + if _, err := s.Write(6, makeBlock(ctBlockSize, 0x96)); err != nil { + t.Fatal(err) + } + w.mu.Lock() + spilled := w.side != nil + w.mu.Unlock() + if !spilled { + t.Fatal("the save did not spill") + } + unblock() + if err := waitErr(t, cutDone, "spilled lazy cut"); err != nil { + t.Fatal(err) + } + want := append([]byte(nil), source...) + for lba, value := range map[int]byte{1: 0x51, 4: 0x54, 5: 0x55} { + copy(want[lba*ctBlockSize:], makeBlock(ctBlockSize, value)) + } + if !bytes.Equal(f.imageOf(t, f.stats().head), want) { + t.Fatal("spilled COW save lost local bytes or HEAD's bytes for its missing blocks") + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go index 68d8e3471a..a6f9473ea1 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go @@ -817,8 +817,9 @@ func TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD(t *testing.T) { go func() { defer close(cutDone); _, cutErr = l.Cut(context.Background()) }() cowWaitSignal(t, live, "first actual copied chunk") // 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 + // rules 1/2): the saver captures only the chunk's LOCAL blocks and + // lists the lazily-absent ones as missing (the copier fills them from + // HEAD later, off the write path), so with every HEAD fetch held the // saving write must finish without one. gets, releaseGet := holdGets(t, f) t.Cleanup(releaseGet) diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index a4281471d9..86dd77f065 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -301,6 +301,9 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) { } l := layer.(*chunkLayerImpl) + writerParked := make(chan struct{}) + var parkOnce sync.Once + l.testCOWWait = func() { parkOnce.Do(func() { close(writerParked) }) } // a writer is waiting on a COW entry inCopy, releaseCopy := make(chan struct{}), make(chan struct{}) var copyOnce, releaseOnce sync.Once unblockCopy := func() { releaseOnce.Do(func() { close(releaseCopy) }) } @@ -334,10 +337,11 @@ func TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut(t *testing.T) { _, err := s.Write(10, late) wrote <- err }() + cowWaitSignal(t, writerParked, "the write parked on chunk 2's copy entry") 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; the write must wait for it + default: // parked on the held copy's entry, as it must be } 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 {