From f337e8de991b917d33c647c282eeb2f1e2861132 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:13:08 -0800 Subject: [PATCH] feat(storage): drain admission before authoritative pre-copy barrier --- .../frontend/durable/precopy_admission.go | 13 ++++++ .../core/frontend/durable/provider_chunk.go | 4 +- .../core/frontend/durable/storage_adapter.go | 8 +++- seaweed-block/core/storage/chunk_layer.go | 34 ++++++++++++-- seaweed-block/core/storage/chunk_precopy.go | 46 +++++++++++++++++-- 5 files changed, 92 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_admission.go b/seaweed-block/core/frontend/durable/precopy_admission.go index 9735849fd2..c8ba6045dc 100644 --- a/seaweed-block/core/frontend/durable/precopy_admission.go +++ b/seaweed-block/core/frontend/durable/precopy_admission.go @@ -2,6 +2,7 @@ package durable import ( "context" + "errors" "fmt" "sync" "time" @@ -132,6 +133,15 @@ func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), } return release, err } + b.mu.Unlock() + if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) { + return nil, err + } + b.mu.Lock() + if b.precopy != p { + b.mu.Unlock() + continue + } w := &precopyWaiter{ready: make(chan struct{})} p.waiters = append(p.waiters, w) if !p.active && len(p.waiters) == 1 { @@ -139,6 +149,9 @@ func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(), } deadline := p.started.Add(precopyQueueBudget) b.mu.Unlock() + if hook := b.testPrecopyQueued; hook != nil { + hook() + } waitCtx, cancel := context.WithDeadline(ctx, deadline) select { case <-w.ready: diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index a8d3cf1964..9663bf89ce 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -935,7 +935,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st var r storage.ChunkCutResult if p.cfg.ChunkDetachPrecopy { owner, ok := layer.(interface { - PrecopyDetach(context.Context, func() bool) (storage.ChunkCutResult, error) + PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) }) if !ok { return r, 0, fmt.Errorf("%w: layer lacks pre-copy", storage.ErrPrecopyUnknown) @@ -944,7 +944,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st notifyDetach() // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) - r, err = owner.PrecopyDetach(hostlimit.WithClass(cutCtx, hostlimit.Urgent), func() bool { + r, err = owner.PrecopyDetachWithAdmission(hostlimit.WithClass(cutCtx, hostlimit.Urgent), h.backend.BeginPrecopyPause, func() bool { if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 8e4da51484..c772c61696 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -148,7 +148,8 @@ const maxFullBlockBatchBlocks = 64 type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). - testBeforeIOLock func() + testBeforeIOLock func() + testPrecopyQueued func() // after FIFO registration, outside mu // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() testAfterAttachRefusal func() @@ -488,8 +489,11 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { // A drained admission pause excludes late gate callers even if they still // hold ioMu's read side. Their final registration check cannot reach storage. if b.mu.TryLock() { - if b.precopy != nil && b.precopy.active { + if b.precopy != nil { defer b.mu.Unlock() + if !b.precopy.active { + return false + } if b.admittedIO != 0 || b.closed || !b.operational.Load() { return false } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index b5296395ee..96d38a9ee4 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -54,6 +54,7 @@ const defaultReadMissTimeout = 30 * time.Second type chunkLayerImpl struct { // capMu serializes pre-copy admission and its recent measurements. precopyFreeze func(uint64, time.Time) bool + precopyPrepare func(context.Context) (func(), error) precopySamples []precopySample precopyPause func(time.Duration) @@ -905,6 +906,31 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // paused too. LockWaitNs reports that wait on its own. payloadBeforeBarrier = st.PayloadNs pauseStart = time.Now() + var releasePrecopy func() + if prepare := l.precopyPrepare; prepare != nil { + releasePrecopy, _ = prepare(ctx) + } + defer func() { + if releasePrecopy != nil && !detach { + releasePrecopy() + } + }() + if cause := context.Cause(ctx); cause != nil { + if releasePrecopy != nil { + releasePrecopy() + releasePrecopy = nil + } + l.dropIntents(ctx, intents) + return chunkCutResult{}, cause + } + // Resume rejected tentative admission before any ordinary COW upload. + unlockCapture := func() { + l.s.captureMu.Unlock() + if !detach && releasePrecopy != nil { + releasePrecopy() + releasePrecopy = nil + } + } if hook := l.testBeforeBarrierLockHook; hook != nil { hook() } @@ -917,7 +943,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch hook(h) } if err != nil { - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() l.dropIntents(ctx, intents) // a clean abort: staged keys are released return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) @@ -977,7 +1003,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() // HEAD holds the image of a later LSN than this host's log has // reached: publishing would move remote_lsn backwards. Refused @@ -997,7 +1023,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if copyErr == nil { w.budget = budget } - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() copyStart = time.Now() if copyErr == nil { @@ -1029,7 +1055,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)}) } - l.s.captureMu.Unlock() + unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() } st.CopyNs = time.Since(copyStart).Nanoseconds() diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 985995073c..3b35e301a9 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -13,10 +13,11 @@ var ( ) const ( - precopyAttempts = 5 - precopyDuration = 60 * time.Second - precopyAllowance = 1200 * time.Millisecond - precopyMargin = 100 * time.Millisecond + precopyAttempts = 5 + precopyDuration = 60 * time.Second + precopyAllowance = 1200 * time.Millisecond + precopyMargin = 100 * time.Millisecond + precopyDrainBound = 100 * time.Millisecond ) type precopySample struct { @@ -27,6 +28,8 @@ type precopySample struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + Drain time.Duration `json:"drainNs"` + DrainTimedOut bool `json:"drainTimedOut"` Attempts int `json:"attempts"` TailBytes uint64 `json:"tailBytes"` Fixed time.Duration `json:"fixedNs"` @@ -62,6 +65,16 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo // capMu owns the callback and samples; no owner lock is taken while waiting // for capMu. The callback must never wait for an I/O holding a backend read lock. func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) (ChunkCutResult, error) { + return l.precopyDetach(ctx, nil, stopIO) +} + +// prepare closes frontend admission and drains before the store barrier. Its +// release reopens only that tentative admission; it must not undo a host fence. +func (l *chunkLayerImpl) PrecopyDetachWithAdmission(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) { + return l.precopyDetach(ctx, prepare, stopIO) +} + +func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) { if stopIO == nil { return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown) } @@ -83,6 +96,20 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) var frozenAt time.Time var casAtFreeze uint64 var pauseTotal, longestPause time.Duration + var drain time.Duration + var drainErr error + if prepare != nil { + l.precopyPrepare = func(ctx context.Context) (func(), error) { + dc, cancel := context.WithTimeout(ctx, precopyDrainBound) + defer cancel() + start := time.Now() + release, err := prepare(dc) + drain = time.Since(start) + drainErr = err + return release, err + } + } + l.precopyPause = func(pause time.Duration) { pauseTotal += pause if pause > longestPause { @@ -91,6 +118,15 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) } l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool { report = l.precopyEstimate(tail, report.Attempts) + report.Drain = drain + report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) + if drainErr != nil { + report.Reason = "drain_refused" + if report.DrainTimedOut { + report.Reason = "drain_timeout" + } + return false + } spent := time.Since(barrierStart) if spent > report.Fixed { report.Estimate += spent - report.Fixed @@ -110,7 +146,7 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) frozenAt, casAtFreeze = barrierStart, countCAS() return true } - defer func() { l.precopyFreeze = nil; l.precopyPause = nil }() + defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() for attempt := 1; attempt <= precopyAttempts; attempt++ { report.Attempts = attempt if err := ctx.Err(); err != nil {