From 0bccd0d68642e16d9455a81fb8cda18bc8d4995b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:39:58 -0800 Subject: [PATCH 01/59] test: require rolling pre-copy before final detach --- .../core/storage/chunk_precopy_detach_test.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_precopy_detach_test.go diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go new file mode 100644 index 0000000000..c3c83b8a46 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -0,0 +1,31 @@ +package storage + +import ( + "bytes" + "context" + "testing" +) + +// Exercise the owner-facing optional seam without changing ChunkLayer's +// existing interface or the remote protocol. +func TestPrecopyDetachConvergesBeforeStoppingIO(t *testing.T) { + s, f, l, _ := precopyLayer(t, 1024, 2) + type precopy interface { + PrecopyDetach(context.Context, func() bool) (ChunkCutResult, error) + } + owner, ok := any(l).(precopy) + if !ok { t.Fatal("chunk layer cannot converge rolling cuts before final detach") } + frozen := false + r, err := owner.PrecopyDetach(ctTimeout(t), func() bool { frozen = true; return true }) + if err != nil { t.Fatal(err) } + if !frozen || r.Head.State != ChunkHeadDetached { t.Fatalf("frozen=%v state=%s", frozen, r.Head.State) } + got := f.imageOf(t, r.Head) + want := make([]byte, len(got)) + for i := uint32(0); i < ctNumBlocks; i++ { + b := make([]byte, ctBlockSize) + if _, err := s.Read(i, b); err != nil { t.Fatal(err) } + copy(want[int(i)*ctBlockSize:], b) + } + if !bytes.Equal(got, want) { t.Fatal("detached HEAD differs from local image") } + assertNoIntentsLeft(t, f) +} From 80e40c6cc0320944c3cd83deaf589ab5612005c9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:40:12 -0800 Subject: [PATCH 02/59] test: read local blocks through store interface --- seaweed-block/core/storage/chunk_precopy_detach_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index c3c83b8a46..c3a675f2c1 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -22,8 +22,8 @@ func TestPrecopyDetachConvergesBeforeStoppingIO(t *testing.T) { got := f.imageOf(t, r.Head) want := make([]byte, len(got)) for i := uint32(0); i < ctNumBlocks; i++ { - b := make([]byte, ctBlockSize) - if _, err := s.Read(i, b); err != nil { t.Fatal(err) } + b, err := s.Read(i) + if err != nil { t.Fatal(err) } copy(want[int(i)*ctBlockSize:], b) } if !bytes.Equal(got, want) { t.Fatal("detached HEAD differs from local image") } From 6bbdbc398310f1b760061e3be2a96d2298f988b4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:41:09 -0800 Subject: [PATCH 03/59] storage: admit final detached cut at tentative capture barrier --- seaweed-block/core/storage/chunk_layer.go | 12 ++ seaweed-block/core/storage/chunk_precopy.go | 155 ++++++++++++++++++ .../core/storage/chunk_precopy_detach_test.go | 54 +++--- seaweed-block/core/storage/chunk_seam.go | 1 + 4 files changed, 200 insertions(+), 22 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_precopy.go diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 309405a16d..dd204b694f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -52,6 +52,10 @@ type chunkHooks struct { const defaultReadMissTimeout = 30 * time.Second type chunkLayerImpl struct { + // capMu serializes pre-copy admission and its recent measurements. + precopyFreeze func(uint64) bool + precopySamples []precopySample + s *WALStore remote chunkRemote cfg chunkLayerConfig @@ -806,6 +810,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.TotalNs = time.Since(start).Nanoseconds() if err == nil { res.Stats = st + l.samplePrecopy(st) } if errors.Is(err, errChunkLayerFenced) { l.stMu.Lock() @@ -949,6 +954,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Candidates, mutation versions and births belong to the same barrier. // Do not sample the owned map after COW writers are admitted again. births := l.captureBirths(candidates, h) + // The authoritative candidate set is fixed with mutation admission closed. + // The owner callback is nonblocking and may stop only an already drained + // frontend; rejected attempts remain ordinary COW cuts. + if freeze := l.precopyFreeze; freeze != nil { + tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks + detach = freeze(tail) + } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { l.s.captureMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go new file mode 100644 index 0000000000..bdd5adbf97 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -0,0 +1,155 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "time" +) + +var ( + ErrPrecopyUnknown = errors.New("storage: pre-copy cost unknown") + ErrPrecopyNotConverged = errors.New("storage: pre-copy not converged") +) + +const ( + precopyAttempts = 5 + precopyDuration = 60 * time.Second + precopyAllowance = 1200 * time.Millisecond + precopyMargin = 100 * time.Millisecond +) + +type precopySample struct { + at time.Time + fixed time.Duration + rate float64 +} + +// PrecopyReport records admission estimates, not a worst-case latency proof. +type PrecopyReport struct { + Attempts int + TailBytes uint64 + Fixed, Estimate, SampleAge time.Duration + BytesPerSecond float64 + Reason string + Frozen bool +} + +// PrecopyDetach runs rolling cuts before the final detached cut. stopIO is +// called at the capture barrier only when the measured tail fits. It must +// atomically refuse new frontend I/O and return true only if all previously +// admitted I/O has drained, without blocking or calling the store. False leaves +// admission unchanged. The owner settles any error after a successful stop. +// capMu owns the callback and samples; no owner lock is taken while waiting +// for capMu. The callback must never wait for an I/O holding a backend read lock. +func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) (ChunkCutResult, error) { + if stopIO == nil { + return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown) + } + l.capMu.Lock() + defer l.capMu.Unlock() + if r, ok := l.storedDetach(); ok { + return r, nil + } + ctx, cancel := context.WithTimeout(ctx, precopyDuration) + defer cancel() + var report PrecopyReport + l.precopyFreeze = func(tail uint64) bool { + report = l.precopyEstimate(tail, report.Attempts) + if report.Reason != "fit" { + return false + } + if !stopIO() { + report.Reason = "admitted_io" + return false + } + report.Frozen = true + return true + } + defer func() { l.precopyFreeze = nil }() + for attempt := 1; attempt <= precopyAttempts; attempt++ { + report.Attempts = attempt + if err := ctx.Err(); err != nil { + return ChunkCutResult{Precopy: report}, err + } + r, err := l.captureLocked(ctx, false) + r.Precopy = report + if report.Frozen { + return r, err + } + if err != nil { + // An unresolved publication or lost authority is never another rolling point. + if errors.Is(err, errChunkCASOutcomeUnknown) || errors.Is(err, errChunkLayerFenced) || errors.Is(err, errChunkLayerClosed) || ctx.Err() != nil { + return r, err + } + } + } + cause := ErrPrecopyNotConverged + if report.Reason == "samples_unknown" { + cause = ErrPrecopyUnknown + } + return ChunkCutResult{Precopy: report}, fmt.Errorf("%w: reason=%s attempts=%d tail=%d rate=%.0f age=%s fixed=%s estimate=%s allowance=%s", cause, report.Reason, report.Attempts, report.TailBytes, report.BytesPerSecond, report.SampleAge, report.Fixed, report.Estimate, precopyAllowance) +} + +func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyReport { + r := PrecopyReport{Attempts: attempts, TailBytes: tail, Reason: "samples_unknown"} + now := time.Now() + var rates []float64 + for _, s := range l.precopySamples { + age := now.Sub(s.at) + if age > precopyDuration { + continue + } + if age > r.SampleAge { + r.SampleAge = age + } + // With at most 32 observations the maximum is a conservative empirical + // p99 envelope. Whole-cut time includes transfer too, so it overcharges, + // rather than omitting, manifest/read-back/local work. The stop is drained. + if s.fixed > r.Fixed { + r.Fixed = s.fixed + } + if s.rate > 0 { + rates = append(rates, s.rate) + } + } + if r.Fixed <= 0 { + return r + } + r.Estimate = r.Fixed + precopyMargin + if tail != 0 { + if len(rates) < 3 { + return r + } + minRate := rates[len(rates)-3] + for _, rate := range rates[len(rates)-2:] { + if rate < minRate { + minRate = rate + } + } + r.BytesPerSecond = minRate / 2 + seconds := float64(tail) / r.BytesPerSecond + if seconds > precopyDuration.Seconds() { + r.Reason = "tail_too_large" + r.Estimate = precopyDuration + return r + } + r.Estimate += time.Duration(seconds * float64(time.Second)) + } + r.Reason = "tail_too_large" + if r.Estimate <= precopyAllowance { + r.Reason = "fit" + } + return r +} + +func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats) { + s := precopySample{at: time.Now(), fixed: time.Duration(st.TotalNs)} + if st.UploadedBytes > 0 && st.UploadNs > 0 { + s.rate = float64(st.UploadedBytes) / time.Duration(st.UploadNs).Seconds() + } + l.precopySamples = append(l.precopySamples, s) + if len(l.precopySamples) > 32 { + l.precopySamples = l.precopySamples[len(l.precopySamples)-32:] + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index c3a675f2c1..c7ef043274 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -1,31 +1,41 @@ package storage import ( - "bytes" - "context" - "testing" + "bytes" + "context" + "testing" ) // Exercise the owner-facing optional seam without changing ChunkLayer's // existing interface or the remote protocol. func TestPrecopyDetachConvergesBeforeStoppingIO(t *testing.T) { - s, f, l, _ := precopyLayer(t, 1024, 2) - type precopy interface { - PrecopyDetach(context.Context, func() bool) (ChunkCutResult, error) - } - owner, ok := any(l).(precopy) - if !ok { t.Fatal("chunk layer cannot converge rolling cuts before final detach") } - frozen := false - r, err := owner.PrecopyDetach(ctTimeout(t), func() bool { frozen = true; return true }) - if err != nil { t.Fatal(err) } - if !frozen || r.Head.State != ChunkHeadDetached { t.Fatalf("frozen=%v state=%s", frozen, r.Head.State) } - got := f.imageOf(t, r.Head) - want := make([]byte, len(got)) - for i := uint32(0); i < ctNumBlocks; i++ { - b, err := s.Read(i) - if err != nil { t.Fatal(err) } - copy(want[int(i)*ctBlockSize:], b) - } - if !bytes.Equal(got, want) { t.Fatal("detached HEAD differs from local image") } - assertNoIntentsLeft(t, f) + s, f, l, _ := precopyLayer(t, 1024, 2) + type precopy interface { + PrecopyDetach(context.Context, func() bool) (ChunkCutResult, error) + } + owner, ok := any(l).(precopy) + if !ok { + t.Fatal("chunk layer cannot converge rolling cuts before final detach") + } + frozen := false + r, err := owner.PrecopyDetach(ctTimeout(t), func() bool { frozen = true; return true }) + if err != nil { + t.Fatal(err) + } + if !frozen || r.Head.State != ChunkHeadDetached { + t.Fatalf("frozen=%v state=%s", frozen, r.Head.State) + } + got := f.imageOf(t, r.Head) + want := make([]byte, len(got)) + for i := uint32(0); i < ctNumBlocks; i++ { + b, err := s.Read(i) + if err != nil { + t.Fatal(err) + } + copy(want[int(i)*ctBlockSize:], b) + } + if !bytes.Equal(got, want) { + t.Fatal("detached HEAD differs from local image") + } + assertNoIntentsLeft(t, f) } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 90a8d87316..f21eb65044 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -482,6 +482,7 @@ type chunkLayerStats struct { // - FullHash says the cut compared every chunk by hash (no usable bitmap, // or the first cut after a BASE install). type chunkCutResult struct { + Precopy PrecopyReport H uint64 Head chunkHead Noop bool From c64244c61dc9295b571a0765c0b3edaf2b9fcb86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:42:11 -0800 Subject: [PATCH 04/59] test: tentative freeze never waits for admitted frontend I/O --- .../durable/provider_chunk_precopy_test.go | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go new file mode 100644 index 0000000000..21dff047d1 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -0,0 +1,67 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestPrecopyFreezeDoesNotWaitForAdmittedIO(t *testing.T) { + p, view := parkedProvider(t, storage.NewMemChunkRemote()) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + gate, ok := b.(interface{ TryStopIO(string) bool }) + if !ok { + t.Fatal("backend has no nonblocking tentative freeze") + } + view.arm() + done := make(chan error, 1) + t.Cleanup(func() { + view.unpark() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not join") + } + }) + go func() { _, err := b.Write(context.Background(), 4096, block(7)); done <- err }() + select { + case <-view.entered: + case <-time.After(5 * time.Second): + t.Fatal("write never admitted") + } + frozen := make(chan bool, 1) + go func() { frozen <- gate.TryStopIO("pre-copy final cut") }() + select { + case stopped := <-frozen: + if stopped { + t.Fatal("stopped before admitted write drained") + } + case <-time.After(time.Second): + t.Fatal("freeze blocked on admitted I/O") + } + if _, err := b.Write(context.Background(), 8192, block(8)); err != nil { + t.Fatal("rejected tentative freeze stopped service:", err) + } + view.unpark() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + done <- nil + case <-time.After(5 * time.Second): + t.Fatal("writer stuck") + } + if !gate.TryStopIO("pre-copy final cut") { + t.Fatal("idle frontend did not freeze") + } + if _, err := b.Write(context.Background(), 8192, block(9)); err == nil { + t.Fatal("write served after successful freeze") + } +} From 6f771c8169eb5b547a08e9f444362a0b0840bc2b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:43:25 -0800 Subject: [PATCH 05/59] durable: wire opt-in pre-copy into settled detach lifecycle --- seaweed-block/cmd/blockvolume/chunk_remote.go | 3 +- seaweed-block/cmd/blockvolume/main.go | 2 + .../core/frontend/durable/provider.go | 3 + .../core/frontend/durable/provider_chunk.go | 75 ++++++++++++++----- .../core/frontend/durable/storage_adapter.go | 16 ++++ .../core/host/volume/chunk_control.go | 4 + 6 files changed, 85 insertions(+), 18 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 4a312fa1bf..a64963c9f6 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -29,6 +29,7 @@ const ( ) type chunkFlags struct { + detachPrecopy bool filer string path string collection string @@ -47,7 +48,7 @@ func validateChunkFlags(f flags) error { if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || - c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint { + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } return nil diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ad5126c180..7185c26da4 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -198,6 +198,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)") fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") + fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") @@ -655,6 +656,7 @@ func run(f flags) int { if cfg.Impl == durable.ImplWALStoreChunk { chunk, chunkErr = newChunkWiring(f.chunk) cfg.ChunkCaptureInterval = f.chunk.captureInterval + cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 134802d749..1c59337323 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -179,6 +179,9 @@ type ProviderConfig struct { // host's 30 s I/O timeout; a freeze past the 5 s target is logged as an // alarm. Cooperative: a syscall that never returns is not bounded. DetachFreezeTimeout time.Duration + // ChunkDetachPrecopy attempts bounded rolling cuts before stopping I/O. + // Nonconvergence leaves service live; no fallback to an unbounded tail. + ChunkDetachPrecopy bool // ChunkDirtyThreshold is the number of candidate chunks above which // a cut pre-copies (stages) chunks before its barrier, in rounds of // this size; copy-before-write copies the rest outside the barrier. diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 3d4c7c1869..bceac9998d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -869,30 +869,71 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // One freeze budget covers the drain, the final cut AND the settlement: // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. - start := time.Now() - cutCtx, cancel := context.WithDeadline(ctx, start.Add(freeze*3/4)) + var start time.Time + cutCtx, cancel := context.WithCancel(ctx) defer cancel() + var timer *time.Timer + beginFreeze := func() { + start = time.Now() + timer = time.AfterFunc(freeze*3/4, cancel) + } defer func() { - if d := time.Since(start); d > detachFreezeTarget { - log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) + if timer != nil { + timer.Stop() + } + if !start.IsZero() { + if d := time.Since(start); d > detachFreezeTarget { + log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) + } } }() - if trace := p.testDetachTrace; trace != nil { - dl, _ := cutCtx.Deadline() - trace("cut", dl) - } - h.chunkDetach = true - if stop := p.testDetachStopIO; stop != nil { - err = stop(cutCtx) - } else { - err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") - } - if err == nil { + var r storage.ChunkCutResult + if p.cfg.ChunkDetachPrecopy { + // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) - var r storage.ChunkCutResult - if r, err = layer.Detach(cutCtx); err == nil { + owner, ok := layer.(interface { + PrecopyDetach(context.Context, func() bool) (storage.ChunkCutResult, error) + }) + if !ok { + return r, 0, fmt.Errorf("%w: layer lacks pre-copy", storage.ErrPrecopyUnknown) + } + r, err = owner.PrecopyDetach(cutCtx, func() bool { + if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { + return false + } + h.chunkDetach = true + beginFreeze() + return true + }) + log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) + if err == nil { return r, h.storage.NextLSN() - 1, nil } + if !r.Precopy.Frozen { + p.mu.Lock() + if !p.closed && h.chunk == layer { + p.startChunkLoop(volumeID, h, layer) + } + p.mu.Unlock() + return r, 0, err + } + } else { + beginFreeze() + if trace := p.testDetachTrace; trace != nil { + trace("cut", start.Add(freeze*3/4)) + } + h.chunkDetach = true + if stop := p.testDetachStopIO; stop != nil { + err = stop(cutCtx) + } else { + err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") + } + if err == nil { + p.stopChunkLoop(h) + if r, err = layer.Detach(cutCtx); err == nil { + return r, h.storage.NextLSN() - 1, nil + } + } } // Every failure, a failed drain included, is settled before anything // resumes: an earlier detach that applied, an unresolved detach CAS or a diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 83545e2a54..3dc932bbe1 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -471,6 +471,22 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { b.mu.Unlock() } +// TryStopIO closes admission only if every admitted I/O has drained already. +// Used under the capture barrier: never wait for ioMu there, since an I/O +// holding its read side may itself be queued on that barrier. Failed attempts +// leave the frontend unchanged. Lock order: try ioMu -> mu; no store calls. +func (b *StorageBackend) TryStopIO(evidence string) bool { + if !b.ioMu.TryLock() { + return false + } + defer b.ioMu.Unlock() + if !b.operational.Load() { + return false + } + b.SetOperational(false, evidence) + return true +} + // StopIO makes the backend refuse every new Read, Write and Sync with // ErrNotReady (evidence), then waits, bounded by ctx, for the I/O admitted // before the stop to finish. After a nil return no I/O admitted before the diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 43db86794e..2e640d3e2e 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -234,6 +234,10 @@ func writeChunkFailure(w http.ResponseWriter, err error) { func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError switch { + case errors.Is(err, storage.ErrPrecopyUnknown): + return http.StatusConflict, "precopy_unknown", true + case errors.Is(err, storage.ErrPrecopyNotConverged): + return http.StatusConflict, "precopy_not_converged", true case errors.Is(err, durable.ErrDetachAborted): // Before any cause (a catalog error included): nothing was // published and serving resumed here. From 27f1f5bedacfd6714126422bb361f52edc77599f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:44:14 -0800 Subject: [PATCH 06/59] durable: preserve freeze deadline cause during settlement --- seaweed-block/core/frontend/durable/provider_chunk.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index bceac9998d..2f50e561ad 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -870,12 +870,12 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. var start time.Time - cutCtx, cancel := context.WithCancel(ctx) - defer cancel() + cutCtx, cancel := context.WithCancelCause(ctx) + defer cancel(context.Canceled) var timer *time.Timer beginFreeze := func() { start = time.Now() - timer = time.AfterFunc(freeze*3/4, cancel) + timer = time.AfterFunc(freeze*3/4, func() { cancel(context.DeadlineExceeded) }) } defer func() { if timer != nil { @@ -935,6 +935,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } } + err = errors.Join(err, context.Cause(cutCtx)) // Every failure, a failed drain included, is settled before anything // resumes: an earlier detach that applied, an unresolved detach CAS or a // fenced layer must never resume serving. The settlement keeps the rest From 89b7f3729092efadd7f9ccbccf662ea190dca735 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:45:27 -0800 Subject: [PATCH 07/59] test: pre-copy exhaustion and aborted rounds preserve old service --- .../core/storage/chunk_precopy_detach_test.go | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index c7ef043274..7cd40b1046 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "context" + "errors" "testing" ) @@ -39,3 +40,62 @@ func TestPrecopyDetachConvergesBeforeStoppingIO(t *testing.T) { } assertNoIntentsLeft(t, f) } + +func TestPrecopyDetachUnsettledRoundsKeepDirtyBytes(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 1) + // Fail before publication, after a candidate image has been collected. + f.failPutIntent = errFakeRemoteDown + stopped := 0 + _, err := l.PrecopyDetach(ctTimeout(t), func() bool { stopped++; return true }) + if !errors.Is(err, ErrPrecopyUnknown) || stopped != 0 { + t.Fatalf("err=%v stopped=%d", err, stopped) + } + if f.stats().head.State == ChunkHeadDetached { + t.Fatal("failed rounds detached") + } + f.failPutIntent = nil + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Stats.CandidateChunks == 0 { + t.Fatal("aborted rounds marked dirty chunks clean") + } + assertEveryHeadIsPrefixImage(t, f, w) + if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x10)) { + t.Fatal("failed rounds lost acknowledged bytes") + } + if _, err := s.Write(2, makeBlock(ctBlockSize, 0x99)); err != nil { + t.Fatal("failed migration stopped old owner:", err) + } +} + +func TestPrecopyDetachBusyOwnerExhaustsWithoutStopping(t *testing.T) { + s, f, l, _ := precopyLayer(t, 1024, 1) + calls := 0 + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { calls++; return false }) + if !errors.Is(err, ErrPrecopyNotConverged) || r.Precopy.Attempts != 5 || r.Precopy.Frozen || calls == 0 { + t.Fatalf("report=%+v calls=%d err=%v", r.Precopy, calls, err) + } + if f.stats().head.State == ChunkHeadDetached { + t.Fatal("busy frontend detached") + } + if _, err := s.Write(2, makeBlock(ctBlockSize, 0x99)); err != nil { + t.Fatal(err) + } +} + +func TestPrecopyDetachCountsBurstAtNextBarrier(t *testing.T) { + s, _, l, _ := precopyLayer(t, 1024, 0) + writes := 0 + l.testBeforeBarrierLockHook = func() { + writes++ + if _, err := s.Write(1, makeBlock(ctBlockSize, byte(writes))); err != nil { + t.Fatal(err) + } + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return false }) + if !errors.Is(err, ErrPrecopyNotConverged) || writes != 5 || r.Precopy.TailBytes != uint64(ctChunkBytes) { + t.Fatalf("writes=%d report=%+v err=%v", writes, r.Precopy, err) + } +} From f28b4f271c0e56a7856cfc33df4e5fcd4fbed5e0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:47:27 -0800 Subject: [PATCH 08/59] storage: measure disjoint pre-copy payload and fixed costs --- seaweed-block/core/storage/chunk_layer.go | 12 ++++++++++++ seaweed-block/core/storage/chunk_precopy.go | 13 +++++++------ seaweed-block/core/storage/chunk_seam.go | 2 ++ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index dd204b694f..c22152366f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -875,7 +875,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Pre-copy large native dirty sets outside the barrier, bounded by the // remaining COW exposure rather than a fixed candidate count. + stageStart := time.Now() staged, intents, err := l.stage(ctx, &st) + if st.UploadedBytes > 0 { + st.precopyPayloadNs += time.Since(stageStart).Nanoseconds() + } if err != nil { l.dropIntents(ctx, intents) return chunkCutResult{}, err @@ -976,6 +980,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CandidateChunks = len(candidates) var copyErr error copyStart := time.Now() + bytesBeforeCopy := st.UploadedBytes if l.usesOwnedMapV3() { var w *cutCOWWindow w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) @@ -1018,6 +1023,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() } st.CopyNs = time.Since(copyStart).Nanoseconds() + if st.UploadedBytes > bytesBeforeCopy { + st.precopyPayloadNs += st.CopyNs + } if l.usesOwnedMapV3() { st.UploadNs = st.CopyNs } @@ -1085,6 +1093,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } intents = append(intents, id) } + payloadStart := time.Now() if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] return l.putCaptured(ctx, u.key, u.c.data) @@ -1093,6 +1102,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.dropIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } + if len(uploads) > 0 { + st.precopyPayloadNs += time.Since(payloadStart).Nanoseconds() + } for _, u := range uploads { next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} newKeys[u.c.idx] = u.key diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index bdd5adbf97..1d639d8c77 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -49,6 +49,7 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) l.capMu.Lock() defer l.capMu.Unlock() if r, ok := l.storedDetach(); ok { + r.Precopy.Frozen = true return r, nil } ctx, cancel := context.WithTimeout(ctx, precopyDuration) @@ -79,7 +80,7 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) } if err != nil { // An unresolved publication or lost authority is never another rolling point. - if errors.Is(err, errChunkCASOutcomeUnknown) || errors.Is(err, errChunkLayerFenced) || errors.Is(err, errChunkLayerClosed) || ctx.Err() != nil { + if errors.Is(err, errChunkCASOutcomeUnknown) || errors.Is(err, errChunkLayerFenced) || errors.Is(err, errChunkLayerClosed) || ctx.Err() != nil || !(errors.Is(err, errCutCOWAborted) || errors.Is(err, errChunkRemoteUnavailable) || errors.Is(err, errChunkHeadPrecondition)) { return r, err } } @@ -104,8 +105,8 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor r.SampleAge = age } // With at most 32 observations the maximum is a conservative empirical - // p99 envelope. Whole-cut time includes transfer too, so it overcharges, - // rather than omitting, manifest/read-back/local work. The stop is drained. + // p99 envelope of the measured non-payload path (including final + // metadata, CAS/read-back and settlement). The stop is already drained. if s.fixed > r.Fixed { r.Fixed = s.fixed } @@ -144,9 +145,9 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor } func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats) { - s := precopySample{at: time.Now(), fixed: time.Duration(st.TotalNs)} - if st.UploadedBytes > 0 && st.UploadNs > 0 { - s.rate = float64(st.UploadedBytes) / time.Duration(st.UploadNs).Seconds() + s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), st.TotalNs-st.precopyPayloadNs))} + if st.UploadedBytes > 0 && st.precopyPayloadNs > 0 { + s.rate = float64(st.UploadedBytes) / time.Duration(st.precopyPayloadNs).Seconds() } l.precopySamples = append(l.precopySamples, s) if len(l.precopySamples) > 32 { diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index f21eb65044..3795ce8294 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -397,6 +397,8 @@ type chunkLayerConfig struct { // chunkCutStats describes one cut. The periodic-cut work fills it; a zero // value means "not measured". type chunkCutStats struct { + precopyPayloadNs int64 // disjoint streaming/copy/upload wall intervals + // Local validated WAL attempts and local copy duration, including savers. COWWALReadAttempts uint64 COWLocalReadNs int64 From c80613db48d8bb95a70f5b1f959eca2bf0c25dce Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:48:07 -0800 Subject: [PATCH 09/59] test: cover provider pre-copy drain and refused final settlement --- .../durable/provider_chunk_precopy_test.go | 99 +++++++++++++++++++ .../core/storage/chunk_precopy_detach_test.go | 28 ++++++ 2 files changed, 127 insertions(+) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 21dff047d1..3685deeb12 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -1,7 +1,10 @@ package durable_test import ( + "bytes" "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "testing" "time" @@ -65,3 +68,99 @@ func TestPrecopyFreezeDoesNotWaitForAdmittedIO(t *testing.T) { t.Fatal("write served after successful freeze") } } + +func precopyProvider(t *testing.T, remote storage.ChunkRemote, view *parkView) *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func TestPrecopyProviderPublishesExactDetachedImage(t *testing.T) { + remote := storage.NewMemChunkRemote() + p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(context.Background(), 4096, block(0x8a)); err != nil { + t.Fatal(err) + } + r, last, err := p.DetachVolume(context.Background(), "v1") + if err != nil || !r.Precopy.Frozen || r.Head.State != storage.ChunkHeadDetached || r.H != last { + t.Fatalf("detach=%+v last=%d err=%v", r, last, err) + } + if !bytes.Equal(headBlock(t, remote, 1), block(0x8a)) { + t.Fatal("detached image lost write") + } + if _, err = b.Write(context.Background(), 4096, block(0x9a)); err == nil { + t.Fatal("old owner serves after final detach") + } + again, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || again.Head.Gen != r.Head.Gen { + t.Fatalf("repeated detach: %+v %v", again, err) + } +} + +func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { + remote := storage.NewMemChunkRemote() + view := &parkView{stubView: v1View()} + p := precopyProvider(t, remote, view) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + view.arm() + done := make(chan error, 1) + t.Cleanup(func() { + view.unpark() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not join") + } + }) + go func() { _, err := b.Write(context.Background(), 4096, block(0x8a)); done <- err }() + select { + case <-view.entered: + case <-time.After(5 * time.Second): + t.Fatal("write not admitted") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + r, _, err := p.DetachVolume(ctx, "v1") + if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen { + t.Fatalf("report=%+v err=%v", r.Precopy, err) + } + if h, _ := remote.GetHead(ctx); h.State == storage.ChunkHeadDetached { + t.Fatal("busy owner detached") + } + if _, err = b.Write(ctx, 8192, block(0x9b)); err != nil { + t.Fatal("nonconverged owner stopped:", err) + } + view.unpark() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + done <- nil + case <-ctx.Done(): + t.Fatal("held write did not finish") + } + r, _, err = p.DetachVolume(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(headBlock(t, remote, 1), block(0x8a)) || !bytes.Equal(headBlock(t, remote, 2), block(0x9b)) { + t.Fatal("retry lost admitted bytes") + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 7cd40b1046..790f0e9e8e 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -99,3 +99,31 @@ func TestPrecopyDetachCountsBurstAtNextBarrier(t *testing.T) { t.Fatalf("writes=%d report=%+v err=%v", writes, r.Precopy, err) } } + +func TestPrecopyDetachRefusedFinalCutKeepsChangedBytes(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + for i := 0; i < 3; i++ { + w.write(t, s, 1, byte(0x40+i)) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + } + w.write(t, s, 1, 0xbb) + f.beforeCAS = func(f *fakeChunkRemote) { f.installLocked(copyHead(f.head)) } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if !r.Precopy.Frozen || !errors.Is(err, ErrChunkHeadPrecondition) { + t.Fatalf("report=%+v err=%v", r.Precopy, err) + } + how, _, err := l.SettleDetach(ctTimeout(t)) + if err != nil || how != DetachNotPublished { + t.Fatalf("settlement=%v err=%v", how, err) + } + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0xbb)) { + t.Fatal("refused final cut marked changed bytes clean") + } + assertEveryHeadIsPrefixImage(t, f, w) +} From 9faf91a36bbed0139a51215f6ad76717978146d7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:50:59 -0800 Subject: [PATCH 10/59] test: qualify pre-copy across WAL wrap and fresh-host restore --- .../core/host/volume/chunk_control.go | 17 +++-- .../core/storage/chunk_precopy_detach_test.go | 71 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 8 ++- 3 files changed, 88 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 2e640d3e2e..5152abe604 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -121,11 +121,12 @@ type ChunkSnapshotRequest struct { // ChunkDetachResponse is the body of a successful POST /chunk/detach (§3.6). type ChunkDetachResponse struct { - VolumeID string `json:"volumeID"` - CutLSN uint64 `json:"cutLSN"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - LastWrittenLSN uint64 `json:"lastWrittenLSN"` + Precopy *storage.PrecopyReport `json:"precopy,omitempty"` + VolumeID string `json:"volumeID"` + CutLSN uint64 `json:"cutLSN"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + LastWrittenLSN uint64 `json:"lastWrittenLSN"` } // snapshotBody is POST /chunk/snapshot's success body, exactly §3.2's fields. @@ -597,5 +598,9 @@ func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetach if err != nil { return ChunkDetachResponse{}, err } - return ChunkDetachResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, LastWrittenLSN: last}, nil + response := ChunkDetachResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, LastWrittenLSN: last} + if r.Precopy.Frozen { + response.Precopy = &r.Precopy + } + return response, nil } diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 790f0e9e8e..6c88b693b0 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "path/filepath" "testing" ) @@ -127,3 +128,73 @@ func TestPrecopyDetachRefusedFinalCutKeepsChangedBytes(t *testing.T) { } assertEveryHeadIsPrefixImage(t, f, w) } + +func TestPrecopyDetachSustainedWrapFlushAndFreshRestore(t *testing.T) { + makeStore := func(name string) *WALStore { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), name), ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.SetRecoveryRetentionLSNs(0) + t.Cleanup(func() { closeBounded(t, s) }) + return s + } + s := makeStore("old") + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + want := make([]byte, ctNumBlocks*ctBlockSize) + written := 0 + for i := 0; written <= 2*int(s.sb.WALSize); i++ { + lba := uint32(i % ctNumBlocks) + data := makeBlock(ctBlockSize, byte(i%250+1)) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + copy(want[int(lba)*ctBlockSize:], data) + written += len(data) + if i%4 == 3 { + mustSyncFlush(t, s) + } + if i%16 == 15 { + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + } + } + mustSyncFlush(t, s) + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, r.Head), want) { + t.Fatal("sustained writes/Flush detached the wrong image") + } + fresh := makeStore("new") + next := ctConfig(2) + next.Holder = "host-b" + next.FreshFromHead = true + next.RestoreChunkBytes = ctChunkBytes + next.PrepareRestore = func(h ChunkHead) error { return fresh.SeedChunkFrontier(h.RemoteLSN) } + h, err := ClaimChunkHead(ctTimeout(t), f, next) + if err != nil { + t.Fatal(err) + } + next.RestoreGuard = &ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch} + mustAttach(t, fresh, f, next) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + got, err := fresh.Read(lba) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want[int(lba)*ctBlockSize:int(lba+1)*ctBlockSize]) { + t.Fatalf("fresh restore LBA %d differs", lba) + } + } + t.Logf("wrote %d bytes > WAL %d with periodic Flush; fresh host exact readback", written, s.sb.WALSize) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ffb480fdd3..4a71b24968 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -192,7 +192,9 @@ stateDiagram-v2 Admit --> Refused: budget refused, closed, fenced, detached, base install, reconciling, or lineage or lease invalid Admit --> Stage: budget admitted, earlier unknown CAS settled Stage --> Quiesce: spill-budget remainder reached or no shrink - Quiesce --> OpenWindow: Sync H and D fixed under barrier + Quiesce --> FinalFreeze: opt-in pre-copy fits and frontend already drained + FinalFreeze --> OpenWindow: admission stays closed through detached settlement + Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier OpenWindow --> Copy: release barrier Copy --> Upload: local entry released, intent durable first Upload --> Copy: next unsent candidate @@ -217,7 +219,9 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | -| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-PRECOPY-001` | Opt-in final-tail admission uses authoritative barrier candidates; a busy frontend or nonconvergence never stops service. Aborted rounds keep dirty bytes, and only settled final detached publication permits handoff. Latency estimates are measured goals, not worst-case proofs. | M5 Quiesce -> ordinary COW round or FinalFreeze | `chunk_precopy.go`; `storage_adapter.go` `TryStopIO`; `provider_chunk.go` `DetachVolume` | `TestPrecopyDetachConvergesBeforeStoppingIO`, `TestPrecopyDetachUnsettledRoundsKeepDirtyBytes`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachCountsBurstAtNextBarrier`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyFreezeDoesNotWaitForAdmittedIO` | Deterministic caller controls; measured latency is not a model proof | ACTIVE | +| `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; barrier candidates and recent measured costs admit the final cut only after a nonblocking frontend drain check, otherwise service stays live | `chunk_precopy.go` `PrecopyDetach`; `StorageBackend.TryStopIO`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | | Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | From 1a97fc9638369ec108bd2efc67d648b589aac9ba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:52:05 -0800 Subject: [PATCH 11/59] storage: report freeze and extra CAS failure-path allowance --- .../core/frontend/durable/provider_chunk.go | 20 +++++++++- seaweed-block/core/storage/chunk_head_belt.go | 17 +++++++++ seaweed-block/core/storage/chunk_precopy.go | 38 ++++++++++++++++--- 3 files changed, 67 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2f50e561ad..2cbb756ee0 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -870,11 +870,14 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. var start time.Time - cutCtx, cancel := context.WithCancelCause(ctx) + accountCtx, countCAS := storage.WithChunkCASAccounting(ctx) + var casAtFreeze uint64 + cutCtx, cancel := context.WithCancelCause(accountCtx) defer cancel(context.Canceled) var timer *time.Timer beginFreeze := func() { start = time.Now() + casAtFreeze = countCAS() timer = time.AfterFunc(freeze*3/4, func() { cancel(context.DeadlineExceeded) }) } defer func() { @@ -907,6 +910,9 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st }) log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) if err == nil { + if !start.IsZero() { + r.Precopy.Finish(time.Since(start), 0, false) + } return r, h.storage.NextLSN() - 1, nil } if !r.Precopy.Frozen { @@ -940,13 +946,23 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // resumes: an earlier detach that applied, an unresolved detach CAS or a // fenced layer must never resume serving. The settlement keeps the rest // of the freeze budget even when the caller's context is gone. - sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze)) + sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), start.Add(freeze)) defer scancel() if trace := p.testDetachTrace; trace != nil { dl, _ := sctx.Deadline() trace("settle", dl) } how, dr, serr := layer.SettleDetach(sctx) + if p.cfg.ChunkDetachPrecopy { + attempts := countCAS() - casAtFreeze + extra := uint64(0) + if attempts > 0 { + extra = attempts - 1 + } + r.Precopy.Finish(time.Since(start), extra, true) + log.Printf("durable: pre-copy settlement volume=%s elapsed=%s extra_cas=%d declared_worst=%s latency_gate_failed=%t outcome=%v err=%v", volumeID, r.Precopy.FreezeElapsed, extra, r.Precopy.DeclaredWorst, r.Precopy.LatencyGateFailed, how, serr) + dr.Precopy = r.Precopy + } switch { case serr != nil: return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr) diff --git a/seaweed-block/core/storage/chunk_head_belt.go b/seaweed-block/core/storage/chunk_head_belt.go index 1648d018e2..46ac62aa60 100644 --- a/seaweed-block/core/storage/chunk_head_belt.go +++ b/seaweed-block/core/storage/chunk_head_belt.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "sync/atomic" "time" ) @@ -19,9 +20,25 @@ func validateHeadCoolingWindow(window time.Duration) error { return nil } +type chunkCASCountKey struct{} + +// WithChunkCASAccounting counts actual CAS attempts through final publication +// and its settlement. Reusing its context preserves the same operation scope. +func WithChunkCASAccounting(ctx context.Context) (context.Context, func() uint64) { + counter, _ := ctx.Value(chunkCASCountKey{}).(*atomic.Uint64) + if counter == nil { + counter = &atomic.Uint64{} + ctx = context.WithValue(ctx, chunkCASCountKey{}, counter) + } + return ctx, counter.Load +} + func casChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead) (uint64, error) { ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout) defer cancel() + if counter, _ := ctx.Value(chunkCASCountKey{}).(*atomic.Uint64); counter != nil { + counter.Add(1) + } return remote.CASHead(ctx, expected, next) } diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 1d639d8c77..027b549969 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -27,12 +27,28 @@ type precopySample struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { - Attempts int - TailBytes uint64 - Fixed, Estimate, SampleAge time.Duration - BytesPerSecond float64 - Reason string - Frozen bool + Attempts int `json:"attempts"` + TailBytes uint64 `json:"tailBytes"` + Fixed time.Duration `json:"fixedNs"` + Estimate time.Duration `json:"estimateNs"` + SampleAge time.Duration `json:"sampleAgeNs"` + BytesPerSecond float64 `json:"bytesPerSecond"` + Reason string `json:"reason"` + Frozen bool `json:"frozen"` + FreezeElapsed time.Duration `json:"freezeElapsedNs"` + ExtraCASAttempts uint64 `json:"extraCASAttempts"` + CASFailureTimeout time.Duration `json:"casFailureTimeoutNs"` + DeclaredWorst time.Duration `json:"declaredWorstNs"` + LatencyGateFailed bool `json:"latencyGateFailed"` +} + +// Finish records the whole freeze, including any owner-driven settlement. +// D_cas is failure allowance only; it never enters successful admission. +func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bool) { + r.FreezeElapsed, r.ExtraCASAttempts = elapsed, extraCAS + r.CASFailureTimeout = chunkHeadOperationTimeout + r.DeclaredWorst = r.Estimate + time.Duration(extraCAS)*chunkHeadOperationTimeout + r.LatencyGateFailed = failed || elapsed > precopyAllowance } // PrecopyDetach runs rolling cuts before the final detached cut. stopIO is @@ -52,9 +68,12 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) r.Precopy.Frozen = true return r, nil } + ctx, countCAS := WithChunkCASAccounting(ctx) ctx, cancel := context.WithTimeout(ctx, precopyDuration) defer cancel() var report PrecopyReport + var frozenAt time.Time + var casAtFreeze uint64 l.precopyFreeze = func(tail uint64) bool { report = l.precopyEstimate(tail, report.Attempts) if report.Reason != "fit" { @@ -65,6 +84,7 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) return false } report.Frozen = true + frozenAt, casAtFreeze = time.Now(), countCAS() return true } defer func() { l.precopyFreeze = nil }() @@ -76,6 +96,12 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) r, err := l.captureLocked(ctx, false) r.Precopy = report if report.Frozen { + attempts := countCAS() - casAtFreeze + extra := uint64(0) + if attempts > 0 { + extra = attempts - 1 + } + r.Precopy.Finish(time.Since(frozenAt), extra, err != nil) return r, err } if err != nil { From d7a25b63a853fd090af198973c12878a66813e44 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:57:35 -0800 Subject: [PATCH 12/59] test: canceled tentative barrier must not stop service --- .../core/storage/chunk_precopy_detach_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 6c88b693b0..2ee44698b5 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -198,3 +198,18 @@ func TestPrecopyDetachSustainedWrapFlushAndFreshRestore(t *testing.T) { } t.Logf("wrote %d bytes > WAL %d with periodic Flush; fresh host exact readback", written, s.sb.WALSize) } + +func TestPrecopyDetachCanceledBarrierNeverStopsFrontend(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + l.testAfterBarrierSyncHook = func(uint64) { cancel() } + stopped := false + _, err := l.PrecopyDetach(ctx, func() bool { stopped = true; return true }) + if stopped { + t.Fatal("cancellation at the tentative barrier still stopped the frontend") + } + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled attempt: %v", err) + } +} From a8c0142340dfba1e466bc23d929f9ff12985056c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:00:43 -0800 Subject: [PATCH 13/59] test: freeze timing includes tentative barrier pause --- .../core/storage/chunk_precopy_detach_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 2ee44698b5..30fcb89560 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -6,6 +6,7 @@ import ( "errors" "path/filepath" "testing" + "time" ) // Exercise the owner-facing optional seam without changing ChunkLayer's @@ -213,3 +214,15 @@ func TestPrecopyDetachCanceledBarrierNeverStopsFrontend(t *testing.T) { t.Fatalf("canceled attempt: %v", err) } } + +func TestPrecopyDetachFreezeIncludesBarrierPause(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + l.testBeforeBarrierLockHook = func() { time.Sleep(120 * time.Millisecond) } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if err != nil { + t.Fatal(err) + } + if r.Precopy.FreezeElapsed < 120*time.Millisecond { + t.Fatalf("freeze %s omitted tentative barrier pause", r.Precopy.FreezeElapsed) + } +} From 0c9ca13a29c18ac4df510000fca0a7e75cee5696 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:02:09 -0800 Subject: [PATCH 14/59] storage: retain cancellation and complete barrier timing in pre-copy --- .../core/frontend/durable/provider_chunk.go | 4 +- .../core/host/volume/chunk_control.go | 2 + seaweed-block/core/storage/chunk_layer.go | 16 ++++-- seaweed-block/core/storage/chunk_precopy.go | 57 ++++++++++++------- seaweed-block/core/storage/chunk_seam.go | 2 +- 5 files changed, 53 insertions(+), 28 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2cbb756ee0..6a1d02ff74 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -911,7 +911,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) if err == nil { if !start.IsZero() { - r.Precopy.Finish(time.Since(start), 0, false) + r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, 0, false) } return r, h.storage.NextLSN() - 1, nil } @@ -959,7 +959,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if attempts > 0 { extra = attempts - 1 } - r.Precopy.Finish(time.Since(start), extra, true) + r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, extra, true) log.Printf("durable: pre-copy settlement volume=%s elapsed=%s extra_cas=%d declared_worst=%s latency_gate_failed=%t outcome=%v err=%v", volumeID, r.Precopy.FreezeElapsed, extra, r.Precopy.DeclaredWorst, r.Precopy.LatencyGateFailed, how, serr) dr.Precopy = r.Precopy } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 5152abe604..c1743562f8 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -55,6 +55,7 @@ type ChunkCutResponse struct { // mirrors storage.ChunkCutStats field for field (a test keeps the two in // step); every duration is in nanoseconds. type ChunkCutStatsBody struct { + PayloadNs int64 `json:"payloadNs"` COWWALReadAttempts uint64 `json:"cowWALReadAttempts"` COWLocalReadNs int64 `json:"cowLocalReadNs"` COWSavedChunks int `json:"cowSavedChunks"` @@ -82,6 +83,7 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ + PayloadNs: s.PayloadNs, COWWALReadAttempts: s.COWWALReadAttempts, COWLocalReadNs: s.COWLocalReadNs, BarrierPauseNs: s.BarrierPauseNs, diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index c22152366f..325f375e3f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -53,8 +53,9 @@ const defaultReadMissTimeout = 30 * time.Second type chunkLayerImpl struct { // capMu serializes pre-copy admission and its recent measurements. - precopyFreeze func(uint64) bool + precopyFreeze func(uint64, time.Time) bool precopySamples []precopySample + precopyPause func(time.Duration) s *WALStore remote chunkRemote @@ -824,6 +825,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.stMu.Unlock() l.dropIntents(ctx, ids) } + if observe := l.precopyPause; observe != nil { + observe(time.Duration(st.BarrierPauseNs)) + } l.recordCut(res, st, err) }() if err := l.admit(); err != nil { @@ -878,7 +882,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch stageStart := time.Now() staged, intents, err := l.stage(ctx, &st) if st.UploadedBytes > 0 { - st.precopyPayloadNs += time.Since(stageStart).Nanoseconds() + st.PayloadNs += time.Since(stageStart).Nanoseconds() } if err != nil { l.dropIntents(ctx, intents) @@ -961,9 +965,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // The authoritative candidate set is fixed with mutation admission closed. // The owner callback is nonblocking and may stop only an already drained // frontend; rejected attempts remain ordinary COW cuts. - if freeze := l.precopyFreeze; freeze != nil { + if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil { tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks - detach = freeze(tail) + detach = freeze(tail, pauseStart) } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { @@ -1024,7 +1028,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } st.CopyNs = time.Since(copyStart).Nanoseconds() if st.UploadedBytes > bytesBeforeCopy { - st.precopyPayloadNs += st.CopyNs + st.PayloadNs += st.CopyNs } if l.usesOwnedMapV3() { st.UploadNs = st.CopyNs @@ -1103,7 +1107,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } if len(uploads) > 0 { - st.precopyPayloadNs += time.Since(payloadStart).Nanoseconds() + st.PayloadNs += time.Since(payloadStart).Nanoseconds() } for _, u := range uploads { next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 027b549969..65a7b9be4f 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -27,19 +27,22 @@ type precopySample struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { - Attempts int `json:"attempts"` - TailBytes uint64 `json:"tailBytes"` - Fixed time.Duration `json:"fixedNs"` - Estimate time.Duration `json:"estimateNs"` - SampleAge time.Duration `json:"sampleAgeNs"` - BytesPerSecond float64 `json:"bytesPerSecond"` - Reason string `json:"reason"` - Frozen bool `json:"frozen"` - FreezeElapsed time.Duration `json:"freezeElapsedNs"` - ExtraCASAttempts uint64 `json:"extraCASAttempts"` - CASFailureTimeout time.Duration `json:"casFailureTimeoutNs"` - DeclaredWorst time.Duration `json:"declaredWorstNs"` - LatencyGateFailed bool `json:"latencyGateFailed"` + Attempts int `json:"attempts"` + TailBytes uint64 `json:"tailBytes"` + Fixed time.Duration `json:"fixedNs"` + Estimate time.Duration `json:"estimateNs"` + SampleAge time.Duration `json:"sampleAgeNs"` + BytesPerSecond float64 `json:"bytesPerSecond"` + Reason string `json:"reason"` + Frozen bool `json:"frozen"` + FreezeElapsed time.Duration `json:"freezeElapsedNs"` + ExtraCASAttempts uint64 `json:"extraCASAttempts"` + CASFailureTimeout time.Duration `json:"casFailureTimeoutNs"` + DeclaredWorst time.Duration `json:"declaredWorstNs"` + LatencyGateFailed bool `json:"latencyGateFailed"` + BarrierBeforeFreeze time.Duration `json:"barrierBeforeFreezeNs"` + TentativePauseTotal time.Duration `json:"tentativePauseTotalNs"` + LongestTentativePause time.Duration `json:"longestTentativePauseNs"` } // Finish records the whole freeze, including any owner-driven settlement. @@ -74,8 +77,22 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) var report PrecopyReport var frozenAt time.Time var casAtFreeze uint64 - l.precopyFreeze = func(tail uint64) bool { + var pauseTotal, longestPause time.Duration + l.precopyPause = func(pause time.Duration) { + pauseTotal += pause + if pause > longestPause { + longestPause = pause + } + } + l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool { report = l.precopyEstimate(tail, report.Attempts) + spent := time.Since(barrierStart) + if spent > report.Fixed { + report.Estimate += spent - report.Fixed + } + if report.Reason == "fit" && report.Estimate > precopyAllowance { + report.Reason = "barrier_over_budget" + } if report.Reason != "fit" { return false } @@ -84,16 +101,18 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) return false } report.Frozen = true - frozenAt, casAtFreeze = time.Now(), countCAS() + report.BarrierBeforeFreeze = time.Since(barrierStart) + frozenAt, casAtFreeze = barrierStart, countCAS() return true } - defer func() { l.precopyFreeze = nil }() + defer func() { l.precopyFreeze = nil; l.precopyPause = nil }() for attempt := 1; attempt <= precopyAttempts; attempt++ { report.Attempts = attempt if err := ctx.Err(); err != nil { return ChunkCutResult{Precopy: report}, err } r, err := l.captureLocked(ctx, false) + report.TentativePauseTotal, report.LongestTentativePause = pauseTotal, longestPause r.Precopy = report if report.Frozen { attempts := countCAS() - casAtFreeze @@ -171,9 +190,9 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor } func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats) { - s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), st.TotalNs-st.precopyPayloadNs))} - if st.UploadedBytes > 0 && st.precopyPayloadNs > 0 { - s.rate = float64(st.UploadedBytes) / time.Duration(st.precopyPayloadNs).Seconds() + s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), st.TotalNs-st.PayloadNs))} + if st.UploadedBytes > 0 && st.PayloadNs > 0 { + s.rate = float64(st.UploadedBytes) / time.Duration(st.PayloadNs).Seconds() } l.precopySamples = append(l.precopySamples, s) if len(l.precopySamples) > 32 { diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 3795ce8294..9aa3940b08 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -397,7 +397,7 @@ type chunkLayerConfig struct { // chunkCutStats describes one cut. The periodic-cut work fills it; a zero // value means "not measured". type chunkCutStats struct { - precopyPayloadNs int64 // disjoint streaming/copy/upload wall intervals + PayloadNs int64 // disjoint streaming/copy/upload wall intervals // Local validated WAL attempts and local copy duration, including savers. COWWALReadAttempts uint64 From a587453ca8b75e025cb63f7f2561edc043364bc5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:03:26 -0800 Subject: [PATCH 15/59] test: queued pre-copy respects the caller deadline --- .../core/storage/chunk_precopy_detach_test.go | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 30fcb89560..243bad8c9e 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -226,3 +226,41 @@ func TestPrecopyDetachFreezeIncludesBarrierPause(t *testing.T) { t.Fatalf("freeze %s omitted tentative barrier pause", r.Precopy.FreezeElapsed) } } + +func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *testing.T) { + _, f, l, _ := precopyLayer(t, 1024, 1) + entered, release := holdPuts(t, f) + cutDone, preDone := make(chan struct{}), make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + var precopyErr error + t.Cleanup(func() { + release() + cancel() + for _, done := range []chan struct{}{cutDone, preDone} { + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("cut owner did not join") + } + } + }) + go func() { defer close(cutDone); _, _ = l.Cut(context.Background()) }() + select { + case <-entered: + case <-time.After(5 * time.Second): + close(preDone) + t.Fatal("other cut did not reach held upload") + } + go func() { + defer close(preDone) + _, precopyErr = l.PrecopyDetach(ctx, func() bool { t.Error("queued canceled caller stopped I/O"); return false }) + }() + select { + case <-preDone: + if !errors.Is(precopyErr, context.DeadlineExceeded) { + t.Fatalf("queued error: %v", precopyErr) + } + case <-time.After(time.Second): + t.Fatal("queued pre-copy ignored its caller deadline") + } +} From 6cefc26f419a9f2f604d8668a46d888780d47d11 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:06:19 -0800 Subject: [PATCH 16/59] storage: bound queued pre-copy by its caller context --- .../core/frontend/durable/provider_chunk.go | 4 +-- seaweed-block/core/storage/chunk_precopy.go | 34 +++++++++++++++++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 6a1d02ff74..9efc49e3fa 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -892,14 +892,14 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st }() var r storage.ChunkCutResult if p.cfg.ChunkDetachPrecopy { - // Cancel/join the periodic owner before any final freeze, while serving. - p.stopChunkLoop(h) owner, ok := layer.(interface { PrecopyDetach(context.Context, func() bool) (storage.ChunkCutResult, error) }) if !ok { return r, 0, fmt.Errorf("%w: layer lacks pre-copy", storage.ErrPrecopyUnknown) } + // Cancel/join the periodic owner before any final freeze, while serving. + p.stopChunkLoop(h) r, err = owner.PrecopyDetach(cutCtx, func() bool { if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 65a7b9be4f..3bcc5b3a15 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -65,15 +65,20 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) if stopIO == nil { return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown) } - l.capMu.Lock() + ctx, cancel := context.WithTimeout(ctx, precopyDuration) + defer cancel() + if err := l.lockPrecopy(ctx); err != nil { + return ChunkCutResult{}, err + } defer l.capMu.Unlock() + if err := ctx.Err(); err != nil { + return ChunkCutResult{}, err + } if r, ok := l.storedDetach(); ok { r.Precopy.Frozen = true return r, nil } ctx, countCAS := WithChunkCASAccounting(ctx) - ctx, cancel := context.WithTimeout(ctx, precopyDuration) - defer cancel() var report PrecopyReport var frozenAt time.Time var casAtFreeze uint64 @@ -199,3 +204,26 @@ func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats) { l.precopySamples = l.precopySamples[len(l.precopySamples)-32:] } } + +// A queued caller's cooperative budget starts before pipeline ownership. +// No background lock waiter can outlive cancellation or capture a later cut. +func (l *chunkLayerImpl) lockPrecopy(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + if l.capMu.TryLock() { + return nil + } + tick := time.NewTicker(10 * time.Millisecond) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-tick.C: + if l.capMu.TryLock() { + return nil + } + } + } +} From d721b69bdc2b99734e585bdfb8864ab8885e0cca Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:35:17 -0800 Subject: [PATCH 17/59] test: final barrier never waits for backend state lock --- .../frontend/durable/precopy_gate_test.go | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/precopy_gate_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_gate_test.go b/seaweed-block/core/frontend/durable/precopy_gate_test.go new file mode 100644 index 0000000000..6ef1208ed4 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_gate_test.go @@ -0,0 +1,42 @@ +package durable + +import ( + "testing" + "time" +) + +func TestPrecopyFreezeDoesNotWaitForBackendState(t *testing.T) { + b := &StorageBackend{} + b.operational.Store(true) + b.mu.Lock() + released := false + done := make(chan struct{}) + var stopped bool + t.Cleanup(func() { + if !released { + b.mu.Unlock() + } + select { + case <-done: + case <-time.After(time.Second): + t.Error("freeze owner did not join") + } + }) + go func() { defer close(done); stopped = b.TryStopIO("pre-copy final cut") }() + select { + case <-done: + if stopped { + t.Fatal("freeze ignored held backend state") + } + case <-time.After(200 * time.Millisecond): + t.Fatal("freeze waited for backend state under capture barrier") + } + b.mu.Unlock() + released = true + if !b.operational.Load() { + t.Fatal("failed freeze changed admission") + } + if !b.TryStopIO("pre-copy final cut") || b.operational.Load() { + t.Fatal("idle backend failed to freeze") + } +} From 6c3687f50a9a22fb38fbdb9ef883090ab6f0db7a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:39:34 -0800 Subject: [PATCH 18/59] durable: keep final freeze nonblocking across both backend locks --- .../core/frontend/durable/storage_adapter.go | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3dc932bbe1..2d078b8670 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -464,26 +464,38 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { } } b.mu.Lock() + b.setOperationalLocked(ok, evidence) + b.mu.Unlock() +} + +// The caller owns mu; publication never calls the store or waits for I/O. +func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { b.opEvidence.Store(evidence) b.operational.Store(ok) b.waitAttachReady = false b.notifyReadReadyLocked() - b.mu.Unlock() } // TryStopIO closes admission only if every admitted I/O has drained already. // Used under the capture barrier: never wait for ioMu there, since an I/O // holding its read side may itself be queued on that barrier. Failed attempts -// leave the frontend unchanged. Lock order: try ioMu -> mu; no store calls. +// leave the frontend unchanged. Lock order: try ioMu -> try mu; neither lock waits, and no store calls. func (b *StorageBackend) TryStopIO(evidence string) bool { if !b.ioMu.TryLock() { return false } defer b.ioMu.Unlock() - if !b.operational.Load() { + if !b.mu.TryLock() { return false } - b.SetOperational(false, evidence) + defer b.mu.Unlock() + if b.closed || !b.operational.Load() { + return false + } + if evidence == "" { + evidence = "not operational" + } + b.setOperationalLocked(false, evidence) return true } From 88cfcdd9394d3b846fa76d8d6d023475352a074e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:44:51 -0800 Subject: [PATCH 19/59] test: pre-copy cost scope and applied-detach retry --- .../core/storage/chunk_precopy_detach_test.go | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 243bad8c9e..6fb7a15325 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -264,3 +264,40 @@ func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *test t.Fatal("queued pre-copy ignored its caller deadline") } } + +func TestPrecopyDetachExcludesServingPreparationFromFreezeCost(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + l.testAfterAdmitHook = func() { l.testAfterAdmitHook = nil; time.Sleep(1300 * time.Millisecond) } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if err != nil { + t.Fatalf("preparation while serving was charged as frozen time: %v", err) + } + if !r.Precopy.Frozen { + t.Fatal("empty final tail never froze") + } +} + +func TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut(t *testing.T) { + _, f, l, _ := precopyLayer(t, 1024, 1) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if !r.Precopy.Frozen || !errors.Is(err, ErrChunkCASOutcomeUnknown) { + t.Fatalf("first report=%+v err=%v", r.Precopy, err) + } + f.failGet = nil + before := f.stats() + r, err = l.PrecopyDetach(ctTimeout(t), func() bool { t.Fatal("retry stopped I/O again instead of resolving the applied detach"); return false }) + if err != nil || r.Head.State != ChunkHeadDetached || r.Head.Gen != before.head.Gen { + t.Fatalf("resolved result=%+v err=%v", r, err) + } + if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x10)) { + t.Fatal("resolved detach lost bytes") + } +} From 973e27e988ea1f73e03d315d217b5eb034dc3be4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:47:30 -0800 Subject: [PATCH 20/59] storage: scope freeze costs and resolve applied detach retries --- seaweed-block/core/storage/chunk_layer.go | 10 ++++++++-- seaweed-block/core/storage/chunk_precopy.go | 17 +++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 325f375e3f..b5296395ee 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -807,11 +807,16 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch defer done() start := time.Now() var st chunkCutStats + var pauseStart time.Time + var payloadBeforeBarrier int64 defer func() { st.TotalNs = time.Since(start).Nanoseconds() if err == nil { res.Stats = st - l.samplePrecopy(st) + if !pauseStart.IsZero() { + fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier + l.samplePrecopy(st, fixed) + } } if errors.Is(err, errChunkLayerFenced) { l.stMu.Lock() @@ -898,7 +903,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // writer blocks new readers of captureMu, so a write arriving while the cut // waits for writers already holding it (e.g. parked in WAL admission) is // paused too. LockWaitNs reports that wait on its own. - pauseStart := time.Now() + payloadBeforeBarrier = st.PayloadNs + pauseStart = time.Now() if hook := l.testBeforeBarrierLockHook; hook != nil { hook() } diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 3bcc5b3a15..8d3c12cab5 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -119,6 +119,14 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) r, err := l.captureLocked(ctx, false) report.TentativePauseTotal, report.LongestTentativePause = pauseTotal, longestPause r.Precopy = report + if errors.Is(err, errChunkLayerDetached) { + if previous, ok := l.storedDetach(); ok { + previous.Precopy = report + previous.Precopy.Frozen = true + previous.Precopy.Reason = "previous_detach_applied" + return previous, nil + } + } if report.Frozen { attempts := countCAS() - casAtFreeze extra := uint64(0) @@ -155,8 +163,9 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor r.SampleAge = age } // With at most 32 observations the maximum is a conservative empirical - // p99 envelope of the measured non-payload path (including final - // metadata, CAS/read-back and settlement). The stop is already drained. + // p99 envelope of barrier-to-settlement non-payload work. Serving + // preparation and host-budget waits are outside the freeze. The stop + // is already drained; metadata and CAS/read-back remain included. if s.fixed > r.Fixed { r.Fixed = s.fixed } @@ -194,8 +203,8 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor return r } -func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats) { - s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), st.TotalNs-st.PayloadNs))} +func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { + s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), fixedNs))} if st.UploadedBytes > 0 && st.PayloadNs > 0 { s.rate = float64(st.UploadedBytes) / time.Duration(st.PayloadNs).Seconds() } From 40d217d91ae20aa56df4d3ba88916d11105dea24 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:51:32 -0800 Subject: [PATCH 21/59] test: empty tails still need an observed CAS cost --- .../core/storage/chunk_precopy_detach_test.go | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 6fb7a15325..b707e04699 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -266,7 +266,10 @@ func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *test } func TestPrecopyDetachExcludesServingPreparationFromFreezeCost(t *testing.T) { - _, _, l, _ := precopyLayer(t, 1024, 0) + store, _, l, _ := precopyLayer(t, 1024, 0) + if _, err := store.Write(1, makeBlock(ctBlockSize, 0x6e)); err != nil { + t.Fatal(err) + } l.testAfterAdmitHook = func() { l.testAfterAdmitHook = nil; time.Sleep(1300 * time.Millisecond) } if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) @@ -301,3 +304,31 @@ func TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut(t *testing.T) { t.Fatal("resolved detach lost bytes") } } + +func TestPrecopyDetachColdNoopRequiresMeasuredCASCost(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + f.seedHead(t, make([]byte, ctNumBlocks*ctBlockSize), 0, 1) + cfg := ctConfig(1) + cfg.Holder = "seed" + cfg.FreshFromHead = true + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + stopped := 0 + _, err := l.PrecopyDetach(ctTimeout(t), func() bool { stopped++; return true }) + if !errors.Is(err, ErrPrecopyUnknown) || stopped != 0 { + t.Fatalf("no-op read treated as measured CAS cost: stopped=%d err=%v", stopped, err) + } + if f.stats().head.Gen != 1 { + t.Fatal("unknown cost published a final detached HEAD") + } + if _, err := s.Write(1, makeBlock(ctBlockSize, 0x61)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { stopped++; return true }) + if err != nil || !r.Precopy.Frozen || stopped != 1 { + t.Fatalf("measured CAS did not enable empty-tail freeze: report=%+v stopped=%d err=%v", r.Precopy, stopped, err) + } +} From 7d0195d8a7a406a09b25e094e0d1590c4563ee1e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:57:19 -0800 Subject: [PATCH 22/59] storage: require real CAS samples for freeze admission --- seaweed-block/core/storage/chunk_precopy.go | 4 ++++ seaweed-block/core/storage/chunk_precopy_detach_test.go | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 8d3c12cab5..985995073c 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -204,6 +204,10 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor } func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { + // A no-op root read is not a measurement of final CAS + confirmation. + if st.CASNs <= 0 { + return + } s := precopySample{at: time.Now(), fixed: time.Duration(max(int64(1), fixedNs))} if st.UploadedBytes > 0 && st.PayloadNs > 0 { s.rate = float64(st.UploadedBytes) / time.Duration(st.PayloadNs).Seconds() diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index b707e04699..09278ddf56 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -231,7 +231,8 @@ func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *test _, f, l, _ := precopyLayer(t, 1024, 1) entered, release := holdPuts(t, f) cutDone, preDone := make(chan struct{}), make(chan struct{}) - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + var ctx context.Context + cancel := func() {} var precopyErr error t.Cleanup(func() { release() @@ -251,6 +252,7 @@ func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *test close(preDone) t.Fatal("other cut did not reach held upload") } + ctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond) go func() { defer close(preDone) _, precopyErr = l.PrecopyDetach(ctx, func() bool { t.Error("queued canceled caller stopped I/O"); return false }) From 0b5a0181605726b8b564672f40acb0bedc9909af Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:50:57 -0800 Subject: [PATCH 23/59] test(durable): require retryable queued I/O during pre-copy freeze --- .../frontend/durable/precopy_wait_test.go | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/precopy_wait_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_wait_test.go b/seaweed-block/core/frontend/durable/precopy_wait_test.go new file mode 100644 index 0000000000..1704615260 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_wait_test.go @@ -0,0 +1,104 @@ +package durable_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestPrecopyFreezeQueuesIOUntilResume(t *testing.T) { + for _, op := range []string{"read", "write", "sync"} { + t.Run(op, func(t *testing.T) { + p := precopyProvider(t, storage.NewMemChunkRemote(), &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + gate := b.(interface { + TryStopIO(string) bool + SetOperational(bool, string) + }) + if !gate.TryStopIO("pre-copy final cut") { + t.Fatal("idle frontend did not freeze") + } + done, started := make(chan struct{}), make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + var result error + t.Cleanup(func() { + cancel() + gate.SetOperational(true, "test cleanup") + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("I/O did not join") + } + }) + go func() { + defer close(done) + close(started) + switch op { + case "read": + var n int + n, result = b.Read(ctx, 4096, make([]byte, 4096)) + if result == nil && n != 4096 { + result = fmt.Errorf("read %d bytes", n) + } + case "write": + _, result = b.Write(ctx, 8192, block(0x8a)) + case "sync": + result = b.Sync(ctx) + } + }() + <-started + select { + case <-done: + t.Fatalf("guest I/O escaped tentative freeze: %v", result) + case <-time.After(80 * time.Millisecond): + } + gate.SetOperational(true, "final cut safely aborted") + select { + case <-done: + if result != nil { + t.Fatal(result) + } + case <-ctx.Done(): + t.Fatal("resumed I/O did not finish") + } + if op == "write" { + buf := make([]byte, 4096) + if n, err := b.Read(context.Background(), 8192, buf); err != nil || n != 4096 || buf[0] != 0x8a { + t.Fatalf("resumed write not present: n=%d err=%v", n, err) + } + } + }) + } +} + +func TestPrecopyFreezeCallerDeadlineIsRetryable(t *testing.T) { + p := precopyProvider(t, storage.NewMemChunkRemote(), &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + gate := b.(interface { + TryStopIO(string) bool + SetOperational(bool, string) + }) + if !gate.TryStopIO("pre-copy final cut") { + t.Fatal("idle frontend did not freeze") + } + t.Cleanup(func() { gate.SetOperational(true, "test cleanup") }) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + _, err = b.Write(ctx, 4096, block(7)) + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline lost retryable admission status: %v", err) + } +} From 106aa567e26ddc6da61367831d06bd4067e9fa41 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:52:22 -0800 Subject: [PATCH 24/59] fix(durable): queue I/O during a pre-copy final freeze --- .../core/frontend/durable/storage_adapter.go | 89 ++++++++++++------- 1 file changed, 57 insertions(+), 32 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 2d078b8670..3165fbce44 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -5,7 +5,7 @@ // or any future impl) and exposes the `frontend.Backend` surface // iSCSI and NVMe consume. Responsibilities: // -// 1. byte ↔ LBA translation (G-int.1). +// 1. byte ↔ LBA translation (G-int.1). // Frontend layer speaks byte offsets + length; storage layer // speaks LBA + full-block data. The adapter bridges: partial- // block writes trigger read-modify-write; full-block writes @@ -14,13 +14,13 @@ // // 2. Per-I/O fence check (G-int.2). // Re-reads `ProjectionView` on every operation; ANY drift -// (identity field mismatch or Healthy=false) → ErrStalePrimary. +// (identity field mismatch or Healthy=false) → ErrStalePrimary. // Preserves INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY} under // a durable backend. // // 3. Operational gate (G-int.3, Addendum A). // Before SetOperational(true, _) is called, every I/O returns -// ErrNotReady with evidence. Starts non-operational — host/ +// ErrNotReady with evidence. Starts non-operational — host/ // provider flips to true after recovery succeeds. This is // local readiness only; NEVER advances epoch / mints authority. // @@ -29,7 +29,7 @@ // verbatim. iSCSI SYNCHRONIZE CACHE + NVMe Flush wiring lands // in T3b. // -// StorageBackend does NOT own the LogicalStorage lifecycle — the +// StorageBackend does NOT own the LogicalStorage lifecycle — the // Provider (T3b) opens and closes storage. Backend.Close marks the // handle closed but does not tear down storage. // @@ -80,7 +80,7 @@ var ErrReplicationAckUnavailable = errors.New("durable: replication ack unavaila // core/frontend/durable from importing replication directly and lets // tests inject mocks. // -// Observe contract (matches V2 BlockVol.shipMu → ShipAll invariant): +// Observe contract (matches V2 BlockVol.shipMu → ShipAll invariant): // - StorageBackend calls Observe AFTER LogicalStorage.Write // returns successfully, with the LBA + block data + LSN the // storage layer just assigned. @@ -96,9 +96,9 @@ var ErrReplicationAckUnavailable = errors.New("durable: replication ack unavaila // ReplicationVolume resequences callbacks by storage-assigned LSN, // then dispatches through one ordered queue per peer lineage. // -// Sync contract (T4b-5 — matches V2 BlockVol.MakeDistributedSync): +// Sync contract (T4b-5 — matches V2 BlockVol.MakeDistributedSync): // - When an observer is installed, StorageBackend.Sync DELEGATES -// the full sync job to observer.Sync — the observer owns both +// the full sync job to observer.Sync — the observer owns both // the local LogicalStorage.Sync call and the peer barriers, with // barriers ordered behind prior writes in each peer queue. // - targetLSN is the primary's current walHead at the moment the @@ -164,10 +164,11 @@ type StorageBackend struct { // (e.g., "awaiting recovery", "local epoch ahead of assignment"). // Only a successfully recovered chunk volume awaiting attachment may wait. // waitAttachReady and readyChanged are protected by mu. - waitAttachReady bool - readyChanged chan struct{} - operational atomic.Bool - opEvidence atomic.Value // string + waitAttachReady bool + waitPrecopyReady bool // temporary pre-copy freeze; queued I/O has not reached storage + readyChanged chan struct{} + operational atomic.Bool + opEvidence atomic.Value // string // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -238,7 +239,7 @@ func (b *StorageBackend) Identity() frontend.Identity { // VolumeID/ReplicaID from CLI config (non-empty even pre-assignment) // but Epoch=0/EV=0 (engine state is zero-value until OnAssignment // runs). So a freshly-constructed backend has b.id = {v1, r1, 0, 0} -// — partially-zero, not all-zero. The latch condition keys on +// — partially-zero, not all-zero. The latch condition keys on // Epoch=0 (the meaningful "no authority line yet" indicator); // VolumeID/ReplicaID match is asserted but unchanged. // @@ -247,7 +248,7 @@ func (b *StorageBackend) Identity() frontend.Identity { // master-minted advances for the SAME volume/replica are accepted // (epoch increase, or endpoint-version increase within the same // epoch). Cross-volume, cross-replica, or backward lineage changes -// are rejected so old primaries still fail closed via lineageCheck → +// are rejected so old primaries still fail closed via lineageCheck → // ErrStalePrimary. // // Returns true if the identity changed. Returns false on no-op and @@ -257,7 +258,7 @@ func (b *StorageBackend) SetIdentity(id frontend.Identity) bool { defer b.mu.Unlock() // VolumeID/ReplicaID came from CLI config at backend construction // time and don't change; refuse silently if caller tries to install - // a different volume/replica (paranoia — should never happen in + // a different volume/replica (paranoia — should never happen in // production). if (b.id.VolumeID != "" && b.id.VolumeID != id.VolumeID) || (b.id.ReplicaID != "" && b.id.ReplicaID != id.ReplicaID) { @@ -353,7 +354,7 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus // Close marks the backend closed. All subsequent I/O + Sync // return ErrBackendClosed. Does NOT close the underlying -// storage — the Provider owns LogicalStorage lifecycle. +// storage — the Provider owns LogicalStorage lifecycle. func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() @@ -364,14 +365,14 @@ func (b *StorageBackend) Close() error { // SetWriteObserver installs the per-write notification seam used by // the replication layer. Safe to call only during setup (before -// I/O begins) — the seam is intentionally not hot-swappable so a +// I/O begins) — the seam is intentionally not hot-swappable so a // well-behaved caller cannot race replication wiring against live // writes. Pass nil to disable replication fan-out on this backend. // // Called by: Provider (T3b) / Host (T4a-5) during volume wiring, // once per backend lifetime. // Owns: observer pointer under b.mu. -// Borrows: the observer — caller retains ownership; StorageBackend +// Borrows: the observer — caller retains ownership; StorageBackend // does not close or otherwise tear down the observer. // // An observer that orders writes by LSN (ShipLSNRebaser) is first rebased @@ -449,11 +450,11 @@ func (b *StorageBackend) WriteProfile() WriteProfileStatus { } // SetOperational flips the readiness gate. evidence is surfaced -// in error strings and diagnostic logs — pass a short reason like +// in error strings and diagnostic logs — pass a short reason like // "recovered LSN=123 epoch=4" or "superblock ahead of assignment". // Safe to call from any goroutine. // -// Invariant: does NOT touch identity/lineage/epoch — see package +// Invariant: does NOT touch identity/lineage/epoch — see package // godoc + INV-DURABLE-OPGATE-001. func (b *StorageBackend) SetOperational(ok bool, evidence string) { if evidence == "" { @@ -473,6 +474,7 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { b.opEvidence.Store(evidence) b.operational.Store(ok) b.waitAttachReady = false + b.waitPrecopyReady = false b.notifyReadReadyLocked() } @@ -496,6 +498,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { evidence = "not operational" } b.setOperationalLocked(false, evidence) + b.waitPrecopyReady = true return true } @@ -532,29 +535,29 @@ func (b *StorageBackend) StopIO(ctx context.Context, evidence string) error { // Sync flushes everything the storage has to its durability // boundary. Returns nil iff the stable frontier advanced without -// error. Subject to the same gate stack as I/O: closed → Err- -// BackendClosed, non-operational → ErrNotReady, lineage drift → +// error. Subject to the same gate stack as I/O: closed → Err- +// BackendClosed, non-operational → ErrNotReady, lineage drift → // ErrStalePrimary. func (b *StorageBackend) Sync(ctx context.Context) error { iolatency.BackendEnter(ctx) defer iolatency.BackendExit(ctx) latencyStart := time.Now() defer func() { b.profile.syncLatency.Observe(time.Since(latencyStart)) }() - release, err := b.admit() + release, err := b.admitAfterPrecopy(ctx) if err != nil { return err } defer release() start := time.Now() // T4b-5: if an observer is installed, delegate the FULL sync - // job — the observer (ReplicationVolume) owns both the local + // job — the observer (ReplicationVolume) owns both the local // LogicalStorage.Sync call and the peer barriers fanned out // through the peer queues. Without this branch the // local sync would run twice (once here, once inside the // observer) which is both wasteful and semantically wrong // (primary would be "durable" before peers were even queried). // - // targetLSN is the primary's current walHead — the replica-facing + // targetLSN is the primary's current walHead — the replica-facing // intent for what must be durable. Local sync's achieved LSN // should meet or exceed this; per-peer barriers carry the // session lineage (TargetLSN fixed per session per peer.Barrier @@ -570,7 +573,7 @@ func (b *StorageBackend) Sync(ctx context.Context) error { b.profile.recordBackendSync(time.Since(start)) return nil } - // No observer installed — observer-free path runs local sync only + // No observer installed — observer-free path runs local sync only // (T0 / bootstrap / single-replica dev configurations). if _, err := b.storage.Sync(); err != nil { return fmt.Errorf("durable: storage sync: %w", err) @@ -624,7 +627,7 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { hook() } b.mu.Lock() - pending := b.waitAttachReady + pending := b.waitAttachReady || b.waitPrecopyReady b.mu.Unlock() if !pending { // Readiness may have published after the initial refusal. @@ -635,6 +638,24 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { return b.awaitAttachAdmission(ctx) } +// Sync keeps its immediate pre-attach refusal; only the pre-copy pause may wait. +func (b *StorageBackend) admitAfterPrecopy(ctx context.Context) (func(), error) { + release, err := b.admit() + if !errors.Is(err, frontend.ErrNotReady) { + return release, err + } + b.mu.Lock() + pending := b.waitPrecopyReady + b.mu.Unlock() + if pending { + return b.admitAfterAttach(ctx) + } + if b.operational.Load() { + return b.admit() + } + return release, err +} + // notifyReadReadyLocked wakes waiting I/O without making them hold ioMu while // the provider is attaching or draining the backend. Caller holds mu. func (b *StorageBackend) notifyReadReadyLocked() { @@ -653,7 +674,7 @@ func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), erro b.readyChanged = make(chan struct{}) } changed := b.readyChanged - terminal := b.closed || b.observerErr != nil || !b.waitAttachReady + terminal := b.closed || b.observerErr != nil || !(b.waitAttachReady || b.waitPrecopyReady) b.mu.Unlock() if err := ctx.Err(); err != nil { return nil, b.attachReadyTimeout(err) @@ -767,7 +788,7 @@ func (b *StorageBackend) admit() (func(), error) { // 3. lineage: tests that the captured Identity still matches // the live projection; preserves INV-FRONTEND-002 // -// Returning ANY error short-circuits — no partial I/O. +// Returning ANY error short-circuits — no partial I/O. func (b *StorageBackend) gate() error { if err := b.readyCheck(); err != nil { return err @@ -782,6 +803,7 @@ func (b *StorageBackend) readyCheck() error { closed := b.closed chunkFenced := b.chunkFenced observerErr := b.observerErr + precopyPending := b.waitPrecopyReady b.mu.Unlock() if closed { return frontend.ErrBackendClosed @@ -794,13 +816,16 @@ func (b *StorageBackend) readyCheck() error { } if !b.operational.Load() { ev, _ := b.opEvidence.Load().(string) + if precopyPending { + return fmt.Errorf("%w: %w: %s", frontend.ErrNotReady, frontend.ErrBackendBusy, ev) + } return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev) } return nil } // lineageCheck re-reads the projection and compares all four -// facets plus Healthy. Any drift → ErrStalePrimary. +// facets plus Healthy. Any drift → ErrStalePrimary. // INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY}. func (b *StorageBackend) lineageCheck() error { proj := b.view.Projection() @@ -862,7 +887,7 @@ func hydrationPendingCauseOnly(err error) bool { return hydrationPendingCauseOnly(errors.Unwrap(err)) } -// readBytes performs the byte-range → LBA-range fanout for Read. +// readBytes performs the byte-range → LBA-range fanout for Read. // Reads block-at-a-time, copying the sub-slice covered by the // current byte range. Handles three cases: // @@ -886,7 +911,7 @@ func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) inBlockOff := int(pos % bs) if inBlockOff >= len(block) { // Short block (shouldn't happen with fixed-size storage) - // — treat as zeros, advance. + // — treat as zeros, advance. advance := int(bs) - inBlockOff if advance > len(buf) { advance = len(buf) @@ -907,7 +932,7 @@ func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) return total, nil } -// writeBytes performs the byte-range → LBA-range fanout for Write. +// writeBytes performs the byte-range → LBA-range fanout for Write. // Full-block writes skip the read (optimization for the hot path); // partial-block writes read-modify-write to preserve the bytes // outside the range. From e0fe4f72fecf48326a1854b10e6b30a9c9ef3fb7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:53:18 -0800 Subject: [PATCH 25/59] chore: preserve existing UTF-8 source comments --- .../core/frontend/durable/storage_adapter.go | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3165fbce44..52ddfa13b4 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -5,7 +5,7 @@ // or any future impl) and exposes the `frontend.Backend` surface // iSCSI and NVMe consume. Responsibilities: // -// 1. byte ↔ LBA translation (G-int.1). +// 1. byte ↔ LBA translation (G-int.1). // Frontend layer speaks byte offsets + length; storage layer // speaks LBA + full-block data. The adapter bridges: partial- // block writes trigger read-modify-write; full-block writes @@ -14,13 +14,13 @@ // // 2. Per-I/O fence check (G-int.2). // Re-reads `ProjectionView` on every operation; ANY drift -// (identity field mismatch or Healthy=false) → ErrStalePrimary. +// (identity field mismatch or Healthy=false) → ErrStalePrimary. // Preserves INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY} under // a durable backend. // // 3. Operational gate (G-int.3, Addendum A). // Before SetOperational(true, _) is called, every I/O returns -// ErrNotReady with evidence. Starts non-operational — host/ +// ErrNotReady with evidence. Starts non-operational — host/ // provider flips to true after recovery succeeds. This is // local readiness only; NEVER advances epoch / mints authority. // @@ -29,7 +29,7 @@ // verbatim. iSCSI SYNCHRONIZE CACHE + NVMe Flush wiring lands // in T3b. // -// StorageBackend does NOT own the LogicalStorage lifecycle — the +// StorageBackend does NOT own the LogicalStorage lifecycle — the // Provider (T3b) opens and closes storage. Backend.Close marks the // handle closed but does not tear down storage. // @@ -80,7 +80,7 @@ var ErrReplicationAckUnavailable = errors.New("durable: replication ack unavaila // core/frontend/durable from importing replication directly and lets // tests inject mocks. // -// Observe contract (matches V2 BlockVol.shipMu → ShipAll invariant): +// Observe contract (matches V2 BlockVol.shipMu → ShipAll invariant): // - StorageBackend calls Observe AFTER LogicalStorage.Write // returns successfully, with the LBA + block data + LSN the // storage layer just assigned. @@ -96,9 +96,9 @@ var ErrReplicationAckUnavailable = errors.New("durable: replication ack unavaila // ReplicationVolume resequences callbacks by storage-assigned LSN, // then dispatches through one ordered queue per peer lineage. // -// Sync contract (T4b-5 — matches V2 BlockVol.MakeDistributedSync): +// Sync contract (T4b-5 — matches V2 BlockVol.MakeDistributedSync): // - When an observer is installed, StorageBackend.Sync DELEGATES -// the full sync job to observer.Sync — the observer owns both +// the full sync job to observer.Sync — the observer owns both // the local LogicalStorage.Sync call and the peer barriers, with // barriers ordered behind prior writes in each peer queue. // - targetLSN is the primary's current walHead at the moment the @@ -239,7 +239,7 @@ func (b *StorageBackend) Identity() frontend.Identity { // VolumeID/ReplicaID from CLI config (non-empty even pre-assignment) // but Epoch=0/EV=0 (engine state is zero-value until OnAssignment // runs). So a freshly-constructed backend has b.id = {v1, r1, 0, 0} -// — partially-zero, not all-zero. The latch condition keys on +// — partially-zero, not all-zero. The latch condition keys on // Epoch=0 (the meaningful "no authority line yet" indicator); // VolumeID/ReplicaID match is asserted but unchanged. // @@ -248,7 +248,7 @@ func (b *StorageBackend) Identity() frontend.Identity { // master-minted advances for the SAME volume/replica are accepted // (epoch increase, or endpoint-version increase within the same // epoch). Cross-volume, cross-replica, or backward lineage changes -// are rejected so old primaries still fail closed via lineageCheck → +// are rejected so old primaries still fail closed via lineageCheck → // ErrStalePrimary. // // Returns true if the identity changed. Returns false on no-op and @@ -258,7 +258,7 @@ func (b *StorageBackend) SetIdentity(id frontend.Identity) bool { defer b.mu.Unlock() // VolumeID/ReplicaID came from CLI config at backend construction // time and don't change; refuse silently if caller tries to install - // a different volume/replica (paranoia — should never happen in + // a different volume/replica (paranoia — should never happen in // production). if (b.id.VolumeID != "" && b.id.VolumeID != id.VolumeID) || (b.id.ReplicaID != "" && b.id.ReplicaID != id.ReplicaID) { @@ -354,7 +354,7 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus // Close marks the backend closed. All subsequent I/O + Sync // return ErrBackendClosed. Does NOT close the underlying -// storage — the Provider owns LogicalStorage lifecycle. +// storage — the Provider owns LogicalStorage lifecycle. func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() @@ -365,14 +365,14 @@ func (b *StorageBackend) Close() error { // SetWriteObserver installs the per-write notification seam used by // the replication layer. Safe to call only during setup (before -// I/O begins) — the seam is intentionally not hot-swappable so a +// I/O begins) — the seam is intentionally not hot-swappable so a // well-behaved caller cannot race replication wiring against live // writes. Pass nil to disable replication fan-out on this backend. // // Called by: Provider (T3b) / Host (T4a-5) during volume wiring, // once per backend lifetime. // Owns: observer pointer under b.mu. -// Borrows: the observer — caller retains ownership; StorageBackend +// Borrows: the observer — caller retains ownership; StorageBackend // does not close or otherwise tear down the observer. // // An observer that orders writes by LSN (ShipLSNRebaser) is first rebased @@ -450,11 +450,11 @@ func (b *StorageBackend) WriteProfile() WriteProfileStatus { } // SetOperational flips the readiness gate. evidence is surfaced -// in error strings and diagnostic logs — pass a short reason like +// in error strings and diagnostic logs — pass a short reason like // "recovered LSN=123 epoch=4" or "superblock ahead of assignment". // Safe to call from any goroutine. // -// Invariant: does NOT touch identity/lineage/epoch — see package +// Invariant: does NOT touch identity/lineage/epoch — see package // godoc + INV-DURABLE-OPGATE-001. func (b *StorageBackend) SetOperational(ok bool, evidence string) { if evidence == "" { @@ -535,8 +535,8 @@ func (b *StorageBackend) StopIO(ctx context.Context, evidence string) error { // Sync flushes everything the storage has to its durability // boundary. Returns nil iff the stable frontier advanced without -// error. Subject to the same gate stack as I/O: closed → Err- -// BackendClosed, non-operational → ErrNotReady, lineage drift → +// error. Subject to the same gate stack as I/O: closed → Err- +// BackendClosed, non-operational → ErrNotReady, lineage drift → // ErrStalePrimary. func (b *StorageBackend) Sync(ctx context.Context) error { iolatency.BackendEnter(ctx) @@ -550,14 +550,14 @@ func (b *StorageBackend) Sync(ctx context.Context) error { defer release() start := time.Now() // T4b-5: if an observer is installed, delegate the FULL sync - // job — the observer (ReplicationVolume) owns both the local + // job — the observer (ReplicationVolume) owns both the local // LogicalStorage.Sync call and the peer barriers fanned out // through the peer queues. Without this branch the // local sync would run twice (once here, once inside the // observer) which is both wasteful and semantically wrong // (primary would be "durable" before peers were even queried). // - // targetLSN is the primary's current walHead — the replica-facing + // targetLSN is the primary's current walHead — the replica-facing // intent for what must be durable. Local sync's achieved LSN // should meet or exceed this; per-peer barriers carry the // session lineage (TargetLSN fixed per session per peer.Barrier @@ -573,7 +573,7 @@ func (b *StorageBackend) Sync(ctx context.Context) error { b.profile.recordBackendSync(time.Since(start)) return nil } - // No observer installed — observer-free path runs local sync only + // No observer installed — observer-free path runs local sync only // (T0 / bootstrap / single-replica dev configurations). if _, err := b.storage.Sync(); err != nil { return fmt.Errorf("durable: storage sync: %w", err) @@ -788,7 +788,7 @@ func (b *StorageBackend) admit() (func(), error) { // 3. lineage: tests that the captured Identity still matches // the live projection; preserves INV-FRONTEND-002 // -// Returning ANY error short-circuits — no partial I/O. +// Returning ANY error short-circuits — no partial I/O. func (b *StorageBackend) gate() error { if err := b.readyCheck(); err != nil { return err @@ -825,7 +825,7 @@ func (b *StorageBackend) readyCheck() error { } // lineageCheck re-reads the projection and compares all four -// facets plus Healthy. Any drift → ErrStalePrimary. +// facets plus Healthy. Any drift → ErrStalePrimary. // INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY}. func (b *StorageBackend) lineageCheck() error { proj := b.view.Projection() @@ -887,7 +887,7 @@ func hydrationPendingCauseOnly(err error) bool { return hydrationPendingCauseOnly(errors.Unwrap(err)) } -// readBytes performs the byte-range → LBA-range fanout for Read. +// readBytes performs the byte-range → LBA-range fanout for Read. // Reads block-at-a-time, copying the sub-slice covered by the // current byte range. Handles three cases: // @@ -911,7 +911,7 @@ func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) inBlockOff := int(pos % bs) if inBlockOff >= len(block) { // Short block (shouldn't happen with fixed-size storage) - // — treat as zeros, advance. + // — treat as zeros, advance. advance := int(bs) - inBlockOff if advance > len(buf) { advance = len(buf) @@ -932,7 +932,7 @@ func (b *StorageBackend) readBytes(ctx context.Context, offset int64, p []byte) return total, nil } -// writeBytes performs the byte-range → LBA-range fanout for Write. +// writeBytes performs the byte-range → LBA-range fanout for Write. // Full-block writes skip the read (optimization for the hot path); // partial-block writes read-modify-write to preserve the bytes // outside the range. From 1f4a2d2ad25bc7c6e1465afa6b186da2bc071b2a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:54:20 -0800 Subject: [PATCH 26/59] test(durable): retain terminal stop semantics for queued pre-copy I/O --- .../frontend/durable/precopy_wait_test.go | 56 +++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 4 +- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_wait_test.go b/seaweed-block/core/frontend/durable/precopy_wait_test.go index 1704615260..549506474f 100644 --- a/seaweed-block/core/frontend/durable/precopy_wait_test.go +++ b/seaweed-block/core/frontend/durable/precopy_wait_test.go @@ -102,3 +102,59 @@ func TestPrecopyFreezeCallerDeadlineIsRetryable(t *testing.T) { t.Fatalf("deadline lost retryable admission status: %v", err) } } + +func TestPrecopyFreezeTerminalStopWakesQueuedIO(t *testing.T) { + for _, terminal := range []string{"close", "stop"} { + t.Run(terminal, func(t *testing.T) { + p := precopyProvider(t, storage.NewMemChunkRemote(), &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + gate := b.(interface { + TryStopIO(string) bool + SetOperational(bool, string) + }) + if !gate.TryStopIO("pre-copy final cut") { + t.Fatal("freeze failed") + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + started, done := make(chan struct{}), make(chan struct{}) + var result error + t.Cleanup(func() { + cancel() + gate.SetOperational(false, "cleanup") + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("queued command did not join") + } + }) + go func() { defer close(done); close(started); _, result = b.Write(ctx, 4096, block(9)) }() + <-started + select { + case <-done: + t.Fatalf("command escaped freeze: %v", result) + case <-time.After(30 * time.Millisecond): + } + want := frontend.ErrNotReady + if terminal == "close" { + want = frontend.ErrBackendClosed + if err := b.Close(); err != nil { + t.Fatal(err) + } + } else { + gate.SetOperational(false, "workspace lease self-fence") + } + select { + case <-done: + if !errors.Is(result, want) || errors.Is(result, frontend.ErrBackendBusy) { + t.Fatalf("terminal gate masked: %v", result) + } + case <-time.After(time.Second): + t.Fatal("terminal stop did not wake command") + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 52ddfa13b4..62ff9d0184 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -162,8 +162,8 @@ type StorageBackend struct { // false; provider flips true after Recover() succeeds (T3b). // opEvidence is the reason reported when operational=false // (e.g., "awaiting recovery", "local epoch ahead of assignment"). - // Only a successfully recovered chunk volume awaiting attachment may wait. - // waitAttachReady and readyChanged are protected by mu. + // Readiness waits cover pending chunk attachment and temporary pre-copy freezes. + // Readiness flags and readyChanged are protected by mu. waitAttachReady bool waitPrecopyReady bool // temporary pre-copy freeze; queued I/O has not reached storage readyChanged chan struct{} From 7d1816f0d34c880d4c2788d0d16e64eea489eaf9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:59:13 -0800 Subject: [PATCH 27/59] test(storage): make queued caller cancellation explicit for vet --- seaweed-block/core/storage/chunk_precopy_detach_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 09278ddf56..93f0a4ef2a 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -253,6 +253,7 @@ func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *test t.Fatal("other cut did not reach held upload") } ctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() go func() { defer close(preDone) _, precopyErr = l.PrecopyDetach(ctx, func() bool { t.Error("queued canceled caller stopped I/O"); return false }) From 16f3b31e2753f55c2d4928eecaa122db92f0443a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:08:22 -0800 Subject: [PATCH 28/59] test(durable): require bounded pre-copy admission pause --- .../frontend/durable/precopy_drain_test.go | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/precopy_drain_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_drain_test.go b/seaweed-block/core/frontend/durable/precopy_drain_test.go new file mode 100644 index 0000000000..97896cbde4 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_test.go @@ -0,0 +1,73 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestPrecopyAdmissionPauseBoundsDrainAndReopens(t *testing.T) { + p, view := parkedProvider(t, storage.NewMemChunkRemote()) + openRecovered(t, p) + backend, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + pause, ok := backend.(interface { + BeginPrecopyPause(context.Context) (func(), error) + }) + if !ok { + t.Fatal("backend lacks bounded pre-copy admission drain") + } + view.arm() + written := make(chan error, 1) + t.Cleanup(func() { + view.unpark() + select { + case <-written: + case <-time.After(3 * time.Second): + t.Error("writer not joined") + } + }) + go func() { _, err := backend.Write(context.Background(), 4096, block(7)); written <- err }() + select { + case <-view.entered: + case <-time.After(3 * time.Second): + t.Fatal("writer never entered") + } + // The late gate caller is blocked before it can affect storage. Pausing must + // account for it safely without waiting under the storage capture lock. + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + release, err := pause.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + if release == nil { + t.Fatal("pause has no release") + } + t.Cleanup(release) + blocked, cancelWrite := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancelWrite() + if _, err := backend.Write(blocked, 8192, block(8)); !errors.Is(err, frontend.ErrBackendBusy) { + t.Fatalf("new I/O bypassed pause: %v", err) + } + release() + view.unpark() + select { + case err := <-written: + if err != nil { + t.Fatal(err) + } + written <- nil + case <-time.After(3 * time.Second): + t.Fatal("resumed writer blocked") + } + if _, err := backend.Write(context.Background(), 8192, block(8)); err != nil { + t.Fatal(err) + } +} From ffce8c1dd68a1ab024746d78f9ea7ec2414d4f76 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:10:23 -0800 Subject: [PATCH 29/59] feat(durable): bound pre-copy admission drain and preserve queued order --- .../frontend/durable/precopy_admission.go | 160 ++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 97 +++++++---- 2 files changed, 220 insertions(+), 37 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/precopy_admission.go diff --git a/seaweed-block/core/frontend/durable/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go new file mode 100644 index 0000000000..9735849fd2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -0,0 +1,160 @@ +package durable + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +const precopyQueueBudget = 5 * time.Second + +type precopyWaiter struct { + ready chan struct{} + signaled bool +} +type precopyAdmission struct { + active bool + started time.Time + drained chan struct{} + drainDone bool + waiters []*precopyWaiter +} + +// Lock order: no store, provider, capture or projection call while holding mu. +// Physical I/O is counted only after the complete gate. Drain waits without mu +// or ioMu, before the storage capture barrier, so admitted writers can finish. +func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) { + if err := ctx.Err(); err != nil { + return nil, err + } + b.mu.Lock() + if b.closed || !b.operational.Load() || b.observerErr != nil || b.precopy != nil { + b.mu.Unlock() + return nil, fmt.Errorf("%w: pre-copy admission unavailable", frontend.ErrBackendBusy) + } + p := &precopyAdmission{active: true, started: time.Now(), drained: make(chan struct{})} + b.precopy = p + if b.admittedIO == 0 { + close(p.drained) + p.drainDone = true + } + b.mu.Unlock() + var once sync.Once + resume := func() { + once.Do(func() { + b.mu.Lock() + if b.precopy == p { + b.finishPrecopyLocked(b.operational.Load() && !b.closed) + } + b.mu.Unlock() + }) + } + select { + case <-p.drained: + if err := ctx.Err(); err != nil { + resume() + return nil, err + } + return resume, nil + case <-ctx.Done(): + resume() + return nil, ctx.Err() + } +} + +func signalPrecopy(w *precopyWaiter) { + if !w.signaled { + close(w.ready) + w.signaled = true + } +} + +// Caller owns mu. Resume admits the old queue serially; a terminal stop wakes +// every command to observe the terminal gate, without issuing storage I/O. +func (b *StorageBackend) finishPrecopyLocked(resume bool) { + p := b.precopy + if p == nil { + return + } + p.active = false + if !resume { + for _, w := range p.waiters { + signalPrecopy(w) + } + b.precopy = nil + } else if len(p.waiters) == 0 { + b.precopy = nil + } else { + signalPrecopy(p.waiters[0]) + } +} + +func (b *StorageBackend) removePrecopyWaiter(p *precopyAdmission, w *precopyWaiter) { + b.mu.Lock() + defer b.mu.Unlock() + if b.precopy != p { + return + } + for i, v := range p.waiters { + if v == w { + p.waiters = append(p.waiters[:i], p.waiters[i+1:]...) + break + } + } + if !p.active { + if len(p.waiters) == 0 { + b.precopy = nil + } else { + signalPrecopy(p.waiters[0]) + } + } +} + +// An unqueued caller races the pause only at admit's final registration check. +// Waiting callers own no I/O lock and execute no storage/observer operation. +func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), error)) (func(), error) { + for { + b.mu.Lock() + p := b.precopy + if p == nil { + b.mu.Unlock() + release, err := admit() + if err != nil { + b.mu.Lock() + pending := b.precopy != nil + b.mu.Unlock() + if pending { + continue + } + } + return release, err + } + w := &precopyWaiter{ready: make(chan struct{})} + p.waiters = append(p.waiters, w) + if !p.active && len(p.waiters) == 1 { + signalPrecopy(w) + } + deadline := p.started.Add(precopyQueueBudget) + b.mu.Unlock() + waitCtx, cancel := context.WithDeadline(ctx, deadline) + select { + case <-w.ready: + case <-waitCtx.Done(): + } + cause := waitCtx.Err() + cancel() + if cause != nil { + b.removePrecopyWaiter(p, w) + return nil, b.attachReadyTimeout(cause) + } + release, err := admit() + if err != nil { + b.removePrecopyWaiter(p, w) + return nil, err + } + return func() { release(); b.removePrecopyWaiter(p, w) }, nil + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 62ff9d0184..8e4da51484 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -164,11 +164,12 @@ type StorageBackend struct { // (e.g., "awaiting recovery", "local epoch ahead of assignment"). // Readiness waits cover pending chunk attachment and temporary pre-copy freezes. // Readiness flags and readyChanged are protected by mu. - waitAttachReady bool - waitPrecopyReady bool // temporary pre-copy freeze; queued I/O has not reached storage - readyChanged chan struct{} - operational atomic.Bool - opEvidence atomic.Value // string + waitAttachReady bool + precopy *precopyAdmission // under mu; owns transient admission and FIFO waiters + admittedIO int // under mu; operations past the complete gate + readyChanged chan struct{} + operational atomic.Bool + opEvidence atomic.Value // string // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -359,6 +360,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.finishPrecopyLocked(false) b.notifyReadReadyLocked() return nil } @@ -474,7 +476,7 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { b.opEvidence.Store(evidence) b.operational.Store(ok) b.waitAttachReady = false - b.waitPrecopyReady = false + b.finishPrecopyLocked(ok) b.notifyReadReadyLocked() } @@ -483,6 +485,22 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { // holding its read side may itself be queued on that barrier. Failed attempts // leave the frontend unchanged. Lock order: try ioMu -> try mu; neither lock waits, and no store calls. func (b *StorageBackend) TryStopIO(evidence string) bool { + // A drained admission pause excludes late gate callers even if they still + // hold ioMu's read side. Their final registration check cannot reach storage. + if b.mu.TryLock() { + if b.precopy != nil && b.precopy.active { + defer b.mu.Unlock() + if b.admittedIO != 0 || b.closed || !b.operational.Load() { + return false + } + b.opEvidence.Store(evidence) + b.operational.Store(false) + b.waitAttachReady = false + b.notifyReadReadyLocked() + return true + } + b.mu.Unlock() + } if !b.ioMu.TryLock() { return false } @@ -494,11 +512,13 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { if b.closed || !b.operational.Load() { return false } - if evidence == "" { - evidence = "not operational" - } - b.setOperationalLocked(false, evidence) - b.waitPrecopyReady = true + p := &precopyAdmission{active: true, started: time.Now(), drained: make(chan struct{}), drainDone: true} + close(p.drained) + b.precopy = p + b.opEvidence.Store(evidence) + b.operational.Store(false) + b.waitAttachReady = false + b.notifyReadReadyLocked() return true } @@ -543,7 +563,7 @@ func (b *StorageBackend) Sync(ctx context.Context) error { defer iolatency.BackendExit(ctx) latencyStart := time.Now() defer func() { b.profile.syncLatency.Observe(time.Since(latencyStart)) }() - release, err := b.admitAfterPrecopy(ctx) + release, err := b.admitPrecopy(ctx, b.admit) if err != nil { return err } @@ -619,6 +639,10 @@ func (b *StorageBackend) setChunkAttachPending(evidence string) { } func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { + return b.admitPrecopy(ctx, func() (func(), error) { return b.admitAfterAttachUnqueued(ctx) }) +} + +func (b *StorageBackend) admitAfterAttachUnqueued(ctx context.Context) (func(), error) { release, err := b.admit() if !errors.Is(err, frontend.ErrNotReady) { return release, err @@ -627,7 +651,7 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { hook() } b.mu.Lock() - pending := b.waitAttachReady || b.waitPrecopyReady + pending := b.waitAttachReady b.mu.Unlock() if !pending { // Readiness may have published after the initial refusal. @@ -638,24 +662,6 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { return b.awaitAttachAdmission(ctx) } -// Sync keeps its immediate pre-attach refusal; only the pre-copy pause may wait. -func (b *StorageBackend) admitAfterPrecopy(ctx context.Context) (func(), error) { - release, err := b.admit() - if !errors.Is(err, frontend.ErrNotReady) { - return release, err - } - b.mu.Lock() - pending := b.waitPrecopyReady - b.mu.Unlock() - if pending { - return b.admitAfterAttach(ctx) - } - if b.operational.Load() { - return b.admit() - } - return release, err -} - // notifyReadReadyLocked wakes waiting I/O without making them hold ioMu while // the provider is attaching or draining the backend. Caller holds mu. func (b *StorageBackend) notifyReadReadyLocked() { @@ -674,7 +680,7 @@ func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), erro b.readyChanged = make(chan struct{}) } changed := b.readyChanged - terminal := b.closed || b.observerErr != nil || !(b.waitAttachReady || b.waitPrecopyReady) + terminal := b.closed || b.observerErr != nil || !b.waitAttachReady b.mu.Unlock() if err := ctx.Err(); err != nil { return nil, b.attachReadyTimeout(err) @@ -778,7 +784,24 @@ func (b *StorageBackend) admit() (func(), error) { b.ioMu.RUnlock() return nil, err } - return b.ioMu.RUnlock, nil + b.mu.Lock() + if b.precopy != nil && b.precopy.active { + b.mu.Unlock() + b.ioMu.RUnlock() + return nil, fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + } + b.admittedIO++ + b.mu.Unlock() + return func() { + b.mu.Lock() + b.admittedIO-- + if p := b.precopy; p != nil && p.active && b.admittedIO == 0 && !p.drainDone { + close(p.drained) + p.drainDone = true + } + b.mu.Unlock() + b.ioMu.RUnlock() + }, nil } // gate is the per-I/O precondition stack. Order matters: @@ -803,7 +826,7 @@ func (b *StorageBackend) readyCheck() error { closed := b.closed chunkFenced := b.chunkFenced observerErr := b.observerErr - precopyPending := b.waitPrecopyReady + precopyPending := b.precopy != nil && b.precopy.active b.mu.Unlock() if closed { return frontend.ErrBackendClosed @@ -814,11 +837,11 @@ func (b *StorageBackend) readyCheck() error { if chunkFenced != nil && chunkFenced() { return frontend.ErrStalePrimary } + if precopyPending { + return fmt.Errorf("%w: %w: pre-copy admission paused", frontend.ErrNotReady, frontend.ErrBackendBusy) + } if !b.operational.Load() { ev, _ := b.opEvidence.Load().(string) - if precopyPending { - return fmt.Errorf("%w: %w: %s", frontend.ErrNotReady, frontend.ErrBackendBusy, ev) - } return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev) } return nil From f337e8de991b917d33c647c282eeb2f1e2861132 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:13:08 -0800 Subject: [PATCH 30/59] feat(storage): drain admission before authoritative pre-copy barrier --- .../frontend/durable/precopy_admission.go | 13 ++++++ .../core/frontend/durable/provider_chunk.go | 4 +- .../core/frontend/durable/storage_adapter.go | 8 +++- seaweed-block/core/storage/chunk_layer.go | 34 ++++++++++++-- seaweed-block/core/storage/chunk_precopy.go | 46 +++++++++++++++++-- 5 files changed, 92 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go index 9735849fd2..c8ba6045dc 100644 --- a/seaweed-block/core/frontend/durable/precopy_admission.go +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -2,6 +2,7 @@ package durable import ( "context" + "errors" "fmt" "sync" "time" @@ -132,6 +133,15 @@ func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), } return release, err } + b.mu.Unlock() + if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { + return nil, err + } + b.mu.Lock() + if b.precopy != p { + b.mu.Unlock() + continue + } w := &precopyWaiter{ready: make(chan struct{})} p.waiters = append(p.waiters, w) if !p.active && len(p.waiters) == 1 { @@ -139,6 +149,9 @@ func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), } deadline := p.started.Add(precopyQueueBudget) b.mu.Unlock() + if hook := b.testPrecopyQueued; hook != nil { + hook() + } waitCtx, cancel := context.WithDeadline(ctx, deadline) select { case <-w.ready: diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index a8d3cf1964..9663bf89ce 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -935,7 +935,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st var r storage.ChunkCutResult if p.cfg.ChunkDetachPrecopy { owner, ok := layer.(interface { - PrecopyDetach(context.Context, func() bool) (storage.ChunkCutResult, error) + PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) }) if !ok { return r, 0, fmt.Errorf("%w: layer lacks pre-copy", storage.ErrPrecopyUnknown) @@ -944,7 +944,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st notifyDetach() // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) - r, err = owner.PrecopyDetach(hostlimit.WithClass(cutCtx, hostlimit.Urgent), func() bool { + r, err = owner.PrecopyDetachWithAdmission(hostlimit.WithClass(cutCtx, hostlimit.Urgent), h.backend.BeginPrecopyPause, func() bool { if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 8e4da51484..c772c61696 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -148,7 +148,8 @@ const maxFullBlockBatchBlocks = 64 type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). - testBeforeIOLock func() + testBeforeIOLock func() + testPrecopyQueued func() // after FIFO registration, outside mu // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() testAfterAttachRefusal func() @@ -488,8 +489,11 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { // A drained admission pause excludes late gate callers even if they still // hold ioMu's read side. Their final registration check cannot reach storage. if b.mu.TryLock() { - if b.precopy != nil && b.precopy.active { + if b.precopy != nil { defer b.mu.Unlock() + if !b.precopy.active { + return false + } if b.admittedIO != 0 || b.closed || !b.operational.Load() { return false } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index b5296395ee..96d38a9ee4 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -54,6 +54,7 @@ const defaultReadMissTimeout = 30 * time.Second type chunkLayerImpl struct { // capMu serializes pre-copy admission and its recent measurements. precopyFreeze func(uint64, time.Time) bool + precopyPrepare func(context.Context) (func(), error) precopySamples []precopySample precopyPause func(time.Duration) @@ -905,6 +906,31 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // paused too. LockWaitNs reports that wait on its own. payloadBeforeBarrier = st.PayloadNs pauseStart = time.Now() + var releasePrecopy func() + if prepare := l.precopyPrepare; prepare != nil { + releasePrecopy, _ = prepare(ctx) + } + defer func() { + if releasePrecopy != nil && !detach { + releasePrecopy() + } + }() + if cause := context.Cause(ctx); cause != nil { + if releasePrecopy != nil { + releasePrecopy() + releasePrecopy = nil + } + l.dropIntents(ctx, intents) + return chunkCutResult{}, cause + } + // Resume rejected tentative admission before any ordinary COW upload. + unlockCapture := func() { + l.s.captureMu.Unlock() + if !detach && releasePrecopy != nil { + releasePrecopy() + releasePrecopy = nil + } + } if hook := l.testBeforeBarrierLockHook; hook != nil { hook() } @@ -917,7 +943,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch hook(h) } if err != nil { - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() l.dropIntents(ctx, intents) // a clean abort: staged keys are released return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) @@ -977,7 +1003,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() // HEAD holds the image of a later LSN than this host's log has // reached: publishing would move remote_lsn backwards. Refused @@ -997,7 +1023,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if copyErr == nil { w.budget = budget } - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() copyStart = time.Now() if copyErr == nil { @@ -1029,7 +1055,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)}) } - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() } st.CopyNs = time.Since(copyStart).Nanoseconds() diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 985995073c..3b35e301a9 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -13,10 +13,11 @@ var ( ) const ( - precopyAttempts = 5 - precopyDuration = 60 * time.Second - precopyAllowance = 1200 * time.Millisecond - precopyMargin = 100 * time.Millisecond + precopyAttempts = 5 + precopyDuration = 60 * time.Second + precopyAllowance = 1200 * time.Millisecond + precopyMargin = 100 * time.Millisecond + precopyDrainBound = 100 * time.Millisecond ) type precopySample struct { @@ -27,6 +28,8 @@ type precopySample struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + Drain time.Duration `json:"drainNs"` + DrainTimedOut bool `json:"drainTimedOut"` Attempts int `json:"attempts"` TailBytes uint64 `json:"tailBytes"` Fixed time.Duration `json:"fixedNs"` @@ -62,6 +65,16 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo // capMu owns the callback and samples; no owner lock is taken while waiting // for capMu. The callback must never wait for an I/O holding a backend read lock. func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) (ChunkCutResult, error) { + return l.precopyDetach(ctx, nil, stopIO) +} + +// prepare closes frontend admission and drains before the store barrier. Its +// release reopens only that tentative admission; it must not undo a host fence. +func (l *chunkLayerImpl) PrecopyDetachWithAdmission(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) { + return l.precopyDetach(ctx, prepare, stopIO) +} + +func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) { if stopIO == nil { return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown) } @@ -83,6 +96,20 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) var frozenAt time.Time var casAtFreeze uint64 var pauseTotal, longestPause time.Duration + var drain time.Duration + var drainErr error + if prepare != nil { + l.precopyPrepare = func(ctx context.Context) (func(), error) { + dc, cancel := context.WithTimeout(ctx, precopyDrainBound) + defer cancel() + start := time.Now() + release, err := prepare(dc) + drain = time.Since(start) + drainErr = err + return release, err + } + } + l.precopyPause = func(pause time.Duration) { pauseTotal += pause if pause > longestPause { @@ -91,6 +118,15 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) } l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool { report = l.precopyEstimate(tail, report.Attempts) + report.Drain = drain + report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) + if drainErr != nil { + report.Reason = "drain_refused" + if report.DrainTimedOut { + report.Reason = "drain_timeout" + } + return false + } spent := time.Since(barrierStart) if spent > report.Fixed { report.Estimate += spent - report.Fixed @@ -110,7 +146,7 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) frozenAt, casAtFreeze = barrierStart, countCAS() return true } - defer func() { l.precopyFreeze = nil; l.precopyPause = nil }() + defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() for attempt := 1; attempt <= precopyAttempts; attempt++ { report.Attempts = attempt if err := ctx.Err(); err != nil { From f9b8d969ce0f6ede0ceaad077143b15cda32646d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:15:45 -0800 Subject: [PATCH 31/59] test(durable): force first-round convergence with synchronous write pressure --- .../durable/precopy_fifty_iops_test.go | 133 ++++++++++++++++++ .../durable/provider_chunk_precopy_test.go | 27 +++- 2 files changed, 155 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go new file mode 100644 index 0000000000..e95a0380a7 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -0,0 +1,133 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Backend Write+Sync models the guest's 4KiB synchronous command stream. The +// peer reply is held until a separate control probe witnesses closed admission, +// then released after20ms. This is a forced schedule, not physical NVMe proof. +func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { + remote := storage.NewMemChunkRemote() + p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + openRecovered(t, p) + backend, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + for i := byte(1); i <= 3; i++ { + if _, err := backend.Write(context.Background(), 4096, block(i)); err != nil { + t.Fatal(err) + } + if err := backend.Sync(context.Background()); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + } + entered, release := make(chan struct{}), make(chan struct{}) + var enteredOnce, releaseOnce sync.Once + releasePeer := func() { releaseOnce.Do(func() { close(release) }) } + if err := backend.(*durable.StorageBackend).SetWriteObserver(writeObserverFunc{sync: func(ctx context.Context, _ uint64) error { + enteredOnce.Do(func() { close(entered) }) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + writerDone, probeDone := make(chan struct{}), make(chan struct{}) + var stopped atomic.Bool + var guestErrors atomic.Int64 + t.Cleanup(func() { + stopped.Store(true) + releasePeer() + cancel() + for _, done := range []chan struct{}{writerDone, probeDone} { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("writer/probe did not join") + } + } + }) + go func() { + defer close(writerDone) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + _, err := backend.Write(ctx, 4096, block(0x5b)) + if err == nil { + err = backend.Sync(ctx) + } + if err != nil { + if !stopped.Load() { + guestErrors.Add(1) + } + return + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } + }() + select { + case <-entered: + case <-ctx.Done(): + close(probeDone) + t.Fatal("synchronous writer not admitted") + } + go func() { + defer close(probeDone) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + probe, stop := context.WithTimeout(ctx, 5*time.Millisecond) + _, err := backend.Write(probe, 8192, block(0x6d)) + stop() + if errors.Is(err, frontend.ErrBackendBusy) && errors.Is(err, context.DeadlineExceeded) { + timer := time.NewTimer(20 * time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + releasePeer() + case <-ctx.Done(): + } + return + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } + }() + result, _, err := p.DetachVolume(ctx, "v1") + stopped.Store(true) + if err != nil || !result.Precopy.Frozen || result.Precopy.Attempts != 1 { + t.Fatalf("50IOPS cutover: report=%+v err=%v", result.Precopy, err) + } + if guestErrors.Load() != 0 { + t.Fatalf("guest errors before cutover: %d", guestErrors.Load()) + } + if !bytes.Equal(headBlock(t, remote, 1), block(0x5b)) { + t.Fatal("final cut lost synchronous writer bytes") + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index ae086c106e..ab64579e83 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "sync" "testing" "time" @@ -124,19 +125,35 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { if err != nil { t.Fatal(err) } - view.arm() + if _, err := b.Write(context.Background(), 4096, block(0x8a)); err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + unpark := func() { releaseOnce.Do(func() { close(release) }) } + if err := b.(*durable.StorageBackend).SetWriteObserver(writeObserverFunc{sync: func(ctx context.Context, _ uint64) error { + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } done := make(chan error, 1) t.Cleanup(func() { - view.unpark() + unpark() select { case <-done: case <-time.After(5 * time.Second): t.Error("writer did not join") } }) - go func() { _, err := b.Write(context.Background(), 4096, block(0x8a)); done <- err }() + go func() { done <- b.Sync(context.Background()) }() select { - case <-view.entered: + case <-entered: case <-time.After(5 * time.Second): t.Fatal("write not admitted") } @@ -155,7 +172,7 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { if _, err = b.Write(ctx, 8192, block(0x9b)); err != nil { t.Fatal("nonconverged owner stopped:", err) } - view.unpark() + unpark() select { case err := <-done: if err != nil { From e45513ae9d8f3f7f9d0154887e62298386e7ffc4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:17:00 -0800 Subject: [PATCH 32/59] test(durable): cover bounded drain FIFO restart and cutover queue budget --- .../frontend/durable/precopy_admission.go | 7 + .../frontend/durable/precopy_fifo_test.go | 218 ++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/precopy_fifo_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go index c8ba6045dc..9e58424413 100644 --- a/seaweed-block/core/frontend/durable/precopy_admission.go +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -55,6 +55,13 @@ func (b *StorageBackend) BeginPrecopyPause(ctx context.Context) (func(), error) } select { case <-p.drained: + b.mu.Lock() + valid := b.precopy == p && p.active && b.operational.Load() && !b.closed + b.mu.Unlock() + if !valid { + resume() + return nil, frontend.ErrNotReady + } if err := ctx.Err(); err != nil { resume() return nil, err diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go new file mode 100644 index 0000000000..d36087e436 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -0,0 +1,218 @@ +package durable + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage/memorywal" +) + +type precopyQueueView struct{ id frontend.Identity } + +func (v precopyQueueView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: v.id.VolumeID, ReplicaID: v.id.ReplicaID, Epoch: v.id.Epoch, EndpointVersion: v.id.EndpointVersion, Healthy: true} +} + +type precopyQueueObserver struct { + observe func(byte) + sync func(context.Context) error +} + +func (o precopyQueueObserver) Observe(_ context.Context, _ uint32, _ uint64, p []byte) error { + if o.observe != nil { + o.observe(p[0]) + } + return nil +} +func (o precopyQueueObserver) Sync(ctx context.Context, _ uint64) error { + if o.sync != nil { + return o.sync(ctx) + } + return nil +} +func precopyMemoryBackend(t *testing.T) *StorageBackend { + t.Helper() + s := memorywal.NewStore(8, 4096) + t.Cleanup(func() { _ = s.Close() }) + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := NewStorageBackend(s, precopyQueueView{id}, id) + b.SetOperational(true, "test") + t.Cleanup(func() { _ = b.Close() }) + return b +} + +func TestPrecopyQueueResumesInFIFOOrder(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + queued := make(chan struct{}, 4) + b.testPrecopyQueued = func() { queued <- struct{}{} } + first, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + seen := make(chan byte, 4) + if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { + seen <- v + if v == 1 { + close(first) + select { + case <-release: + case <-ctx.Done(): + } + } + }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + joined := make(chan struct{}) + errs := make(chan error, 4) + t.Cleanup(func() { + cancel() + unpark() + resume() + _ = b.Close() + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(3 * time.Second): + t.Error("queue workers did not join") + } + }) + start := func(v byte) { + wg.Add(1) + go func() { defer wg.Done(); _, err := b.Write(ctx, 0, bytes.Repeat([]byte{v}, 4096)); errs <- err }() + select { + case <-queued: + case <-ctx.Done(): + t.Fatal("command was not queued") + } + } + start(1) + start(2) + start(3) + resume() + select { + case <-first: + case <-ctx.Done(): + t.Fatal("first queued write did not enter") + } + start(4) // New arrivals cannot bypass the old queue during an aborted cut. + if v := <-seen; v != 1 { + t.Fatalf("first write=%d", v) + } + select { + case v := <-seen: + t.Fatalf("write %d bypassed held FIFO head", v) + case <-time.After(30 * time.Millisecond): + } + unpark() + for _, want := range []byte{2, 3, 4} { + select { + case got := <-seen: + if got != want { + t.Fatalf("write=%d want%d", got, want) + } + case <-ctx.Done(): + t.Fatal("FIFO queue did not drain") + } + } + for i := 0; i < 4; i++ { + select { + case err := <-errs: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("queued write did not finish") + } + } + data := make([]byte, 4096) + if _, err := b.Read(ctx, 0, data); err != nil || data[0] != 4 { + t.Fatalf("ordered final bytes=%d err=%v", data[0], err) + } +} + +func TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture(t *testing.T) { + b := precopyMemoryBackend(t) + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unpark := func() { once.Do(func() { close(release) }) } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + t.Cleanup(func() { + unpark() + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Error("Sync did not join") + } + }) + if err := b.SetWriteObserver(precopyQueueObserver{sync: func(ctx context.Context) error { + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } + go func() { defer close(done); _ = b.Sync(ctx) }() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("Sync not admitted") + } + drain, stop := context.WithTimeout(ctx, 30*time.Millisecond) + defer stop() + resume, err := b.BeginPrecopyPause(drain) + if !errors.Is(err, context.DeadlineExceeded) || resume != nil { + t.Fatalf("drain=%v release=%v", err, resume != nil) + } + if _, err := b.Write(ctx, 4096, bytes.Repeat([]byte{9}, 4096)); err != nil { + t.Fatal("drain refusal did not reopen admission:", err) + } + unpark() +} + +func TestPrecopyQueueUsesFiveSecondCutoverBudget(t *testing.T) { + b := precopyMemoryBackend(t) + if !b.TryStopIO("final cut") { + t.Fatal("freeze failed") + } + ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second) + done := make(chan struct{}) + var result error + t.Cleanup(func() { + cancel() + b.SetOperational(false, "cleanup") + select { + case <-done: + case <-time.After(time.Second): + t.Error("queue did not join") + } + }) + go func() { defer close(done); _, result = b.Write(ctx, 0, make([]byte, 4096)) }() + select { + case <-done: + t.Fatalf("queue expired before cutover budget: %v", result) + case <-time.After(3200 * time.Millisecond): + } + select { + case <-done: + if !errors.Is(result, frontend.ErrBackendBusy) || !errors.Is(result, context.DeadlineExceeded) { + t.Fatalf("deadline=%v", result) + } + case <-ctx.Done(): + t.Fatal("five-second queue budget was not enforced") + } +} From 390f8fb32eb37aa109b42c863ccdf3232874d8a5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:20:39 -0800 Subject: [PATCH 33/59] test(durable): release tentative admission before rolling uploads --- .../durable/precopy_fifty_iops_test.go | 1 + .../durable/precopy_rolling_pause_test.go | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index e95a0380a7..519193c7bf 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -121,6 +121,7 @@ func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { }() result, _, err := p.DetachVolume(ctx, "v1") stopped.Store(true) + t.Logf("attempts=%d drain=%s estimate=%s frozen=%t guest_errors=%d", result.Precopy.Attempts, result.Precopy.Drain, result.Precopy.Estimate, result.Precopy.Frozen, guestErrors.Load()) if err != nil || !result.Precopy.Frozen || result.Precopy.Attempts != 1 { t.Fatalf("50IOPS cutover: report=%+v err=%v", result.Precopy, err) } diff --git a/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go b/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go new file mode 100644 index 0000000000..47547cfd63 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go @@ -0,0 +1,78 @@ +package durable_test + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type precopyRollingHeldRemote struct { + *storage.MemChunkRemote + entered, release chan struct{} + once sync.Once +} + +func (r *precopyRollingHeldRemote) Put(ctx context.Context, key string, data []byte) error { + r.once.Do(func() { close(r.entered) }) + select { + case <-r.release: + return r.MemChunkRemote.Put(ctx, key, data) + case <-ctx.Done(): + return ctx.Err() + } +} + +func TestPrecopyRollingUploadReopensTentativeAdmission(t *testing.T) { + r := &precopyRollingHeldRemote{MemChunkRemote: storage.NewMemChunkRemote(), entered: make(chan struct{}), release: make(chan struct{})} + p := precopyProvider(t, r, &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(0x5b)); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + var once sync.Once + unpark := func() { once.Do(func() { close(r.release) }) } + done := make(chan struct{}) + var cutErr error + t.Cleanup(func() { + unpark() + cancel() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("cut did not join") + } + }) + go func() { defer close(done); _, _, cutErr = p.DetachVolume(ctx, "v1") }() + select { + case <-r.entered: + case <-ctx.Done(): + t.Fatal("cold rolling cut never uploaded") + } + // This chunk is outside the held cut's COW candidate set. Missing cost + // samples must reopen admission before the ordinary upload can complete. + write, stop := context.WithTimeout(ctx, 100*time.Millisecond) + defer stop() + if _, err := b.Write(write, 80*4096, block(0x6d)); err != nil { + t.Fatal("rolling upload held guest admission:", err) + } + unpark() + select { + case <-done: + if cutErr != nil { + t.Fatal(cutErr) + } + case <-ctx.Done(): + t.Fatal("rolling rounds did not converge") + } + if headBlock(t, r.MemChunkRemote, 80)[0] != 0x6d { + t.Fatal("later admitted write missing from final image") + } +} From 7e31afeda110c0fc7a79ec27fe31714ff6243ece Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:22:42 -0800 Subject: [PATCH 34/59] test(storage): pin drain deadline and exclude late unadmitted writes --- .../frontend/durable/precopy_drain_test.go | 65 +++++++++++++++++++ .../core/storage/chunk_precopy_detach_test.go | 16 +++++ 2 files changed, 81 insertions(+) diff --git a/seaweed-block/core/frontend/durable/precopy_drain_test.go b/seaweed-block/core/frontend/durable/precopy_drain_test.go index 97896cbde4..2f3c00847d 100644 --- a/seaweed-block/core/frontend/durable/precopy_drain_test.go +++ b/seaweed-block/core/frontend/durable/precopy_drain_test.go @@ -71,3 +71,68 @@ func TestPrecopyAdmissionPauseBoundsDrainAndReopens(t *testing.T) { t.Fatal(err) } } + +func TestPrecopyLateGateCallerCannotCrossFreeze(t *testing.T) { + remote := storage.NewMemChunkRemote() + p, view := parkedProvider(t, remote) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + gate := b.(interface { + BeginPrecopyPause(context.Context) (func(), error) + TryStopIO(string) bool + }) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + view.arm() + done := make(chan struct{}) + var writeErr error + t.Cleanup(func() { + view.unpark() + cancel() + _ = b.Close() + select { + case <-done: + case <-time.After(time.Second): + t.Error("late command did not join") + } + }) + go func() { defer close(done); _, writeErr = b.Write(ctx, 4096, block(0x5b)) }() + select { + case <-view.entered: + case <-ctx.Done(): + t.Fatal("late gate not reached") + } + resume, err := gate.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + t.Cleanup(resume) + if !gate.TryStopIO("final pre-copy cut") { + t.Fatal("drained pause failed to commit") + } + view.unpark() + select { + case <-done: + t.Fatalf("late gate crossed frozen admission: %v", writeErr) + case <-time.After(50 * time.Millisecond): + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if headBlock(t, remote, 1)[0] != 0 { + t.Fatal("unadmitted late write reached captured bytes") + } + if err := b.Close(); err != nil { + t.Fatal(err) + } + select { + case <-done: + if !errors.Is(writeErr, frontend.ErrBackendClosed) { + t.Fatal(writeErr) + } + case <-ctx.Done(): + t.Fatal("closed path did not settle late command") + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 93f0a4ef2a..45563ac169 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -335,3 +335,19 @@ func TestPrecopyDetachColdNoopRequiresMeasuredCASCost(t *testing.T) { t.Fatalf("measured CAS did not enable empty-tail freeze: report=%+v stopped=%d err=%v", r.Precopy, stopped, err) } } + +func TestPrecopyDrainReceives100MillisecondBound(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 1) + calls := 0 + _, err := l.PrecopyDetachWithAdmission(context.Background(), func(ctx context.Context) (func(), error) { + calls++ + deadline, ok := ctx.Deadline() + if !ok || time.Until(deadline) > 100*time.Millisecond { + t.Fatalf("unbounded pre-copy drain: deadline=%v present=%t", deadline, ok) + } + return nil, errors.New("controlled drain refusal") + }, func() bool { t.Error("refused drain committed freeze"); return true }) + if calls == 0 || !errors.Is(err, ErrPrecopyNotConverged) { + t.Fatalf("calls=%d err=%v", calls, err) + } +} From 1e2b792f49379a381a53f10d69581e28de75d494 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:27:02 -0800 Subject: [PATCH 35/59] docs: align pre-copy invariant with bounded admission drain --- seaweed-block/docs/design/invariants.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a4e22a1c18..c208b6d76f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -199,7 +199,7 @@ stateDiagram-v2 Admit --> Refused: budget refused, closed, fenced, detached, base install, reconciling, or lineage or lease invalid Admit --> Stage: budget admitted, earlier unknown CAS settled Stage --> Quiesce: spill-budget remainder reached or no shrink - Quiesce --> FinalFreeze: opt-in pre-copy fits and frontend already drained + Quiesce --> FinalFreeze: opt-in measured tail fits after bounded admission drain FinalFreeze --> OpenWindow: admission stays closed through detached settlement Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier OpenWindow --> Copy: release barrier @@ -226,9 +226,9 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | -| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-PRECOPY-001` | Opt-in final-tail admission uses authoritative barrier candidates; a busy frontend or nonconvergence never stops service. Aborted rounds keep dirty bytes, and only settled final detached publication permits handoff. Latency estimates are measured goals, not worst-case proofs. | M5 Quiesce -> ordinary COW round or FinalFreeze | `chunk_precopy.go`; `storage_adapter.go` `TryStopIO`; `provider_chunk.go` `DetachVolume` | `TestPrecopyDetachConvergesBeforeStoppingIO`, `TestPrecopyDetachUnsettledRoundsKeepDirtyBytes`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachCountsBurstAtNextBarrier`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyFreezeDoesNotWaitForAdmittedIO` | Deterministic caller controls; measured latency is not a model proof | ACTIVE | -| `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | -| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; barrier candidates and recent measured costs admit the final cut only after a nonblocking frontend drain check, otherwise service stays live | `chunk_precopy.go` `PrecopyDetach`; `StorageBackend.TryStopIO`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | +| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | | Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | @@ -464,6 +464,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO and terminal stops never issue queued storage work. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From 5de43e8703a0f95730d2626d40b3e1d2311389a7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:57:59 -0800 Subject: [PATCH 36/59] test(storage): prove admission drains before the capture barrier --- .../core/storage/chunk_precopy_detach_test.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 45563ac169..ffcedf81ed 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -351,3 +351,43 @@ func TestPrecopyDrainReceives100MillisecondBound(t *testing.T) { t.Fatalf("calls=%d err=%v", calls, err) } } + +func TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier(t *testing.T) { + s, f, l, _ := precopyLayer(t, 1024, 3) + written := make(chan error, 1) + started, timedOut := false, false + t.Cleanup(func() { + if !started { + return + } + select { + case <-written: + case <-time.After(3 * time.Second): + t.Error("admitted writer did not join") + } + }) + r, err := l.PrecopyDetachWithAdmission(ctTimeout(t), func(ctx context.Context) (func(), error) { + if started { + return func() {}, nil + } + started = true + go func() { + _, err := s.Write(2, makeBlock(ctBlockSize, 0xa7)) + written <- err + }() + select { + case err := <-written: + written <- err // retain the completion for the cleanup join + return func() {}, err + case <-ctx.Done(): + timedOut = true + return nil, ctx.Err() + } + }, func() bool { return true }) + if timedOut || err != nil || !r.Precopy.Frozen || r.Precopy.Attempts != 1 { + t.Fatalf("drain blocked admitted writer: timed_out=%t report=%+v err=%v", timedOut, r.Precopy, err) + } + if !bytes.Equal(f.imageOf(t, r.Head)[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0xa7)) { + t.Fatal("authoritative barrier omitted the drained writer") + } +} From f2f6f1f2d8f0311911889ad2e103fa5d809d60e1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:59:31 -0800 Subject: [PATCH 37/59] test(storage): isolate drain lock ordering from sample warmup --- seaweed-block/core/storage/chunk_precopy_detach_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index ffcedf81ed..fe91c09bd2 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -384,7 +384,7 @@ func TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier(t *testing.T) { return nil, ctx.Err() } }, func() bool { return true }) - if timedOut || err != nil || !r.Precopy.Frozen || r.Precopy.Attempts != 1 { + if timedOut || err != nil || !r.Precopy.Frozen { t.Fatalf("drain blocked admitted writer: timed_out=%t report=%+v err=%v", timedOut, r.Precopy, err) } if !bytes.Equal(f.imageOf(t, r.Head)[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0xa7)) { From 26dda9cf5680d1a48a65f0dbe5968efa304c3592 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:05:17 -0800 Subject: [PATCH 38/59] test(durable): reproduce cold convergence and post-cut host drain completions --- .../frontend/durable/precopy_fifo_test.go | 37 +++++++++++++++++++ .../durable/precopy_fifty_iops_test.go | 11 +++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go index d36087e436..dbabccd991 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifo_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -46,6 +46,43 @@ func precopyMemoryBackend(t *testing.T) *StorageBackend { return b } +func TestPrecopyHostDrainDoesNotCompleteHeldGuestIO(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + queued, done := make(chan struct{}), make(chan struct{}) + b.testPrecopyQueued = func() { close(queued) } + var result error + t.Cleanup(func() { + cancel() + _ = b.Close() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("held command did not join") + } + }) + if !b.TryStopIO("final detached cut") { + t.Fatal("freeze failed") + } + go func() { + defer close(done) + _, result = b.Write(ctx, 0, make([]byte, 4096)) + }() + select { + case <-queued: + case <-ctx.Done(): + t.Fatal("command did not enter the freeze queue") + } + if err := b.StopIO(ctx, "workspace lease fenced"); err != nil { + t.Fatal(err) + } + select { + case <-done: + t.Fatalf("host drain completed held guest I/O before old path teardown: %v", result) + case <-time.After(80 * time.Millisecond): + } +} + func TestPrecopyQueueResumesInFIFOOrder(t *testing.T) { b := precopyMemoryBackend(t) ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 519193c7bf..81bb1f470f 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -18,6 +18,15 @@ import ( // peer reply is held until a separate control probe witnesses closed admission, // then released after20ms. This is a forced schedule, not physical NVMe proof. func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { + precopyFiftyIOPS(t, 3) +} + +func TestPrecopyFiftyIOPSOnePriorSampleConvergesFirstAttempt(t *testing.T) { + precopyFiftyIOPS(t, 1) +} + +func precopyFiftyIOPS(t *testing.T, samples byte) { + t.Helper() remote := storage.NewMemChunkRemote() p := precopyProvider(t, remote, &parkView{stubView: v1View()}) openRecovered(t, p) @@ -25,7 +34,7 @@ func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { if err != nil { t.Fatal(err) } - for i := byte(1); i <= 3; i++ { + for i := byte(1); i <= samples; i++ { if _, err := backend.Write(context.Background(), 4096, block(i)); err != nil { t.Fatal(err) } From 78c90bc9b5817260b23f131a9aff253651a226bf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:07:31 -0800 Subject: [PATCH 39/59] fix(durable): retain frozen commands through the host drain --- .../durable/precopy_fifty_iops_test.go | 17 +++++++++++++---- .../core/frontend/durable/precopy_wait_test.go | 18 ++++++++++-------- .../core/frontend/durable/storage_adapter.go | 7 ++++++- 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 81bb1f470f..7cdc1b4721 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -18,14 +18,14 @@ import ( // peer reply is held until a separate control probe witnesses closed admission, // then released after20ms. This is a forced schedule, not physical NVMe proof. func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { - precopyFiftyIOPS(t, 3) + precopyFiftyIOPS(t, 3, false) } -func TestPrecopyFiftyIOPSOnePriorSampleConvergesFirstAttempt(t *testing.T) { - precopyFiftyIOPS(t, 1) +func TestPrecopyFiftyIOPSUnknownCostKeepsServing(t *testing.T) { + precopyFiftyIOPS(t, 1, true) } -func precopyFiftyIOPS(t *testing.T, samples byte) { +func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { t.Helper() remote := storage.NewMemChunkRemote() p := precopyProvider(t, remote, &parkView{stubView: v1View()}) @@ -131,6 +131,15 @@ func precopyFiftyIOPS(t *testing.T, samples byte) { result, _, err := p.DetachVolume(ctx, "v1") stopped.Store(true) t.Logf("attempts=%d drain=%s estimate=%s frozen=%t guest_errors=%d", result.Precopy.Attempts, result.Precopy.Drain, result.Precopy.Estimate, result.Precopy.Frozen, guestErrors.Load()) + if wantUnknown { + if !errors.Is(err, storage.ErrPrecopyUnknown) || result.Precopy.Frozen || guestErrors.Load() != 0 { + t.Fatalf("unknown cost did not preserve live service: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) + } + if _, err := backend.Write(ctx, 12288, block(0x7d)); err != nil { + t.Fatal("unknown-cost refusal stopped the frontend:", err) + } + return + } if err != nil || !result.Precopy.Frozen || result.Precopy.Attempts != 1 { t.Fatalf("50IOPS cutover: report=%+v err=%v", result.Precopy, err) } diff --git a/seaweed-block/core/frontend/durable/precopy_wait_test.go b/seaweed-block/core/frontend/durable/precopy_wait_test.go index 549506474f..e6786b8ce2 100644 --- a/seaweed-block/core/frontend/durable/precopy_wait_test.go +++ b/seaweed-block/core/frontend/durable/precopy_wait_test.go @@ -138,18 +138,20 @@ func TestPrecopyFreezeTerminalStopWakesQueuedIO(t *testing.T) { t.Fatalf("command escaped freeze: %v", result) case <-time.After(30 * time.Millisecond): } - want := frontend.ErrNotReady - if terminal == "close" { - want = frontend.ErrBackendClosed - if err := b.Close(); err != nil { - t.Fatal(err) - } - } else { + if terminal == "stop" { gate.SetOperational(false, "workspace lease self-fence") + select { + case <-done: + t.Fatalf("host fence completed a held command: %v", result) + case <-time.After(30 * time.Millisecond): + } + } + if err := b.Close(); err != nil { + t.Fatal(err) } select { case <-done: - if !errors.Is(result, want) || errors.Is(result, frontend.ErrBackendBusy) { + if !errors.Is(result, frontend.ErrBackendClosed) || errors.Is(result, frontend.ErrBackendBusy) { t.Fatalf("terminal gate masked: %v", result) } case <-time.After(time.Second): diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index c772c61696..8179bc941e 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -477,7 +477,12 @@ func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { b.opEvidence.Store(evidence) b.operational.Store(ok) b.waitAttachReady = false - b.finishPrecopyLocked(ok) + // A host drain closes storage admission, but is not the old path's + // teardown. Keep a final pre-copy queue parked until Close or its budget; + // publishing readiness loss must not complete commands on that path. + if ok || b.precopy == nil || !b.precopy.active { + b.finishPrecopyLocked(ok) + } b.notifyReadReadyLocked() } From 924d621e5c6cffa1b4f249d9d65ab4d2985389c1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:08:44 -0800 Subject: [PATCH 40/59] test(nvme): require teardown to cancel frozen commands without a CQE --- .../core/frontend/nvme/group_sync_test.go | 7 +- .../nvme/precopy_target_drain_test.go | 65 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/frontend/nvme/precopy_target_drain_test.go diff --git a/seaweed-block/core/frontend/nvme/group_sync_test.go b/seaweed-block/core/frontend/nvme/group_sync_test.go index ef6f6b85ff..36443d560e 100644 --- a/seaweed-block/core/frontend/nvme/group_sync_test.go +++ b/seaweed-block/core/frontend/nvme/group_sync_test.go @@ -48,6 +48,11 @@ func (o *syncPairObserver) Sync(_ context.Context, target uint64) error { } func newSyncPairFixture(t *testing.T, path string) (*storage.WALStore, *durable.StorageBackend, *nvmeClient) { + s, b, c, _ := newSyncPairTargetFixture(t, path) + return s, b, c +} + +func newSyncPairTargetFixture(t *testing.T, path string) (*storage.WALStore, *durable.StorageBackend, *nvmeClient, *nvme.Target) { t.Helper() id := frontend.Identity{VolumeID: strings.TrimSuffix(filepath.Base(path), ".bin"), ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} provider, err := durable.NewDurableProvider(durable.ProviderConfig{ @@ -78,7 +83,7 @@ func newSyncPairFixture(t *testing.T, path string) (*storage.WALStore, *durable. if err := c.io.SetDeadline(time.Now().Add(15 * time.Second)); err != nil { t.Fatal(err) } - return s, backend, c + return s, backend, c, tg } func syncPairFlush(t *testing.T, c *nvmeClient, cid uint16) uint16 { t.Helper() diff --git a/seaweed-block/core/frontend/nvme/precopy_target_drain_test.go b/seaweed-block/core/frontend/nvme/precopy_target_drain_test.go new file mode 100644 index 0000000000..7a8e0a37e8 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/precopy_target_drain_test.go @@ -0,0 +1,65 @@ +package nvme_test + +import ( + "context" + "errors" + "net" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +func TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion(t *testing.T) { + _, backend, client, target := newSyncPairTargetFixture(t, filepath.Join(t.TempDir(), "precopy.bin")) + closed := make(chan error, 1) + closing := false + t.Cleanup(func() { + _ = backend.Close() + if closing { + select { + case <-closed: + case <-time.After(3 * time.Second): + t.Error("target close did not join") + } + } + }) + if !backend.TryStopIO("final detached cut") { + t.Fatal("freeze failed") + } + cmd := nvme.CapsuleCommand{OpCode: 0, CID: 77, NSID: 1} + if err := client.ioW.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(2 * time.Second) + for target.Stats().FlushCommands == 0 { + if time.Now().After(deadline) { + t.Fatal("flush did not reach target") + } + time.Sleep(time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if err := backend.StopIO(ctx, "workspace lease fenced"); err != nil { + t.Fatal(err) + } + _ = client.io.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) + _, err := client.ioR.Dequeue() + var ne net.Error + if !errors.As(err, &ne) || !ne.Timeout() { + t.Fatalf("host drain emitted a completion on the held path: %v", err) + } + _ = client.io.SetReadDeadline(time.Time{}) + closing = true + go func() { closed <- target.Close() }() + select { + case err := <-closed: + closing = false + if err != nil { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("target teardown waited for the frozen command budget") + } +} From 83b00b62db1339b37a2179af0b44063f9395f175 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:09:35 -0800 Subject: [PATCH 41/59] fix(nvme): cancel held commands before joining a closed session --- .../core/frontend/durable/precopy_fifty_iops_test.go | 12 ++++++++++-- seaweed-block/core/frontend/nvme/session.go | 5 +++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 7cdc1b4721..35fbf14223 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -21,7 +21,7 @@ func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { precopyFiftyIOPS(t, 3, false) } -func TestPrecopyFiftyIOPSUnknownCostKeepsServing(t *testing.T) { +func TestPrecopyFiftyIOPSColdCostsDoNotClaimFirstAttempt(t *testing.T) { precopyFiftyIOPS(t, 1, true) } @@ -132,7 +132,15 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { stopped.Store(true) t.Logf("attempts=%d drain=%s estimate=%s frozen=%t guest_errors=%d", result.Precopy.Attempts, result.Precopy.Drain, result.Precopy.Estimate, result.Precopy.Frozen, guestErrors.Load()) if wantUnknown { - if !errors.Is(err, storage.ErrPrecopyUnknown) || result.Precopy.Frozen || guestErrors.Load() != 0 { + if result.Precopy.Frozen { + // Later rolling cuts may leave an empty tail, which needs only a + // measured fixed cost. They must not masquerade as first-round fit. + if err != nil || result.Precopy.Attempts <= 1 || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x5b)) { + t.Fatalf("cold samples claimed premature fit: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) + } + return + } + if !errors.Is(err, storage.ErrPrecopyUnknown) || guestErrors.Load() != 0 { t.Fatalf("unknown cost did not preserve live service: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) } if _, err := backend.Write(ctx, 12288, block(0x7d)); err != nil { diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index 48f76d5210..823f126e62 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -153,6 +153,8 @@ func newSession(conn net.Conn, h *IOHandler, target *Target, expectedSubNQN stri func (s *Session) serve(ctx context.Context) error { defer s.close() + ctx, cancelCommands := context.WithCancel(ctx) + defer cancelCommands() if err := s.handleICReq(); err != nil { return fmt.Errorf("ICReq: %w", err) @@ -168,6 +170,9 @@ func (s *Session) serve(ctx context.Context) error { rxErr := s.rxLoop(ctx) + // The old transport is gone. Unacknowledged commands held by pre-copy + // must stop waiting before we join them; they cannot complete this path. + cancelCommands() s.cmdWg.Wait() close(s.done) txErr := <-txErrCh From fdd23d4efd47b893b20df01e24eb021c4d72f0da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:15:44 -0800 Subject: [PATCH 42/59] test(durable): allow a staged empty tail without upload samples --- .../core/frontend/durable/precopy_fifty_iops_test.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 35fbf14223..488d5b8128 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -21,7 +21,7 @@ func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { precopyFiftyIOPS(t, 3, false) } -func TestPrecopyFiftyIOPSColdCostsDoNotClaimFirstAttempt(t *testing.T) { +func TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest(t *testing.T) { precopyFiftyIOPS(t, 1, true) } @@ -133,9 +133,10 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { t.Logf("attempts=%d drain=%s estimate=%s frozen=%t guest_errors=%d", result.Precopy.Attempts, result.Precopy.Drain, result.Precopy.Estimate, result.Precopy.Frozen, guestErrors.Load()) if wantUnknown { if result.Precopy.Frozen { - // Later rolling cuts may leave an empty tail, which needs only a - // measured fixed cost. They must not masquerade as first-round fit. - if err != nil || result.Precopy.Attempts <= 1 || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x5b)) { + // Staging or later rounds may leave an empty tail, which needs + // only measured fixed cost. A nonempty first tail still needs + // three upload samples; the one-sample fixture cannot supply them. + if err != nil || (result.Precopy.Attempts == 1 && result.Precopy.TailBytes != 0) || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x5b)) { t.Fatalf("cold samples claimed premature fit: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) } return From 14cd10d361d0d2578f2f4db59bfe57fcafd82dde Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:16:09 -0800 Subject: [PATCH 43/59] docs: pin held-command lifetime through host and transport drain --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c208b6d76f..62b688f5a0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -229,6 +229,7 @@ stateDiagram-v2 | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | +| Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | | Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | @@ -464,7 +465,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO and terminal stops never issue queued storage work. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From 1aa87c60d3cdda0d1b4138fad525c51cff0ab28c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:26:09 -0800 Subject: [PATCH 44/59] test(durable): require diagnostics for every pre-copy drain attempt --- .../durable/provider_chunk_precopy_test.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index ab64579e83..31507e9d9b 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -5,6 +5,8 @@ import ( "context" "errors" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "strconv" + "strings" "sync" "testing" "time" @@ -159,10 +161,34 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() + logs := &lockedLog{} + captureWriteLogs(t, logs) r, _, err := p.DetachVolume(ctx, "v1") if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen { t.Fatalf("report=%+v err=%v", r.Precopy, err) } + lines := 0 + for _, line := range strings.Split(logs.String(), "\n") { + if !strings.Contains(line, "durable: pre-copy attempt ") { + continue + } + lines++ + fields := map[string]string{} + for _, token := range strings.Fields(line) { + if key, value, ok := strings.Cut(token, "="); ok { + fields[key] = value + } + } + drain, de := strconv.ParseFloat(fields["drain_ms"], 64) + barrier, be := strconv.ParseFloat(fields["barrier_ms"], 64) + pause, pe := strconv.ParseFloat(fields["pause_ms"], 64) + if fields["attempt"] != strconv.Itoa(lines) || fields["reason"] != "drain_timeout" || fields["volume"] != "v1" || de != nil || be != nil || pe != nil || drain <= 0 || barrier < 0 || pause < drain { + t.Fatalf("incomplete pre-copy attempt diagnostic: %s", line) + } + } + if lines != r.Precopy.Attempts { + t.Fatalf("pre-copy attempt diagnostics missing: got %d, want %d", lines, r.Precopy.Attempts) + } if started, resumed := k.calls(); len(started) != 1 || len(resumed) != 1 { t.Fatalf("nonconverged hooks: started=%v resumed=%v", started, resumed) } From 0141be5aafb2d770b5d5a8948bb05c538f1d2da9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:27:14 -0800 Subject: [PATCH 45/59] feat(storage): report each pre-copy admission attempt outside the barrier --- .../core/frontend/durable/provider_chunk.go | 4 ++ seaweed-block/core/storage/chunk_precopy.go | 71 ++++++++++++++----- .../core/storage/chunk_precopy_detach_test.go | 25 +++++++ 3 files changed, 81 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 9663bf89ce..68a7675f58 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -952,6 +952,10 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st beginFreeze() return true }) + // Log only after capture releases its barrier; at most five records. + for _, a := range r.Precopy.Rounds { + log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, a.Error) + } log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) if err == nil { if !start.IsZero() { diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 3b35e301a9..4bd2194e51 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -26,26 +26,41 @@ type precopySample struct { rate float64 } +type PrecopyAttempt struct { + Attempt int `json:"attempt"` + Drain time.Duration `json:"drainNs"` + Barrier time.Duration `json:"barrierNs"` + Pause time.Duration `json:"pauseNs"` + TailBytes uint64 `json:"tailBytes"` + RateSamples int `json:"rateSamples"` + Estimate time.Duration `json:"estimateNs"` + Reason string `json:"reason"` + Frozen bool `json:"frozen"` + Error string `json:"error,omitempty"` +} + // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { - Drain time.Duration `json:"drainNs"` - DrainTimedOut bool `json:"drainTimedOut"` - Attempts int `json:"attempts"` - TailBytes uint64 `json:"tailBytes"` - Fixed time.Duration `json:"fixedNs"` - Estimate time.Duration `json:"estimateNs"` - SampleAge time.Duration `json:"sampleAgeNs"` - BytesPerSecond float64 `json:"bytesPerSecond"` - Reason string `json:"reason"` - Frozen bool `json:"frozen"` - FreezeElapsed time.Duration `json:"freezeElapsedNs"` - ExtraCASAttempts uint64 `json:"extraCASAttempts"` - CASFailureTimeout time.Duration `json:"casFailureTimeoutNs"` - DeclaredWorst time.Duration `json:"declaredWorstNs"` - LatencyGateFailed bool `json:"latencyGateFailed"` - BarrierBeforeFreeze time.Duration `json:"barrierBeforeFreezeNs"` - TentativePauseTotal time.Duration `json:"tentativePauseTotalNs"` - LongestTentativePause time.Duration `json:"longestTentativePauseNs"` + Rounds []PrecopyAttempt `json:"rounds,omitempty"` + Drain time.Duration `json:"drainNs"` + DrainTimedOut bool `json:"drainTimedOut"` + Attempts int `json:"attempts"` + TailBytes uint64 `json:"tailBytes"` + Fixed time.Duration `json:"fixedNs"` + Estimate time.Duration `json:"estimateNs"` + SampleAge time.Duration `json:"sampleAgeNs"` + BytesPerSecond float64 `json:"bytesPerSecond"` + RateSamples int `json:"rateSamples"` + Reason string `json:"reason"` + Frozen bool `json:"frozen"` + FreezeElapsed time.Duration `json:"freezeElapsedNs"` + ExtraCASAttempts uint64 `json:"extraCASAttempts"` + CASFailureTimeout time.Duration `json:"casFailureTimeoutNs"` + DeclaredWorst time.Duration `json:"declaredWorstNs"` + LatencyGateFailed bool `json:"latencyGateFailed"` + BarrierBeforeFreeze time.Duration `json:"barrierBeforeFreezeNs"` + TentativePauseTotal time.Duration `json:"tentativePauseTotalNs"` + LongestTentativePause time.Duration `json:"longestTentativePauseNs"` } // Finish records the whole freeze, including any owner-driven settlement. @@ -98,6 +113,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context var pauseTotal, longestPause time.Duration var drain time.Duration var drainErr error + var rounds []PrecopyAttempt if prepare != nil { l.precopyPrepare = func(ctx context.Context) (func(), error) { dc, cancel := context.WithTimeout(ctx, precopyDrainBound) @@ -148,11 +164,27 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() for attempt := 1; attempt <= precopyAttempts; attempt++ { - report.Attempts = attempt + report = PrecopyReport{Attempts: attempt, Rounds: rounds} + drain, drainErr = 0, nil if err := ctx.Err(); err != nil { return ChunkCutResult{Precopy: report}, err } + pauseBefore := pauseTotal r, err := l.captureLocked(ctx, false) + a := PrecopyAttempt{ + Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, + TailBytes: report.TailBytes, RateSamples: report.RateSamples, + Estimate: report.Estimate, Reason: report.Reason, Frozen: report.Frozen, + } + a.Barrier = max(time.Duration(0), a.Pause-a.Drain) + if a.Reason == "" { + a.Reason = "before_barrier" + } + if err != nil { + a.Error = err.Error() + } + rounds = append(rounds, a) + report.Rounds = rounds report.TentativePauseTotal, report.LongestTentativePause = pauseTotal, longestPause r.Precopy = report if errors.Is(err, errChunkLayerDetached) { @@ -209,6 +241,7 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor rates = append(rates, s.rate) } } + r.RateSamples = len(rates) if r.Fixed <= 0 { return r } diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index fe91c09bd2..74d07fef4a 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -391,3 +391,28 @@ func TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier(t *testing.T) { t.Fatal("authoritative barrier omitted the drained writer") } } + +func TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + calls := 0 + r, err := l.PrecopyDetachWithAdmission(ctTimeout(t), func(ctx context.Context) (func(), error) { + calls++ + if calls == 1 { + <-ctx.Done() + return nil, ctx.Err() + } + return func() {}, nil + }, func() bool { return true }) + if err != nil || len(r.Precopy.Rounds) != 2 { + t.Fatalf("rounds=%+v err=%v", r.Precopy.Rounds, err) + } + first, second := r.Precopy.Rounds[0], r.Precopy.Rounds[1] + if first.Attempt != 1 || first.Reason != "drain_timeout" || first.Frozen || second.Attempt != 2 || second.Reason != "fit" || !second.Frozen { + t.Fatalf("attempt outcomes mixed: first=%+v second=%+v", first, second) + } + for _, a := range r.Precopy.Rounds { + if a.Drain <= 0 || a.Pause < a.Drain || a.Barrier != a.Pause-a.Drain { + t.Fatalf("pause accounting: %+v", a) + } + } +} From 68d8cabada9c3f6624c512d759bbd1600ed2db30 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:40:14 -0800 Subject: [PATCH 46/59] test(storage): distinguish warm attempts from measurement rounds --- .../core/storage/chunk_precopy_detach_test.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 74d07fef4a..07c1006ea7 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "context" + "encoding/json" "errors" "path/filepath" "testing" @@ -416,3 +417,35 @@ func TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit(t *testing.T) { } } } + +func TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds(t *testing.T) { + for _, warm := range []bool{false, true} { + t.Run(map[bool]string{false: "cold", true: "warm"}[warm], func(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + l.precopySamples = nil + if warm { + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: 1 << 30}) + } + } + r, _ := l.PrecopyDetachWithAdmission(ctTimeout(t), func(context.Context) (func(), error) { + return nil, errors.New("controlled admission refusal") + }, func() bool { t.Fatal("refused admission froze"); return false }) + data, err := json.Marshal(r.Precopy) + if err != nil { + t.Fatal(err) + } + var fields map[string]any + if err := json.Unmarshal(data, &fields); err != nil { + t.Fatal(err) + } + wantSamples, wantAttempts, wantMeasurement := float64(0), float64(0), float64(5) + if warm { + wantSamples, wantAttempts, wantMeasurement = 3, 5, 0 + } + if fields["samplesAtStart"] != wantSamples || fields["attempts"] != wantAttempts || fields["measurementRounds"] != wantMeasurement || len(r.Precopy.Rounds) != 5 { + t.Fatalf("warm=%t report=%s", warm, data) + } + }) + } +} From 6c17c0c9016f64259e8f53f5af70e17da6ef8acb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:41:24 -0800 Subject: [PATCH 47/59] storage: report warm pre-copy attempts separately from sampling rounds --- .../frontend/durable/precopy_fifty_iops_test.go | 4 ++-- .../core/frontend/durable/provider_chunk.go | 2 +- .../durable/provider_chunk_precopy_test.go | 4 ++-- seaweed-block/core/storage/chunk_precopy.go | 15 ++++++++++++++- .../core/storage/chunk_precopy_detach_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 6 files changed, 21 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 488d5b8128..c25cbd4a02 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -130,13 +130,13 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { }() result, _, err := p.DetachVolume(ctx, "v1") stopped.Store(true) - t.Logf("attempts=%d drain=%s estimate=%s frozen=%t guest_errors=%d", result.Precopy.Attempts, result.Precopy.Drain, result.Precopy.Estimate, result.Precopy.Frozen, guestErrors.Load()) + t.Logf("attempts=%d measurement_rounds=%d samples_at_start=%d drain=%s estimate=%s frozen=%t guest_errors=%d", result.Precopy.Attempts, result.Precopy.MeasurementRounds, result.Precopy.SamplesAtStart, result.Precopy.Drain, result.Precopy.Estimate, result.Precopy.Frozen, guestErrors.Load()) if wantUnknown { if result.Precopy.Frozen { // Staging or later rounds may leave an empty tail, which needs // only measured fixed cost. A nonempty first tail still needs // three upload samples; the one-sample fixture cannot supply them. - if err != nil || (result.Precopy.Attempts == 1 && result.Precopy.TailBytes != 0) || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x5b)) { + if err != nil || (len(result.Precopy.Rounds) == 1 && result.Precopy.TailBytes != 0) || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x5b)) { t.Fatalf("cold samples claimed premature fit: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) } return diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 68a7675f58..615c15141c 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -956,7 +956,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st for _, a := range r.Precopy.Rounds { log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, a.Error) } - log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) + log.Printf("durable: pre-copy volume=%s attempts=%d measurement_rounds=%d samples_at_start=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.MeasurementRounds, r.Precopy.SamplesAtStart, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) if err == nil { if !start.IsZero() { r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, 0, false) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 31507e9d9b..afd040af33 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -186,8 +186,8 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { t.Fatalf("incomplete pre-copy attempt diagnostic: %s", line) } } - if lines != r.Precopy.Attempts { - t.Fatalf("pre-copy attempt diagnostics missing: got %d, want %d", lines, r.Precopy.Attempts) + if lines != len(r.Precopy.Rounds) || lines != r.Precopy.Attempts+r.Precopy.MeasurementRounds { + t.Fatalf("pre-copy round diagnostics missing: got %d, report=%+v", lines, r.Precopy) } if started, resumed := k.calls(); len(started) != 1 || len(resumed) != 1 { t.Fatalf("nonconverged hooks: started=%v resumed=%v", started, resumed) diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 4bd2194e51..56bd430b37 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -27,6 +27,7 @@ type precopySample struct { } type PrecopyAttempt struct { + // Attempt is the physical round ordinal, including measurement rounds. Attempt int `json:"attempt"` Drain time.Duration `json:"drainNs"` Barrier time.Duration `json:"barrierNs"` @@ -45,6 +46,8 @@ type PrecopyReport struct { Drain time.Duration `json:"drainNs"` DrainTimedOut bool `json:"drainTimedOut"` Attempts int `json:"attempts"` + MeasurementRounds int `json:"measurementRounds"` + SamplesAtStart int `json:"samplesAtStart"` TailBytes uint64 `json:"tailBytes"` Fixed time.Duration `json:"fixedNs"` Estimate time.Duration `json:"estimateNs"` @@ -114,6 +117,8 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context var drain time.Duration var drainErr error var rounds []PrecopyAttempt + samplesAtStart := l.precopyEstimate(0, 0).RateSamples + warmAttempts, measurementRounds := 0, 0 if prepare != nil { l.precopyPrepare = func(ctx context.Context) (func(), error) { dc, cancel := context.WithTimeout(ctx, precopyDrainBound) @@ -164,13 +169,21 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() for attempt := 1; attempt <= precopyAttempts; attempt++ { - report = PrecopyReport{Attempts: attempt, Rounds: rounds} + // Measurement rounds still consume the same five-round/60s budget. + // Count an admission attempt only with a warm rate window at entry. + if l.precopyEstimate(0, 0).RateSamples >= 3 { + warmAttempts++ + } else { + measurementRounds++ + } + report = PrecopyReport{Attempts: warmAttempts, Rounds: rounds, SamplesAtStart: samplesAtStart, MeasurementRounds: measurementRounds} drain, drainErr = 0, nil if err := ctx.Err(); err != nil { return ChunkCutResult{Precopy: report}, err } pauseBefore := pauseTotal r, err := l.captureLocked(ctx, false) + report.SamplesAtStart, report.MeasurementRounds = samplesAtStart, measurementRounds a := PrecopyAttempt{ Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, TailBytes: report.TailBytes, RateSamples: report.RateSamples, diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 07c1006ea7..db98a782f5 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -77,7 +77,7 @@ func TestPrecopyDetachBusyOwnerExhaustsWithoutStopping(t *testing.T) { s, f, l, _ := precopyLayer(t, 1024, 1) calls := 0 r, err := l.PrecopyDetach(ctTimeout(t), func() bool { calls++; return false }) - if !errors.Is(err, ErrPrecopyNotConverged) || r.Precopy.Attempts != 5 || r.Precopy.Frozen || calls == 0 { + if !errors.Is(err, ErrPrecopyNotConverged) || len(r.Precopy.Rounds) != 5 || r.Precopy.Frozen || calls == 0 { t.Fatalf("report=%+v calls=%d err=%v", r.Precopy, calls, err) } if f.stats().head.State == ChunkHeadDetached { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 62b688f5a0..2bcdc8a2be 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -465,7 +465,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From f6995c899a8ee91226b4d9d90771e1e382b5f3ff Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:43:53 -0800 Subject: [PATCH 48/59] test(durable): reproduce retained slow-cost refusal after busy owner release --- .../durable/provider_chunk_precopy_test.go | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 31507e9d9b..4c62b1aa54 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -117,8 +118,35 @@ func TestPrecopyProviderPublishesExactDetachedImage(t *testing.T) { } } +type precopyFixedSampleRemote struct { + *storage.MemChunkRemote + nextDelay atomic.Int64 +} + +func (r *precopyFixedSampleRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if delay := time.Duration(r.nextDelay.Swap(0)); delay > 0 { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + return 0, ctx.Err() + } + } + return r.MemChunkRemote.CASHead(ctx, expected, next) +} + func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { - remote := storage.NewMemChunkRemote() + precopyBusyOwnerKeepsServing(t, 0) +} + +func TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample(t *testing.T) { + precopyBusyOwnerKeepsServing(t, 1300*time.Millisecond) +} + +func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { + t.Helper() + remote := &precopyFixedSampleRemote{MemChunkRemote: storage.NewMemChunkRemote()} view := &parkView{stubView: v1View()} k := &detachHooks{} p := precopyProvider(t, remote, view, k) @@ -159,6 +187,7 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("write not admitted") } + remote.nextDelay.Store(int64(delay)) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() logs := &lockedLog{} @@ -215,7 +244,7 @@ func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { if started, resumed := k.calls(); len(started) != 2 || len(resumed) != 1 { t.Fatalf("successful retry hooks: started=%v resumed=%v", started, resumed) } - if !bytes.Equal(headBlock(t, remote, 1), block(0x8a)) || !bytes.Equal(headBlock(t, remote, 2), block(0x9b)) { + if !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x8a)) || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 2), block(0x9b)) { t.Fatal("retry lost admitted bytes") } } From 2639a1e6c4c6b65a6a69376ce3128f609a42886e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:46:07 -0800 Subject: [PATCH 49/59] fix(durable): preserve measured retry refusal and timestamp completed I/O stops --- seaweed-block/cmd/blockvolume/main.go | 1 + .../core/frontend/durable/provider_chunk.go | 9 ++++++- .../durable/provider_chunk_precopy_test.go | 24 ++++++++++++++++--- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 9514710a1e..66e0be8221 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1258,6 +1258,7 @@ func run(f flags) int { var drainErr error if leaseStop != nil && durableProv != nil { drainErr = durableProv.Backend(f.volumeID).StopIO(leaseStop.ctx, "workspace lease fenced") + fmt.Fprintf(os.Stderr, "blockvolume: stop volume=%s stop_io_returned_at=%s\n", f.volumeID, time.Now().UTC().Format(time.RFC3339Nano)) } h.SetFrontendTargets(nil) // The ublk device drains with the other frontends: its Close (STOP_DEV, diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 68a7675f58..a1e835207b 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -933,6 +933,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } var r storage.ChunkCutResult + var stopIOReturned time.Time if p.cfg.ChunkDetachPrecopy { owner, ok := layer.(interface { PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) @@ -948,6 +949,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } + stopIOReturned = time.Now() h.chunkDetach = true beginFreeze() return true @@ -956,7 +958,11 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st for _, a := range r.Precopy.Rounds { log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, a.Error) } - log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) + stopAt := "none" + if !stopIOReturned.IsZero() { + stopAt = stopIOReturned.UTC().Format(time.RFC3339Nano) + } + log.Printf("durable: pre-copy volume=%s attempts=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s stop_io_returned_at=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, stopAt, err) if err == nil { if !start.IsZero() { r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, 0, false) @@ -989,6 +995,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } else { err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") } + log.Printf("durable: stop volume=%s stop_io_returned_at=%s", volumeID, time.Now().UTC().Format(time.RFC3339Nano)) if err == nil { p.stopChunkLoop(h) if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil { diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 4c62b1aa54..131b3312ae 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -238,11 +238,29 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { t.Fatal("held write did not finish") } r, _, err = p.DetachVolume(ctx, "v1") + resumedCount := 1 if err != nil { - t.Fatal(err) + // Releasing the owner does not erase a slow sample. Admission must + // still refuse a measured final cut above its unchanged 1.2s allowance. + if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen || r.Precopy.Estimate <= 1200*time.Millisecond || (r.Precopy.Reason != "tail_too_large" && r.Precopy.Reason != "barrier_over_budget") { + t.Fatalf("post-release retry violated measured admission: report=%+v err=%v", r.Precopy, err) + } + if delay > 0 && r.Precopy.Fixed < delay { + t.Fatal("retry forgot the controlled slow fixed sample") + } + resumedCount = 2 + if h, e := remote.GetHead(ctx); e != nil || h.State == storage.ChunkHeadDetached { + t.Fatalf("over-budget retry detached: head=%+v err=%v", h, e) + } + buf := make([]byte, 4096) + if n, e := b.Read(ctx, 8192, buf); e != nil || n != len(buf) || !bytes.Equal(buf, block(0x9b)) { + t.Fatalf("over-budget retry failed to resume service: n=%d err=%v", n, e) + } + } else if delay > 0 { + t.Fatal("retry froze despite a retained fixed sample above the allowance") } - if started, resumed := k.calls(); len(started) != 2 || len(resumed) != 1 { - t.Fatalf("successful retry hooks: started=%v resumed=%v", started, resumed) + if started, resumed := k.calls(); len(started) != 2 || len(resumed) != resumedCount { + t.Fatalf("retry hooks: started=%v resumed=%v", started, resumed) } if !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x8a)) || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 2), block(0x9b)) { t.Fatal("retry lost admitted bytes") diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 62b688f5a0..68e9e298e9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -465,7 +465,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From 9972bfb70c7e376ef68460810e5da7a1810c1691 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:52:50 -0800 Subject: [PATCH 50/59] test(durable): allow the serving phase its pre-copy operation deadline --- .../core/frontend/durable/provider_chunk_precopy_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 4ffe3845dd..510c3f43af 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -188,7 +188,9 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { t.Fatal("write not admitted") } remote.nextDelay.Store(int64(delay)) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Rolling cuts run while serving and have a 60s operation budget. + // The drain and frozen admission bounds are checked independently. + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() logs := &lockedLog{} captureWriteLogs(t, logs) From e62b039cd71bfe21f3cfd559ee65b717a62dc957 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:54:17 -0800 Subject: [PATCH 51/59] test(durable): witness StopIO return before final HEAD publication --- .../durable/precopy_stop_boundary_test.go | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go diff --git a/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go b/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go new file mode 100644 index 0000000000..fbd8bb9a41 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go @@ -0,0 +1,90 @@ +package durable_test + +import ( + "context" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type stopBoundaryRemote struct { + storage.ChunkRemote + entered chan time.Time + release chan struct{} +} + +func (r *stopBoundaryRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if next.State == storage.ChunkHeadDetached { + r.entered <- time.Now() + select { + case <-r.release: + case <-ctx.Done(): + return 0, ctx.Err() + } + } + return r.ChunkRemote.CASHead(ctx, expected, next) +} + +func TestPrecopyStopIOReturnTimestampPrecedesFinalPublication(t *testing.T) { + r := &stopBoundaryRemote{ChunkRemote: storage.NewMemChunkRemote(), entered: make(chan time.Time, 1), release: make(chan struct{})} + p := precopyProvider(t, r, &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(0x67)); err != nil { + t.Fatal(err) + } + logs := &lockedLog{} + captureWriteLogs(t, logs) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + done := make(chan error, 1) + var once sync.Once + release := func() { once.Do(func() { close(r.release) }) } + t.Cleanup(func() { + release() + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("detach did not join") + } + }) + started := time.Now() + go func() { _, _, err := p.DetachVolume(ctx, "v1"); done <- err }() + var beforePublication time.Time + select { + case beforePublication = <-r.entered: + case <-ctx.Done(): + t.Fatal("final publication never entered") + } + release() + select { + case err := <-done: + done <- err + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("detach did not finish") + } + count := 0 + for _, line := range strings.Split(logs.String(), "\n") { + _, stamp, ok := strings.Cut(line, "volume=v1 StopIO returned at ") + if !ok { + continue + } + count++ + at, err := time.Parse(time.RFC3339Nano, stamp) + if err != nil || at.Before(started) || at.After(beforePublication) { + t.Fatalf("StopIO timestamp is not its return boundary: stamp=%q started=%s finalCAS=%s err=%v", stamp, started, beforePublication, err) + } + } + if count != 1 { + t.Fatalf("StopIO returned timestamp count=%d, want 1", count) + } +} From 8f3054f52a61189cea4ff85f6b3f84853313558d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 07:54:51 -0800 Subject: [PATCH 52/59] durable: log precise StopIO return boundary after detach barrier --- seaweed-block/core/frontend/durable/provider_chunk.go | 11 +++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 615c15141c..415d804e56 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -903,6 +903,13 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. var start time.Time + var stopIOReturned time.Time + defer func() { + if !stopIOReturned.IsZero() { + // Emit after the cut releases its barrier, using the actual return time. + log.Printf("durable: volume=%s StopIO returned at %s", volumeID, stopIOReturned.UTC().Format(time.RFC3339Nano)) + } + }() accountCtx, countCAS := storage.WithChunkCASAccounting(ctx) var casAtFreeze uint64 cutCtx, cancel := context.WithCancelCause(accountCtx) @@ -948,6 +955,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } + stopIOReturned = time.Now() h.chunkDetach = true beginFreeze() return true @@ -989,6 +997,9 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } else { err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") } + if err == nil { + stopIOReturned = time.Now() + } if err == nil { p.stopChunkLoop(h) if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2bcdc8a2be..96a2fd65f7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -465,7 +465,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From 5d82c26a0cb91904adf36d836f41b736657780c3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 08:12:03 -0800 Subject: [PATCH 53/59] test(durable): witness pre-copy fallback queue replacement --- .../frontend/durable/precopy_fifo_test.go | 123 ++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 8 +- 2 files changed, 129 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go index dbabccd991..b400374366 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifo_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -253,3 +253,126 @@ func TestPrecopyQueueUsesFiveSecondCutoverBudget(t *testing.T) { t.Fatal("five-second queue budget was not enforced") } } + +// The initial state-lock miss is witnessed while a real pause owns queued I/O. +// Releasing that lock before the fallback must not replace the pause identity. +func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { + for _, terminal := range []bool{false, true} { + name := "resume_fifo" + if terminal { + name = "close" + } + t.Run(name, func(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + queued := make(chan struct{}, 2) + b.testPrecopyQueued = func() { queued <- struct{}{} } + fallback, proceed := make(chan struct{}), make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(proceed) }) } + b.testPrecopyStopFallback = func() { close(fallback); <-proceed } + seen := make(chan byte, 2) + if err := b.SetWriteObserver(precopyQueueObserver{observe: func(v byte) { seen <- v }}); err != nil { + t.Fatal(err) + } + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + results := make(chan error, 2) + stopDone := make(chan bool, 1) + locked := false + t.Cleanup(func() { + if locked { + b.mu.Unlock() + } + release() + cancel() + _ = b.Close() + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("queued writers did not settle") + } + }) + for _, v := range []byte{1, 2} { + wg.Add(1) + go func(v byte) { + defer wg.Done() + _, err := b.Write(ctx, 0, bytes.Repeat([]byte{v}, 4096)) + results <- err + }(v) + select { + case <-queued: + case <-ctx.Done(): + t.Fatal("writer did not queue") + } + } + b.mu.Lock() + locked = true + original, started := b.precopy, b.precopy.started + wg.Add(1) + go func() { defer wg.Done(); stopDone <- b.TryStopIO("final cut") }() + select { + case <-fallback: + case <-ctx.Done(): + t.Fatal("first state lock miss not witnessed") + } + b.mu.Unlock() + locked = false + release() + select { + case <-stopDone: + case <-ctx.Done(): + t.Fatal("fallback did not settle") + } + b.mu.Lock() + same := b.precopy == original && b.precopy.started.Equal(started) && len(b.precopy.waiters) == 2 + b.mu.Unlock() + if !same { + t.Fatal("fallback orphaned the original pause queue or reset its clock") + } + if terminal { + _ = b.Close() + } else { + b.SetOperational(true, "safe abort") + resume() + } + for i := 0; i < 2; i++ { + select { + case err := <-results: + if terminal && !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Close result=%v", err) + } + if !terminal && err != nil { + t.Fatalf("resume result=%v", err) + } + case <-ctx.Done(): + t.Fatal("original queue was unreachable by resume/Close") + } + } + if terminal { + select { + case v := <-seen: + t.Fatalf("closed queue issued write %d", v) + default: + } + } else { + for _, want := range []byte{1, 2} { + select { + case got := <-seen: + if got != want { + t.Fatalf("FIFO got %d want %d", got, want) + } + case <-ctx.Done(): + t.Fatal("missing write") + } + } + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 8179bc941e..7db7ef01e8 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -148,8 +148,9 @@ const maxFullBlockBatchBlocks = 64 type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). - testBeforeIOLock func() - testPrecopyQueued func() // after FIFO registration, outside mu + testBeforeIOLock func() + testPrecopyQueued func() // after FIFO registration, outside mu + testPrecopyStopFallback func() // before fallback lock attempts, outside mu // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() testAfterAttachRefusal func() @@ -510,6 +511,9 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { } b.mu.Unlock() } + if hook := b.testPrecopyStopFallback; hook != nil { + hook() + } if !b.ioMu.TryLock() { return false } From f4ce23ce124332bd84e712fce2e516c43f16fa96 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 08:12:51 -0800 Subject: [PATCH 54/59] fix(durable): preserve queued pause on contended freeze fallback --- seaweed-block/core/frontend/durable/precopy_fifo_test.go | 5 ++++- seaweed-block/core/frontend/durable/storage_adapter.go | 4 +++- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go index b400374366..7b41c5f2fe 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifo_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -326,7 +326,10 @@ func TestPrecopyStopFallbackPreservesQueuedPause(t *testing.T) { locked = false release() select { - case <-stopDone: + case stopped := <-stopDone: + if stopped || !b.operational.Load() { + t.Fatal("fallback did not refuse without changing admission") + } case <-ctx.Done(): t.Fatal("fallback did not settle") } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 7db7ef01e8..d5613d5024 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -522,7 +522,9 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { return false } defer b.mu.Unlock() - if b.closed || !b.operational.Load() { + // State may have changed after the initial mu attempt. An existing pause + // owns its waiters and shared clock; refuse rather than replace it. + if b.precopy != nil || b.closed || !b.operational.Load() { return false } p := &precopyAdmission{active: true, started: time.Now(), drained: make(chan struct{}), drainDone: true} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6a0caa5c86..d3370165d9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -477,7 +477,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From 69cda12786a2d965a863ec118a925f3ad28a1e2a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 08:33:32 -0800 Subject: [PATCH 55/59] test(storage): reproduce slow-sample pre-copy control failures --- .../core/storage/chunk_precopy_detach_test.go | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index db98a782f5..e8bc430fe2 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -74,7 +74,19 @@ func TestPrecopyDetachUnsettledRoundsKeepDirtyBytes(t *testing.T) { } func TestPrecopyDetachBusyOwnerExhaustsWithoutStopping(t *testing.T) { + precopyBusyOwnerControl(t, false) +} + +func TestPrecopyDetachBusyOwnerRetainsSlowFixedCost(t *testing.T) { + precopyBusyOwnerControl(t, true) +} + +func precopyBusyOwnerControl(t *testing.T, slow bool) { + t.Helper() s, f, l, _ := precopyLayer(t, 1024, 1) + if slow { + f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(1300 * time.Millisecond) } + } calls := 0 r, err := l.PrecopyDetach(ctTimeout(t), func() bool { calls++; return false }) if !errors.Is(err, ErrPrecopyNotConverged) || len(r.Precopy.Rounds) != 5 || r.Precopy.Frozen || calls == 0 { @@ -104,7 +116,19 @@ func TestPrecopyDetachCountsBurstAtNextBarrier(t *testing.T) { } func TestPrecopyDetachRefusedFinalCutKeepsChangedBytes(t *testing.T) { + precopyRefusedFinalCutControl(t, false) +} + +func TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost(t *testing.T) { + precopyRefusedFinalCutControl(t, true) +} + +func precopyRefusedFinalCutControl(t *testing.T, slow bool) { + t.Helper() s, f, l, w := precopyLayer(t, 1024, 0) + if slow { + f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(1300 * time.Millisecond) } + } for i := 0; i < 3; i++ { w.write(t, s, 1, byte(0x40+i)) if _, err := l.Cut(ctTimeout(t)); err != nil { From 0fa349c78daf16aea5ef7d69c810a4ebac8d803a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 08:34:54 -0800 Subject: [PATCH 56/59] test(storage): accept measured pre-copy refusals without losing service --- .../core/storage/chunk_precopy_detach_test.go | 56 ++++++++++++++++--- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index e8bc430fe2..e7a8b5dfb6 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -83,21 +83,35 @@ func TestPrecopyDetachBusyOwnerRetainsSlowFixedCost(t *testing.T) { func precopyBusyOwnerControl(t *testing.T, slow bool) { t.Helper() - s, f, l, _ := precopyLayer(t, 1024, 1) + s, f, l, w := precopyLayer(t, 1024, 1) if slow { f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(1300 * time.Millisecond) } } calls := 0 r, err := l.PrecopyDetach(ctTimeout(t), func() bool { calls++; return false }) - if !errors.Is(err, ErrPrecopyNotConverged) || len(r.Precopy.Rounds) != 5 || r.Precopy.Frozen || calls == 0 { + if !errors.Is(err, ErrPrecopyNotConverged) || len(r.Precopy.Rounds) != 5 || r.Precopy.Frozen { t.Fatalf("report=%+v calls=%d err=%v", r.Precopy, calls, err) } - if f.stats().head.State == ChunkHeadDetached { - t.Fatal("busy frontend detached") + if calls == 0 { + assertPrecopyMeasuredRefusal(t, r.Precopy, err) } - if _, err := s.Write(2, makeBlock(ctBlockSize, 0x99)); err != nil { + if slow && (calls != 0 || r.Precopy.Fixed < 1300*time.Millisecond) { + t.Fatalf("slow fixed cost did not refuse before stop: calls=%d report=%+v", calls, r.Precopy) + } + if f.stats().head.State != ChunkHeadActive { + t.Fatal("busy frontend lost its active HEAD") + } + w.write(t, s, 2, 0x99) // The old owner must still serve after either refusal. + r, err = l.Cut(ctTimeout(t)) + if err != nil { t.Fatal(err) } + image := f.imageOf(t, r.Head) + if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x10)) || + !bytes.Equal(image[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0x99)) { + t.Fatal("busy-owner refusal lost existing or resumed-write bytes") + } + assertEveryHeadIsPrefixImage(t, f, w) } func TestPrecopyDetachCountsBurstAtNextBarrier(t *testing.T) { @@ -138,23 +152,47 @@ func precopyRefusedFinalCutControl(t *testing.T, slow bool) { w.write(t, s, 1, 0xbb) f.beforeCAS = func(f *fakeChunkRemote) { f.installLocked(copyHead(f.head)) } r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) - if !r.Precopy.Frozen || !errors.Is(err, ErrChunkHeadPrecondition) { - t.Fatalf("report=%+v err=%v", r.Precopy, err) + if r.Precopy.Frozen { + if !errors.Is(err, ErrChunkHeadPrecondition) { + t.Fatalf("report=%+v err=%v", r.Precopy, err) + } + } else { + assertPrecopyMeasuredRefusal(t, r.Precopy, err) + } + if slow && (r.Precopy.Frozen || r.Precopy.Fixed < 1300*time.Millisecond) { + t.Fatalf("slow fixed cost incorrectly admitted a final cut: report=%+v", r.Precopy) + } + if f.stats().head.State != ChunkHeadActive { + t.Fatal("refused final cut lost its active HEAD") } how, _, err := l.SettleDetach(ctTimeout(t)) if err != nil || how != DetachNotPublished { t.Fatalf("settlement=%v err=%v", how, err) } + w.write(t, s, 2, 0x99) // A safe refusal leaves the old owner serving. r, err = l.Cut(ctTimeout(t)) if err != nil { t.Fatal(err) } - if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0xbb)) { - t.Fatal("refused final cut marked changed bytes clean") + image := f.imageOf(t, r.Head) + if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0xbb)) || + !bytes.Equal(image[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0x99)) { + t.Fatal("refused final cut lost changed or resumed-write bytes") } assertEveryHeadIsPrefixImage(t, f, w) } +// A retained slow observation can refuse admission under load. This is a +// valid outcome only with the exact refusal class, budget and active owner. +func assertPrecopyMeasuredRefusal(t *testing.T, report PrecopyReport, err error) { + t.Helper() + if !errors.Is(err, ErrPrecopyNotConverged) || report.Frozen || + report.Estimate <= 1200*time.Millisecond || + (report.Reason != "tail_too_large" && report.Reason != "barrier_over_budget") { + t.Fatalf("not a valid measured over-budget refusal: report=%+v err=%v", report, err) + } +} + func TestPrecopyDetachSustainedWrapFlushAndFreshRestore(t *testing.T) { makeStore := func(name string) *WALStore { s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), name), ctNumBlocks, ctBlockSize, v3TestWAL, WModeStrict, ctChunkBlocks) From 8b3c48771ce8db36353e834cc6c18cb91b3c967e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 08:35:37 -0800 Subject: [PATCH 57/59] docs: map retained-cost pre-copy regression controls --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d3370165d9..e0f890b7af 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -477,7 +477,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | From 127a122785a2c42d0002d43d4ee4eff8c81b2c8d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 10:13:02 -0800 Subject: [PATCH 58/59] test(storage): reproduce over-budget retry and drain controls --- .../core/storage/chunk_precopy_detach_test.go | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index e7a8b5dfb6..41b33c5fce 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -350,7 +350,19 @@ func TestPrecopyDetachExcludesServingPreparationFromFreezeCost(t *testing.T) { } func TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut(t *testing.T) { + precopyAppliedDetachRetryControl(t, false) +} + +func TestPrecopyDetachAppliedRetryRetainsSlowFixedCost(t *testing.T) { + precopyAppliedDetachRetryControl(t, true) +} + +func precopyAppliedDetachRetryControl(t *testing.T, slow bool) { + t.Helper() _, f, l, _ := precopyLayer(t, 1024, 1) + if slow { + f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(1300 * time.Millisecond) } + } if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } @@ -456,7 +468,23 @@ func TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier(t *testing.T) { } func TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit(t *testing.T) { - _, _, l, _ := precopyLayer(t, 1024, 0) + precopyAttemptDiagnosticsControl(t, false) +} + +func TestPrecopyAttemptDiagnosticsRetainSlowFixedCost(t *testing.T) { + precopyAttemptDiagnosticsControl(t, true) +} + +func precopyAttemptDiagnosticsControl(t *testing.T, slow bool) { + t.Helper() + s, f, l, w := precopyLayer(t, 1024, 0) + if slow { + w.write(t, s, 1, 0x10) + f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(1300 * time.Millisecond) } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + } calls := 0 r, err := l.PrecopyDetachWithAdmission(ctTimeout(t), func(ctx context.Context) (func(), error) { calls++ From 610c39aee951627514f5aaa88de8e88f0e363fe5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 10:14:15 -0800 Subject: [PATCH 59/59] test(storage): distinguish measured refusal in retry and drain controls --- .../core/storage/chunk_precopy_detach_test.go | 63 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 41b33c5fce..7200aff910 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -359,7 +359,7 @@ func TestPrecopyDetachAppliedRetryRetainsSlowFixedCost(t *testing.T) { func precopyAppliedDetachRetryControl(t *testing.T, slow bool) { t.Helper() - _, f, l, _ := precopyLayer(t, 1024, 1) + s, f, l, w := precopyLayer(t, 1024, 1) if slow { f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(1300 * time.Millisecond) } } @@ -369,6 +369,30 @@ func precopyAppliedDetachRetryControl(t *testing.T, slow bool) { f.casModes = []fakeCASMode{casAppliedLost} f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if slow && (r.Precopy.Frozen || r.Precopy.Fixed < 1300*time.Millisecond) { + t.Fatalf("slow retry control bypassed measured admission: report=%+v", r.Precopy) + } + if !r.Precopy.Frozen { + assertPrecopyMeasuredRefusal(t, r.Precopy, err) + if f.stats().head.State != ChunkHeadActive || len(f.casModes) != 1 || f.failGet != nil { + t.Fatal("over-budget refusal issued the final CAS or lost the active owner") + } + // No detach CAS was attempted. Remove its pending fault before checking + // that the old owner can publish an ordinary serving cut. + f.casModes, f.afterCAS = nil, nil + w.write(t, s, 2, 0x99) + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + image := f.imageOf(t, r.Head) + if !bytes.Equal(image[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x10)) || + !bytes.Equal(image[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0x99)) { + t.Fatal("refused applied-retry control lost original or resumed-write bytes") + } + assertEveryHeadIsPrefixImage(t, f, w) + return + } if !r.Precopy.Frozen || !errors.Is(err, ErrChunkCASOutcomeUnknown) { t.Fatalf("first report=%+v err=%v", r.Precopy, err) } @@ -494,13 +518,46 @@ func precopyAttemptDiagnosticsControl(t *testing.T, slow bool) { } return func() {}, nil }, func() bool { return true }) - if err != nil || len(r.Precopy.Rounds) != 2 { + if len(r.Precopy.Rounds) < 2 { t.Fatalf("rounds=%+v err=%v", r.Precopy.Rounds, err) } first, second := r.Precopy.Rounds[0], r.Precopy.Rounds[1] - if first.Attempt != 1 || first.Reason != "drain_timeout" || first.Frozen || second.Attempt != 2 || second.Reason != "fit" || !second.Frozen { + if first.Attempt != 1 || first.Reason != "drain_timeout" || first.Frozen || second.Attempt != 2 { t.Fatalf("attempt outcomes mixed: first=%+v second=%+v", first, second) } + if slow && (r.Precopy.Frozen || r.Precopy.Fixed < 1300*time.Millisecond) { + t.Fatalf("slow diagnostics control bypassed measured admission: report=%+v", r.Precopy) + } + if r.Precopy.Frozen { + if err != nil || len(r.Precopy.Rounds) != 2 || second.Reason != "fit" || !second.Frozen { + t.Fatalf("invalid fit after drain timeout: report=%+v err=%v", r.Precopy, err) + } + } else { + assertPrecopyMeasuredRefusal(t, r.Precopy, err) + if len(r.Precopy.Rounds) != 5 || f.stats().head.State != ChunkHeadActive { + t.Fatalf("budget refusal did not keep the owner active: report=%+v", r.Precopy) + } + for _, a := range r.Precopy.Rounds[1:] { + if a.Frozen || a.Estimate <= 1200*time.Millisecond || + (a.Reason != "tail_too_large" && a.Reason != "barrier_over_budget") { + t.Fatalf("budget refusal mixed with the initial drain timeout: %+v", a) + } + } + w.write(t, s, 2, 0x99) + cut, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + want := make([]byte, ctNumBlocks*ctBlockSize) + if slow { + copy(want[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x10)) + } + copy(want[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0x99)) + if !bytes.Equal(f.imageOf(t, cut.Head), want) { + t.Fatal("diagnostic refusal lost original or resumed-write bytes") + } + assertEveryHeadIsPrefixImage(t, f, w) + } for _, a := range r.Precopy.Rounds { if a.Drain <= 0 || a.Pause < a.Drain || a.Barrier != a.Pause-a.Drain { t.Fatalf("pause accounting: %+v", a) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e0f890b7af..7fa02b22bc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -477,7 +477,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | | `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |