diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index ec9ac529ab..80cc5f67ad 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -226,19 +226,35 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int { func chunkDetach(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("detach", stderr) var ( - volumeID, statusAddr string - timeout time.Duration + volumeID, statusAddr string + timeout time.Duration + frozen, allowOverBudget bool + freezeStartedAtNs int64 ) fs.StringVar(&volumeID, "volume", "", "volume id") fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)") + fs.BoolVar(&frozen, "frozen", false, "guest is already frozen; use one cut within its remaining five-second budget") + fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "guest freeze start in Unix nanoseconds on the serving host clock") + fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "explicit final frozen attempt; record over_budget rather than refuse its estimate") if err := fs.Parse(args); err != nil { return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } if volumeID == "" || statusAddr == "" { return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) } - return chunkPost("detach", statusAddr, "/chunk/detach", timeout, map[string]any{"volumeID": volumeID}, stdout, stderr) + if (frozen && freezeStartedAtNs <= 0) || (!frozen && (freezeStartedAtNs != 0 || allowOverBudget)) { + return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--frozen requires --freeze-started-at-ns; --allow-over-budget requires --frozen", false) + } + body := map[string]any{"volumeID": volumeID} + if frozen { + body["frozen"] = true + body["freezeStartedAtNs"] = freezeStartedAtNs + if allowOverBudget { + body["allowOverBudget"] = true + } + } + return chunkPost("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr) } // chunkCatalog opens the catalog under --chunk-path on --chunk-filer. diff --git a/seaweed-block/cmd/sw-block/chunk_frozen_test.go b/seaweed-block/cmd/sw-block/chunk_frozen_test.go new file mode 100644 index 0000000000..f2e30173b1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_frozen_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "testing" +) + +func TestOpsChunkFrozenDetachFlags(t *testing.T) { + srv, got := chunkServer(t, 200, `{"volumeID":"v1"}`) + code, _, errs := runChunk("detach", "--volume=v1", "--status-addr="+srv.URL, "--frozen", "--freeze-started-at-ns=1234567", "--allow-over-budget") + if code != 0 || len(*got) != 1 || (*got)[0].body["frozen"] != true || (*got)[0].body["freezeStartedAtNs"] != float64(1234567) || (*got)[0].body["allowOverBudget"] != true { + t.Fatalf("frozen request lost budget: %d %s %+v", code, errs, *got) + } + for _, flags := range [][]string{{"--frozen"}, {"--allow-over-budget"}, {"--freeze-started-at-ns=123"}} { + args := append([]string{"detach", "--volume=v1", "--status-addr=" + srv.URL}, flags...) + if code, _, _ := runChunk(args...); code == 0 || len(*got) != 1 { + t.Fatalf("invalid flags sent request: %v", flags) + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 32e83250d0..c96a1d64e8 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -886,6 +886,15 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st return p.detachVolume(ctx, volumeID, false) } +// DetachVolumeFrozen uses one budgeted cut when the guest is already frozen. +func (p *DurableProvider) DetachVolumeFrozen(ctx context.Context, volumeID string, opts storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) { + ctx, err := storage.WithFrozenDetach(ctx, opts) + if err != nil { + return storage.ChunkCutResult{}, 0, err + } + 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") @@ -913,11 +922,15 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla return storage.ChunkCutResult{}, 0, err } } - precopy := p.cfg.ChunkDetachPrecopy && !plain + guestFreeze, guestFrozen := storage.FrozenDetachFromContext(ctx) + precopy := (p.cfg.ChunkDetachPrecopy || guestFrozen) && !plain freeze := p.cfg.DetachFreezeTimeout if freeze <= 0 { freeze = defaultDetachFreezeTimeout } + if guestFrozen && !guestFreeze.AllowOverBudget { + freeze = detachFreezeTarget + } // One freeze budget covers the drain, the final cut AND the settlement: // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. @@ -934,10 +947,27 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla cutCtx, cancel := context.WithCancelCause(accountCtx) defer cancel(context.Canceled) var timer *time.Timer + var settleDeadline time.Time beginFreeze := func() { + if timer != nil { + return + } start = time.Now() + if guestFrozen { + start = guestFreeze.StartedAt + } casAtFreeze = countCAS() - timer = time.AfterFunc(freeze*3/4, func() { cancel(context.DeadlineExceeded) }) + operationStart := start + if guestFrozen && guestFreeze.AllowOverBudget { + operationStart = time.Now() + } + settleDeadline = operationStart.Add(freeze) + remaining := max(time.Duration(0), time.Until(settleDeadline)) + // An already exhausted normal guest budget must reach the no-I/O + // forecast refusal, rather than racing a zero-delay cancellation. + if remaining > 0 { + timer = time.AfterFunc(remaining*3/4, func() { cancel(context.DeadlineExceeded) }) + } } defer func() { if timer != nil { @@ -959,6 +989,9 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } } var r storage.ChunkCutResult + if guestFrozen { + beginFreeze() + } if precopy { owner, ok := layer.(interface { PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) @@ -981,12 +1014,21 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla }) // Log only after capture releases its barrier; at most five records. for _, a := range r.Precopy.Rounds { + p := a.FixedParts + log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f intent_cleanup_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_capture_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f live_sync_lifecycle_wait_ms=%.3f live_sync_store_wait_ms=%.3f live_sync_group_commit_ms=%.3f live_sync_completion_wait_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.IntentCleanup)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.LifecycleWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.StoreWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.GroupCommitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.CompletionWaitNs)/float64(time.Millisecond)) 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 { - if !start.IsZero() { - r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, 0, false) + if !start.IsZero() && !r.Precopy.IsReplay() { + elapsed := time.Since(start) + if !guestFrozen { + elapsed += r.Precopy.BarrierBeforeFreeze + } + r.Precopy.Finish(elapsed, 0, false) + if recorder, ok := layer.(interface{ RememberDetachReport(storage.PrecopyReport) }); ok { + recorder.RememberDetachReport(r.Precopy) + } } return r, h.storage.NextLSN() - 1, nil } @@ -1036,7 +1078,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // resumes: an earlier detach that applied, an unresolved detach CAS or a // fenced layer must never resume serving. The settlement keeps the rest // of the freeze budget even when the caller's context is gone. - sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), start.Add(freeze)) + sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline) defer scancel() if trace := p.testDetachTrace; trace != nil { dl, _ := sctx.Deadline() @@ -1049,9 +1091,16 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla if attempts > 0 { extra = attempts - 1 } - r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, extra, true) + elapsed := time.Since(start) + if !guestFrozen { + elapsed += r.Precopy.BarrierBeforeFreeze + } + r.Precopy.Finish(elapsed, extra, true) log.Printf("durable: pre-copy settlement volume=%s elapsed=%s extra_cas=%d declared_worst=%s latency_gate_failed=%t outcome=%v err=%v", volumeID, r.Precopy.FreezeElapsed, extra, r.Precopy.DeclaredWorst, r.Precopy.LatencyGateFailed, how, serr) dr.Precopy = r.Precopy + if recorder, ok := layer.(interface{ RememberDetachReport(storage.PrecopyReport) }); ok { + recorder.RememberDetachReport(r.Precopy) + } } switch { case serr != nil: diff --git a/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go new file mode 100644 index 0000000000..2f9e9ef024 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go @@ -0,0 +1,60 @@ +package durable_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync/atomic" + "testing" + "time" +) + +type frozenCountRemote struct { + storage.ChunkRemote + puts atomic.Int64 +} + +func (r *frozenCountRemote) Put(ctx context.Context, key string, p []byte) error { + r.puts.Add(1) + return r.ChunkRemote.Put(ctx, key, p) +} +func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) { + mem := storage.NewMemChunkRemote() + remote := &frozenCountRemote{ChunkRemote: mem} + p, _ := parkedProvider(t, remote) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(context.Background(), 4096, block(0x77)); err != nil { + t.Fatal(err) + } + before, _ := remote.GetHead(context.Background()) + puts := remote.puts.Load() + r, _, err := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-6 * time.Second)}) + after, _ := remote.GetHead(context.Background()) + if !errors.Is(err, storage.ErrFrozenTailTooLarge) || r.Precopy.Frozen || puts != remote.puts.Load() || before.Gen != after.Gen { + t.Fatalf("frozen refusal mutated remote: %+v %v puts=%d/%d", r.Precopy, err, puts, remote.puts.Load()) + } + if _, err = b.Write(context.Background(), 8192, block(0x88)); err != nil { + t.Fatalf("refusal stopped serving before thaw: %v", err) + } + r, _, err = p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-time.Minute), AllowOverBudget: true}) + if err != nil || !r.Precopy.GuestFrozen || !r.Precopy.OverBudget || !r.Precopy.Frozen || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 1 || r.Precopy.FreezeElapsed < time.Minute || r.Precopy.DeclaredWorst < time.Minute || !r.Precopy.LatencyGateFailed { + t.Fatalf("explicit final failed/underreported total freeze: %+v %v", r, err) + } + original, _ := json.Marshal(r.Precopy) + originalHead := r.Head.Gen + puts = remote.puts.Load() + replay, _, replayErr := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now()}) + replayJSON, _ := json.Marshal(replay.Precopy) + if replayErr != nil || replay.Head.Gen != originalHead || !bytes.Equal(original, replayJSON) || remote.puts.Load() != puts { + t.Fatalf("provider replay changed original freeze report or re-uploaded: original=%s replay=%s err=%v", original, replayJSON, replayErr) + } + if headBlock(t, mem, 1)[0] != 0x77 || headBlock(t, mem, 2)[0] != 0x88 { + t.Fatal("final detached point lost writes") + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 3308ce2d34..c3ad60dd8b 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -39,13 +39,14 @@ type ChunkControl interface { // ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). type ChunkCutResponse struct { - VolumeID string `json:"volumeID"` - CutLSN uint64 `json:"cutLSN"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - Holder string `json:"holder"` - Noop bool `json:"noop"` - FullHash bool `json:"fullHash"` + CandidateTail *storage.ChunkCandidateTail `json:"candidateTail,omitempty"` + VolumeID string `json:"volumeID"` + CutLSN uint64 `json:"cutLSN"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + Holder string `json:"holder"` + Noop bool `json:"noop"` + FullHash bool `json:"fullHash"` // Stats are the statistics the chunk layer measured for this cut // (§3.1). A zero field is "not measured" or "none" (a Noop cut // uploads nothing). @@ -56,6 +57,15 @@ type ChunkCutResponse struct { // mirrors storage.ChunkCutStats field for field (a test keeps the two in // step); every duration is in nanoseconds. type ChunkCutStatsBody struct { + SyncPhases storage.SyncPhaseStats `json:"syncPhases"` + CandidateNs int64 `json:"candidateNs"` + WindowSetupNs int64 `json:"windowSetupNs"` + PublishPrepareNs int64 `json:"publishPrepareNs"` + ManifestNs int64 `json:"manifestNs"` + CommitStateNs int64 `json:"commitStateNs"` + IntentCleanupNs int64 `json:"intentCleanupNs"` + NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` + PayloadNs int64 `json:"payloadNs"` COWWALReadAttempts uint64 `json:"cowWALReadAttempts"` COWLocalReadNs int64 `json:"cowLocalReadNs"` @@ -88,6 +98,15 @@ type ChunkCutStatsBody struct { func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { return ChunkCutStatsBody{ + SyncPhases: s.SyncPhases, + CandidateNs: s.CandidateNs, + WindowSetupNs: s.WindowSetupNs, + PublishPrepareNs: s.PublishPrepareNs, + ManifestNs: s.ManifestNs, + CommitStateNs: s.CommitStateNs, + IntentCleanupNs: s.IntentCleanupNs, + NonPayloadCopyNs: s.NonPayloadCopyNs, + PayloadNs: s.PayloadNs, COWWALReadAttempts: s.COWWALReadAttempts, COWLocalReadNs: s.COWLocalReadNs, @@ -286,6 +305,12 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusConflict, codeClosing, false // stays closed until a new attach case errors.Is(err, storage.ErrChunkLayerClosed): return http.StatusServiceUnavailable, codeClosing, false // the process is shutting down + case errors.Is(err, errFrozenDetachUnsupported): + return http.StatusConflict, "frozen_detach_unsupported", false + case errors.Is(err, storage.ErrInvalidFreezeBudget): + return http.StatusBadRequest, "bad_request", false + case errors.Is(err, storage.ErrFrozenTailTooLarge): + return http.StatusConflict, "frozen_tail_too_large", true // A local window abort cancels its uploads; that cancellation is not // a remote outage. Keep authority and uncertain-publication precedence. case errors.Is(err, storage.ErrCutCOWAborted): @@ -496,13 +521,20 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) return } var req struct { - VolumeID string `json:"volumeID"` - TimeoutMs int64 `json:"timeoutMs"` - Plain bool `json:"plain,omitempty"` + VolumeID string `json:"volumeID"` + TimeoutMs int64 `json:"timeoutMs"` + Plain bool `json:"plain,omitempty"` + Frozen bool `json:"frozen,omitempty"` + FreezeStartedAtNs int64 `json:"freezeStartedAtNs,omitempty"` + AllowOverBudget bool `json:"allowOverBudget,omitempty"` } if !decodeChunkBody(w, r, &req) { return } + if (req.Frozen && (req.Plain || req.FreezeStartedAtNs <= 0 || time.Unix(0, req.FreezeStartedAtNs).After(time.Now()))) || (!req.Frozen && (req.FreezeStartedAtNs != 0 || req.AllowOverBudget)) { + writeChunkErr(w, http.StatusBadRequest, "bad_request", false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen") + return + } ctl := s.chunkTarget(w, req.VolumeID) if ctl == nil { return @@ -511,7 +543,16 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) defer cancel() var res ChunkDetachResponse var err error - if req.Plain { + if req.Frozen { + frozen, ok := ctl.(interface { + DetachFrozen(context.Context, string, storage.FrozenDetachOptions) (ChunkDetachResponse, error) + }) + if !ok { + writeChunkErr(w, http.StatusConflict, "frozen_detach_unsupported", false, "frozen detach unsupported") + return + } + res, err = frozen.DetachFrozen(ctx, req.VolumeID, storage.FrozenDetachOptions{StartedAt: time.Unix(0, req.FreezeStartedAtNs), AllowOverBudget: req.AllowOverBudget}) + } else if req.Plain { plain, ok := ctl.(interface { DetachPlain(context.Context, string) (ChunkDetachResponse, error) }) @@ -543,6 +584,8 @@ type ChunkProvider interface { DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) } +var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") + type chunkControl struct { p ChunkProvider cat *chunkstore.Catalog @@ -560,7 +603,7 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) return ChunkCutResponse{}, err } return ChunkCutResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, Holder: r.Head.Holder, - Noop: r.Noop, FullHash: r.FullHash, Stats: cutStatsBody(r.Stats)}, nil + Noop: r.Noop, FullHash: r.FullHash, CandidateTail: r.CandidateTail, Stats: cutStatsBody(r.Stats)}, nil } // Snapshot resolves the request against the catalog first (§3.2 step 1): @@ -626,6 +669,17 @@ func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetach return chunkDetachResponse(volumeID, r, last, err) } +func (c *chunkControl) DetachFrozen(ctx context.Context, volumeID string, opts storage.FrozenDetachOptions) (ChunkDetachResponse, error) { + p, ok := c.p.(interface { + DetachVolumeFrozen(context.Context, string, storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) + }) + if !ok { + return ChunkDetachResponse{}, errFrozenDetachUnsupported + } + r, last, err := p.DetachVolumeFrozen(ctx, volumeID, opts) + 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) diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index 2f26ba2509..51f9a57876 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -182,6 +182,13 @@ func TestChunkCutStatsBody_MirrorsTheLayerStats(t *testing.T) { f.SetString("s") case reflect.Bool: f.SetBool(true) + case reflect.Struct: + for j := 0; j < f.NumField(); j++ { + if f.Field(j).Kind() != reflect.Int64 { + t.Fatalf("nested field %s.%s is not a duration counter", v.Type().Field(i).Name, f.Type().Field(j).Name) + } + f.Field(j).SetInt(int64(100*(i+1) + j + 1)) + } default: t.Fatalf("field %s: unhandled kind %s", v.Type().Field(i).Name, f.Kind()) } diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go new file mode 100644 index 0000000000..58534c3fee --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -0,0 +1,66 @@ +package volume + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "github.com/seaweedfs/seaweed-block/core/storage" + "net/http" + "testing" + "time" +) + +type frozenDetachProvider struct { + *fakeChunkProvider + opts storage.FrozenDetachOptions + calls int + err error +} + +func (p *frozenDetachProvider) DetachVolumeFrozen(_ context.Context, _ string, opts storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) { + p.opts = opts + p.calls++ + return p.detach, p.last, p.err +} +func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) { + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 7, Head: storage.ChunkHead{Gen: 2, Epoch: 1, State: storage.ChunkHeadDetached}}, last: 7}} + s := chunkServer(t, NewChunkControl(p, nil), true) + at := time.Now().Add(-time.Second).UnixNano() + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, at) + w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") + if w.Code != 200 || p.calls != 1 || p.opts.StartedAt.UnixNano() != at || !p.opts.AllowOverBudget { + t.Fatalf("frozen wire lost fields: %d %s %+v", w.Code, w.Body, p.opts) + } + for _, invalid := range []string{`{"volumeID":"v1","frozen":true}`, `{"volumeID":"v1","allowOverBudget":true}`, fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(time.Hour).UnixNano()), fmt.Sprintf(`{"volumeID":"v1","frozen":true,"plain":true,"freezeStartedAtNs":%d}`, at)} { + before := p.calls + w = serve(t, s, http.MethodPost, "/chunk/detach", invalid, "") + if w.Code != 400 || p.calls != before { + t.Fatalf("invalid request reached provider: %d %s", w.Code, w.Body) + } + } + p.err = storage.ErrFrozenTailTooLarge + w = serve(t, s, http.MethodPost, "/chunk/detach", body, "") + var e chunkErrorBody + _ = json.Unmarshal(w.Body.Bytes(), &e) + if w.Code != 409 || e.Code != "frozen_tail_too_large" || !e.Retryable { + t.Fatalf("wrong frozen refusal: %d %s", w.Code, w.Body) + } + for _, terminal := range []error{storage.ErrChunkLayerClosed, storage.ErrChunkLayerFenced, storage.ErrChunkCASOutcomeUnknown} { + expectedStatus, expectedCode, expectedRetry := chunkErrorCode(terminal) + status, code, retry := chunkErrorCode(errors.Join(terminal, storage.ErrFrozenTailTooLarge)) + if status != expectedStatus || code != expectedCode || retry != expectedRetry { + t.Fatalf("frozen refusal hid terminal/unknown cause %v: %d %s %t", terminal, status, code, retry) + } + } +} +func TestChunkCheckpointCarriesCandidateTail(t *testing.T) { + tail := &storage.ChunkCandidateTail{Bytes: 4096, Estimate: time.Second, Known: true, RateSamples: 3, BytesPerSecond: 4096} + p := &fakeChunkProvider{cut: storage.ChunkCutResult{CandidateTail: tail}} + s := chunkServer(t, NewChunkControl(p, nil), true) + w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "") + var body ChunkCutResponse + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 200 || body.CandidateTail == nil || *body.CandidateTail != *tail { + t.Fatalf("cut response lost tail: %d %s %v", w.Code, w.Body, err) + } +} diff --git a/seaweed-block/core/storage/chunk_candidate_tail_test.go b/seaweed-block/core/storage/chunk_candidate_tail_test.go new file mode 100644 index 0000000000..1e467e429e --- /dev/null +++ b/seaweed-block/core/storage/chunk_candidate_tail_test.go @@ -0,0 +1,61 @@ +package storage + +import ( + "testing" + "time" +) + +func TestCheckpointTailMeasuresWritesAfterItsCut(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: 2 * float64(ctChunkBytes)}) + } + w.write(t, s, 1, 0x11) + f.beforeCAS = func(*fakeChunkRemote) { f.beforeCAS = nil; w.write(t, s, 2, 0x22) } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + tail := r.CandidateTail + if tail == nil || tail.Bytes != ctChunkBytes || !tail.Known || tail.BytesPerSecond <= 0 { + t.Fatalf("missing post-cut dirty tail: %+v", tail) + } + expected := time.Duration(float64(tail.Bytes) / tail.BytesPerSecond * float64(time.Second)) + if expected > precopyDuration { + expected = precopyDuration + } + if tail.Estimate != expected { + t.Fatalf("tail and rate sampled inconsistently: %+v want=%s", tail, expected) + } + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.CandidateTail == nil || r.CandidateTail.Bytes != 0 || !r.CandidateTail.Known || r.CandidateTail.Estimate != 0 { + t.Fatalf("settled checkpoint not clean: %+v", r.CandidateTail) + } + assertEveryHeadIsPrefixImage(t, f, w) +} +func TestCheckpointTailUnknownRateIsNotZeroCost(t *testing.T) { + s, _, l, w := precopyLayer(t, 1024, 0) + w.write(t, s, 1, 0x44) + l.precopySamples = []precopySample{{at: time.Now(), fixed: time.Millisecond, rate: 100}} + tail := l.candidateTail() + if tail.Bytes == 0 || tail.Known || tail.RateSamples != 1 { + t.Fatalf("partial rate window misreported ready: %+v", tail) + } +} + +func TestCheckpointTailUsesLiteralLatestThreeConservativeRate(t *testing.T) { + s, _, l, w := precopyLayer(t, 1024, 0) + w.write(t, s, 1, 0x51) + // Old slow rate must be excluded; latest three min is 2 chunks/s, + // conservative divisor is 2 => exactly one chunk/s and one second. + for _, multiplier := range []float64{0.25, 2, 6, 4} { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: multiplier * float64(ctChunkBytes)}) + } + tail := l.candidateTail() + if tail.Bytes != ctChunkBytes || !tail.Known || tail.BytesPerSecond != float64(ctChunkBytes) || tail.Estimate != time.Second || tail.RateSamples != 4 { + t.Fatalf("literal latest-three rate/estimate mismatch: %+v", tail) + } +} diff --git a/seaweed-block/core/storage/chunk_fixed_spans_test.go b/seaweed-block/core/storage/chunk_fixed_spans_test.go new file mode 100644 index 0000000000..1576aae80c --- /dev/null +++ b/seaweed-block/core/storage/chunk_fixed_spans_test.go @@ -0,0 +1,96 @@ +package storage + +import ( + "context" + "reflect" + "testing" + "time" +) + +type fixedSpanRemote struct { + *fakeChunkRemote + delay time.Duration +} + +func (r *fixedSpanRemote) PrepareManifest(_ context.Context, _ ChunkHead, next ChunkHead, _ uint64) (ChunkHead, []string, error) { + time.Sleep(r.delay) + return next, nil, nil +} +func (r *fixedSpanRemote) CASHead(ctx context.Context, v ChunkHeadVersion, h ChunkHead) (uint64, error) { + time.Sleep(r.delay) + return r.fakeChunkRemote.CASHead(ctx, v, h) +} + +func (r *fixedSpanRemote) DeleteIntent(ctx context.Context, id string) error { + time.Sleep(r.delay) + return r.fakeChunkRemote.DeleteIntent(ctx, id) +} +func TestChunkCutFixedSpansAttributeManifestAndCleanup(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + delay := 10 * time.Millisecond + l.remote = &fixedSpanRemote{fakeChunkRemote: f, delay: delay} + w.write(t, s, 1, 0x32) + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"ManifestNs", "IntentCleanupNs"} { + v := reflect.ValueOf(r.Stats).FieldByName(name) + if !v.IsValid() || time.Duration(v.Int()) < delay { + t.Fatalf("missing fixed span %s: %+v", name, r.Stats) + } + } + if len(l.precopySamples) == 0 { + t.Fatal("no fixed sample") + } + parts := reflect.ValueOf(l.precopySamples[len(l.precopySamples)-1].parts) + for _, name := range []string{"Manifest", "IntentCleanup"} { + v := parts.FieldByName(name) + if !v.IsValid() || time.Duration(v.Int()) < delay { + t.Fatalf("missing selected fixed part %s", name) + } + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestPrecopyLiveBarrierSpansExplainOverage(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + seedFrozenSamples(l, time.Millisecond) + delay := 20 * time.Millisecond + l.testBeforeBarrierLockHook = func() { time.Sleep(delay) } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true }) + if err != nil { + t.Fatal(err) + } + if r.Precopy.BarrierOverage <= 0 || r.Precopy.BarrierParts.StoreLock < delay || len(r.Precopy.Rounds) != 1 || r.Precopy.Rounds[0].BarrierParts.StoreLock < delay { + t.Fatalf("live lock overage hidden as retained other: %+v", r.Precopy) + } +} + +func TestPrecopyFixedPartsDoNotDoubleCountSyncPhases(t *testing.T) { + st := chunkCutStats{SyncNs: int64(100 * time.Millisecond), SyncPhases: SyncPhaseStats{StoreWaitNs: int64(30 * time.Millisecond), GroupCommitNs: int64(70 * time.Millisecond)}} + p := precopyFixedParts(st, 150*time.Millisecond) + if p.DataSync != 100*time.Millisecond || p.Other != 50*time.Millisecond || p.SyncPhases != st.SyncPhases { + t.Fatalf("nested Sync cost counted twice or dropped: %+v", p) + } +} + +func TestCheckpointTailScanIncludedInTotalAndFixedCosts(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + l.remote = &fixedSpanRemote{fakeChunkRemote: f, delay: time.Millisecond} + w.write(t, s, 1, 0x6a) + delay := 20 * time.Millisecond + scans := 0 + l.testBeforeTailScanHook = func() { scans++; time.Sleep(delay) } + result, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if scans != 1 || result.Stats.CandidateNs < int64(delay) || result.Stats.TotalNs < int64(delay) { + t.Fatalf("scan missing from returned costs: scans=%d stats=%+v", scans, result.Stats) + } + sample := l.precopySamples[len(l.precopySamples)-1] + if sample.fixed < delay || sample.parts.Candidate < delay { + t.Fatalf("scan omitted from fixed observation: %+v", sample) + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go new file mode 100644 index 0000000000..4f6ce4090e --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -0,0 +1,89 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "time" +) + +var ErrFrozenTailTooLarge = errors.New("storage: frozen tail does not fit remaining freeze budget") +var ErrInvalidFreezeBudget = errors.New("storage: invalid guest freeze budget") + +// FrozenDetachOptions is supplied by the trusted guest orchestrator. It owns +// the maximum two re-freeze cycles; AllowOverBudget explicitly requests its +// final attempt. It never bypasses authority, lifecycle or CAS settlement. +type FrozenDetachOptions struct { + StartedAt time.Time + AllowOverBudget bool +} +type frozenDetachKey struct{} + +func WithFrozenDetach(ctx context.Context, opts FrozenDetachOptions) (context.Context, error) { + now := time.Now() + if opts.StartedAt.IsZero() || opts.StartedAt.Before(time.Unix(0, 1)) || opts.StartedAt.After(now) { + return nil, ErrInvalidFreezeBudget + } + // Convert remote wall time to a local monotonic origin once at admission. + opts.StartedAt = now.Add(-now.Sub(opts.StartedAt)) + return context.WithValue(ctx, frozenDetachKey{}, opts), nil +} +func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) { + v, ok := ctx.Value(frozenDetachKey{}).(FrozenDetachOptions) + return v, ok +} +func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { + return r.admitFrozenAt(opts, time.Now()) +} +func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { + r.GuestFrozen = true + r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt)) + r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) + known := r.Reason != "samples_unknown" && r.Estimate > 0 + if opts.AllowOverBudget { + r.Reason = "over_budget" + r.OverBudget = true + } else if !known || r.Estimate > r.RemainingFreeze { + r.Reason = "frozen_tail_too_large" + return false + } else { + r.Reason = "fit" + } + r.DeclaredFreeze = r.GuestFreezeElapsed + r.Estimate + if !known { + r.DeclaredFreeze = max(r.DeclaredFreeze, precopyFreezeLimit) + } + return true +} +func frozenRefusal(r PrecopyReport) error { + return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) +} + +// IsReplay distinguishes a replayed applied point from a newly completed freeze. +// The original report remains unchanged on the wire. +func (r PrecopyReport) IsReplay() bool { return r.replayed } + +func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { + now := time.Now() + if hook := l.testFrozenNow; hook != nil { + now = hook() + } + return r.admitFrozenAt(opts, now) +} + +// RememberDetachReport completes the telemetry kept with an applied or still +// pending point. The durable provider calls it after its final settlement spans. +// It changes no publication identity or authority state. +func (l *chunkLayerImpl) RememberDetachReport(report PrecopyReport) { + if report.IsReplay() { + return + } + l.stMu.Lock() + defer l.stMu.Unlock() + if l.detached != nil { + l.detached.Precopy = report + } + if l.pendingDetach { + l.pendingCut.Precopy = report + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget_test.go b/seaweed-block/core/storage/chunk_frozen_budget_test.go new file mode 100644 index 0000000000..d9313d872a --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_budget_test.go @@ -0,0 +1,171 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "reflect" + "testing" + "time" +) + +func frozenContext(t *testing.T, elapsed time.Duration, force bool) context.Context { + t.Helper() + ctx, err := WithFrozenDetach(ctTimeout(t), FrozenDetachOptions{StartedAt: time.Now().Add(-elapsed), AllowOverBudget: force}) + if err != nil { + t.Fatal(err) + } + return ctx +} +func seedFrozenSamples(l *chunkLayerImpl, fixed time.Duration) { + l.precopySamples = nil + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, rate: 20 * float64(ctChunkBytes)}) + } +} +func TestFrozenDetachRejectsBeforeStagingOrUpload(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x12) + seedFrozenSamples(l, 1300*time.Millisecond) + before := f.stats() + l.testBeforeBarrierLockHook = func() { t.Fatal("preflight rejection reached capture") } + r, err := l.PrecopyDetach(frozenContext(t, 4*time.Second, false), func() bool { t.Fatal("over-budget attempt stopped backend"); return true }) + after := f.stats() + if !errors.Is(err, ErrFrozenTailTooLarge) || r.Precopy.Frozen || r.Precopy.Reason != "frozen_tail_too_large" || after.puts != before.puts || after.cas != before.cas || after.head.Gen != before.head.Gen { + t.Fatalf("over-budget frozen cut did work: %+v %v before=%+v after=%+v", r.Precopy, err, before, after) + } + l.testBeforeBarrierLockHook = nil + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x12)) { + t.Fatal("refusal dropped dirty bytes") + } +} +func TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x24) + seedFrozenSamples(l, time.Millisecond) + before := f.stats() + reached := false + l.testBeforeBarrierLockHook = func() { reached = true; seedFrozenSamples(l, 6*time.Second) } + r, err := l.PrecopyDetach(frozenContext(t, 0, false), func() bool { t.Fatal("authoritative refusal stopped backend"); return true }) + after := f.stats() + if !reached || !errors.Is(err, ErrFrozenTailTooLarge) || r.Precopy.Frozen || len(r.Precopy.Rounds) != 1 || after.puts != before.puts || after.cas != before.cas || after.head.Gen != before.head.Gen { + t.Fatalf("barrier rejection uploaded or rolled: %+v %v", r.Precopy, err) + } + l.testBeforeBarrierLockHook = nil + r, err = l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} +func TestFrozenDetachForcedFinalCommitsSamePoint(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x36) + seedFrozenSamples(l, 6*time.Second) + stops := 0 + r, err := l.PrecopyDetach(frozenContext(t, 6*time.Second, true), func() bool { stops++; return true }) + if err != nil || !r.Precopy.OverBudget || !r.Precopy.GuestFrozen || !r.Precopy.Frozen || r.Precopy.Reason != "over_budget" || len(r.Precopy.Rounds) != 1 || stops != 1 || r.Head.State != ChunkHeadDetached { + t.Fatalf("explicit final did not commit once: %+v %v", r, err) + } + if !r.Precopy.LatencyGateFailed || r.Precopy.FreezeElapsed < 6*time.Second { + t.Fatalf("external elapsed hidden: %+v", r.Precopy) + } + assertEveryHeadIsPrefixImage(t, f, w) + r2, err := l.PrecopyDetach(frozenContext(t, 7*time.Second, false), func() bool { t.Fatal("applied retry stopped again"); return true }) + want := r.Precopy + want.replayed = true + if err != nil || r2.Head.Gen != r.Head.Gen || !reflect.DeepEqual(r2.Precopy, want) { + t.Fatalf("applied retry budget-refused: %+v %v", r2, err) + } +} +func TestFrozenBudgetInputValidation(t *testing.T) { + for _, at := range []time.Time{{}, time.Now().Add(time.Hour)} { + if _, err := WithFrozenDetach(context.Background(), FrozenDetachOptions{StartedAt: at}); !errors.Is(err, ErrInvalidFreezeBudget) { + t.Fatalf("invalid origin accepted: %v", err) + } + } +} + +func TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits(t *testing.T) { + r := PrecopyReport{Estimate: time.Second, Reason: "fit"} + if !r.admitFrozen(FrozenDetachOptions{StartedAt: time.Now(), AllowOverBudget: true}) || !r.OverBudget || r.Reason != "over_budget" { + t.Fatalf("explicit override hidden: %+v", r) + } +} + +func TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards(t *testing.T) { + for _, closed := range []bool{false, true} { + t.Run(map[bool]string{false: "fenced", true: "closed"}[closed], func(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x4a) + before := f.stats() + want := ErrChunkLayerFenced + if closed { + if err := l.Close(); err != nil { + t.Fatal(err) + } + want = ErrChunkLayerClosed + } else { + l.cfg.CaptureAllowed = func() error { return ErrChunkLayerFenced } + } + _, err := l.PrecopyDetach(frozenContext(t, time.Minute, true), func() bool { t.Fatal("override bypassed gate"); return true }) + after := f.stats() + if !errors.Is(err, want) || after.puts != before.puts || after.cas != before.cas { + t.Fatalf("override bypassed %v: %v", want, err) + } + }) + } +} +func TestFrozenRetryDoesNotHideUnknownPublication(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 0) + w.write(t, s, 1, 0x5b) + seedFrozenSamples(l, time.Millisecond) + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } + r, err := l.PrecopyDetach(frozenContext(t, 0, true), func() bool { return true }) + if !r.Precopy.Frozen || !errors.Is(err, ErrChunkCASOutcomeUnknown) { + t.Fatalf("missing unknown publication: %+v %v", r.Precopy, err) + } + before := f.stats() + _, err = l.PrecopyDetach(frozenContext(t, time.Minute, false), func() bool { t.Fatal("unknown retry stopped again"); return true }) + if !errors.Is(err, ErrChunkCASOutcomeUnknown) || errors.Is(err, ErrFrozenTailTooLarge) || f.stats().puts != before.puts { + t.Fatalf("budget hid uncertainty: %v", err) + } + f.failGet = nil + r, err = l.PrecopyDetach(frozenContext(t, time.Minute, false), func() bool { t.Fatal("applied retry stopped again"); return true }) + if err != nil || r.Head.Gen != before.head.Gen || r.Head.State != ChunkHeadDetached { + t.Fatalf("applied same-point result budget-refused: %+v %v", r, err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +func TestFrozenBarrierConsumesElapsedWithoutNewAllowance(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x61) + seedFrozenSamples(l, 1300*time.Millisecond) + origin := time.Now() + now := origin + l.testFrozenNow = func() time.Time { return now } + reached := false + l.testBeforeBarrierLockHook = func() { reached = true; now = origin.Add(4 * time.Second) } + before := f.stats() + ctx, err := WithFrozenDetach(ctTimeout(t), FrozenDetachOptions{StartedAt: origin}) + if err != nil { + t.Fatal(err) + } + stops := 0 + result, err := l.PrecopyDetach(ctx, func() bool { stops++; return true }) + after := f.stats() + if !reached || stops != 0 || !errors.Is(err, ErrFrozenTailTooLarge) || result.Precopy.Estimate >= 5*time.Second || result.Precopy.RemainingFreeze > 1100*time.Millisecond || result.Precopy.Estimate <= result.Precopy.RemainingFreeze || after.puts != before.puts || after.cas != before.cas { + t.Fatalf("elapsed barrier budget not enforced without upload: %+v %v", result.Precopy, err) + } + l.testBeforeBarrierLockHook = nil + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + assertEveryHeadIsPrefixImage(t, f, w) +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 5c32d22aeb..dc8beddfa9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -53,7 +53,7 @@ const defaultReadMissTimeout = 30 * time.Second type chunkLayerImpl struct { // capMu serializes pre-copy admission and its recent measurements. - precopyFreeze func(uint64, time.Time) bool + precopyFreeze func(uint64, time.Time, chunkCutStats) bool precopyPrepare func(context.Context) (func(), error) precopySamples []precopySample precopyPause func(time.Duration) @@ -133,6 +133,8 @@ type chunkLayerImpl struct { testCOWSave func() error testPresenceSnapshotHook func() // after a presence snapshot, before it is written testBaseTransitionBeforeLock func() // test handshake before capMu drain + testBeforeTailScanHook func() // diagnostic tail scan cost witness + testFrozenNow func() time.Time // controlled guest elapsed at admission testAfterAdmitHook func() // right after a capture is admitted testAfterStageHook func(round int) // after each pre-copy staging round testAfterStageReadHook func(idx uint64) // after a staging read, before its result is kept @@ -669,9 +671,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.HeadReadbackNs += time.Since(start).Nanoseconds() return head, err } + dropCapturedIntents := func(ctx context.Context, ids []string) { + start := time.Now() + l.dropIntents(ctx, ids) + st.IntentCleanupNs += time.Since(start).Nanoseconds() + } + finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) { + start := time.Now() + l.finishCut(head, h, changed, keys) + st.CommitStateNs += time.Since(start).Nanoseconds() + } var pauseStart time.Time var payloadBeforeBarrier int64 defer func() { + var tailBytes uint64 + if err == nil { + scanStart := time.Now() + tailBytes = l.candidateTailBytes() + st.CandidateNs += time.Since(scanStart).Nanoseconds() + } st.TotalNs = time.Since(start).Nanoseconds() if err == nil { res.Stats = st @@ -679,6 +697,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier l.samplePrecopy(st, fixed) } + res.CandidateTail = l.estimateCandidateTail(tailBytes) } if errors.Is(err, errChunkLayerFenced) { l.stMu.Lock() @@ -690,7 +709,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } l.reusable = nil l.stMu.Unlock() - l.dropIntents(ctx, ids) + dropCapturedIntents(ctx, ids) } if observe := l.precopyPause; observe != nil { observe(time.Duration(st.BarrierPauseNs)) @@ -742,17 +761,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Pre-copy large native dirty sets outside the barrier, bounded by the // remaining COW exposure rather than a fixed candidate count. stageStart := time.Now() - staged, intents, err := l.stage(ctx, &st) + var staged map[uint64]stagedChunk + var intents []string + _, guestFrozen := FrozenDetachFromContext(ctx) + if !guestFrozen { + staged, intents, err = l.stage(ctx, &st) + } if st.UploadedBytes > 0 { st.PayloadNs += time.Since(stageStart).Nanoseconds() } if err != nil { - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } if cause := context.Cause(ctx); cause != nil { - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, cause } @@ -777,7 +801,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch releasePrecopy() releasePrecopy = nil } - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, cause } // Resume rejected tentative admission before any ordinary COW upload. @@ -794,7 +818,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.s.captureMu.Lock() barrier := time.Now() st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds() - h, err := l.s.Sync() + h, err := l.s.syncWithPhases(&st.SyncPhases) st.SyncNs = time.Since(barrier).Nanoseconds() if hook := l.testAfterBarrierSyncHook; hook != nil && err == nil { hook(h) @@ -802,9 +826,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if err != nil { unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() - l.dropIntents(ctx, intents) // a clean abort: staged keys are released + dropCapturedIntents(ctx, intents) // a clean abort: staged keys are released return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) } + candidateStart := time.Now() candidates := map[uint64]bool{} for idx := range l.captureCandidates() { candidates[idx] = true @@ -851,12 +876,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Candidates, mutation versions and births belong to the same barrier. // Do not sample the owned map after COW writers are admitted again. births := l.captureBirths(candidates, h) + st.CandidateNs += time.Since(candidateStart).Nanoseconds() // The authoritative candidate set is fixed with mutation admission closed. // The owner callback is nonblocking and may stop only an already drained // frontend; rejected attempts remain ordinary COW cuts. if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil { tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks - detach = freeze(tail, pauseStart) + detach = freeze(tail, pauseStart, st) + } + if guestFrozen && !detach { + unlockCapture() + st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() + l.abortCut(all) + dropCapturedIntents(ctx, intents) + return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit()) } if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) { @@ -866,7 +899,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // reached: publishing would move remote_lsn backwards. Refused // before any upload. (A HEAD of a newer holder fences below.) l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("%w: %w: cut LSN %d, HEAD remote_lsn %d", errChunkCaptureRefused, errChunkLSNBehind, h, baseHead.RemoteLSN) } @@ -876,11 +909,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch bytesBeforeCopy := st.UploadedBytes { var w *cutCOWWindow + windowStart := time.Now() w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) if copyErr == nil { w.budget = budget } unlockCapture() + st.WindowSetupNs += time.Since(windowStart).Nanoseconds() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() copyStart = time.Now() if copyErr == nil { @@ -904,11 +939,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CopyNs = time.Since(copyStart).Nanoseconds() if st.UploadedBytes > bytesBeforeCopy { st.PayloadNs += st.CopyNs + } else { + st.NonPayloadCopyNs += st.CopyNs } st.UploadNs = st.CopyNs if copyErr != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr) } if b := l.cfg.BarrierBound; b > 0 && st.BarrierCopyChunks > b { @@ -916,6 +953,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } // Upload only what changed against HEAD. + prepareStart := time.Now() next := copyHead(baseHead) next.Epoch, next.Holder, next.RemoteLSN = l.cfg.Epoch, l.cfg.Holder, h next.State, next.DetachedBy = chunkHeadActive, nil @@ -965,23 +1003,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: baseHead.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) if err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err) } intents = append(intents, id) } + st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds() payloadStart := time.Now() if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error { u := uploads[i] return l.putCaptured(ctx, u.key, u.c.data) }); err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } if len(uploads) > 0 { st.PayloadNs += time.Since(payloadStart).Nanoseconds() } + prepareStart = time.Now() for _, u := range uploads { next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} newKeys[u.c.idx] = u.key @@ -989,16 +1029,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.UploadedChunks++ st.UploadedBytes += int64(max(len(u.c.data), u.c.size)) } + st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds() upgrade := false if builder, ok := l.remote.(ChunkManifestBuilder); ok { upgrade = baseHead.Segments == nil var ids []string var err error + manifestStart := time.Now() next, ids, err = builder.PrepareManifest(ctx, baseHead, next, uint64(l.blockSize)*l.chunkBlocks) + st.ManifestNs += time.Since(manifestStart).Nanoseconds() intents = append(intents, ids...) if err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } } @@ -1009,7 +1052,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch cur, err := readCapturedHead() if err != nil { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) } if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) { @@ -1020,19 +1063,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.fencePublication(cur) return chunkCutResult{}, errChunkLayerFenced } - l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS + finishCapturedCut(baseHead, h, nil, nil) // nothing new: no CAS persistCapturedMap(capturedVersions) - l.dropIntents(ctx, intents) // superseded staged uploads only + dropCapturedIntents(ctx, intents) // superseded staged uploads only return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } if err := l.admit(); err != nil { // admission re-checked right before the CAS l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } if l.supersededBy(baseHead) { l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) l.stMu.Lock() l.fenced = true l.stMu.Unlock() @@ -1051,9 +1094,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if casErr == nil { next.Gen = gen - l.finishCut(next, h, changed, newKeys) + finishCapturedCut(next, h, changed, newKeys) persistCapturedMap(capturedVersions) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by @@ -1091,14 +1134,14 @@ 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) + finishCapturedCut(cur, h, changed, newKeys) persistCapturedMap(capturedVersions) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } // HEAD moved past the CAS's base without it: it can never land. l.abortCut(all) - l.dropIntents(ctx, intents) + dropCapturedIntents(ctx, intents) if l.supersededBy(cur) { l.stMu.Lock() l.fenced = true diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index fdb1c142ed..da22b9a1a9 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -25,6 +25,16 @@ const ( // PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample. type PrecopyFixedParts struct { + // Nested DataSync details, excluded from the additive measured sum. + SyncPhases SyncPhaseStats `json:"syncPhases"` + Candidate time.Duration `json:"candidateNs"` + WindowSetup time.Duration `json:"windowSetupNs"` + PublishPrepare time.Duration `json:"publishPrepareNs"` + Manifest time.Duration `json:"manifestNs"` + CommitState time.Duration `json:"commitStateNs"` + IntentCleanup time.Duration `json:"intentCleanupNs"` + NonPayloadCopy time.Duration `json:"nonPayloadCopyNs"` + Drain time.Duration `json:"drainNs"` StoreLock time.Duration `json:"storeLockNs"` DataSync time.Duration `json:"dataSyncNs"` @@ -35,8 +45,8 @@ type PrecopyFixedParts struct { } 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), MapPersist: time.Duration(st.MapPersistNs)} - p.Other = max(time.Duration(0), fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist) + p := PrecopyFixedParts{SyncPhases: st.SyncPhases, Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), IntentCleanup: time.Duration(st.IntentCleanupNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), 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.measured()) return p } @@ -48,6 +58,8 @@ type precopySample struct { } type PrecopyAttempt struct { + BarrierParts PrecopyFixedParts `json:"barrierParts"` + BarrierOverage time.Duration `json:"barrierOverageNs"` // Attempt is the physical round ordinal, including measurement rounds. Attempt int `json:"attempt"` Drain time.Duration `json:"drainNs"` @@ -68,6 +80,15 @@ type PrecopyAttempt struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + replayed bool // transport-local marker; never replaces the original freeze telemetry. + + // Live barrier prefix is diagnostic, not additive to the selected forecast. + BarrierParts PrecopyFixedParts `json:"barrierParts"` + BarrierOverage time.Duration `json:"barrierOverageNs"` + GuestFrozen bool `json:"guestFrozen,omitempty"` + GuestFreezeElapsed time.Duration `json:"guestFreezeElapsedNs,omitempty"` + RemainingFreeze time.Duration `json:"remainingFreezeNs,omitempty"` + OverBudget bool `json:"overBudget,omitempty"` Rounds []PrecopyAttempt `json:"rounds,omitempty"` Drain time.Duration `json:"drainNs"` DrainTimedOut bool `json:"drainTimedOut"` @@ -103,7 +124,10 @@ 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 == "no_progress" || r.Reason == "final_attempt" { + if r.GuestFrozen { + r.DeclaredWorst = r.DeclaredFreeze + time.Duration(extraCAS)*chunkHeadOperationTimeout + limit = precopyFreezeLimit + } else if r.Reason == "no_progress" || r.Reason == "final_attempt" { limit = min(r.DeclaredFreeze, precopyFreezeLimit) } r.LatencyGateFailed = failed || elapsed > limit @@ -126,7 +150,7 @@ func (l *chunkLayerImpl) PrecopyDetachWithAdmission(ctx context.Context, prepare return l.precopyDetach(ctx, prepare, stopIO) } -func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) { +func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (result ChunkCutResult, resultErr error) { if stopIO == nil { return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown) } @@ -136,13 +160,34 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return ChunkCutResult{}, err } defer l.capMu.Unlock() + defer func() { + if result.Precopy.Frozen && !result.Precopy.IsReplay() { + l.RememberDetachReport(result.Precopy) + } + }() + guestFreeze, externallyFrozen := FrozenDetachFromContext(ctx) + if err := ctx.Err(); err != nil { return ChunkCutResult{}, err } if r, ok := l.storedDetach(); ok { r.Precopy.Frozen = true + r.Precopy.replayed = true return r, nil } + l.stMu.Lock() + pending := l.pending != nil + l.stMu.Unlock() + if externallyFrozen && !pending { + if err := l.admit(); err != nil { + return ChunkCutResult{}, err + } + tail := l.candidateTail() + r := l.precopyEstimate(tail.Bytes, 0) + if !l.admitFrozen(&r, guestFreeze) { + return ChunkCutResult{Precopy: r}, frozenRefusal(r) + } + } ctx, countCAS := WithChunkCASAccounting(ctx) var report PrecopyReport var frozenAt time.Time @@ -171,7 +216,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context longestPause = pause } } - l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool { + l.precopyFreeze = func(tail uint64, barrierStart time.Time, current chunkCutStats) bool { report = l.precopyEstimate(tail, report.Attempts) report.Drain = drain report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) @@ -183,8 +228,10 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return false } spent := time.Since(barrierStart) + report.BarrierParts = precopyFixedParts(current, spent) if spent > report.Fixed { extra := spent - report.Fixed + report.BarrierOverage = extra report.Estimate += extra report.FixedParts.Other += extra report.Fixed = spent @@ -196,10 +243,18 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if len(rounds) > 0 { previous = &rounds[len(rounds)-1] } - if !report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) { + admitted := false + if externallyFrozen { + admitted = l.admitFrozen(&report, guestFreeze) + } else { + admitted = report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) + } + if !admitted { return false } - report.DeclaredFreeze = report.Estimate + if !externallyFrozen { + report.DeclaredFreeze = report.Estimate + } if !stopIO() { report.Reason = "admitted_io" return false @@ -210,7 +265,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context return true } defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }() - for attempt := 1; attempt <= precopyAttempts; attempt++ { + maxAttempts := precopyAttempts + if externallyFrozen { + maxAttempts = 1 + } + for attempt := 1; attempt <= maxAttempts; 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 { @@ -227,7 +286,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context r, err := l.captureLocked(ctx, false) report.SamplesAtStart, report.MeasurementRounds = samplesAtStart, measurementRounds a := PrecopyAttempt{ - Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, + Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, BarrierParts: report.BarrierParts, BarrierOverage: report.BarrierOverage, 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, @@ -243,11 +302,13 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context report.Rounds = rounds report.TentativePauseTotal, report.LongestTentativePause = pauseTotal, longestPause r.Precopy = report + if errors.Is(err, ErrFrozenTailTooLarge) { + return r, errors.Join(err, frozenRefusal(report)) + } if errors.Is(err, errChunkLayerDetached) { if previous, ok := l.storedDetach(); ok { - previous.Precopy = report previous.Precopy.Frozen = true - previous.Precopy.Reason = "previous_detach_applied" + previous.Precopy.replayed = true return previous, nil } } @@ -257,7 +318,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if attempts > 0 { extra = attempts - 1 } - r.Precopy.Finish(time.Since(frozenAt), extra, err != nil) + elapsed := time.Since(frozenAt) + if externallyFrozen { + elapsed = time.Since(guestFreeze.StartedAt) + } + r.Precopy.Finish(elapsed, extra, err != nil) return r, err } if err != nil { @@ -370,7 +435,7 @@ func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt, final bool) bool 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) + p.Other = max(time.Duration(0), s.fixed-p.measured()) return p } @@ -426,3 +491,38 @@ func comparablePrecopyAttempt(a *PrecopyAttempt) bool { return false } } + +func (p PrecopyFixedParts) measured() time.Duration { + return p.Drain + p.StoreLock + p.DataSync + p.HeadCAS + p.HeadReadback + p.MapPersist + p.Candidate + p.WindowSetup + p.PublishPrepare + p.Manifest + p.CommitState + p.IntentCleanup + p.NonPayloadCopy +} + +// Candidate count is conservative and advisory while guest writes continue. +// The same immutable rate observation supplies both the estimate and its rate. +func (l *chunkLayerImpl) candidateTail() *ChunkCandidateTail { + return l.estimateCandidateTail(l.candidateTailBytes()) +} + +func (l *chunkLayerImpl) candidateTailBytes() uint64 { + if hook := l.testBeforeTailScanHook; hook != nil { + hook() + } + candidates := l.captureCandidates() + l.stMu.Lock() + for idx := range l.dirty { + candidates[idx] = true + } + if l.allDirty { + for idx := uint64(0); idx < l.numChunks; idx++ { + if !l.absent[idx] || l.chunkHasLocalLocked(idx) { + candidates[idx] = true + } + } + } + l.stMu.Unlock() + return uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks +} + +func (l *chunkLayerImpl) estimateCandidateTail(bytes uint64) *ChunkCandidateTail { + r := l.precopyEstimate(bytes, 0) + return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 2fda490f07..ca42de1f14 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -396,7 +396,25 @@ type chunkLayerConfig struct { // chunkCutStats describes one cut. The periodic-cut work fills it; a zero // value means "not measured". +// SyncPhaseStats are nested details of SyncNs; never add them to SyncNs. +type SyncPhaseStats struct { + LifecycleWaitNs int64 `json:"lifecycleWaitNs"` + StoreWaitNs int64 `json:"storeWaitNs"` + GroupCommitNs int64 `json:"groupCommitNs"` + CompletionWaitNs int64 `json:"completionWaitNs"` +} + type chunkCutStats struct { + SyncPhases SyncPhaseStats + // Disjoint non-payload intervals within barrier-to-settlement fixed cost. + CandidateNs int64 + WindowSetupNs int64 + PublishPrepareNs int64 + ManifestNs int64 + CommitStateNs int64 + IntentCleanupNs int64 + NonPayloadCopyNs int64 + PayloadNs int64 // disjoint streaming/copy/upload wall intervals // Local validated WAL attempts and local copy duration, including savers. @@ -487,13 +505,27 @@ type chunkLayerStats struct { // the current HEAD when the cut had nothing new (Noop: no CAS). // - FullHash says the cut compared every chunk by hash (no usable bitmap, // or the first cut after a BASE install). +// +// ChunkCandidateTail is advisory pending work sampled after a successful cut. +// Bytes and rate/estimate belong to one sampler observation; Known=false must +// never be interpreted as a zero-cost tail. Admission rechecks at its barrier. +type ChunkCandidateTail struct { + Bytes uint64 `json:"bytes"` + Estimate time.Duration `json:"estimateNs"` + BytesPerSecond float64 `json:"bytesPerSecond"` + RateSamples int `json:"rateSamples"` + SampleAge time.Duration `json:"sampleAgeNs"` + Known bool `json:"known"` +} + type chunkCutResult struct { - Precopy PrecopyReport - H uint64 - Head chunkHead - Noop bool - FullHash bool - Stats chunkCutStats + CandidateTail *ChunkCandidateTail + Precopy PrecopyReport + H uint64 + Head chunkHead + Noop bool + FullHash bool + Stats chunkCutStats } // chunkLayer is what the store owner drives. diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 3898345e91..250a6bfa45 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -752,10 +752,25 @@ func (s *WALStore) readExtentBlock(lba uint32) ([]byte, error) { // becomes crash-survivable only when a Sync that covers its LSN // returns nil. Group commit batches concurrent Sync callers into one // fsync. -func (s *WALStore) Sync() (uint64, error) { +func (s *WALStore) Sync() (uint64, error) { return s.syncWithPhases(nil) } + +// Optional capture telemetry leaves the ordinary Sync contract and lock order +// unchanged. Only the requesting goroutine updates these nested phase costs. +func (s *WALStore) syncWithPhases(phases *SyncPhaseStats) (uint64, error) { + var at time.Time + if phases != nil { + at = time.Now() + } s.lifecycleMu.RLock() + if phases != nil { + phases.LifecycleWaitNs += time.Since(at).Nanoseconds() + at = time.Now() + } defer s.lifecycleMu.RUnlock() s.mu.RLock() + if phases != nil { + phases.StoreWaitNs += time.Since(at).Nanoseconds() + } if s.closed { s.mu.RUnlock() return 0, errors.New("storage: Sync after Close") @@ -778,6 +793,9 @@ func (s *WALStore) Sync() (uint64, error) { s.mu.RUnlock() + if phases != nil { + at = time.Now() + } if s.walSyncCovered() { // Preserve shutdown refusal even when no file I/O is necessary. select { @@ -788,6 +806,9 @@ func (s *WALStore) Sync() (uint64, error) { } else if err := s.syncCache(); err != nil { return 0, fmt.Errorf("storage: group commit fsync: %w", err) } + if phases != nil { + phases.GroupCommitNs += time.Since(at).Nanoseconds() + } s.syncs.Add(1) { @@ -797,7 +818,13 @@ func (s *WALStore) Sync() (uint64, error) { } // The completion is validated against the recovery generation under // the leader role: a recovery since the capture refuses the ack. + if phases != nil { + at = time.Now() + } v.syncMu.Lock() + if phases != nil { + phases.CompletionWaitNs += time.Since(at).Nanoseconds() + } defer v.syncMu.Unlock() if v.recoverGen.Load() != targetGen { return 0, errV3RecoveredMeanwhile @@ -807,7 +834,13 @@ func (s *WALStore) Sync() (uint64, error) { } } + if phases != nil { + at = time.Now() + } s.mu.Lock() + if phases != nil { + phases.StoreWaitNs += time.Since(at).Nanoseconds() + } // A fault latched while this Sync waited (another caller's fsync or // append, or a flusher fsync) refuses it: nothing is acknowledged. if err := s.stickyIOFault(); err != nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9749f085ec..ca99e35d51 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -208,9 +208,13 @@ stateDiagram-v2 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 + Admit --> FrozenForecast: guest already frozen with an explicit origin + FrozenForecast --> Refused: unknown or non-fitting remaining budget + FrozenForecast --> Quiesce: plausible estimate or explicit final override; skip staging + Admit --> Stage: ordinary cut; 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 + Quiesce --> Refused: guest-frozen budget recheck failed; no payload upload + Quiesce --> FinalFreeze: measured admission or explicit frozen final override FinalFreeze --> OpenWindow: admission stays closed through detached settlement Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier OpenWindow --> Copy: release barrier @@ -241,6 +245,8 @@ stateDiagram-v2 | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; 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` | +| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001` | +| Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `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 +487,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 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-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. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. 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. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `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` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); 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/FrozenDetachBudget.tla b/seaweed-block/docs/spec/FrozenDetachBudget.tla new file mode 100644 index 0000000000..e8f83cb8ee --- /dev/null +++ b/seaweed-block/docs/spec/FrozenDetachBudget.tla @@ -0,0 +1,56 @@ +------------------------ MODULE FrozenDetachBudget ------------------------ +\* One externally frozen attempt; physical latency and orchestrator retries +\* are outside this model. Authority is stable during the modeled attempt; +\* mid-cut authority/CAS races remain CutCOW2/publication proof obligations. +EXTENDS Integers, TLC +CONSTANTS OmitElapsed, OmitBarrierGuard, OmitStageGuard, + OmitOverrideRecord, OmitAuthority +Limit == 50 +VARIABLES phase, elapsed, estimate, known, force, authority, admitted, + uploaded, published, overBudget, atElapsed, atEstimate, atKnown +vars == <> +Init == /\ phase = "forecast" /\ elapsed \in {0,30,60} + /\ estimate \in {5,30,60} /\ known \in BOOLEAN + /\ force \in BOOLEAN /\ authority \in BOOLEAN + /\ admitted = FALSE /\ uploaded = FALSE /\ published = FALSE + /\ overBudget = FALSE /\ atElapsed = 0 /\ atEstimate = 0 + /\ atKnown = FALSE +AuthorityOK == authority \/ OmitAuthority +Fits == known /\ estimate > 0 /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit +Eligible == AuthorityOK /\ (force \/ Fits) +Forecast == /\ phase = "forecast" /\ Eligible /\ phase' = "stage" + /\ UNCHANGED <> +RefuseForecast == /\ phase = "forecast" /\ ~Eligible /\ phase' = "refused" + /\ UNCHANGED <> +Barrier == /\ phase = "stage" /\ phase' = "barrier" + /\ elapsed' \in {elapsed,elapsed+20} + /\ estimate' \in {estimate,estimate+30} /\ known' \in BOOLEAN + /\ uploaded' = (uploaded \/ OmitStageGuard) + /\ UNCHANGED <> +Admit == /\ phase = "barrier" /\ (Eligible \/ (OmitBarrierGuard /\ AuthorityOK)) + /\ phase' = "admitted" /\ admitted' = TRUE + /\ atElapsed' = elapsed /\ atEstimate' = estimate /\ atKnown' = known + /\ overBudget' = (force /\ ~OmitOverrideRecord) + /\ UNCHANGED <> +RefuseBarrier == /\ phase = "barrier" /\ ~Eligible /\ ~OmitBarrierGuard + /\ phase' = "refused" + /\ UNCHANGED <> +Upload == /\ phase = "admitted" /\ phase' = "uploaded" /\ uploaded' = TRUE + /\ UNCHANGED <> +Publish == /\ phase = "uploaded" /\ AuthorityOK /\ phase' = "done" + /\ published' = TRUE + /\ UNCHANGED <> +Done == /\ phase \in {"done","refused"} /\ UNCHANGED vars +Next == Forecast \/ RefuseForecast \/ Barrier \/ Admit \/ RefuseBarrier \/ Upload \/ Publish \/ Done +Spec == Init /\ [][Next]_vars +NoUploadBeforeAdmission == uploaded => admitted +BudgetAtAdmission == admitted /\ ~force => atKnown /\ atEstimate > 0 /\ atElapsed + atEstimate <= Limit +OverrideVisible == admitted /\ force => overBudget +AuthorityAtPublication == published => authority +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 0e2834003b..0fb0a0bd28 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -381,3 +381,30 @@ From `docs/spec`, SANY `PlainDetach.tla` exited 0; TLC 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. + + +## Guest-frozen detach admission + +`FrozenDetachBudget.tla` models one externally frozen attempt: a forecast, +skipped staging, changed time/estimate/knowledge at the barrier, explicit +admission, upload and publication. Time units are tenths of a second. It checks +`NoUploadBeforeAdmission`, `BudgetAtAdmission`, `OverrideVisible` and +`AuthorityAtPublication`. Authority is stable within this finite model; mid-cut +fencing and CAS races remain covered by the publication/COW contracts. It does +not prove physical latency or the external controller's two-re-freeze limit. + +Local run 2026-11-21 02:53 UTC, TLC2.19, tools SHA-256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`: + +```sh +java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/FrozenDetachBudget.cfg FrozenDetachBudget +``` + +Positive exited0:667 generated/439 distinct states, queue empty, complete depth6. +The same command with each negative config exited12 at its intended invariant: +`no_elapsed`410/267 depth4; `no_barrier`386/237 depth4; +`staging_upload`151/145 depth3; `hidden_override`367/229 depth4; +`no_authority`951/603 depth6. The first two violate `BudgetAtAdmission`, the +third `NoUploadBeforeAdmission`, the fourth `OverrideVisible`, and the last +`AuthorityAtPublication`. Source tests separately check time/metadata handling, +no-upload refusal, preserved bytes, uncertain outcomes and typed API dispatch. diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg new file mode 100644 index 0000000000..7992b80dde --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg new file mode 100644 index 0000000000..39d18fdaf3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_hidden_override.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = TRUE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg new file mode 100644 index 0000000000..0efc975f94 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_authority.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = TRUE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg new file mode 100644 index 0000000000..668dc2795c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_barrier.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = TRUE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg new file mode 100644 index 0000000000..1c570f2a9c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_no_elapsed.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = TRUE + OmitBarrierGuard = FALSE + OmitStageGuard = FALSE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg new file mode 100644 index 0000000000..61689d8b61 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget_staging_upload.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + OmitElapsed = FALSE + OmitBarrierGuard = FALSE + OmitStageGuard = TRUE + OmitOverrideRecord = FALSE + OmitAuthority = FALSE +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication