From 9f50a717fd98c04d95383494185ea9fe61c6b896 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 14:24:16 -0800 Subject: [PATCH 01/20] test(storage): distinguish fixed-bound and tail-bound pre-copy costs --- .../chunk_precopy_fixed_commit_test.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go new file mode 100644 index 0000000000..de9764aa43 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -0,0 +1,64 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +func TestPrecopyFixedCostSmallTailCommitsBySecondAttempt(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + fixed := 1300 * time.Millisecond + f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(fixed) } + rounds := 0 + l.testBeforeBarrierLockHook = func() { + rounds++ + w.write(t, s, 1, byte(rounds)) + // Keep the same known small tail and fixed envelope in each attempt. + l.precopySamples = nil + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, rate: 20 * float64(ctChunkBytes)}) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + r, err := l.PrecopyDetach(ctx, func() bool { return true }) + if err != nil || !r.Precopy.Frozen || r.Precopy.Attempts > 2 || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { + t.Fatalf("fixed cost cannot converge by recopying the same small tail: report=%+v err=%v", r.Precopy, err) + } + if r.Head.State != ChunkHeadDetached || !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, byte(rounds))) { + t.Fatal("amended commit lost the exact point") + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestPrecopyLargeTailStillRefusesFixedCostException(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + rounds := 0 + l.testBeforeBarrierLockHook = func() { + rounds++ + w.write(t, s, 1, byte(rounds)) + l.precopySamples = nil + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: float64(ctChunkBytes)}) + } + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { t.Fatal("large tail froze"); return true }) + if !errors.Is(err, ErrPrecopyNotConverged) || r.Precopy.Frozen || len(r.Precopy.Rounds) != 5 || r.Precopy.Reason != "tail_too_large" { + t.Fatalf("large tail was not refused: %+v %v", r.Precopy, err) + } + if f.stats().head.State != ChunkHeadActive { + t.Fatal("refusal lost active owner") + } + w.write(t, s, 2, 0x77) + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, r.Head)[2*ctBlockSize:3*ctBlockSize], makeBlock(ctBlockSize, 0x77)) { + t.Fatal("refusal stopped serving") + } + assertEveryHeadIsPrefixImage(t, f, w) +} From 24e3ba4ad06bae7b9a119c0e6d586e8deec177b8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 14:27:49 -0800 Subject: [PATCH 02/20] fix(storage): declare stalled fixed-bound pre-copy commits and cost parts --- .../core/frontend/durable/provider_chunk.go | 2 +- seaweed-block/core/storage/chunk_head_belt.go | 15 +- seaweed-block/core/storage/chunk_layer.go | 3 +- seaweed-block/core/storage/chunk_precopy.go | 150 +++++++++++++----- .../core/storage/chunk_precopy_detach_test.go | 18 +-- .../chunk_precopy_fixed_commit_test.go | 71 ++++++++- seaweed-block/core/storage/chunk_seam.go | 3 + 7 files changed, 208 insertions(+), 54 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 415d804e56..b5f9bfedb9 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -962,7 +962,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st }) // 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 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 fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f 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, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), 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 { diff --git a/seaweed-block/core/storage/chunk_head_belt.go b/seaweed-block/core/storage/chunk_head_belt.go index 46ac62aa60..dae4ffe573 100644 --- a/seaweed-block/core/storage/chunk_head_belt.go +++ b/seaweed-block/core/storage/chunk_head_belt.go @@ -77,12 +77,25 @@ func confirmChunkHead(ctx context.Context, remote chunkRemote, want chunkHead) e // Every successful CAS is confirmed, including calls near or beyond a lease // horizon. No lease renewal or guard lock is needed across these remote calls. func casAndConfirmChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead) (uint64, error) { + return casAndConfirmChunkHeadMeasured(ctx, remote, expected, next, nil) +} + +func casAndConfirmChunkHeadMeasured(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead, st *chunkCutStats) (uint64, error) { + start := time.Now() gen, err := casChunkHead(ctx, remote, expected, next) + if st != nil { + st.CASWriteNs += time.Since(start).Nanoseconds() + } if err != nil { return gen, err } next.Gen = gen - return gen, confirmChunkHead(ctx, remote, next) + start = time.Now() + err = confirmChunkHead(ctx, remote, next) + if st != nil { + st.HeadReadbackNs += time.Since(start).Nanoseconds() + } + return gen, err } func confirmChunkTakeover(ctx context.Context, remote chunkRemote, head chunkHead, window time.Duration) error { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 7ed3c1631c..4a4a01f478 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -754,6 +754,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch var releasePrecopy func() if prepare := l.precopyPrepare; prepare != nil { releasePrecopy, _ = prepare(ctx) + st.DrainNs = time.Since(pauseStart).Nanoseconds() } defer func() { if releasePrecopy != nil && !detach { @@ -1029,7 +1030,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} casStart := time.Now() - gen, casErr := casAndConfirmChunkHead(ctx, l.remote, expected, next) + gen, casErr := casAndConfirmChunkHeadMeasured(ctx, l.remote, expected, next, &st) st.CASNs = time.Since(casStart).Nanoseconds() st.CASResult = "ok" if errors.Is(casErr, errChunkHeadPrecondition) { diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 56bd430b37..e31a529193 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -13,57 +13,84 @@ var ( ) const ( - precopyAttempts = 5 - precopyDuration = 60 * time.Second - precopyAllowance = 1200 * time.Millisecond - precopyMargin = 100 * time.Millisecond - precopyDrainBound = 100 * time.Millisecond + precopyAttempts = 5 + precopyDuration = 60 * time.Second + precopyAllowance = 1200 * time.Millisecond + precopyMargin = 100 * time.Millisecond + precopyDrainBound = 100 * time.Millisecond + precopyFreezeLimit = 5 * time.Second ) +// PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample. +type PrecopyFixedParts struct { + Drain time.Duration `json:"drainNs"` + StoreLock time.Duration `json:"storeLockNs"` + DataSync time.Duration `json:"dataSyncNs"` + HeadCAS time.Duration `json:"headCASNs"` + HeadReadback time.Duration `json:"headReadbackNs"` + Other time.Duration `json:"otherNs"` +} + +func precopyFixedParts(st chunkCutStats, fixed time.Duration) PrecopyFixedParts { + p := PrecopyFixedParts{Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs)} + p.Other = max(time.Duration(0), fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback) + return p +} + type precopySample struct { at time.Time fixed time.Duration + parts PrecopyFixedParts 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"` + Attempt int `json:"attempt"` + Drain time.Duration `json:"drainNs"` + Barrier time.Duration `json:"barrierNs"` + Pause time.Duration `json:"pauseNs"` + Fixed time.Duration `json:"fixedNs"` + FixedParts PrecopyFixedParts `json:"fixedParts"` + TailEstimate time.Duration `json:"tailEstimateNs"` + DeclaredFreeze time.Duration `json:"declaredFreezeNs"` + PreviousEstimate time.Duration `json:"previousEstimateNs"` + 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"` + 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"` + FixedParts PrecopyFixedParts `json:"fixedParts"` + TailEstimate time.Duration `json:"tailEstimateNs"` + DeclaredFreeze time.Duration `json:"declaredFreezeNs"` + PreviousEstimate time.Duration `json:"previousEstimateNs"` + 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. @@ -72,7 +99,11 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo r.FreezeElapsed, r.ExtraCASAttempts = elapsed, extraCAS r.CASFailureTimeout = chunkHeadOperationTimeout r.DeclaredWorst = r.Estimate + time.Duration(extraCAS)*chunkHeadOperationTimeout - r.LatencyGateFailed = failed || elapsed > precopyAllowance + limit := precopyAllowance + if r.Reason == "fixed_cost_over_allowance" { + limit = min(r.DeclaredFreeze, precopyFreezeLimit) + } + r.LatencyGateFailed = failed || elapsed > limit } // PrecopyDetach runs rolling cuts before the final detached cut. stopIO is @@ -150,14 +181,22 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } spent := time.Since(barrierStart) if spent > report.Fixed { - report.Estimate += spent - report.Fixed + extra := spent - report.Fixed + report.Estimate += extra + report.FixedParts.Other += extra + report.Fixed = spent } if report.Reason == "fit" && report.Estimate > precopyAllowance { report.Reason = "barrier_over_budget" } - if report.Reason != "fit" { + var previous *PrecopyAttempt + if len(rounds) > 0 { + previous = &rounds[len(rounds)-1] + } + if !report.admitPrecopy(previous) { return false } + report.DeclaredFreeze = report.Estimate if !stopIO() { report.Reason = "admitted_io" return false @@ -188,6 +227,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, TailBytes: report.TailBytes, RateSamples: report.RateSamples, Estimate: report.Estimate, Reason: report.Reason, Frozen: report.Frozen, + Fixed: report.Fixed, FixedParts: report.FixedParts, TailEstimate: report.TailEstimate, DeclaredFreeze: report.DeclaredFreeze, PreviousEstimate: report.PreviousEstimate, } a.Barrier = max(time.Duration(0), a.Pause-a.Drain) if a.Reason == "" { @@ -249,6 +289,9 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor // is already drained; metadata and CAS/read-back remain included. if s.fixed > r.Fixed { r.Fixed = s.fixed + r.FixedParts = s.parts + known := s.parts.Drain + s.parts.StoreLock + s.parts.DataSync + s.parts.HeadCAS + s.parts.HeadReadback + r.FixedParts.Other = max(time.Duration(0), s.fixed-known) } if s.rate > 0 { rates = append(rates, s.rate) @@ -274,9 +317,11 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor if seconds > precopyDuration.Seconds() { r.Reason = "tail_too_large" r.Estimate = precopyDuration + r.TailEstimate = precopyDuration return r } - r.Estimate += time.Duration(seconds * float64(time.Second)) + r.TailEstimate = time.Duration(seconds * float64(time.Second)) + r.Estimate += r.TailEstimate } r.Reason = "tail_too_large" if r.Estimate <= precopyAllowance { @@ -285,12 +330,35 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor return r } +// More copying cannot reduce a fixed-bound plateau. Only the measured tail +// may use at most a quarter of the normal allowance on this exception path. +func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt) bool { + if r.Reason == "fit" && r.Estimate <= precopyAllowance { + return true + } + if previous == nil || previous.Estimate <= 0 || r.Reason == "samples_unknown" { + return false + } + r.PreviousEstimate = previous.Estimate + if r.TailEstimate > precopyAllowance/4 || r.Estimate < previous.Estimate { + return false + } + // Preserve the frontend's existing five-second held-command ceiling. + if r.Estimate > precopyFreezeLimit { + r.Reason = "fixed_cost_exceeds_freeze_budget" + return false + } + r.Reason = "fixed_cost_over_allowance" + return true +} + 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))} + s.parts = precopyFixedParts(st, s.fixed) if st.UploadedBytes > 0 && st.PayloadNs > 0 { s.rate = float64(st.UploadedBytes) / time.Duration(st.PayloadNs).Seconds() } diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 7200aff910..f0b8f04ebf 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -95,8 +95,8 @@ func precopyBusyOwnerControl(t *testing.T, slow bool) { 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 slow && (calls == 0 || r.Precopy.Fixed < 1300*time.Millisecond) { + t.Fatalf("slow fixed cost did not reach the nonblocking stop gate: calls=%d report=%+v", calls, r.Precopy) } if f.stats().head.State != ChunkHeadActive { t.Fatal("busy frontend lost its active HEAD") @@ -159,8 +159,8 @@ func precopyRefusedFinalCutControl(t *testing.T, slow bool) { } 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 slow && r.Precopy.Fixed < 1300*time.Millisecond { + t.Fatalf("slow fixed sample was lost: report=%+v", r.Precopy) } if f.stats().head.State != ChunkHeadActive { t.Fatal("refused final cut lost its active HEAD") @@ -369,8 +369,8 @@ func precopyAppliedDetachRetryControl(t *testing.T, slow bool) { f.casModes = []fakeCASMode{casAppliedLost} f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) - if slow && (r.Precopy.Frozen || r.Precopy.Fixed < 1300*time.Millisecond) { - t.Fatalf("slow retry control bypassed measured admission: report=%+v", r.Precopy) + if slow && r.Precopy.Fixed < 1300*time.Millisecond { + t.Fatalf("slow retry control lost its measured fixed cost: report=%+v", r.Precopy) } if !r.Precopy.Frozen { assertPrecopyMeasuredRefusal(t, r.Precopy, err) @@ -525,11 +525,11 @@ func precopyAttemptDiagnosticsControl(t *testing.T, slow bool) { 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 slow && r.Precopy.Fixed < 1300*time.Millisecond { + t.Fatalf("slow diagnostics control lost its measured fixed cost: report=%+v", r.Precopy) } if r.Precopy.Frozen { - if err != nil || len(r.Precopy.Rounds) != 2 || second.Reason != "fit" || !second.Frozen { + if err != nil || len(r.Precopy.Rounds) != 2 || (second.Reason != "fit" && second.Reason != "fixed_cost_over_allowance") || !second.Frozen { t.Fatalf("invalid fit after drain timeout: report=%+v err=%v", r.Precopy, err) } } else { diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index de9764aa43..c4096122f2 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -25,7 +25,7 @@ func TestPrecopyFixedCostSmallTailCommitsBySecondAttempt(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() r, err := l.PrecopyDetach(ctx, func() bool { return true }) - if err != nil || !r.Precopy.Frozen || r.Precopy.Attempts > 2 || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { + if err != nil || !r.Precopy.Frozen || len(r.Precopy.Rounds) > 2 || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { t.Fatalf("fixed cost cannot converge by recopying the same small tail: report=%+v err=%v", r.Precopy, err) } if r.Head.State != ChunkHeadDetached || !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, byte(rounds))) { @@ -62,3 +62,72 @@ func TestPrecopyLargeTailStillRefusesFixedCostException(t *testing.T) { } assertEveryHeadIsPrefixImage(t, f, w) } + +func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { + for _, tc := range []struct { + name string + tail, estimate, previous time.Duration + known, want bool + }{ + {"first", 100 * time.Millisecond, 1500 * time.Millisecond, 0, true, false}, + {"improving", 100 * time.Millisecond, 1500 * time.Millisecond, 1600 * time.Millisecond, true, false}, + {"stalled", 100 * time.Millisecond, 1500 * time.Millisecond, 1500 * time.Millisecond, true, true}, + {"worse-fixed", 100 * time.Millisecond, 1600 * time.Millisecond, 1500 * time.Millisecond, true, true}, + {"quarter", 300 * time.Millisecond, 1500 * time.Millisecond, 1500 * time.Millisecond, true, true}, + {"large-tail", 300*time.Millisecond + 1, 1500 * time.Millisecond, 1500 * time.Millisecond, true, false}, + {"unknown", 0, 1500 * time.Millisecond, 1500 * time.Millisecond, false, false}, + {"freeze-ceiling", 0, 5*time.Second + 1, 5*time.Second + 1, true, false}, + } { + t.Run(tc.name, func(t *testing.T) { + reason := "tail_too_large" + if !tc.known { + reason = "samples_unknown" + } + r := PrecopyReport{Fixed: 1300 * time.Millisecond, TailEstimate: tc.tail, Estimate: tc.estimate, Reason: reason} + var previous *PrecopyAttempt + if tc.previous > 0 { + previous = &PrecopyAttempt{Estimate: tc.previous} + } + if got := r.admitPrecopy(previous); got != tc.want { + t.Fatalf("admit=%t report=%+v", got, r) + } + if tc.want && r.Reason != "fixed_cost_over_allowance" { + t.Fatalf("missing exception reason: %+v", r) + } + }) + } +} + +func TestPrecopyFixedPartsStayWithLargestObservation(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + l.precopySamples = nil + st := chunkCutStats{CASNs: 1, DrainNs: int64(10 * time.Millisecond), LockWaitNs: int64(30 * time.Millisecond), SyncNs: int64(40 * time.Millisecond), CASWriteNs: int64(50 * time.Millisecond), HeadReadbackNs: int64(60 * time.Millisecond)} + l.samplePrecopy(st, int64(200*time.Millisecond)) + l.samplePrecopy(chunkCutStats{CASNs: 1, SyncNs: int64(100 * time.Millisecond)}, int64(150*time.Millisecond)) + r := l.precopyEstimate(0, 0) + p := r.FixedParts + if r.Fixed != 200*time.Millisecond || p.Drain != 10*time.Millisecond || p.StoreLock != 20*time.Millisecond || p.DataSync != 40*time.Millisecond || p.HeadCAS != 50*time.Millisecond || p.HeadReadback != 60*time.Millisecond || p.Other != 20*time.Millisecond { + t.Fatalf("mixed cost samples or overlapping terms: %+v", r) + } +} + +func TestPrecopyFixedExceptionFinishUsesDeclaredFreeze(t *testing.T) { + r := PrecopyReport{Reason: "fixed_cost_over_allowance", Estimate: 1500 * time.Millisecond, DeclaredFreeze: 1500 * time.Millisecond} + r.Finish(1400*time.Millisecond, 0, false) + if r.LatencyGateFailed || r.DeclaredWorst != 1500*time.Millisecond { + t.Fatalf("new declaration ignored: %+v", r) + } + r.Finish(1600*time.Millisecond, 0, false) + if !r.LatencyGateFailed { + t.Fatal("missed declared freeze overrun") + } + r.Finish(time.Second, 0, true) + if !r.LatencyGateFailed { + t.Fatal("hid physical failure") + } + r = PrecopyReport{Reason: "fit", Estimate: time.Second} + r.Finish(1300*time.Millisecond, 0, false) + if !r.LatencyGateFailed { + t.Fatal("relaxed ordinary fit bound") + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 9aa3940b08..5df9c9d9ee 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -410,6 +410,9 @@ type chunkCutStats struct { // writers already holding the capture barrier shared. BarrierPauseNs int64 LockWaitNs int64 + DrainNs int64 + CASWriteNs int64 + HeadReadbackNs int64 SyncNs int64 CopyNs int64 CandidateChunks int From e29829bbac134f6e4442ffd5a179f5818d0c6909 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 14:32:12 -0800 Subject: [PATCH 03/20] test(storage): compose pre-copy exception controls and bounded admission model --- .../durable/precopy_fifty_iops_test.go | 91 +++++++++++++++++-- .../core/frontend/durable/provider_chunk.go | 2 +- seaweed-block/core/storage/chunk_layer.go | 11 ++- seaweed-block/core/storage/chunk_precopy.go | 7 +- .../core/storage/chunk_precopy_detach_test.go | 7 +- .../chunk_precopy_fixed_commit_test.go | 4 +- seaweed-block/core/storage/chunk_seam.go | 1 + seaweed-block/docs/design/invariants.md | 4 +- .../docs/spec/PrecopyFixedAdmission.tla | 38 ++++++++ .../docs/spec/cfg/PrecopyFixedAdmission.cfg | 6 ++ .../spec/cfg/PrecopyFixedAdmission_no_cap.cfg | 6 ++ .../cfg/PrecopyFixedAdmission_no_stall.cfg | 6 ++ .../cfg/PrecopyFixedAdmission_no_tail.cfg | 6 ++ 13 files changed, 168 insertions(+), 21 deletions(-) create mode 100644 seaweed-block/docs/spec/PrecopyFixedAdmission.tla create mode 100644 seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg create mode 100644 seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg create mode 100644 seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg create mode 100644 seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index c25cbd4a02..e98e8af3de 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -16,24 +16,32 @@ import ( // 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. +// then released after20ms. The first attempt must fit only when its measured +// estimate fits the allowance or the declared small-tail plateau exception; +// host I/O costs are not fixture constants. +// This is a forced schedule, not physical NVMe proof. func TestPrecopyFiftyIOPSSyncConvergesFirstAttempt(t *testing.T) { - precopyFiftyIOPS(t, 3, false) + precopyFiftyIOPS(t, 3, false, 0) } func TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest(t *testing.T) { - precopyFiftyIOPS(t, 1, true) + precopyFiftyIOPS(t, 1, true, 0) } -func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { +func TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing(t *testing.T) { + precopyFiftyIOPS(t, 3, false, 1300*time.Millisecond) +} + +func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool, fixedDelay time.Duration) { t.Helper() - remote := storage.NewMemChunkRemote() + remote := &precopyFixedSampleRemote{MemChunkRemote: 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) } + remote.nextDelay.Store(int64(fixedDelay)) for i := byte(1); i <= samples; i++ { if _, err := backend.Write(context.Background(), 4096, block(i)); err != nil { t.Fatal(err) @@ -45,6 +53,10 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { t.Fatal(err) } } + before, err := remote.GetHead(context.Background()) + if 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) }) } @@ -136,7 +148,7 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { // 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)) { + if err != nil || (len(result.Precopy.Rounds) == 1 && result.Precopy.TailBytes != 0) || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x5b)) { t.Fatalf("cold samples claimed premature fit: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) } return @@ -149,13 +161,76 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool) { } return } - if err != nil || !result.Precopy.Frozen || result.Precopy.Attempts != 1 { + // A loaded host may correctly refuse an expensive tail. Preserve the + // first-attempt oracle whenever it fits: EVERY earlier attempt must have + // been refused by both the ordinary allowance and the small-tail plateau rule. + if fixedDelay > 0 && result.Precopy.Fixed < fixedDelay { + t.Fatalf("lost slow fixed sample: %+v", result.Precopy) + } + const allowance = 1200 * time.Millisecond + if len(result.Precopy.Rounds) == 0 { + t.Fatal("no admission attempts") + } + if result.Precopy.Rounds[len(result.Precopy.Rounds)-1].Frozen != result.Precopy.Frozen { + t.Fatal("final freeze disagrees with attempt report") + } + for i, round := range result.Precopy.Rounds { + eligible := round.Estimate <= allowance + reason := "fit" + if !eligible && i > 0 && round.TailEstimate <= allowance/4 && round.Estimate >= result.Precopy.Rounds[i-1].Estimate && round.Estimate <= 5*time.Second { + eligible = true + reason = "fixed_cost_over_allowance" + } + if round.Frozen { + if !eligible || i != len(result.Precopy.Rounds)-1 || round.Reason != reason || round.DeclaredFreeze != round.Estimate || round.Error != "" { + t.Fatalf("invalid fitting attempt: %+v", round) + } + } else if eligible || (round.Reason != "tail_too_large" && round.Reason != "barrier_over_budget" && round.Reason != "fixed_cost_exceeds_freeze_budget") || round.Error != "" { + t.Fatalf("refused an eligible attempt or hid a failure: %+v", round) + } + } + if !result.Precopy.Frozen { + if !errors.Is(err, storage.ErrPrecopyNotConverged) || len(result.Precopy.Rounds) != 5 || result.Precopy.Attempts != 5 || guestErrors.Load() != 0 { + t.Fatalf("wrong over-budget outcome: report=%+v err=%v", result.Precopy, err) + } + // Settle both guest workers before proving the refused owner is still live. + releasePeer() + cancel() + for _, done := range []chan struct{}{writerDone, probeDone} { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("guest worker did not settle") + } + } + liveCtx, stop := context.WithTimeout(context.Background(), time.Second) + defer stop() + head, headErr := remote.GetHead(liveCtx) + if headErr != nil || head.Gen < before.Gen || head.RemoteLSN < before.RemoteLSN || head.Epoch != before.Epoch || head.Holder != before.Holder || head.State != storage.ChunkHeadActive || head.DetachedBy != nil { + t.Fatalf("refusal lost the active owner or regressed HEAD: %+v %v", head, headErr) + } + if _, writeErr := backend.Write(liveCtx, 12288, block(0x7d)); writeErr != nil { + t.Fatal("refusal stopped service:", writeErr) + } + for _, read := range []struct { + offset int64 + value byte + }{{4096, 0x5b}, {12288, 0x7d}} { + got := make([]byte, 4096) + n, readErr := backend.Read(liveCtx, read.offset, got) + if readErr != nil || n != len(got) || !bytes.Equal(got, block(read.value)) { + t.Fatalf("refused-owner bytes at %d: n=%d err=%v", read.offset, n, readErr) + } + } + return + } + if err != nil { 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)) { + if !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x5b)) { t.Fatal("final cut lost synchronous writer bytes") } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index b5f9bfedb9..b458b507de 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -962,7 +962,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st }) // 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 fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f 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, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), a.Error) + 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 fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f map_persist_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f 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, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.MapPersist)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), 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 { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 4a4a01f478..342aeccff8 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -658,6 +658,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch defer done() start := time.Now() var st chunkCutStats + persistCapturedMap := func(versions map[uint64]uint64) { + start := time.Now() + l.persistCapturedMapV3(versions) + st.MapPersistNs += time.Since(start).Nanoseconds() + } var pauseStart time.Time var payloadBeforeBarrier int64 defer func() { @@ -1010,7 +1015,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, errChunkLayerFenced } l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS - l.persistCapturedMapV3(capturedVersions) + persistCapturedMap(capturedVersions) l.dropIntents(ctx, intents) // superseded staged uploads only return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } @@ -1041,7 +1046,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if casErr == nil { next.Gen = gen l.finishCut(next, h, changed, newKeys) - l.persistCapturedMapV3(capturedVersions) + persistCapturedMap(capturedVersions) l.dropIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } @@ -1081,7 +1086,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if sameProposal(cur, next) { st.CASResult = "resolved-by-reread" l.finishCut(cur, h, changed, newKeys) - l.persistCapturedMapV3(capturedVersions) + persistCapturedMap(capturedVersions) l.dropIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index e31a529193..1c921d0705 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -28,12 +28,13 @@ type PrecopyFixedParts struct { DataSync time.Duration `json:"dataSyncNs"` HeadCAS time.Duration `json:"headCASNs"` HeadReadback time.Duration `json:"headReadbackNs"` + MapPersist time.Duration `json:"mapPersistNs"` Other time.Duration `json:"otherNs"` } func precopyFixedParts(st chunkCutStats, fixed time.Duration) PrecopyFixedParts { - p := PrecopyFixedParts{Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs)} - p.Other = max(time.Duration(0), fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback) + p := PrecopyFixedParts{Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} + p.Other = max(time.Duration(0), fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist) return p } @@ -290,7 +291,7 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor if s.fixed > r.Fixed { r.Fixed = s.fixed r.FixedParts = s.parts - known := s.parts.Drain + s.parts.StoreLock + s.parts.DataSync + s.parts.HeadCAS + s.parts.HeadReadback + known := s.parts.Drain + s.parts.StoreLock + s.parts.DataSync + s.parts.HeadCAS + s.parts.HeadReadback + s.parts.MapPersist r.FixedParts.Other = max(time.Duration(0), s.fixed-known) } if s.rate > 0 { diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index f0b8f04ebf..7a1f1b52a5 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -150,8 +150,11 @@ func precopyRefusedFinalCutControl(t *testing.T, slow bool) { } } w.write(t, s, 1, 0xbb) - f.beforeCAS = func(f *fakeChunkRemote) { f.installLocked(copyHead(f.head)) } - r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { + // Target the final publication, not an earlier refused rolling attempt. + f.beforeCAS = func(f *fakeChunkRemote) { f.installLocked(copyHead(f.head)) } + return true + }) if r.Precopy.Frozen { if !errors.Is(err, ErrChunkHeadPrecondition) { t.Fatalf("report=%+v err=%v", r.Precopy, err) diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index c4096122f2..a44551b82f 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -101,12 +101,12 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { func TestPrecopyFixedPartsStayWithLargestObservation(t *testing.T) { _, _, l, _ := precopyLayer(t, 1024, 0) l.precopySamples = nil - st := chunkCutStats{CASNs: 1, DrainNs: int64(10 * time.Millisecond), LockWaitNs: int64(30 * time.Millisecond), SyncNs: int64(40 * time.Millisecond), CASWriteNs: int64(50 * time.Millisecond), HeadReadbackNs: int64(60 * time.Millisecond)} + st := chunkCutStats{CASNs: 1, DrainNs: int64(10 * time.Millisecond), LockWaitNs: int64(30 * time.Millisecond), SyncNs: int64(40 * time.Millisecond), CASWriteNs: int64(50 * time.Millisecond), HeadReadbackNs: int64(60 * time.Millisecond), MapPersistNs: int64(10 * time.Millisecond)} l.samplePrecopy(st, int64(200*time.Millisecond)) l.samplePrecopy(chunkCutStats{CASNs: 1, SyncNs: int64(100 * time.Millisecond)}, int64(150*time.Millisecond)) r := l.precopyEstimate(0, 0) p := r.FixedParts - if r.Fixed != 200*time.Millisecond || p.Drain != 10*time.Millisecond || p.StoreLock != 20*time.Millisecond || p.DataSync != 40*time.Millisecond || p.HeadCAS != 50*time.Millisecond || p.HeadReadback != 60*time.Millisecond || p.Other != 20*time.Millisecond { + if r.Fixed != 200*time.Millisecond || p.Drain != 10*time.Millisecond || p.StoreLock != 20*time.Millisecond || p.DataSync != 40*time.Millisecond || p.HeadCAS != 50*time.Millisecond || p.HeadReadback != 60*time.Millisecond || p.MapPersist != 10*time.Millisecond || p.Other != 10*time.Millisecond { t.Fatalf("mixed cost samples or overlapping terms: %+v", r) } } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 5df9c9d9ee..2fda490f07 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -422,6 +422,7 @@ type chunkCutStats struct { UnchangedChunks int UploadNs int64 CASNs int64 + MapPersistNs int64 CASResult string TotalNs int64 // Pre-copy (BarrierBound > 0): StageRounds staging rounds staged diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ee58cd7ae4..7bf18589ec 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -237,7 +237,7 @@ stateDiagram-v2 | 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 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; a non-improving tail of at most 25% of allowance may use a declared fixed-cost exception within the existing five-second freeze ceiling; 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` | @@ -477,7 +477,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `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-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. Admission fits the allowance or uses a declared fixed-cost exception only when the tail term is at most 25% and the estimate did not improve versus the prior attempt, within five seconds. Disjoint fixed-cost parts come from the same retained sample. | 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`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are 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 | diff --git a/seaweed-block/docs/spec/PrecopyFixedAdmission.tla b/seaweed-block/docs/spec/PrecopyFixedAdmission.tla new file mode 100644 index 0000000000..7ed7191033 --- /dev/null +++ b/seaweed-block/docs/spec/PrecopyFixedAdmission.tla @@ -0,0 +1,38 @@ +----------------------- MODULE PrecopyFixedAdmission ----------------------- +\* Admission only: data/authority/publication safety is covered by CutCOW2. +EXTENDS Integers, TLC +CONSTANTS OmitTailGuard, OmitStallGuard, OmitFreezeCap +Allowance == 12 +FreezeLimit == 50 +Margin == 1 +VARIABLES fixed, tail, previous, estimate, phase, declared, round +vars == <> +Init == /\ fixed \in {1,13,60} + /\ tail \in {0,1,3,4,20} + /\ previous = 0 /\ estimate = fixed + tail + Margin + /\ phase = "decide" /\ declared = 0 /\ round = 1 +Exception == /\ (OmitTailGuard \/ tail <= Allowance \div 4) + /\ (OmitStallGuard \/ (previous > 0 /\ estimate >= previous)) + /\ (OmitFreezeCap \/ estimate <= FreezeLimit) +Eligible == estimate <= Allowance \/ Exception +Commit == /\ phase = "decide" /\ Eligible + /\ phase' = "committed" /\ declared' = estimate + /\ UNCHANGED <> +Copy == /\ phase = "decide" /\ ~Eligible /\ round < 5 + /\ \E nextTail \in 0..tail: + /\ tail' = nextTail /\ previous' = estimate + /\ estimate' = fixed + nextTail + Margin + /\ round' = round + 1 + /\ UNCHANGED <> +Refuse == /\ phase = "decide" /\ ~Eligible /\ round = 5 + /\ phase' = "refused" + /\ UNCHANGED <> +Done == /\ phase # "decide" /\ UNCHANGED vars +Next == Commit \/ Copy \/ Refuse \/ Done +Spec == Init /\ [][Next]_vars +SafeCommit == phase = "committed" => + /\ declared = estimate /\ estimate <= FreezeLimit + /\ (estimate > Allowance => + /\ tail <= Allowance \div 4 + /\ previous > 0 /\ estimate >= previous) +============================================================================= diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg new file mode 100644 index 0000000000..3a6f20ba4b --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OmitTailGuard = FALSE + OmitStallGuard = FALSE + OmitFreezeCap = FALSE +INVARIANT SafeCommit diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg new file mode 100644 index 0000000000..11c8b345d4 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OmitTailGuard = FALSE + OmitStallGuard = FALSE + OmitFreezeCap = TRUE +INVARIANT SafeCommit diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg new file mode 100644 index 0000000000..8cdce12876 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OmitTailGuard = FALSE + OmitStallGuard = TRUE + OmitFreezeCap = FALSE +INVARIANT SafeCommit diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg new file mode 100644 index 0000000000..885ce1a845 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OmitTailGuard = TRUE + OmitStallGuard = FALSE + OmitFreezeCap = FALSE +INVARIANT SafeCommit From ed867d0c4e0494a2fa775f7b8bbe3e4e11285d59 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 14:34:16 -0800 Subject: [PATCH 04/20] test(storage): retain slow samples while permitting declared plateau commits --- .../core/frontend/durable/provider_chunk_precopy_test.go | 9 ++++++--- seaweed-block/docs/spec/README.md | 6 ++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 510c3f43af..679241547d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -243,8 +243,9 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { 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") { + // still refuse a tail-bound point; a small stalled tail can now declare + // the retained fixed-cost exception instead of recopying indefinitely. + 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" && r.Precopy.Reason != "fixed_cost_exceeds_freeze_budget") { t.Fatalf("post-release retry violated measured admission: report=%+v err=%v", r.Precopy, err) } if delay > 0 && r.Precopy.Fixed < delay { @@ -259,7 +260,9 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { 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 !r.Precopy.Frozen || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < delay || r.Precopy.TailEstimate > 300*time.Millisecond || r.Precopy.PreviousEstimate <= 0 || r.Precopy.Estimate < r.Precopy.PreviousEstimate || r.Precopy.Estimate > 5*time.Second || r.Precopy.DeclaredFreeze != r.Precopy.Estimate { + t.Fatalf("slow retry bypassed the declared small-tail plateau rule: %+v", r.Precopy) + } } if started, resumed := k.calls(); len(started) != 2 || len(resumed) != resumedCount { t.Fatalf("retry hooks: started=%v resumed=%v", started, resumed) diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 7b0862480e..254f474f92 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -334,3 +334,9 @@ one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; four negative controls separately remove retirement, the frame join, the readiness guard or ACK progress restoration. This abstracts successful admitted frames and does not prove physical-I/O, authority rollback or timing behavior. + +`PrecopyFixedAdmission.tla` checks bounded pre-copy cost admission: ordinary +allowance, small non-improving tail, declared freeze and the five-second ceiling. +`PrecopyFixedAdmission.cfg` is the positive configuration; `_no_tail`, `_no_stall` +and `_no_cap` must violate `SafeCommit`. It does not model publication/data safety +or physical latency; those remain separate checks. From 345b4f685eefc65466d3f0d86b05ce4d992aa095 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 14:37:00 -0800 Subject: [PATCH 05/20] test(storage): witness separate HEAD CAS and read-back timings --- .../chunk_precopy_fixed_commit_test.go | 39 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index a44551b82f..6e5e863bb2 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -131,3 +131,42 @@ func TestPrecopyFixedExceptionFinishUsesDeclaredFreeze(t *testing.T) { t.Fatal("relaxed ordinary fit bound") } } + +type precopyTimedHeadRemote struct { + *fakeChunkRemote + casDelay, readDelay time.Duration +} + +func (r *precopyTimedHeadRemote) CASHead(ctx context.Context, v chunkHeadVersion, h chunkHead) (uint64, error) { + timer := time.NewTimer(r.casDelay) + defer timer.Stop() + select { + case <-ctx.Done(): + return 0, ctx.Err() + case <-timer.C: + } + return r.fakeChunkRemote.CASHead(ctx, v, h) +} +func (r *precopyTimedHeadRemote) GetHead(ctx context.Context) (chunkHead, error) { + timer := time.NewTimer(r.readDelay) + defer timer.Stop() + select { + case <-ctx.Done(): + return chunkHead{}, ctx.Err() + case <-timer.C: + } + return r.fakeChunkRemote.GetHead(ctx) +} +func TestPrecopyFixedPartsMeasureCASAndReadbackSeparately(t *testing.T) { + r := &precopyTimedHeadRemote{fakeChunkRemote: newFakeChunkRemote(), casDelay: 15 * time.Millisecond, readDelay: 25 * time.Millisecond} + var st chunkCutStats + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _, err := casAndConfirmChunkHeadMeasured(ctx, r, chunkHeadVersion{}, chunkHead{Epoch: 1, Holder: "owner", Chunks: map[uint64]chunkRef{}}, &st) + if err != nil { + t.Fatal(err) + } + if time.Duration(st.CASWriteNs) < r.casDelay || time.Duration(st.HeadReadbackNs) < r.readDelay { + t.Fatalf("missing or overlapping operation timing: %+v", st) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7bf18589ec..c35f78a0d1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -477,7 +477,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance or uses a declared fixed-cost exception only when the tail term is at most 25% and the estimate did not improve versus the prior attempt, within five seconds. Disjoint fixed-cost parts come from the same retained sample. | 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`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance or uses a declared fixed-cost exception only when the tail term is at most 25% and the estimate did not improve versus the prior attempt, within five seconds. Disjoint fixed-cost parts come from the same retained sample. | 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`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt`, `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are 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 | From fdbac0f4630bd180e643a59ef5788ced020e26fa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 14:42:06 -0800 Subject: [PATCH 06/20] fix(storage): classify ceiling refusals and measure recovery read-backs --- seaweed-block/core/storage/chunk_layer.go | 10 ++++++++-- seaweed-block/core/storage/chunk_precopy.go | 15 +++++++++------ .../storage/chunk_precopy_fixed_commit_test.go | 11 +++++++++-- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 342aeccff8..5c32d22aeb 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -663,6 +663,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.persistCapturedMapV3(versions) st.MapPersistNs += time.Since(start).Nanoseconds() } + readCapturedHead := func() (chunkHead, error) { + start := time.Now() + head, err := readChunkHead(ctx, l.remote) + st.HeadReadbackNs += time.Since(start).Nanoseconds() + return head, err + } var pauseStart time.Time var payloadBeforeBarrier int64 defer func() { @@ -1000,7 +1006,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !upgrade && !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. - cur, err := readChunkHead(ctx, l.remote) + cur, err := readCapturedHead() if err != nil { l.abortCut(all) l.dropIntents(ctx, intents) @@ -1066,7 +1072,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.fencePublication(chunkHead{}) // confirmChunkHead already logged the observed root. return chunkCutResult{}, casErr } - cur, gerr := readChunkHead(ctx, l.remote) + cur, gerr := readCapturedHead() if gerr != nil { keepPending() return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 1c921d0705..54d5ac8689 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -337,18 +337,21 @@ func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt) bool { if r.Reason == "fit" && r.Estimate <= precopyAllowance { return true } - if previous == nil || previous.Estimate <= 0 || r.Reason == "samples_unknown" { + if r.Reason == "samples_unknown" { + return false + } + // Preserve and name the existing frontend ceiling even on the first round. + if r.TailEstimate <= precopyAllowance/4 && r.Estimate > precopyFreezeLimit { + r.Reason = "fixed_cost_exceeds_freeze_budget" + return false + } + if previous == nil || previous.Estimate <= 0 { return false } r.PreviousEstimate = previous.Estimate if r.TailEstimate > precopyAllowance/4 || r.Estimate < previous.Estimate { return false } - // Preserve the frontend's existing five-second held-command ceiling. - if r.Estimate > precopyFreezeLimit { - r.Reason = "fixed_cost_exceeds_freeze_budget" - return false - } r.Reason = "fixed_cost_over_allowance" return true } diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index 6e5e863bb2..be6cdccf54 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -11,15 +11,15 @@ import ( func TestPrecopyFixedCostSmallTailCommitsBySecondAttempt(t *testing.T) { s, f, l, w := precopyLayer(t, 1024, 0) fixed := 1300 * time.Millisecond - f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(fixed) } rounds := 0 l.testBeforeBarrierLockHook = func() { rounds++ w.write(t, s, 1, byte(rounds)) + f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(fixed) } // Keep the same known small tail and fixed envelope in each attempt. l.precopySamples = nil for i := 0; i < 3; i++ { - l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, rate: 20 * float64(ctChunkBytes)}) + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, parts: PrecopyFixedParts{HeadCAS: fixed}, rate: 20 * float64(ctChunkBytes)}) } } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) @@ -28,6 +28,9 @@ func TestPrecopyFixedCostSmallTailCommitsBySecondAttempt(t *testing.T) { if err != nil || !r.Precopy.Frozen || len(r.Precopy.Rounds) > 2 || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { t.Fatalf("fixed cost cannot converge by recopying the same small tail: report=%+v err=%v", r.Precopy, err) } + if r.Precopy.FreezeElapsed < fixed || r.Precopy.LatencyGateFailed || time.Duration(r.Stats.CASWriteNs) < fixed { + t.Fatalf("final fixed-cost operation was not witnessed within its declaration: %+v", r) + } if r.Head.State != ChunkHeadDetached || !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, byte(rounds))) { t.Fatal("amended commit lost the exact point") } @@ -77,6 +80,7 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { {"large-tail", 300*time.Millisecond + 1, 1500 * time.Millisecond, 1500 * time.Millisecond, true, false}, {"unknown", 0, 1500 * time.Millisecond, 1500 * time.Millisecond, false, false}, {"freeze-ceiling", 0, 5*time.Second + 1, 5*time.Second + 1, true, false}, + {"first-freeze-ceiling", 0, 5*time.Second + 1, 0, true, false}, } { t.Run(tc.name, func(t *testing.T) { reason := "tail_too_large" @@ -91,6 +95,9 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { if got := r.admitPrecopy(previous); got != tc.want { t.Fatalf("admit=%t report=%+v", got, r) } + if tc.known && tc.estimate > 5*time.Second && r.Reason != "fixed_cost_exceeds_freeze_budget" { + t.Fatalf("mislabelled fixed ceiling: %+v", r) + } if tc.want && r.Reason != "fixed_cost_over_allowance" { t.Fatalf("missing exception reason: %+v", r) } From 8b95fb320a213be91b131761c024be8f7cf5105d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 15:32:38 -0800 Subject: [PATCH 07/20] ci: give each test job 40 minutes Seven of the last 80 runs were cancelled at the 25-minute job limit while the tests were still running under host load (the default pass alone takes 11-16 minutes on a busy tp04). Each job now carries one pass, and 40 minutes leaves room for a loaded runner without letting a hung run sit for long. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index 9552e6b3bb..ef6b67ab9b 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -22,7 +22,7 @@ jobs: # capped at 8 cores / 8 GiB). Fork PRs never reach it: they stay on a # GitHub-hosted runner. runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'tp04-seaweed-block' || 'ubuntu-latest' }} - timeout-minutes: 25 + timeout-minutes: 40 env: # Pure-Go build: no package in the default build needs cgo, and the # hosted runner should not depend on a C toolchain being present. @@ -62,7 +62,7 @@ jobs: # runners (two instances, so both passes run in parallel); fork PRs stay on # a GitHub-hosted runner, whose shared queue can wait for hours. runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'tp04-seaweed-block' || 'ubuntu-latest' }} - timeout-minutes: 30 + timeout-minutes: 40 env: CGO_ENABLED: "0" steps: From 1bd28f7c53e4b9d3d6fce5fe6da79880bb51c668 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 15:33:41 -0800 Subject: [PATCH 08/20] test: witness disjoint pre-copy phase timing and record model results --- .../chunk_precopy_fixed_commit_test.go | 38 +++++++++++++------ seaweed-block/docs/spec/README.md | 22 +++++++++++ 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index be6cdccf54..e75b81645d 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "testing" + "testing/synctest" "time" ) @@ -142,6 +143,7 @@ func TestPrecopyFixedExceptionFinishUsesDeclaredFreeze(t *testing.T) { type precopyTimedHeadRemote struct { *fakeChunkRemote casDelay, readDelay time.Duration + beforeRead func() } func (r *precopyTimedHeadRemote) CASHead(ctx context.Context, v chunkHeadVersion, h chunkHead) (uint64, error) { @@ -155,6 +157,9 @@ func (r *precopyTimedHeadRemote) CASHead(ctx context.Context, v chunkHeadVersion return r.fakeChunkRemote.CASHead(ctx, v, h) } func (r *precopyTimedHeadRemote) GetHead(ctx context.Context) (chunkHead, error) { + if r.beforeRead != nil { + r.beforeRead() + } timer := time.NewTimer(r.readDelay) defer timer.Stop() select { @@ -165,15 +170,26 @@ func (r *precopyTimedHeadRemote) GetHead(ctx context.Context) (chunkHead, error) return r.fakeChunkRemote.GetHead(ctx) } func TestPrecopyFixedPartsMeasureCASAndReadbackSeparately(t *testing.T) { - r := &precopyTimedHeadRemote{fakeChunkRemote: newFakeChunkRemote(), casDelay: 15 * time.Millisecond, readDelay: 25 * time.Millisecond} - var st chunkCutStats - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - _, err := casAndConfirmChunkHeadMeasured(ctx, r, chunkHeadVersion{}, chunkHead{Epoch: 1, Holder: "owner", Chunks: map[uint64]chunkRef{}}, &st) - if err != nil { - t.Fatal(err) - } - if time.Duration(st.CASWriteNs) < r.casDelay || time.Duration(st.HeadReadbackNs) < r.readDelay { - t.Fatalf("missing or overlapping operation timing: %+v", st) - } + // The bubble's virtual clock advances only during the two blocked phases. + // Exact phase attribution is independent of host scheduling or elapsed limits. + synctest.Test(t, func(t *testing.T) { + r := &precopyTimedHeadRemote{fakeChunkRemote: newFakeChunkRemote(), casDelay: 15 * time.Millisecond, readDelay: 25 * time.Millisecond} + var st chunkCutStats + readEntered := false + r.beforeRead = func() { + readEntered = true + if time.Duration(st.CASWriteNs) != r.casDelay || st.HeadReadbackNs != 0 { + t.Fatalf("CAS must be settled before readback starts: %+v", st) + } + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _, err := casAndConfirmChunkHeadMeasured(ctx, r, chunkHeadVersion{}, chunkHead{Epoch: 1, Holder: "owner", Chunks: map[uint64]chunkRef{}}, &st) + if err != nil { + t.Fatal(err) + } + if !readEntered || time.Duration(st.CASWriteNs) != r.casDelay || time.Duration(st.HeadReadbackNs) != r.readDelay { + t.Fatalf("overlapping or missing phase attribution: %+v readEntered=%t", st, readEntered) + } + }) } diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 254f474f92..6f9709b3c4 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -340,3 +340,25 @@ allowance, small non-improving tail, declared freeze and the five-second ceiling `PrecopyFixedAdmission.cfg` is the positive configuration; `_no_tail`, `_no_stall` and `_no_cap` must violate `SafeCommit`. It does not model publication/data safety or physical latency; those remain separate checks. + + +### PrecopyFixedAdmission checked configurations + +Recorded local run, 2026-11-20 22:30 UTC, using the v1.7.4 tools distribution (TLC 2.19) +(`tla2tools.jar` SHA-256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`), +from `docs/spec`: + +```sh +java -cp /path/to/tla2tools.jar tla2sany.SANY PrecopyFixedAdmission.tla +java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/PrecopyFixedAdmission.cfg PrecopyFixedAdmission +``` + +SANY exited 0. The positive configuration exited 0: 11,240 generated states, +2,856 distinct, queue empty, complete depth 6. With the same command and the +respective `cfg/PrecopyFixedAdmission_no_*.cfg`, each negative exited 12 with +`SafeCommit` violated: `no_tail` (266 generated / 262 distinct, depth 3), +`no_stall` (44 / 41, depth 2), `no_cap` (546 / 517, depth 3). +These are the original local finite-state runs for this model, not a new run +for the documentation update. The bounds and exclusions above still apply; +this does not establish physical latency, publication safety or train qualification. From 45b3ec7c810f5ba5f8c1ffb6a35473b1d3a41292 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 15:43:02 -0800 Subject: [PATCH 09/20] ci: post-merge-review: read an allow list's unterminated last line Co-Authored-By: Claude Opus 5.5 --- .../.github/scripts/post-merge-review-check-test.sh | 11 +++++++++++ .../.github/scripts/post-merge-review-check.sh | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/seaweed-block/.github/scripts/post-merge-review-check-test.sh b/seaweed-block/.github/scripts/post-merge-review-check-test.sh index 7cf3d0c8b5..04e52b6287 100644 --- a/seaweed-block/.github/scripts/post-merge-review-check-test.sh +++ b/seaweed-block/.github/scripts/post-merge-review-check-test.sh @@ -107,6 +107,17 @@ for bad in "$empty" "/nonexistent/post-merge-review-allow.txt"; do done rm -f "$empty" +# A list whose last line has no newline keeps that line (here a denial). +unterminated=$(mktemp) +printf '*_test.go\n!core/workspace/*' >"$unterminated" +got=0 +printf 'M\0core/workspace/orch_test.go\0' | bash "$check" "$unterminated" >/dev/null 2>&1 || got=$? +[[ $got == 1 ]] || { echo "FAIL allow list with an unterminated last line: exit $got, want 1"; fail=1; } +got=0 +printf 'M\0cmd/foo/a_test.go\0' | bash "$check" "$unterminated" >/dev/null 2>&1 || got=$? +[[ $got == 0 ]] || { echo "FAIL allow list with an unterminated last line, allowed path: exit $got, want 0"; fail=1; } +rm -f "$unterminated" + # Real Git: names that git quotes in its default output, a rename out of a # denied directory, a retarget onto a base that differs, and test deletes. repo=$(mktemp -d) diff --git a/seaweed-block/.github/scripts/post-merge-review-check.sh b/seaweed-block/.github/scripts/post-merge-review-check.sh index 5875b0b928..918ee3f4bf 100644 --- a/seaweed-block/.github/scripts/post-merge-review-check.sh +++ b/seaweed-block/.github/scripts/post-merge-review-check.sh @@ -16,7 +16,8 @@ if [[ ! -f $allow_file ]]; then fi allow=() deny=() -while IFS= read -r line; do +# A last line without a newline is read too: dropping it could drop a "!". +while IFS= read -r line || [[ -n $line ]]; do line=${line%%#*} line=${line%"${line##*[![:space:]]}"} line=${line#"${line%%[![:space:]]*}"} From 4f395e23f77dbb5f636240367f6ada15e1dd20cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:02:38 -0800 Subject: [PATCH 10/20] feat: allow idle frontend plain chunk detach --- .../core/frontend/durable/provider_chunk.go | 28 ++++- .../durable/provider_plain_detach_test.go | 113 ++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 20 ++++ .../core/host/volume/chunk_control.go | 33 ++++- .../host/volume/chunk_plain_detach_test.go | 69 +++++++++++ seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/spec/PlainDetach.tla | 19 +++ seaweed-block/docs/spec/README.md | 18 +++ seaweed-block/docs/spec/cfg/PlainDetach.cfg | 3 + .../docs/spec/cfg/PlainDetach_no_idle.cfg | 3 + 10 files changed, 308 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_plain_detach_test.go create mode 100644 seaweed-block/core/host/volume/chunk_plain_detach_test.go create mode 100644 seaweed-block/docs/spec/PlainDetach.tla create mode 100644 seaweed-block/docs/spec/cfg/PlainDetach.cfg create mode 100644 seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 415d804e56..5ab9b9eb68 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -883,6 +883,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN // - HEAD belongs to another holder: stays stopped (fenced); // - undecidable (HEAD unreadable): stays stopped, ErrDetachOutcomeUnknown. func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { + return p.detachVolume(ctx, volumeID, false) +} + +// ErrPlainDetachBusy refuses a plain detach without closing frontend admission. +var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O") + +// DetachVolumePlain bypasses pre-copy cost admission only after atomically +// closing an idle frontend. Publication and failure settlement are unchanged. +func (p *DurableProvider) DetachVolumePlain(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { + return p.detachVolume(ctx, volumeID, true) +} + +func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, plain bool) (storage.ChunkCutResult, uint64, error) { p.mu.Lock() h, ok := p.volumes[volumeID] p.mu.Unlock() @@ -895,6 +908,12 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if err != nil { return storage.ChunkCutResult{}, 0, err } + if plain { + if err := ctx.Err(); err != nil { + return storage.ChunkCutResult{}, 0, err + } + } + precopy := p.cfg.ChunkDetachPrecopy && !plain freeze := p.cfg.DetachFreezeTimeout if freeze <= 0 { freeze = defaultDetachFreezeTimeout @@ -940,7 +959,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } var r storage.ChunkCutResult - if p.cfg.ChunkDetachPrecopy { + if precopy { owner, ok := layer.(interface { PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) }) @@ -987,6 +1006,11 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } else { beginFreeze() + if plain { + if err := h.backend.stopPlainDetachIfIdle(); err != nil { + return r, 0, err + } + } if trace := p.testDetachTrace; trace != nil { trace("cut", start.Add(freeze*3/4)) } @@ -1019,7 +1043,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st trace("settle", dl) } how, dr, serr := layer.SettleDetach(sctx) - if p.cfg.ChunkDetachPrecopy { + if precopy { attempts := countCAS() - casAtFreeze extra := uint64(0) if attempts > 0 { diff --git a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go new file mode 100644 index 0000000000..25760f74b5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go @@ -0,0 +1,113 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + hooks := &detachHooks{} + p := precopyProvider(t, remote, &parkView{stubView: v1View()}, hooks) + openRecovered(t, p) + b, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(ctx, 4096, block(0x4a)); err != nil { + t.Fatal(err) + } + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + joined := false + t.Cleanup(func() { + unblock() + cancel() + if !joined { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("admitted sync did not join") + } + } + }) + 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) + } + go func() { done <- b.Sync(ctx) }() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("sync was not admitted") + } + r, _, err := p.DetachVolume(ctx, "v1") + if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen { + t.Fatalf("expected thawed pre-copy refusal: %+v %v", r, err) + } + before, err := remote.GetHead(ctx) + if err != nil || before.State == storage.ChunkHeadDetached { + t.Fatalf("refusal detached: %+v %v", before, err) + } + if _, _, err = p.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrPlainDetachBusy) { + t.Fatalf("plain accepted admitted I/O: %v", err) + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != before.Gen || after.State != before.State { + t.Fatalf("busy plain mutated HEAD: before=%+v after=%+v err=%v", before, after, err) + } + starts, resumes := hooks.calls() + if len(starts) != 1 || len(resumes) != 1 { + t.Fatalf("busy plain mutated detach hooks: %v %v", starts, resumes) + } + unblock() + select { + case err = <-done: + joined = true + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("sync did not finish") + } + // A refused plain request left service and authority unchanged. + if _, err = b.Write(ctx, 8192, block(0x5b)); err != nil { + t.Fatal("busy plain stopped service:", err) + } + r, last, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last || len(r.Precopy.Rounds) != 0 { + t.Fatalf("plain did not use ordinary detached cut: %+v last=%d err=%v", r, last, err) + } + for _, x := range []struct { + lba uint32 + value byte + }{{1, 0x4a}, {2, 0x5b}} { + if !bytes.Equal(headBlock(t, remote, x.lba), block(x.value)) { + t.Fatalf("plain lost acknowledged block %d", x.lba) + } + } + if _, err = b.Write(ctx, 12288, block(0x6c)); err == nil { + t.Fatal("old frontend serves after plain detach") + } + again, last2, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || again.Head.Gen != r.Head.Gen || last2 != last { + t.Fatalf("plain retry changed result: %+v last=%d err=%v", again, last2, err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3b4830344b..f1c9e3779c 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -543,6 +543,26 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { return true } +// stopPlainDetachIfIdle closes admission without waiting for a live command. +// Taking ioMu exclusively also excludes commands between their gate and final +// registration; a failed try leaves every admission/pause field unchanged. +func (b *StorageBackend) stopPlainDetachIfIdle() error { + if !b.ioMu.TryLock() { + return ErrPlainDetachBusy + } + defer b.ioMu.Unlock() + b.mu.Lock() + defer b.mu.Unlock() + if b.closed { + return frontend.ErrBackendClosed + } + if b.admittedIO != 0 { + return ErrPlainDetachBusy + } + b.setOperationalLocked(false, "chunk plain detach: idle frontend stopped") + return nil +} + // StopIO makes the backend refuse every new Read, Write and Sync with // ErrNotReady (evidence), then waits, bounded by ctx, for the I/O admitted // before the stop to finish. After a nil return no I/O admitted before the diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 392e12a380..7234b81f2d 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -238,6 +238,8 @@ func writeChunkFailure(w http.ResponseWriter, err error) { func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError switch { + case errors.Is(err, durable.ErrPlainDetachBusy): + return http.StatusConflict, "plain_detach_busy", true case errors.Is(err, storage.ErrPrecopyUnknown): return http.StatusConflict, "precopy_unknown", true case errors.Is(err, storage.ErrPrecopyNotConverged): @@ -488,6 +490,7 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) var req struct { VolumeID string `json:"volumeID"` TimeoutMs int64 `json:"timeoutMs"` + Plain bool `json:"plain,omitempty"` } if !decodeChunkBody(w, r, &req) { return @@ -498,7 +501,20 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) } ctx, cancel := chunkContext(r, req.TimeoutMs) defer cancel() - res, err := ctl.Detach(ctx, req.VolumeID) + var res ChunkDetachResponse + var err error + if req.Plain { + plain, ok := ctl.(interface { + DetachPlain(context.Context, string) (ChunkDetachResponse, error) + }) + if !ok { + writeChunkErr(w, http.StatusConflict, "plain_detach_unsupported", false, "plain detach unsupported") + return + } + res, err = plain.DetachPlain(ctx, req.VolumeID) + } else { + res, err = ctl.Detach(ctx, req.VolumeID) + } if err != nil { writeChunkFailure(w, err) return @@ -599,6 +615,21 @@ func (s *StatusServer) handleStatusChunk(w http.ResponseWriter, r *http.Request) func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { r, last, err := c.p.DetachVolume(ctx, volumeID) + return chunkDetachResponse(volumeID, r, last, err) +} + +func (c *chunkControl) DetachPlain(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { + p, ok := c.p.(interface { + DetachVolumePlain(context.Context, string) (storage.ChunkCutResult, uint64, error) + }) + if !ok { + return ChunkDetachResponse{}, fmt.Errorf("plain detach unsupported by provider") + } + r, last, err := p.DetachVolumePlain(ctx, volumeID) + return chunkDetachResponse(volumeID, r, last, err) +} + +func chunkDetachResponse(volumeID string, r storage.ChunkCutResult, last uint64, err error) (ChunkDetachResponse, error) { if err != nil { return ChunkDetachResponse{}, err } diff --git a/seaweed-block/core/host/volume/chunk_plain_detach_test.go b/seaweed-block/core/host/volume/chunk_plain_detach_test.go new file mode 100644 index 0000000000..1d129984aa --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_plain_detach_test.go @@ -0,0 +1,69 @@ +package volume + +import ( + "context" + "encoding/json" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "net/http" + "testing" +) + +type plainDetachControl struct { + *fakeChunkControl + plainCalls int +} + +func (c *plainDetachControl) DetachPlain(ctx context.Context, id string) (ChunkDetachResponse, error) { + c.plainCalls++ + return c.fakeChunkControl.Detach(ctx, id) +} +func TestChunkDetachPlainFieldDispatch(t *testing.T) { + c := &plainDetachControl{fakeChunkControl: &fakeChunkControl{detach: ChunkDetachResponse{VolumeID: "v1"}}} + s := chunkServer(t, c, true) + for _, body := range []string{`{"volumeID":"v1"}`, `{"volumeID":"v1","plain":false}`} { + w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") + if w.Code != 200 || c.plainCalls != 0 { + t.Fatalf("ordinary request changed: %d %s plain=%d", w.Code, w.Body, c.plainCalls) + } + } + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + if w.Code != 200 || c.plainCalls != 1 { + t.Fatalf("plain request not dispatched: %d %s plain=%d", w.Code, w.Body, c.plainCalls) + } +} + +type plainDetachProvider struct { + *fakeChunkProvider + plainCalls int + err error +} + +func (p *plainDetachProvider) DetachVolumePlain(ctx context.Context, id string) (storage.ChunkCutResult, uint64, error) { + p.plainCalls++ + if p.err != nil { + return storage.ChunkCutResult{}, 0, p.err + } + return p.DetachVolume(ctx, id) +} +func TestChunkDetachPlainAdapterAndBusyResponse(t *testing.T) { + p := &plainDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 9, Head: storage.ChunkHead{Gen: 3, Epoch: 2, State: storage.ChunkHeadDetached}}, last: 9}} + s := chunkServer(t, NewChunkControl(p, nil), true) + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + if w.Code != 200 || p.plainCalls != 1 { + t.Fatalf("plain adapter: %d %s calls=%d", w.Code, w.Body, p.plainCalls) + } + p.err = errors.Join(durable.ErrPlainDetachBusy, errors.New("held I/O")) + w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + if w.Code != 409 { + t.Fatalf("busy status: %d %s", w.Code, w.Body) + } + var body struct { + Code string `json:"code"` + Retryable bool `json:"retryable"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Code != "plain_detach_busy" || !body.Retryable { + t.Fatalf("busy classification: %s %v", w.Body, err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cdd34e146d..935e1b5a53 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -206,6 +206,8 @@ A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. Th stateDiagram-v2 [*] --> Admit Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid + Admit --> PlainStop: plain detach and idle frontend lock acquired + PlainStop --> Quiesce: frontend stopped; ordinary detached cut Admit --> Stage: budget admitted, earlier unknown CAS settled Stage --> Quiesce: spill-budget remainder reached or no shrink Quiesce --> FinalFreeze: opt-in measured tail fits after bounded admission drain @@ -235,7 +237,9 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `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` | +| Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `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` | diff --git a/seaweed-block/docs/spec/PlainDetach.tla b/seaweed-block/docs/spec/PlainDetach.tla new file mode 100644 index 0000000000..0bd3733bb2 --- /dev/null +++ b/seaweed-block/docs/spec/PlainDetach.tla @@ -0,0 +1,19 @@ +----------------------------- MODULE PlainDetach ----------------------------- +\* Idle-gated admission only. HEAD CAS, authority, physical I/O and timing +\* remain the existing detach/cut obligations, outside this abstraction. +EXTENDS Naturals, TLC +CONSTANT IdleGuard +VARIABLES phase, readers +vars == <> +Init == /\ phase = "serving" /\ readers = 0 +BeginIO == /\ phase = "serving" /\ readers < 2 + /\ readers' = readers + 1 /\ UNCHANGED phase +EndIO == /\ readers > 0 /\ readers' = readers - 1 /\ UNCHANGED phase +Plain == /\ phase = "serving" /\ (~IdleGuard \/ readers = 0) + /\ phase' = "stopped" /\ UNCHANGED readers +Publish == /\ phase = "stopped" /\ phase' = "detached" /\ UNCHANGED readers +Abort == /\ phase = "stopped" /\ phase' = "serving" /\ UNCHANGED readers +Next == BeginIO \/ EndIO \/ Plain \/ Publish \/ Abort +Spec == Init /\ [][Next]_vars +IdleAtStop == phase \in {"stopped", "detached"} => readers = 0 +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 7b0862480e..bfe79c4383 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -334,3 +334,21 @@ one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; four negative controls separately remove retirement, the frame join, the readiness guard or ACK progress restoration. This abstracts successful admitted frames and does not prove physical-I/O, authority rollback or timing behavior. + + +## Plain detach admission + +`PlainDetach.tla` models the explicit plain-detach idle gate and atomic closure +of frontend admission, with up to two I/O readers. `IdleAtStop` checks that +stopping or detached states have no admitted/entering reader. HEAD publication, +authority, physical I/O, wall-clock bounds, and failure settlement are outside +this small admission abstraction and retain their existing native controls. + +Local run 2026-11-21 00:00 UTC, tools distribution v1.7.4 (TLC 2.19), jar SHA-256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`. +From `docs/spec`, SANY `PlainDetach.tla` exited 0; TLC with +`-deadlock -config cfg/PlainDetach.cfg PlainDetach` exited 0 (8 generated, +5 distinct, queue empty, depth 3). Replacing the config with +`cfg/PlainDetach_no_idle.cfg` exited 12: `IdleAtStop` fails on +BeginIO -> Plain (7 generated / 5 distinct, depth 3). The negative uses a +distinct `-metadir` to avoid timestamp-directory collisions between short runs. diff --git a/seaweed-block/docs/spec/cfg/PlainDetach.cfg b/seaweed-block/docs/spec/cfg/PlainDetach.cfg new file mode 100644 index 0000000000..71ab7aaaa2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PlainDetach.cfg @@ -0,0 +1,3 @@ +CONSTANT IdleGuard = TRUE +SPECIFICATION Spec +INVARIANT IdleAtStop diff --git a/seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg b/seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg new file mode 100644 index 0000000000..300b94071a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg @@ -0,0 +1,3 @@ +CONSTANT IdleGuard = FALSE +SPECIFICATION Spec +INVARIANT IdleAtStop From ea38af0f9c4dd9f138c46686932e3f3fd34cd6f7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:04:25 -0800 Subject: [PATCH 11/20] test: isolate plain detach pre-copy bypass control --- .../durable/provider_plain_detach_test.go | 19 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go index 25760f74b5..37edd575bc 100644 --- a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go +++ b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go @@ -111,3 +111,22 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { t.Fatalf("plain retry changed result: %+v last=%d err=%v", again, last2, err) } } + +func TestPlainDetachSkipsPrecopyCostAdmission(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(ctx, 4096, block(0x7c)); err != nil { + t.Fatal(err) + } + r, _, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x7c)) { + t.Fatalf("plain request used pre-copy admission or lost its point: %+v %v", r, err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 935e1b5a53..4d7b0705b9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -238,7 +238,7 @@ stateDiagram-v2 | 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` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| 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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `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` | From a28f2b73b5cb55193c14f291614c6b68abcf4360 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:13:44 -0800 Subject: [PATCH 12/20] docs: restore pre-copy transition and place plain detach invariant --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4d7b0705b9..5775395d50 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -238,8 +238,7 @@ stateDiagram-v2 | 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` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-CUT-PRECOPY-001` | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | 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` | @@ -481,6 +480,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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | 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` (first fitting attempt; earlier over-budget estimates must refuse), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, active owner and exact local bytes), `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 | From 11227d158a815297e51d44a4c31f2f294515ae14 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:23:50 -0800 Subject: [PATCH 13/20] feat: advertise plain chunk detach capability --- seaweed-block/cmd/blockvolume/main.go | 1 + .../plain_detach_capability_test.go | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/plain_detach_capability_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index de5e5739cf..ca2a80a683 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.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") 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)") diff --git a/seaweed-block/cmd/blockvolume/plain_detach_capability_test.go b/seaweed-block/cmd/blockvolume/plain_detach_capability_test.go new file mode 100644 index 0000000000..e49fb06fb7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/plain_detach_capability_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestPlainDetachCapabilityFlagIsNoop(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + want, err := parseFlags(base) + if err != nil { + t.Fatal(err) + } + for _, arg := range []string{"--chunk-detach-plain-supported", "--chunk-detach-plain-supported=true", "--chunk-detach-plain-supported=false"} { + got, err := parseFlags(append(append([]string{}, base...), arg)) + if err != nil { + t.Fatalf("capability flag unavailable: %s: %v", arg, err) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("capability flag changed runtime configuration: %s", arg) + } + } +} From 92d2c3fa895c84f5950aacd7cf4e4a8e0de2314f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:48:21 -0800 Subject: [PATCH 14/20] fix: expose cut timing fields and admit drain refusal in fixture --- .../durable/precopy_fifty_iops_test.go | 73 +++++++++++++++---- .../core/host/volume/chunk_control.go | 8 ++ 2 files changed, 68 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 4ba4423a44..14470678b4 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -167,11 +167,10 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool, fixedDelay t } // A loaded host may correctly refuse an expensive tail. Preserve the // first-attempt oracle whenever it fits: EVERY earlier attempt must have - // been refused by both the ordinary allowance and the small-tail plateau rule. + // been refused by frontend drain admission or both cost-admission rules. if fixedDelay > 0 && result.Precopy.Fixed < fixedDelay { t.Fatalf("lost slow fixed sample: %+v", result.Precopy) } - const allowance = 1200 * time.Millisecond if len(result.Precopy.Rounds) == 0 { t.Fatal("no admission attempts") } @@ -179,20 +178,15 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool, fixedDelay t t.Fatal("final freeze disagrees with attempt report") } for i, round := range result.Precopy.Rounds { - eligible := round.Estimate <= allowance - reason := "fit" - if !eligible && i > 0 && round.TailEstimate <= allowance/4 && round.Estimate >= result.Precopy.Rounds[i-1].Estimate && round.Estimate <= 5*time.Second { - eligible = true - reason = "fixed_cost_over_allowance" + var previous *storage.PrecopyAttempt + if i > 0 { + previous = &result.Precopy.Rounds[i-1] } - if round.Frozen { - if !eligible || i != len(result.Precopy.Rounds)-1 || round.Reason != reason || round.DeclaredFreeze != round.Estimate || round.Error != "" { - t.Fatalf("invalid fitting attempt: %+v", round) - } - } else if eligible || (round.Reason != "tail_too_large" && round.Reason != "barrier_over_budget" && round.Reason != "fixed_cost_exceeds_freeze_budget") || round.Error != "" { - t.Fatalf("refused an eligible attempt or hid a failure: %+v", round) + if admissionErr := precopyFiftyAttemptError(round, previous, i == len(result.Precopy.Rounds)-1); admissionErr != nil { + t.Fatal(admissionErr) } } + if !result.Precopy.Frozen { if !errors.Is(err, storage.ErrPrecopyNotConverged) || len(result.Precopy.Rounds) != 5 || result.Precopy.Attempts != 5 || guestErrors.Load() != 0 { t.Fatalf("wrong over-budget outcome: report=%+v err=%v", result.Precopy, err) @@ -301,3 +295,56 @@ func TestPrecopyFiftyIOPSRoundAccounting(t *testing.T) { } }) } + +func precopyFiftyAttemptError(round storage.PrecopyAttempt, previous *storage.PrecopyAttempt, last bool) error { + // Drain admission precedes cost admission. A still-draining FIFO pause + // can refuse even a cheap round; it must not freeze or declare admission. + if !round.Frozen && (round.Reason == "drain_refused" || round.Reason == "drain_timeout") { + if round.Error != "" || round.DeclaredFreeze != 0 { + return fmt.Errorf("drain refusal hid a failure or declared admission: %+v", round) + } + return nil + } + const allowance = 1200 * time.Millisecond + eligible := round.Estimate <= allowance + reason := "fit" + if !eligible && previous != nil && round.TailEstimate <= allowance/4 && round.Estimate >= previous.Estimate && round.Estimate <= 5*time.Second { + eligible, reason = true, "fixed_cost_over_allowance" + } + if round.Frozen { + if !eligible || !last || round.Reason != reason || round.DeclaredFreeze != round.Estimate || round.Error != "" { + return fmt.Errorf("invalid fitting attempt: %+v", round) + } + } else if eligible || (round.Reason != "tail_too_large" && round.Reason != "barrier_over_budget" && round.Reason != "fixed_cost_exceeds_freeze_budget") || round.Error != "" { + return fmt.Errorf("refused an eligible attempt or hid a failure: %+v", round) + } + return nil +} + +func TestPrecopyFiftyIOPSDrainRefusalDoesNotClaimAdmission(t *testing.T) { + previous := storage.PrecopyAttempt{Estimate: 1740 * time.Millisecond} + for _, reason := range []string{"drain_refused", "drain_timeout"} { + for _, estimate := range []time.Duration{500 * time.Millisecond, 1740 * time.Millisecond} { + t.Run(fmt.Sprintf("%s_%d", reason, estimate), func(t *testing.T) { + round := storage.PrecopyAttempt{Reason: reason, Estimate: estimate} + if err := precopyFiftyAttemptError(round, &previous, false); err != nil { + t.Fatal(err) + } + round.Error = "physical read failure" + if err := precopyFiftyAttemptError(round, &previous, false); err == nil { + t.Fatal("drain refusal hid a physical failure") + } + round.Error = "" + round.Frozen = true + if err := precopyFiftyAttemptError(round, &previous, true); err == nil { + t.Fatal("drain refusal claimed a frozen command") + } + round.Frozen = false + round.DeclaredFreeze = round.Estimate + if err := precopyFiftyAttemptError(round, &previous, false); err == nil { + t.Fatal("drain refusal claimed a freeze declaration") + } + }) + } + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 392e12a380..1a52a4270a 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -64,6 +64,10 @@ type ChunkCutStatsBody struct { COWWaitNs int64 `json:"cowWaitNs"` BarrierPauseNs int64 `json:"barrierPauseNs"` LockWaitNs int64 `json:"lockWaitNs"` + DrainNs int64 `json:"drainNs"` + CASWriteNs int64 `json:"casWriteNs"` + MapPersistNs int64 `json:"mapPersistNs"` + HeadReadbackNs int64 `json:"headReadbackNs"` SyncNs int64 `json:"syncNs"` CopyNs int64 `json:"copyNs"` CandidateChunks int `json:"candidateChunks"` @@ -89,6 +93,10 @@ func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { COWLocalReadNs: s.COWLocalReadNs, BarrierPauseNs: s.BarrierPauseNs, LockWaitNs: s.LockWaitNs, + DrainNs: s.DrainNs, + CASWriteNs: s.CASWriteNs, + MapPersistNs: s.MapPersistNs, + HeadReadbackNs: s.HeadReadbackNs, SyncNs: s.SyncNs, CopyNs: s.CopyNs, COWSavedChunks: s.COWSavedChunks, From b3734dc2cb4105911620effdca792df145a2bd91 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:48:14 -0800 Subject: [PATCH 15/20] fix(storage): admit bounded pre-copy plateaus and age fixed samples --- .../durable/precopy_fifty_iops_test.go | 18 +++- .../durable/provider_chunk_precopy_test.go | 4 +- seaweed-block/core/storage/chunk_precopy.go | 92 +++++++++++-------- .../storage/chunk_precopy_amendment4_test.go | 88 ++++++++++++++++++ .../core/storage/chunk_precopy_detach_test.go | 2 +- .../chunk_precopy_fixed_commit_test.go | 25 ++--- seaweed-block/docs/design/invariants.md | 2 +- .../docs/spec/PrecopyFixedAdmission.tla | 10 +- seaweed-block/docs/spec/README.md | 34 ++++--- .../docs/spec/cfg/PrecopyFixedAdmission.cfg | 4 +- .../spec/cfg/PrecopyFixedAdmission_no_cap.cfg | 4 +- ...cfg => PrecopyFixedAdmission_no_final.cfg} | 4 +- .../cfg/PrecopyFixedAdmission_no_stall.cfg | 4 +- 13 files changed, 204 insertions(+), 87 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_precopy_amendment4_test.go rename seaweed-block/docs/spec/cfg/{PrecopyFixedAdmission_no_tail.cfg => PrecopyFixedAdmission_no_final.cfg} (54%) diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index 14470678b4..a6d9a32879 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -306,16 +306,26 @@ func precopyFiftyAttemptError(round storage.PrecopyAttempt, previous *storage.Pr return nil } const allowance = 1200 * time.Millisecond - eligible := round.Estimate <= allowance + if round.Reason == "samples_unknown" { + if round.Frozen || round.DeclaredFreeze != 0 || round.Error != "" { + return fmt.Errorf("unknown sample admitted: %+v", round) + } + return nil + } + eligible := round.Estimate > 0 && round.Estimate <= allowance reason := "fit" - if !eligible && previous != nil && round.TailEstimate <= allowance/4 && round.Estimate >= previous.Estimate && round.Estimate <= 5*time.Second { - eligible, reason = true, "fixed_cost_over_allowance" + if !eligible && round.Estimate > 0 && round.Estimate <= 5*time.Second { + if previous != nil && previous.Estimate > 0 && round.Estimate >= previous.Estimate-previous.Estimate/10 { + eligible, reason = true, "no_progress" + } else if round.Attempt == 5 { + eligible, reason = true, "final_attempt" + } } if round.Frozen { if !eligible || !last || round.Reason != reason || round.DeclaredFreeze != round.Estimate || round.Error != "" { return fmt.Errorf("invalid fitting attempt: %+v", round) } - } else if eligible || (round.Reason != "tail_too_large" && round.Reason != "barrier_over_budget" && round.Reason != "fixed_cost_exceeds_freeze_budget") || round.Error != "" { + } else if eligible || (round.Reason != "tail_too_large" && round.Reason != "barrier_over_budget" && round.Reason != "freeze_budget_exceeded") || round.Error != "" { return fmt.Errorf("refused an eligible attempt or hid a failure: %+v", round) } return nil diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 679241547d..07e2f433f9 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -245,7 +245,7 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { // Releasing the owner does not erase a slow sample. Admission must // still refuse a tail-bound point; a small stalled tail can now declare // the retained fixed-cost exception instead of recopying indefinitely. - 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" && r.Precopy.Reason != "fixed_cost_exceeds_freeze_budget") { + 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" && r.Precopy.Reason != "freeze_budget_exceeded") { t.Fatalf("post-release retry violated measured admission: report=%+v err=%v", r.Precopy, err) } if delay > 0 && r.Precopy.Fixed < delay { @@ -260,7 +260,7 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { t.Fatalf("over-budget retry failed to resume service: n=%d err=%v", n, e) } } else if delay > 0 { - if !r.Precopy.Frozen || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < delay || r.Precopy.TailEstimate > 300*time.Millisecond || r.Precopy.PreviousEstimate <= 0 || r.Precopy.Estimate < r.Precopy.PreviousEstimate || r.Precopy.Estimate > 5*time.Second || r.Precopy.DeclaredFreeze != r.Precopy.Estimate { + if !r.Precopy.Frozen || r.Precopy.Reason != "no_progress" || r.Precopy.Fixed < delay || r.Precopy.PreviousEstimate <= 0 || r.Precopy.Estimate < r.Precopy.PreviousEstimate-r.Precopy.PreviousEstimate/10 || r.Precopy.Estimate > 5*time.Second || r.Precopy.DeclaredFreeze != r.Precopy.Estimate { t.Fatalf("slow retry bypassed the declared small-tail plateau rule: %+v", r.Precopy) } } diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 54d5ac8689..922b695340 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -19,6 +19,8 @@ const ( precopyMargin = 100 * time.Millisecond precopyDrainBound = 100 * time.Millisecond precopyFreezeLimit = 5 * time.Second + precopyFixedWindow = 5 + precopyFixedMaxAge = 15 * time.Minute ) // PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample. @@ -101,7 +103,7 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo r.CASFailureTimeout = chunkHeadOperationTimeout r.DeclaredWorst = r.Estimate + time.Duration(extraCAS)*chunkHeadOperationTimeout limit := precopyAllowance - if r.Reason == "fixed_cost_over_allowance" { + if r.Reason == "no_progress" || r.Reason == "final_attempt" { limit = min(r.DeclaredFreeze, precopyFreezeLimit) } r.LatencyGateFailed = failed || elapsed > limit @@ -194,7 +196,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if len(rounds) > 0 { previous = &rounds[len(rounds)-1] } - if !report.admitPrecopy(previous) { + if !report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) { return false } report.DeclaredFreeze = report.Estimate @@ -211,7 +213,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context 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 { + if l.precopyEstimate(0, 0).Reason != "samples_unknown" { warmAttempts++ } else { measurementRounds++ @@ -276,30 +278,34 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor 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 { + // Fixed work uses the last five fresh observations, independent of the + // latest-three-rate window. Parts always belong to the selected observation. + fixedCount := 0 + for i := len(l.precopySamples) - 1; i >= 0; i-- { + sample := l.precopySamples[i] + age := now.Sub(sample.at) + if age < 0 { continue } - if age > r.SampleAge { - r.SampleAge = age + if age <= precopyDuration && sample.rate > 0 { + rates = append(rates, sample.rate) } - // 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 - r.FixedParts = s.parts - known := s.parts.Drain + s.parts.StoreLock + s.parts.DataSync + s.parts.HeadCAS + s.parts.HeadReadback + s.parts.MapPersist - r.FixedParts.Other = max(time.Duration(0), s.fixed-known) + if age >= precopyFixedMaxAge || fixedCount >= precopyFixedWindow { + continue } - if s.rate > 0 { - rates = append(rates, s.rate) + fixedCount++ + r.SampleAge = max(r.SampleAge, age) + if sample.fixed > r.Fixed { + r.Fixed = sample.fixed + r.FixedParts = precopyFixedPartsFromSample(sample) } } + // Rates were visited newest first; only the latest three are used below. r.RateSamples = len(rates) - if r.Fixed <= 0 { + if len(rates) > 3 { + rates = rates[:3] + } + if fixedCount < precopyFixedWindow || r.Fixed <= 0 { return r } r.Estimate = r.Fixed + precopyMargin @@ -331,29 +337,41 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor return r } -// More copying cannot reduce a fixed-bound plateau. Only the measured tail -// may use at most a quarter of the normal allowance on this exception path. -func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt) bool { - if r.Reason == "fit" && r.Estimate <= precopyAllowance { +// Rounds shrink the tail; a plateau or the final round may use the full +// declared freeze budget. The final flag is the physical round, not the number +// of warm admission attempts (measurement rounds consume the same limit). +func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt, final bool) bool { + if r.Reason == "samples_unknown" || r.Estimate <= 0 { + return false + } + if r.Estimate <= precopyAllowance { + r.Reason = "fit" return true } - if r.Reason == "samples_unknown" { + if r.Estimate > precopyFreezeLimit { + r.Reason = "freeze_budget_exceeded" return false } - // Preserve and name the existing frontend ceiling even on the first round. - if r.TailEstimate <= precopyAllowance/4 && r.Estimate > precopyFreezeLimit { - r.Reason = "fixed_cost_exceeds_freeze_budget" - return false + if previous != nil && previous.Estimate > 0 { + r.PreviousEstimate = previous.Estimate + // Division first avoids overflow while retaining nanosecond precision. + threshold := previous.Estimate - previous.Estimate/10 + if r.Estimate >= threshold { + r.Reason = "no_progress" + return true + } } - if previous == nil || previous.Estimate <= 0 { - return false + if final { + r.Reason = "final_attempt" + return true } - r.PreviousEstimate = previous.Estimate - if r.TailEstimate > precopyAllowance/4 || r.Estimate < previous.Estimate { - return false - } - r.Reason = "fixed_cost_over_allowance" - return true + return false +} + +func precopyFixedPartsFromSample(s precopySample) PrecopyFixedParts { + p := s.parts + p.Other = max(time.Duration(0), s.fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist) + return p } func (l *chunkLayerImpl) samplePrecopy(st chunkCutStats, fixedNs int64) { diff --git a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go new file mode 100644 index 0000000000..ef6a9fa263 --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go @@ -0,0 +1,88 @@ +package storage + +import ( + "testing" + "time" +) + +func TestPrecopySmokeTraceAmendment4(t *testing.T) { + estimates := []time.Duration{1475267, 1465874, 1733371, 1733371, 1733371} + tails := []time.Duration{140090, 130697, 398194, 398194, 398194} + var previous *PrecopyAttempt + for i, e := range estimates { + r := PrecopyReport{Fixed: 1235177 * time.Microsecond, Estimate: e * time.Microsecond, TailEstimate: tails[i] * time.Microsecond, Reason: "tail_too_large"} + if r.admitPrecopy(previous, i == 4) { + if i > 2 || r.Reason != "no_progress" { + t.Fatalf("late/wrong admission round%d: %+v", i+1, r) + } + return + } + previous = &PrecopyAttempt{Estimate: r.Estimate} + } + t.Fatal("smoke trace refused despite no meaningful progress within freeze bound") +} +func TestPrecopyFixedWindowDecays(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + now := time.Now() + l.precopySamples = nil + l.precopySamples = append(l.precopySamples, precopySample{at: now, fixed: 1235 * time.Millisecond}) + for i := 0; i < 5; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: now, fixed: 100 * time.Millisecond, rate: 1e9}) + } + if r := l.precopyEstimate(0, 0); r.Fixed != 100*time.Millisecond { + t.Fatalf("old peak retained: %+v", r) + } + l.precopySamples = l.precopySamples[1:] + l.precopySamples[0].at = now.Add(-16 * time.Minute) + if r := l.precopyEstimate(0, 0); r.Reason != "samples_unknown" { + t.Fatalf("fewer than five fresh samples accepted: %+v", r) + } +} +func TestPrecopyFinalAttemptFreezeCeiling(t *testing.T) { + for _, tc := range []struct { + estimate time.Duration + want bool + }{{4500 * time.Millisecond, true}, {5500 * time.Millisecond, false}} { + r := PrecopyReport{Estimate: tc.estimate, TailEstimate: 3 * time.Second, Reason: "tail_too_large"} + previous := &PrecopyAttempt{Estimate: 6 * time.Second} + if got := r.admitPrecopy(previous, true); got != tc.want { + t.Fatalf("final admission=%t want=%t: %+v", got, tc.want, r) + } + if tc.want && r.Reason != "final_attempt" { + t.Fatalf("wrong final reason: %+v", r) + } + } +} + +func TestPrecopyAmendment4AdmissionBoundaries(t *testing.T) { + for _, tc := range []struct { + name string + estimate, previous time.Duration + final bool + reason string + }{ + {"fit", time.Second, 0, false, "fit"}, + {"ten-percent", 1800 * time.Millisecond, 2 * time.Second, false, "no_progress"}, + {"meaningful", 1800*time.Millisecond - 1, 2 * time.Second, false, "tail_too_large"}, + {"final-no-history", 4 * time.Second, 0, true, "final_attempt"}, + {"ceiling", 5 * time.Second, 0, true, "final_attempt"}, + {"over-ceiling", 5*time.Second + 1, 6 * time.Second, true, "freeze_budget_exceeded"}, + } { + t.Run(tc.name, func(t *testing.T) { + r := PrecopyReport{Estimate: tc.estimate, Reason: "tail_too_large"} + var prev *PrecopyAttempt + if tc.previous > 0 { + prev = &PrecopyAttempt{Estimate: tc.previous} + } + got := r.admitPrecopy(prev, tc.final) + want := tc.reason == "fit" || tc.reason == "no_progress" || tc.reason == "final_attempt" + if got != want || r.Reason != tc.reason { + t.Fatalf("admit=%t want=%t reason=%s: %+v", got, want, tc.reason, r) + } + }) + } + r := PrecopyReport{Reason: "samples_unknown", Estimate: time.Second} + if r.admitPrecopy(&PrecopyAttempt{Estimate: time.Second}, true) { + t.Fatal("unknown samples admitted") + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index 7a1f1b52a5..b4b4a9d419 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -532,7 +532,7 @@ func precopyAttemptDiagnosticsControl(t *testing.T, slow bool) { t.Fatalf("slow diagnostics control lost its measured fixed cost: report=%+v", r.Precopy) } if r.Precopy.Frozen { - if err != nil || len(r.Precopy.Rounds) != 2 || (second.Reason != "fit" && second.Reason != "fixed_cost_over_allowance") || !second.Frozen { + if err != nil || len(r.Precopy.Rounds) != 2 || (second.Reason != "fit" && second.Reason != "no_progress") || !second.Frozen { t.Fatalf("invalid fit after drain timeout: report=%+v err=%v", r.Precopy, err) } } else { diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index e75b81645d..7b7d44a7ac 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -19,14 +19,14 @@ func TestPrecopyFixedCostSmallTailCommitsBySecondAttempt(t *testing.T) { f.beforeCAS = func(*fakeChunkRemote) { time.Sleep(fixed) } // Keep the same known small tail and fixed envelope in each attempt. l.precopySamples = nil - for i := 0; i < 3; i++ { + for i := 0; i < 5; i++ { l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, parts: PrecopyFixedParts{HeadCAS: fixed}, rate: 20 * float64(ctChunkBytes)}) } } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() r, err := l.PrecopyDetach(ctx, func() bool { return true }) - if err != nil || !r.Precopy.Frozen || len(r.Precopy.Rounds) > 2 || r.Precopy.Reason != "fixed_cost_over_allowance" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { + if err != nil || !r.Precopy.Frozen || len(r.Precopy.Rounds) > 2 || r.Precopy.Reason != "no_progress" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { t.Fatalf("fixed cost cannot converge by recopying the same small tail: report=%+v err=%v", r.Precopy, err) } if r.Precopy.FreezeElapsed < fixed || r.Precopy.LatencyGateFailed || time.Duration(r.Stats.CASWriteNs) < fixed { @@ -45,12 +45,12 @@ func TestPrecopyLargeTailStillRefusesFixedCostException(t *testing.T) { rounds++ w.write(t, s, 1, byte(rounds)) l.precopySamples = nil - for i := 0; i < 3; i++ { - l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: float64(ctChunkBytes)}) + for i := 0; i < 5; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: float64(ctChunkBytes) / 4}) } } r, err := l.PrecopyDetach(ctTimeout(t), func() bool { t.Fatal("large tail froze"); return true }) - if !errors.Is(err, ErrPrecopyNotConverged) || r.Precopy.Frozen || len(r.Precopy.Rounds) != 5 || r.Precopy.Reason != "tail_too_large" { + if !errors.Is(err, ErrPrecopyNotConverged) || r.Precopy.Frozen || len(r.Precopy.Rounds) != 5 || r.Precopy.Reason != "freeze_budget_exceeded" { t.Fatalf("large tail was not refused: %+v %v", r.Precopy, err) } if f.stats().head.State != ChunkHeadActive { @@ -74,11 +74,11 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { known, want bool }{ {"first", 100 * time.Millisecond, 1500 * time.Millisecond, 0, true, false}, - {"improving", 100 * time.Millisecond, 1500 * time.Millisecond, 1600 * time.Millisecond, true, false}, + {"improving", 100 * time.Millisecond, 1500 * time.Millisecond, 1800 * time.Millisecond, true, false}, {"stalled", 100 * time.Millisecond, 1500 * time.Millisecond, 1500 * time.Millisecond, true, true}, {"worse-fixed", 100 * time.Millisecond, 1600 * time.Millisecond, 1500 * time.Millisecond, true, true}, {"quarter", 300 * time.Millisecond, 1500 * time.Millisecond, 1500 * time.Millisecond, true, true}, - {"large-tail", 300*time.Millisecond + 1, 1500 * time.Millisecond, 1500 * time.Millisecond, true, false}, + {"large-tail", 300*time.Millisecond + 1, 1500 * time.Millisecond, 1500 * time.Millisecond, true, true}, {"unknown", 0, 1500 * time.Millisecond, 1500 * time.Millisecond, false, false}, {"freeze-ceiling", 0, 5*time.Second + 1, 5*time.Second + 1, true, false}, {"first-freeze-ceiling", 0, 5*time.Second + 1, 0, true, false}, @@ -93,13 +93,13 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { if tc.previous > 0 { previous = &PrecopyAttempt{Estimate: tc.previous} } - if got := r.admitPrecopy(previous); got != tc.want { + if got := r.admitPrecopy(previous, false); got != tc.want { t.Fatalf("admit=%t report=%+v", got, r) } - if tc.known && tc.estimate > 5*time.Second && r.Reason != "fixed_cost_exceeds_freeze_budget" { + if tc.known && tc.estimate > 5*time.Second && r.Reason != "freeze_budget_exceeded" { t.Fatalf("mislabelled fixed ceiling: %+v", r) } - if tc.want && r.Reason != "fixed_cost_over_allowance" { + if tc.want && r.Reason != "no_progress" { t.Fatalf("missing exception reason: %+v", r) } }) @@ -109,6 +109,9 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { func TestPrecopyFixedPartsStayWithLargestObservation(t *testing.T) { _, _, l, _ := precopyLayer(t, 1024, 0) l.precopySamples = nil + for i := 0; i < 3; i++ { + l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(time.Millisecond)) + } st := chunkCutStats{CASNs: 1, DrainNs: int64(10 * time.Millisecond), LockWaitNs: int64(30 * time.Millisecond), SyncNs: int64(40 * time.Millisecond), CASWriteNs: int64(50 * time.Millisecond), HeadReadbackNs: int64(60 * time.Millisecond), MapPersistNs: int64(10 * time.Millisecond)} l.samplePrecopy(st, int64(200*time.Millisecond)) l.samplePrecopy(chunkCutStats{CASNs: 1, SyncNs: int64(100 * time.Millisecond)}, int64(150*time.Millisecond)) @@ -120,7 +123,7 @@ func TestPrecopyFixedPartsStayWithLargestObservation(t *testing.T) { } func TestPrecopyFixedExceptionFinishUsesDeclaredFreeze(t *testing.T) { - r := PrecopyReport{Reason: "fixed_cost_over_allowance", Estimate: 1500 * time.Millisecond, DeclaredFreeze: 1500 * time.Millisecond} + r := PrecopyReport{Reason: "no_progress", Estimate: 1500 * time.Millisecond, DeclaredFreeze: 1500 * time.Millisecond} r.Finish(1400*time.Millisecond, 0, false) if r.LatencyGateFailed || r.DeclaredWorst != 1500*time.Millisecond { t.Fatalf("new declaration ignored: %+v", r) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0133a48f39..e4809818f6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -481,7 +481,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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | 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. Admission fits the allowance or uses a declared fixed-cost exception only when the tail term is at most 25% and the estimate did not improve versus the prior attempt, within five seconds. Disjoint fixed-cost parts come from the same retained sample. | 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`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous estimate, or on the final physical round. The fixed input is the maximum of the latest five observations younger than fifteen minutes; disjoint parts come from the same selected observation. Unknown samples never admit. | 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`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are 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 | diff --git a/seaweed-block/docs/spec/PrecopyFixedAdmission.tla b/seaweed-block/docs/spec/PrecopyFixedAdmission.tla index 7ed7191033..12cf420094 100644 --- a/seaweed-block/docs/spec/PrecopyFixedAdmission.tla +++ b/seaweed-block/docs/spec/PrecopyFixedAdmission.tla @@ -1,7 +1,7 @@ ----------------------- MODULE PrecopyFixedAdmission ----------------------- \* Admission only: data/authority/publication safety is covered by CutCOW2. EXTENDS Integers, TLC -CONSTANTS OmitTailGuard, OmitStallGuard, OmitFreezeCap +CONSTANTS OmitFinalGuard, OmitStallGuard, OmitFreezeCap Allowance == 12 FreezeLimit == 50 Margin == 1 @@ -11,8 +11,8 @@ Init == /\ fixed \in {1,13,60} /\ tail \in {0,1,3,4,20} /\ previous = 0 /\ estimate = fixed + tail + Margin /\ phase = "decide" /\ declared = 0 /\ round = 1 -Exception == /\ (OmitTailGuard \/ tail <= Allowance \div 4) - /\ (OmitStallGuard \/ (previous > 0 /\ estimate >= previous)) +Plateau == previous > 0 /\ 10 * estimate >= 9 * previous +Exception == /\ (OmitStallGuard \/ Plateau \/ (~OmitFinalGuard /\ round = 5)) /\ (OmitFreezeCap \/ estimate <= FreezeLimit) Eligible == estimate <= Allowance \/ Exception Commit == /\ phase = "decide" /\ Eligible @@ -33,6 +33,6 @@ Spec == Init /\ [][Next]_vars SafeCommit == phase = "committed" => /\ declared = estimate /\ estimate <= FreezeLimit /\ (estimate > Allowance => - /\ tail <= Allowance \div 4 - /\ previous > 0 /\ estimate >= previous) + (Plateau \/ round = 5)) +FinalWithinBudget == phase = "refused" => estimate > FreezeLimit ============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 57f0d68b54..cb3dc48dfb 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -335,33 +335,31 @@ four negative controls separately remove retirement, the frame join, the readiness guard or ACK progress restoration. This abstracts successful admitted frames and does not prove physical-I/O, authority rollback or timing behavior. -`PrecopyFixedAdmission.tla` checks bounded pre-copy cost admission: ordinary -allowance, small non-improving tail, declared freeze and the five-second ceiling. -`PrecopyFixedAdmission.cfg` is the positive configuration; `_no_tail`, `_no_stall` -and `_no_cap` must violate `SafeCommit`. It does not model publication/data safety -or physical latency; those remain separate checks. - +`PrecopyFixedAdmission.tla` checks cost admission over five physical rounds. +A known estimate fits the 1.2-second allowance, or uses the five-second declared +freeze limit when it is at least 90% of the previous estimate or on the final +round. `SafeCommit` checks the declaration and ceiling; `FinalWithinBudget` +checks that an eligible final round cannot refuse. This model does not model +sample freshness, measurement availability, publication/data safety or physical +latency; those remain separate checks. ### PrecopyFixedAdmission checked configurations -Recorded local run, 2026-11-20 22:30 UTC, using the v1.7.4 tools distribution (TLC 2.19) -(`tla2tools.jar` SHA-256 +Local amendment-4 run, 2026-11-21 01:46 UTC, TLC 2.19 (tools jar SHA-256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`), from `docs/spec`: ```sh -java -cp /path/to/tla2tools.jar tla2sany.SANY PrecopyFixedAdmission.tla -java -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/PrecopyFixedAdmission.cfg PrecopyFixedAdmission +java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/PrecopyFixedAdmission.cfg PrecopyFixedAdmission ``` -SANY exited 0. The positive configuration exited 0: 11,240 generated states, -2,856 distinct, queue empty, complete depth 6. With the same command and the -respective `cfg/PrecopyFixedAdmission_no_*.cfg`, each negative exited 12 with -`SafeCommit` violated: `no_tail` (266 generated / 262 distinct, depth 3), -`no_stall` (44 / 41, depth 2), `no_cap` (546 / 517, depth 3). -These are the original local finite-state runs for this model, not a new run -for the documentation update. The bounds and exclusions above still apply; -this does not establish physical latency, publication safety or train qualification. +The positive configuration exited 0: 6,467 generated / 1,893 distinct states, +queue empty, depth 6. The same invocation with each negative configuration +exited 12: `no_stall` violates `SafeCommit` (24 / 20, depth 2), `no_cap` +violates `SafeCommit` (417 / 390, depth 3), and `no_final` violates +`FinalWithinBudget` (5,759 / 1,605, depth 6). The older quarter-tail model +results are superseded by this rule. These finite-state checks do not establish +physical latency or train qualification. ## Plain detach admission diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg index 3a6f20ba4b..e3243ac2c4 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg @@ -1,6 +1,6 @@ SPECIFICATION Spec CONSTANTS - OmitTailGuard = FALSE + OmitFinalGuard = FALSE OmitStallGuard = FALSE OmitFreezeCap = FALSE -INVARIANT SafeCommit +INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg index 11c8b345d4..0159a8e92a 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg @@ -1,6 +1,6 @@ SPECIFICATION Spec CONSTANTS - OmitTailGuard = FALSE + OmitFinalGuard = FALSE OmitStallGuard = FALSE OmitFreezeCap = TRUE -INVARIANT SafeCommit +INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg similarity index 54% rename from seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg rename to seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg index 885ce1a845..c41aa11e33 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_tail.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg @@ -1,6 +1,6 @@ SPECIFICATION Spec CONSTANTS - OmitTailGuard = TRUE + OmitFinalGuard = TRUE OmitStallGuard = FALSE OmitFreezeCap = FALSE -INVARIANT SafeCommit +INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg index 8cdce12876..304ec20a81 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg @@ -1,6 +1,6 @@ SPECIFICATION Spec CONSTANTS - OmitTailGuard = FALSE + OmitFinalGuard = FALSE OmitStallGuard = TRUE OmitFreezeCap = FALSE -INVARIANT SafeCommit +INVARIANTS SafeCommit FinalWithinBudget From b6a3f5840c49a2f2a43a164bc0c971d50a3c2b9f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:50:38 -0800 Subject: [PATCH 16/20] fix(storage): allow available fresh fixed-cost observations --- seaweed-block/core/storage/chunk_precopy.go | 4 ++-- .../core/storage/chunk_precopy_amendment4_test.go | 12 +++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 922b695340..a534520da6 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -278,7 +278,7 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor r := PrecopyReport{Attempts: attempts, TailBytes: tail, Reason: "samples_unknown"} now := time.Now() var rates []float64 - // Fixed work uses the last five fresh observations, independent of the + // Fixed work uses up to the last five fresh observations, independent of the // latest-three-rate window. Parts always belong to the selected observation. fixedCount := 0 for i := len(l.precopySamples) - 1; i >= 0; i-- { @@ -305,7 +305,7 @@ func (l *chunkLayerImpl) precopyEstimate(tail uint64, attempts int) PrecopyRepor if len(rates) > 3 { rates = rates[:3] } - if fixedCount < precopyFixedWindow || r.Fixed <= 0 { + if fixedCount == 0 || r.Fixed <= 0 { return r } r.Estimate = r.Fixed + precopyMargin diff --git a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go index ef6a9fa263..fa908bac05 100644 --- a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go +++ b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go @@ -34,8 +34,18 @@ func TestPrecopyFixedWindowDecays(t *testing.T) { } l.precopySamples = l.precopySamples[1:] l.precopySamples[0].at = now.Add(-16 * time.Minute) + if r := l.precopyEstimate(0, 0); r.Fixed != 100*time.Millisecond || r.Reason == "samples_unknown" { + t.Fatalf("available fresh samples were refused: %+v", r) + } + for i := range l.precopySamples { + l.precopySamples[i].at = now.Add(-16 * time.Minute) + } if r := l.precopyEstimate(0, 0); r.Reason != "samples_unknown" { - t.Fatalf("fewer than five fresh samples accepted: %+v", r) + t.Fatalf("expired samples admitted: %+v", r) + } + l.precopySamples = []precopySample{{at: now, fixed: 100 * time.Millisecond}} + if r := l.precopyEstimate(0, 0); r.Fixed != 100*time.Millisecond || r.Reason != "fit" { + t.Fatalf("single fresh fixed observation refused: %+v", r) } } func TestPrecopyFinalAttemptFreezeCeiling(t *testing.T) { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e4809818f6..c82bf2e3fb 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -481,7 +481,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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | 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. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous estimate, or on the final physical round. The fixed input is the maximum of the latest five observations younger than fifteen minutes; disjoint parts come from the same selected observation. Unknown samples never admit. | 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`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Unknown samples never admit. | 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`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are 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 | From 96bb2c7f8790bb54da607d1984f2fd4dd3dcd27e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:51:49 -0800 Subject: [PATCH 17/20] fix(storage): preserve warm rate-window reporting --- seaweed-block/core/storage/chunk_precopy.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index a534520da6..f81649ce05 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -213,7 +213,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context 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).Reason != "samples_unknown" { + if l.precopyEstimate(0, 0).RateSamples >= 3 { warmAttempts++ } else { measurementRounds++ From 5eac7ebf886f8032ed7312b31c9dda3250628d9a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:53:47 -0800 Subject: [PATCH 18/20] test(storage): verify declared freeze overruns under disk load --- seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index 7b7d44a7ac..d90b6c0861 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -29,7 +29,9 @@ func TestPrecopyFixedCostSmallTailCommitsBySecondAttempt(t *testing.T) { if err != nil || !r.Precopy.Frozen || len(r.Precopy.Rounds) > 2 || r.Precopy.Reason != "no_progress" || r.Precopy.Fixed < fixed || r.Precopy.DeclaredWorst < fixed { t.Fatalf("fixed cost cannot converge by recopying the same small tail: report=%+v err=%v", r.Precopy, err) } - if r.Precopy.FreezeElapsed < fixed || r.Precopy.LatencyGateFailed || time.Duration(r.Stats.CASWriteNs) < fixed { + // The synthetic estimate excludes real disk scheduling. An overloaded + // checkpoint may exceed it; the product must report that overrun honestly. + if r.Precopy.FreezeElapsed < fixed || r.Precopy.LatencyGateFailed != (r.Precopy.FreezeElapsed > r.Precopy.DeclaredFreeze) || time.Duration(r.Stats.CASWriteNs) < fixed { t.Fatalf("final fixed-cost operation was not witnessed within its declaration: %+v", r) } if r.Head.State != ChunkHeadDetached || !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, byte(rounds))) { From 204334c77648d7806cf5645d9ab3c7c3b3e86791 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:58:15 -0800 Subject: [PATCH 19/20] test(storage): cover zero one and two fresh fixed samples --- .../storage/chunk_precopy_amendment4_test.go | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go index fa908bac05..eda005f942 100644 --- a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go +++ b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go @@ -96,3 +96,25 @@ func TestPrecopyAmendment4AdmissionBoundaries(t *testing.T) { t.Fatal("unknown samples admitted") } } + +func TestPrecopyFixedWindowUsesAvailableFreshSamples(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + for _, n := range []int{0, 1, 2} { + t.Run(string(rune('0'+n)), func(t *testing.T) { + l.precopySamples = nil + for i := 0; i < n; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Duration(i+1) * 100 * time.Millisecond}) + } + r := l.precopyEstimate(0, 0) + if n == 0 { + if r.Reason != "samples_unknown" { + t.Fatalf("zero fresh admitted: %+v", r) + } + return + } + if r.Reason != "fit" || r.Fixed != time.Duration(n)*100*time.Millisecond { + t.Fatalf("%d fresh refused or wrong maximum: %+v", n, r) + } + }) + } +} From 1ad83a4f5cfee33a6151451797d89564582f0f38 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 18:08:02 -0800 Subject: [PATCH 20/20] fix(storage): compare only known pre-copy estimates --- .../frontend/durable/precopy_drain_test.go | 7 +- .../durable/precopy_expiry_close_test.go | 83 +++++++++++++++++++ .../durable/precopy_fifty_iops_test.go | 13 ++- seaweed-block/core/storage/chunk_precopy.go | 16 +++- .../storage/chunk_precopy_amendment4_test.go | 23 ++++- .../core/storage/chunk_precopy_detach_test.go | 15 +++- .../chunk_precopy_fixed_commit_test.go | 2 +- seaweed-block/docs/design/invariants.md | 4 +- .../docs/spec/PrecopyFixedAdmission.tla | 18 ++-- seaweed-block/docs/spec/README.md | 16 ++-- .../docs/spec/cfg/PrecopyFixedAdmission.cfg | 1 + .../spec/cfg/PrecopyFixedAdmission_no_cap.cfg | 1 + .../cfg/PrecopyFixedAdmission_no_final.cfg | 1 + .../cfg/PrecopyFixedAdmission_no_stall.cfg | 1 + ...PrecopyFixedAdmission_unknown_previous.cfg | 7 ++ 15 files changed, 181 insertions(+), 27 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/precopy_expiry_close_test.go create mode 100644 seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_unknown_previous.cfg diff --git a/seaweed-block/core/frontend/durable/precopy_drain_test.go b/seaweed-block/core/frontend/durable/precopy_drain_test.go index 2f3c00847d..de9aeb2b72 100644 --- a/seaweed-block/core/frontend/durable/precopy_drain_test.go +++ b/seaweed-block/core/frontend/durable/precopy_drain_test.go @@ -129,10 +129,13 @@ func TestPrecopyLateGateCallerCannotCrossFreeze(t *testing.T) { } select { case <-done: - if !errors.Is(writeErr, frontend.ErrBackendClosed) { + // Capture can outlast this caller's budget before Close. The exact + // two orderings are witnessed by TestPrecopyCallerExpiryVersusClose. + expired := errors.Is(ctx.Err(), context.DeadlineExceeded) && errors.Is(writeErr, frontend.ErrBackendBusy) && errors.Is(writeErr, context.DeadlineExceeded) + if !errors.Is(writeErr, frontend.ErrBackendClosed) && !expired { t.Fatal(writeErr) } - case <-ctx.Done(): + case <-time.After(time.Second): t.Fatal("closed path did not settle late command") } } diff --git a/seaweed-block/core/frontend/durable/precopy_expiry_close_test.go b/seaweed-block/core/frontend/durable/precopy_expiry_close_test.go new file mode 100644 index 0000000000..db68bbad77 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_expiry_close_test.go @@ -0,0 +1,83 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "testing" + "testing/synctest" + "time" +) + +// The LateGate failure is this ordering: a queued command's caller budget +// expires during capture, before Close. Close cannot rewrite its completed Busy. +func TestPrecopyCallerExpiryVersusClose(t *testing.T) { + for _, closeFirst := range []bool{false, true} { + name := "expiry-before-close" + if closeFirst { + name = "close-before-expiry" + } + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := precopyMemoryBackend(t) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + queued := make(chan struct{}) + done := make(chan error, 1) + b.testPrecopyQueued = func() { close(queued) } + if !b.TryStopIO("held capture") { + t.Fatal("freeze refused") + } + before := b.storage.NextLSN() + go func() { _, err := b.Write(ctx, 0, make([]byte, 4096)); done <- err }() + joined := false + t.Cleanup(func() { + cancel() + _ = b.Close() + if !joined { + select { + case <-done: + case <-time.After(time.Second): + t.Error("queued command did not settle") + } + } + }) + select { + case <-queued: + case <-time.After(time.Second): + t.Fatal("queue not witnessed") + } + synctest.Wait() + if closeFirst { + if err := b.Close(); err != nil { + t.Fatal(err) + } + } else { + time.Sleep(time.Second) + } + synctest.Wait() + var err error + select { + case err = <-done: + joined = true + case <-time.After(time.Second): + t.Fatal("chosen boundary did not settle command") + } + if closeFirst { + if !errors.Is(err, frontend.ErrBackendClosed) || ctx.Err() != nil { + t.Fatalf("Close failed to win before live deadline: %v ctx=%v", err, ctx.Err()) + } + } else { + if !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("expiry before Close misclassified: %v", err) + } + if e := b.Close(); e != nil { + t.Fatal(e) + } + } + if b.storage.NextLSN() != before { + t.Fatal("queued command appended storage") + } + }) + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index a6d9a32879..f7529d2dcb 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -315,7 +315,7 @@ func precopyFiftyAttemptError(round storage.PrecopyAttempt, previous *storage.Pr eligible := round.Estimate > 0 && round.Estimate <= allowance reason := "fit" if !eligible && round.Estimate > 0 && round.Estimate <= 5*time.Second { - if previous != nil && previous.Estimate > 0 && round.Estimate >= previous.Estimate-previous.Estimate/10 { + if precopyFiftyPreviousKnown(previous) && round.Estimate >= previous.Estimate-previous.Estimate/10 { eligible, reason = true, "no_progress" } else if round.Attempt == 5 { eligible, reason = true, "final_attempt" @@ -358,3 +358,14 @@ func TestPrecopyFiftyIOPSDrainRefusalDoesNotClaimAdmission(t *testing.T) { } } } + +func precopyFiftyPreviousKnown(a *storage.PrecopyAttempt) bool { + if a == nil || a.Estimate <= 0 || a.Error != "" { + return false + } + switch a.Reason { + case "fit", "tail_too_large", "barrier_over_budget", "freeze_budget_exceeded", "no_progress", "final_attempt", "admitted_io": + return true + } + return false +} diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index f81649ce05..fdb1c142ed 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -352,7 +352,7 @@ func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt, final bool) bool r.Reason = "freeze_budget_exceeded" return false } - if previous != nil && previous.Estimate > 0 { + if comparablePrecopyAttempt(previous) { r.PreviousEstimate = previous.Estimate // Division first avoids overflow while retaining nanosecond precision. threshold := previous.Estimate - previous.Estimate/10 @@ -412,3 +412,17 @@ func (l *chunkLayerImpl) lockPrecopy(ctx context.Context) error { } } } + +// Only a completed cost estimate is comparable. A drain/before-barrier refusal +// can carry Fixed+margin without a known tail, just like samples_unknown. +func comparablePrecopyAttempt(a *PrecopyAttempt) bool { + if a == nil || a.Estimate <= 0 || a.Error != "" { + return false + } + switch a.Reason { + case "fit", "tail_too_large", "barrier_over_budget", "freeze_budget_exceeded", "no_progress", "final_attempt", "admitted_io": + return true + default: + return false + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go index eda005f942..7de3cda90d 100644 --- a/seaweed-block/core/storage/chunk_precopy_amendment4_test.go +++ b/seaweed-block/core/storage/chunk_precopy_amendment4_test.go @@ -17,7 +17,7 @@ func TestPrecopySmokeTraceAmendment4(t *testing.T) { } return } - previous = &PrecopyAttempt{Estimate: r.Estimate} + previous = &PrecopyAttempt{Reason: "tail_too_large", Estimate: r.Estimate} } t.Fatal("smoke trace refused despite no meaningful progress within freeze bound") } @@ -54,7 +54,7 @@ func TestPrecopyFinalAttemptFreezeCeiling(t *testing.T) { want bool }{{4500 * time.Millisecond, true}, {5500 * time.Millisecond, false}} { r := PrecopyReport{Estimate: tc.estimate, TailEstimate: 3 * time.Second, Reason: "tail_too_large"} - previous := &PrecopyAttempt{Estimate: 6 * time.Second} + previous := &PrecopyAttempt{Reason: "tail_too_large", Estimate: 6 * time.Second} if got := r.admitPrecopy(previous, true); got != tc.want { t.Fatalf("final admission=%t want=%t: %+v", got, tc.want, r) } @@ -82,7 +82,7 @@ func TestPrecopyAmendment4AdmissionBoundaries(t *testing.T) { r := PrecopyReport{Estimate: tc.estimate, Reason: "tail_too_large"} var prev *PrecopyAttempt if tc.previous > 0 { - prev = &PrecopyAttempt{Estimate: tc.previous} + prev = &PrecopyAttempt{Reason: "tail_too_large", Estimate: tc.previous} } got := r.admitPrecopy(prev, tc.final) want := tc.reason == "fit" || tc.reason == "no_progress" || tc.reason == "final_attempt" @@ -92,7 +92,7 @@ func TestPrecopyAmendment4AdmissionBoundaries(t *testing.T) { }) } r := PrecopyReport{Reason: "samples_unknown", Estimate: time.Second} - if r.admitPrecopy(&PrecopyAttempt{Estimate: time.Second}, true) { + if r.admitPrecopy(&PrecopyAttempt{Reason: "tail_too_large", Estimate: time.Second}, true) { t.Fatal("unknown samples admitted") } } @@ -118,3 +118,18 @@ func TestPrecopyFixedWindowUsesAvailableFreshSamples(t *testing.T) { }) } } + +func TestPrecopyUnknownPreviousCannotClaimProgress(t *testing.T) { + for _, reason := range []string{"samples_unknown", "drain_refused", "before_barrier"} { + t.Run(reason, func(t *testing.T) { + r := PrecopyReport{Estimate: 2 * time.Second, Reason: "tail_too_large"} + previous := &PrecopyAttempt{Estimate: 200 * time.Millisecond, Reason: reason} + if r.admitPrecopy(previous, false) || r.PreviousEstimate != 0 { + t.Fatalf("partial previous admitted no_progress: %+v", r) + } + if !r.admitPrecopy(previous, true) || r.Reason != "final_attempt" { + t.Fatalf("unknown previous blocked independent final admission: %+v", r) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index b4b4a9d419..d4f0059803 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -532,8 +532,19 @@ func precopyAttemptDiagnosticsControl(t *testing.T, slow bool) { t.Fatalf("slow diagnostics control lost its measured fixed cost: report=%+v", r.Precopy) } if r.Precopy.Frozen { - if err != nil || len(r.Precopy.Rounds) != 2 || (second.Reason != "fit" && second.Reason != "no_progress") || !second.Frozen { - t.Fatalf("invalid fit after drain timeout: report=%+v err=%v", r.Precopy, err) + // A drain refusal is not a comparable estimate. A cheap second + // round fits directly; a slow second round establishes the first known + // estimate, so only the third may establish no progress. + last := r.Precopy.Rounds[len(r.Precopy.Rounds)-1] + if err != nil || !last.Frozen { + t.Fatalf("invalid admission after drain timeout: report=%+v err=%v", r.Precopy, err) + } + if second.Reason == "fit" { + if len(r.Precopy.Rounds) != 2 || !second.Frozen { + t.Fatalf("first fitting round skipped: %+v", r.Precopy) + } + } else if len(r.Precopy.Rounds) != 3 || second.Frozen || second.Reason != "tail_too_large" || last.Reason != "no_progress" || last.PreviousEstimate != second.Estimate { + t.Fatalf("drain refusal treated as a comparable estimate: %+v", r.Precopy) } } else { assertPrecopyMeasuredRefusal(t, r.Precopy, err) diff --git a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go index d90b6c0861..53d4b89ac8 100644 --- a/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go +++ b/seaweed-block/core/storage/chunk_precopy_fixed_commit_test.go @@ -93,7 +93,7 @@ func TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds(t *testing.T) { r := PrecopyReport{Fixed: 1300 * time.Millisecond, TailEstimate: tc.tail, Estimate: tc.estimate, Reason: reason} var previous *PrecopyAttempt if tc.previous > 0 { - previous = &PrecopyAttempt{Estimate: tc.previous} + previous = &PrecopyAttempt{Reason: "tail_too_large", Estimate: tc.previous} } if got := r.admitPrecopy(previous, false); got != tc.want { t.Fatalf("admit=%t report=%+v", got, r) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c82bf2e3fb..9749f085ec 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -240,7 +240,7 @@ stateDiagram-v2 | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-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; a non-improving tail of at most 25% of allowance may use a declared fixed-cost exception within the existing five-second freeze ceiling; 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 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; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; 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` | @@ -481,7 +481,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-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | 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. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Unknown samples never admit. | 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`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are not a model proof | ACTIVE | +| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Unknown samples never admit. | 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`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are 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 | diff --git a/seaweed-block/docs/spec/PrecopyFixedAdmission.tla b/seaweed-block/docs/spec/PrecopyFixedAdmission.tla index 12cf420094..b336409e42 100644 --- a/seaweed-block/docs/spec/PrecopyFixedAdmission.tla +++ b/seaweed-block/docs/spec/PrecopyFixedAdmission.tla @@ -1,32 +1,34 @@ ----------------------- MODULE PrecopyFixedAdmission ----------------------- \* Admission only: data/authority/publication safety is covered by CutCOW2. EXTENDS Integers, TLC -CONSTANTS OmitFinalGuard, OmitStallGuard, OmitFreezeCap +CONSTANTS OmitFinalGuard, OmitStallGuard, OmitFreezeCap, OmitKnownGuard Allowance == 12 FreezeLimit == 50 Margin == 1 -VARIABLES fixed, tail, previous, estimate, phase, declared, round -vars == <> +VARIABLES fixed, tail, previous, estimate, phase, declared, round, previousKnown +vars == <> Init == /\ fixed \in {1,13,60} /\ tail \in {0,1,3,4,20} - /\ previous = 0 /\ estimate = fixed + tail + Margin + /\ previous = 0 /\ previousKnown = FALSE /\ estimate = fixed + tail + Margin /\ phase = "decide" /\ declared = 0 /\ round = 1 -Plateau == previous > 0 /\ 10 * estimate >= 9 * previous -Exception == /\ (OmitStallGuard \/ Plateau \/ (~OmitFinalGuard /\ round = 5)) +Plateau == previousKnown /\ previous > 0 /\ 10 * estimate >= 9 * previous +UncheckedPlateau == previous > 0 /\ 10 * estimate >= 9 * previous +Exception == /\ (OmitStallGuard \/ Plateau \/ (OmitKnownGuard /\ UncheckedPlateau) \/ (~OmitFinalGuard /\ round = 5)) /\ (OmitFreezeCap \/ estimate <= FreezeLimit) Eligible == estimate <= Allowance \/ Exception Commit == /\ phase = "decide" /\ Eligible /\ phase' = "committed" /\ declared' = estimate - /\ UNCHANGED <> + /\ UNCHANGED <> Copy == /\ phase = "decide" /\ ~Eligible /\ round < 5 /\ \E nextTail \in 0..tail: /\ tail' = nextTail /\ previous' = estimate + /\ previousKnown' \in BOOLEAN /\ estimate' = fixed + nextTail + Margin /\ round' = round + 1 /\ UNCHANGED <> Refuse == /\ phase = "decide" /\ ~Eligible /\ round = 5 /\ phase' = "refused" - /\ UNCHANGED <> + /\ UNCHANGED <> Done == /\ phase # "decide" /\ UNCHANGED vars Next == Commit \/ Copy \/ Refuse \/ Done Spec == Init /\ [][Next]_vars diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index cb3dc48dfb..0e2834003b 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -337,15 +337,15 @@ frames and does not prove physical-I/O, authority rollback or timing behavior. `PrecopyFixedAdmission.tla` checks cost admission over five physical rounds. A known estimate fits the 1.2-second allowance, or uses the five-second declared -freeze limit when it is at least 90% of the previous estimate or on the final +freeze limit when it is at least 90% of the previous comparable known estimate or on the final round. `SafeCommit` checks the declaration and ceiling; `FinalWithinBudget` checks that an eligible final round cannot refuse. This model does not model -sample freshness, measurement availability, publication/data safety or physical +sample freshness, current-measurement availability, publication/data safety or physical latency; those remain separate checks. ### PrecopyFixedAdmission checked configurations -Local amendment-4 run, 2026-11-21 01:46 UTC, TLC 2.19 (tools jar SHA-256 +Local amendment-4 review-fold run, 2026-11-21 02:07 UTC, TLC 2.19 (tools jar SHA-256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`), from `docs/spec`: @@ -353,11 +353,15 @@ from `docs/spec`: java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/PrecopyFixedAdmission.cfg PrecopyFixedAdmission ``` -The positive configuration exited 0: 6,467 generated / 1,893 distinct states, +The positive configuration exited 0: 37,399 generated / 5,851 distinct states, queue empty, depth 6. The same invocation with each negative configuration exited 12: `no_stall` violates `SafeCommit` (24 / 20, depth 2), `no_cap` -violates `SafeCommit` (417 / 390, depth 3), and `no_final` violates -`FinalWithinBudget` (5,759 / 1,605, depth 6). The older quarter-tail model +violates `SafeCommit` (1,634 / 1,024, depth 3), and `no_final` violates +`FinalWithinBudget` (34,330 / 4,620, depth 6). The additional +`unknown_previous` negative violates `SafeCommit` (640 / 426, depth 3), +witnessing that a partial prior estimate cannot establish a plateau. The model +tracks previous-known status nondeterministically across rounds; only the +current estimate is assumed known. The older quarter-tail model results are superseded by this rule. These finite-state checks do not establish physical latency or train qualification. diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg index e3243ac2c4..ab01d51b62 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CONSTANTS OmitFinalGuard = FALSE OmitStallGuard = FALSE + OmitKnownGuard = FALSE OmitFreezeCap = FALSE INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg index 0159a8e92a..3e4da36daa 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_cap.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CONSTANTS OmitFinalGuard = FALSE OmitStallGuard = FALSE + OmitKnownGuard = FALSE OmitFreezeCap = TRUE INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg index c41aa11e33..86bbcf91d5 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_final.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CONSTANTS OmitFinalGuard = TRUE OmitStallGuard = FALSE + OmitKnownGuard = FALSE OmitFreezeCap = FALSE INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg index 304ec20a81..e497b8e9b1 100644 --- a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_no_stall.cfg @@ -2,5 +2,6 @@ SPECIFICATION Spec CONSTANTS OmitFinalGuard = FALSE OmitStallGuard = TRUE + OmitKnownGuard = FALSE OmitFreezeCap = FALSE INVARIANTS SafeCommit FinalWithinBudget diff --git a/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_unknown_previous.cfg b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_unknown_previous.cfg new file mode 100644 index 0000000000..99e590319d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PrecopyFixedAdmission_unknown_previous.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS + OmitFinalGuard = FALSE + OmitStallGuard = FALSE + OmitKnownGuard = TRUE + OmitFreezeCap = FALSE +INVARIANTS SafeCommit FinalWithinBudget