diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index fcc04b65de..ad55735dc9 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -30,6 +30,7 @@ const ( ) type chunkFlags struct { + detachPrecopy bool hostLimit hostlimit.Config filer string path string @@ -56,7 +57,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.hostLimit.Directory != "" { + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" { 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 af733ef9a8..de5e5739cf 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -201,6 +201,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)") @@ -658,6 +659,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/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go new file mode 100644 index 0000000000..9e58424413 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -0,0 +1,180 @@ +package durable + +import ( + "context" + "errors" + "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: + 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 + } + 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 + } + 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 { + signalPrecopy(w) + } + 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: + 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/precopy_drain_test.go b/seaweed-block/core/frontend/durable/precopy_drain_test.go new file mode 100644 index 0000000000..2f3c00847d --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_test.go @@ -0,0 +1,138 @@ +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) + } +} + +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/frontend/durable/precopy_fifo_test.go b/seaweed-block/core/frontend/durable/precopy_fifo_test.go new file mode 100644 index 0000000000..7b41c5f2fe --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_fifo_test.go @@ -0,0 +1,381 @@ +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 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) + 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") + } +} + +// 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 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") + } + 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/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go new file mode 100644 index 0000000000..c25cbd4a02 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -0,0 +1,161 @@ +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) { + precopyFiftyIOPS(t, 3, false) +} + +func TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest(t *testing.T) { + precopyFiftyIOPS(t, 1, true) +} + +func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { + t.Helper() + 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 <= samples; 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) + 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 || (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 + } + 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 { + 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) + } + 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/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") + } +} 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") + } +} 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) + } +} 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..e6786b8ce2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_wait_test.go @@ -0,0 +1,162 @@ +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) + } +} + +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): + } + 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, frontend.ErrBackendClosed) || 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/provider.go b/seaweed-block/core/frontend/durable/provider.go index 9da5367dfc..824d89c2d1 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 // OnChunkDetach, optional, is called with the volume id when DetachVolume // starts a detach (a graceful stop), before the drain and final cut, so // the host can watch for the coming lease revocation; it returns a token diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 83cb311253..415d804e56 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -902,49 +902,133 @@ 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)) - defer cancel() + var start time.Time + var stopIOReturned time.Time 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 !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)) } }() - if trace := p.testDetachTrace; trace != nil { - dl, _ := cutCtx.Deadline() - trace("cut", dl) + 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) }) } - h.chunkDetach = true - var resumed func() // tells the host this attempt aborted and serving resumed - if hook := p.cfg.OnChunkDetach; hook != nil { - attempt := hook(volumeID) - if done := p.cfg.OnChunkDetachResumed; done != nil { - resumed = func() { done(volumeID, attempt) } + defer func() { + 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) + } + } + }() + var resumed func() + notifyDetach := func() { + if hook := p.cfg.OnChunkDetach; hook != nil { + attempt := hook(volumeID) + if done := p.cfg.OnChunkDetachResumed; done != nil { + resumed = func() { done(volumeID, attempt) } + } } } - 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 { + owner, ok := layer.(interface { + 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) + } + // Notify outside captureMu: the host callback may take its own state lock. + notifyDetach() + // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) - var r storage.ChunkCutResult - if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil { + 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 + } + stopIOReturned = time.Now() + h.chunkDetach = true + 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 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) + } return r, h.storage.NextLSN() - 1, nil } + if !r.Precopy.Frozen { + p.mu.Lock() + active := !p.closed && h.chunk == layer + if active { + p.startChunkLoop(volumeID, h, layer) + } + p.mu.Unlock() + // No final freeze occurred: clear only this still-serving attempt's + // fast-poll token. A prior stopped/unknown detach must remain pending. + if active && !h.chunkDetach && h.backend.operational.Load() && !layer.Fenced() && resumed != nil { + resumed() + } + return r, 0, err + } + } else { + beginFreeze() + if trace := p.testDetachTrace; trace != nil { + trace("cut", start.Add(freeze*3/4)) + } + h.chunkDetach = true + notifyDetach() + 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 { + stopIOReturned = time.Now() + } + if err == nil { + p.stopChunkLoop(h) + if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil { + return r, h.storage.NextLSN() - 1, nil + } + } } + 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 // 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)+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 + } switch { case serr != nil: return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr) 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..510c3f43af --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -0,0 +1,270 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "strconv" + "strings" + "sync" + "sync/atomic" + "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") + } +} + +func precopyProvider(t *testing.T, remote storage.ChunkRemote, view *parkView, hooks ...*detachHooks) *durable.DurableProvider { + t.Helper() + cfg := 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 }, + } + if len(hooks) > 0 { + cfg.OnChunkDetach = hooks[0].detach + cfg.OnChunkDetachResumed = hooks[0].resume + } + p, err := durable.NewDurableProvider(cfg, 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) + } +} + +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) { + 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) + 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) + } + 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() { + unpark() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("writer did not join") + } + }) + go func() { done <- b.Sync(context.Background()) }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("write not admitted") + } + remote.nextDelay.Store(int64(delay)) + // 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) + 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 != 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) + } + 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) + } + 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") + resumedCount := 1 + if err != nil { + // 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) != 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/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 83545e2a54..d5613d5024 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -148,7 +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() + 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() @@ -162,9 +164,11 @@ 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 + 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 @@ -358,6 +362,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.finishPrecopyLocked(false) b.notifyReadReadyLocked() return nil } @@ -464,11 +469,72 @@ 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 + // 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() - 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 -> 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 { + defer b.mu.Unlock() + if !b.precopy.active { + return false + } + 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 hook := b.testPrecopyStopFallback; hook != nil { + hook() + } + if !b.ioMu.TryLock() { + return false + } + defer b.ioMu.Unlock() + if !b.mu.TryLock() { + return false + } + defer b.mu.Unlock() + // 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} + close(p.drained) + b.precopy = p + b.opEvidence.Store(evidence) + b.operational.Store(false) + b.waitAttachReady = false + b.notifyReadReadyLocked() + return true } // StopIO makes the backend refuse every new Read, Write and Sync with @@ -512,7 +578,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.admit() + release, err := b.admitPrecopy(ctx, b.admit) if err != nil { return err } @@ -588,6 +654,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 @@ -729,7 +799,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: @@ -754,6 +841,7 @@ func (b *StorageBackend) readyCheck() error { closed := b.closed chunkFenced := b.chunkFenced observerErr := b.observerErr + precopyPending := b.precopy != nil && b.precopy.active b.mu.Unlock() if closed { return frontend.ErrBackendClosed @@ -764,6 +852,9 @@ 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) return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev) 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") + } +} 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 diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c762f4d5f1..392e12a380 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -56,6 +56,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"` @@ -83,6 +84,7 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ + PayloadNs: s.PayloadNs, COWWALReadAttempts: s.COWWALReadAttempts, COWLocalReadNs: s.COWLocalReadNs, BarrierPauseNs: s.BarrierPauseNs, @@ -122,11 +124,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. @@ -235,6 +238,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. @@ -595,5 +602,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_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_layer.go b/seaweed-block/core/storage/chunk_layer.go index 355fcdb19f..7ed3c1631c 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -52,6 +52,12 @@ type chunkHooks struct { 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) + s *WALStore remote chunkRemote cfg chunkLayerConfig @@ -652,10 +658,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 + if !pauseStart.IsZero() { + fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier + l.samplePrecopy(st, fixed) + } } if errors.Is(err, errChunkLayerFenced) { l.stMu.Lock() @@ -669,6 +681,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 { @@ -715,7 +730,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.PayloadNs += time.Since(stageStart).Nanoseconds() + } if err != nil { l.dropIntents(ctx, intents) return chunkCutResult{}, err @@ -730,7 +749,33 @@ 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() + 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() } @@ -743,7 +788,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) @@ -794,9 +839,16 @@ 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 && context.Cause(ctx) == nil { + tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks + detach = freeze(tail, pauseStart) + } 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 @@ -809,14 +861,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CandidateChunks = len(candidates) var copyErr error copyStart := time.Now() + bytesBeforeCopy := st.UploadedBytes { - var w *cutCOWWindow w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) if copyErr == nil { w.budget = budget } - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() copyStart = time.Now() if copyErr == nil { @@ -838,9 +890,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } st.CopyNs = time.Since(copyStart).Nanoseconds() - + if st.UploadedBytes > bytesBeforeCopy { + st.PayloadNs += st.CopyNs + } st.UploadNs = st.CopyNs - if copyErr != nil { l.abortCut(all) l.dropIntents(ctx, intents) @@ -905,6 +958,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) @@ -913,6 +967,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.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} newKeys[u.c.idx] = u.key diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go new file mode 100644 index 0000000000..56bd430b37 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -0,0 +1,324 @@ +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 + precopyDrainBound = 100 * time.Millisecond +) + +type precopySample struct { + at time.Time + fixed time.Duration + rate float64 +} + +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"` + 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 { + Rounds []PrecopyAttempt `json:"rounds,omitempty"` + 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"` + 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. +// 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 +// 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) { + 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) + } + 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) + var report PrecopyReport + var frozenAt time.Time + var casAtFreeze uint64 + var pauseTotal, longestPause time.Duration + 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) + 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 { + longestPause = pause + } + } + 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 + } + if report.Reason == "fit" && report.Estimate > precopyAllowance { + report.Reason = "barrier_over_budget" + } + if report.Reason != "fit" { + return false + } + if !stopIO() { + report.Reason = "admitted_io" + return false + } + report.Frozen = true + report.BarrierBeforeFreeze = time.Since(barrierStart) + frozenAt, casAtFreeze = barrierStart, countCAS() + return true + } + defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() + for attempt := 1; attempt <= precopyAttempts; attempt++ { + // 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, + 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) { + 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) + if attempts > 0 { + extra = attempts - 1 + } + r.Precopy.Finish(time.Since(frozenAt), extra, err != nil) + 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 || !(errors.Is(err, errCutCOWAborted) || errors.Is(err, errChunkRemoteUnavailable) || errors.Is(err, errChunkHeadPrecondition)) { + 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 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 + } + if s.rate > 0 { + rates = append(rates, s.rate) + } + } + r.RateSamples = len(rates) + 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, 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() + } + l.precopySamples = append(l.precopySamples, s) + if len(l.precopySamples) > 32 { + 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 + } + } + } +} 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..7200aff910 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -0,0 +1,598 @@ +package storage + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "path/filepath" + "testing" + "time" +) + +// 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) +} + +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) { + precopyBusyOwnerControl(t, false) +} + +func TestPrecopyDetachBusyOwnerRetainsSlowFixedCost(t *testing.T) { + precopyBusyOwnerControl(t, true) +} + +func precopyBusyOwnerControl(t *testing.T, slow bool) { + t.Helper() + 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 { + t.Fatalf("report=%+v calls=%d err=%v", r.Precopy, calls, err) + } + if calls == 0 { + assertPrecopyMeasuredRefusal(t, r.Precopy, err) + } + 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) { + 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) + } +} + +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 { + 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 { + 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) + } + 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) + 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) +} + +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) + } +} + +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) + } +} + +func TestPrecopyDetachQueuedCancellationReturnsWhileOtherCutOwnsPipeline(t *testing.T) { + _, f, l, _ := precopyLayer(t, 1024, 1) + entered, release := holdPuts(t, f) + cutDone, preDone := make(chan struct{}), make(chan struct{}) + var ctx context.Context + cancel := func() {} + 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") + } + 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 }) + }() + 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") + } +} + +func TestPrecopyDetachExcludesServingPreparationFromFreezeCost(t *testing.T) { + 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) + } + 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) { + precopyAppliedDetachRetryControl(t, false) +} + +func TestPrecopyDetachAppliedRetryRetainsSlowFixedCost(t *testing.T) { + precopyAppliedDetachRetryControl(t, true) +} + +func precopyAppliedDetachRetryControl(t *testing.T, slow bool) { + t.Helper() + s, f, l, w := 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) + } + 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) + } + 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") + } +} + +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) + } +} + +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) + } +} + +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 { + 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") + } +} + +func TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit(t *testing.T) { + 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++ + if calls == 1 { + <-ctx.Done() + return nil, ctx.Err() + } + return func() {}, nil + }, func() bool { return true }) + 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 { + 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) + } + } +} + +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) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 90a8d87316..9aa3940b08 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 { + PayloadNs int64 // disjoint streaming/copy/upload wall intervals + // Local validated WAL attempts and local copy duration, including savers. COWWALReadAttempts uint64 COWLocalReadNs int64 @@ -482,6 +484,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 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d1cc22c341..ee58cd7ae4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -208,7 +208,9 @@ stateDiagram-v2 Admit --> Refused: budget refused, closed, fenced, detached, base install, 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 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 Copy --> Upload: local entry released, intent durable first Upload --> Copy: next unsent candidate @@ -233,7 +235,10 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `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` | +| 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) 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` | @@ -472,6 +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`, `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` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |