fix(storage): budget detach from the guest freeze origin

This commit is contained in:
pingqiu committed 2026-11-20 18:47:48 -08:00
1 parent cc1747aa3a
commit 116c1688bc
11 files changed
+667 -56

No files matched your search

@@ -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,18 @@ 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_store_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_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))
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)
elapsed := time.Since(start)
if !guestFrozen {
elapsed += r.Precopy.BarrierBeforeFreeze
}
r.Precopy.Finish(elapsed, 0, false)
}
return r, h.storage.NextLSN() - 1, nil
}
@@ -1036,7 +1075,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,7 +1088,11 @@ 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
}
@@ -0,0 +1,50 @@
package durable_test
import (
"context"
"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)
}
if headBlock(t, mem, 1)[0] != 0x77 || headBlock(t, mem, 2)[0] != 0x88 {
t.Fatal("final detached point lost writes")
}
}
+64 -12
View File
@@ -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,14 @@ type ChunkCutResponse struct {
// mirrors storage.ChunkCutStats field for field (a test keeps the two in
// step); every duration is in nanoseconds.
type ChunkCutStatsBody struct {
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 +97,14 @@ type ChunkCutStatsBody struct {
func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
return ChunkCutStatsBody{
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 +303,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 +519,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 +541,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 +582,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 +601,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 +667,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)
@@ -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)
}
}
@@ -0,0 +1,47 @@
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)
}
}
@@ -0,0 +1,68 @@
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)
}
}
@@ -0,0 +1,58 @@
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 {
r.GuestFrozen = true
r.GuestFreezeElapsed = time.Since(opts.StartedAt)
r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed)
known := r.Reason != "samples_unknown" && r.Estimate > 0
if !known || r.Estimate > r.RemainingFreeze {
r.Reason = "frozen_tail_too_large"
if !opts.AllowOverBudget {
return false
}
r.Reason = "over_budget"
r.OverBudget = true
} 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)
}
@@ -0,0 +1,88 @@
package storage
import (
"bytes"
"context"
"errors"
"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 })
if err != nil || r2.Head.Gen != r.Head.Gen {
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)
}
}
}
+58 -23
View File
@@ -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)
@@ -669,6 +669,16 @@ 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() {
@@ -679,6 +689,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.candidateTail()
}
if errors.Is(err, errChunkLayerFenced) {
l.stMu.Lock()
@@ -690,7 +701,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 +753,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 +793,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.
@@ -802,9 +818,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 +868,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 +891,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 +901,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 +931,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 +945,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 +995,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 +1021,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 +1044,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 +1055,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 +1086,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 +1126,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
+91 -10
View File
@@ -25,6 +25,14 @@ const (
// PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample.
type PrecopyFixedParts struct {
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 +43,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{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 +56,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 +78,13 @@ type PrecopyAttempt struct {
// PrecopyReport records admission estimates, not a worst-case latency proof.
type PrecopyReport struct {
// 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 +120,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
@@ -136,6 +156,8 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
return ChunkCutResult{}, err
}
defer l.capMu.Unlock()
guestFreeze, externallyFrozen := FrozenDetachFromContext(ctx)
if err := ctx.Err(); err != nil {
return ChunkCutResult{}, err
}
@@ -143,6 +165,19 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
r.Precopy.Frozen = 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 !r.admitFrozen(guestFreeze) {
return ChunkCutResult{Precopy: r}, frozenRefusal(r)
}
}
ctx, countCAS := WithChunkCASAccounting(ctx)
var report PrecopyReport
var frozenAt time.Time
@@ -171,7 +206,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 +218,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 +233,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 = report.admitFrozen(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 +255,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 +276,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,6 +292,9 @@ 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
@@ -257,7 +309,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 +426,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 +482,28 @@ 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 {
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()
bytes := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks
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}
}
+29 -6
View File
@@ -397,6 +397,15 @@ type chunkLayerConfig struct {
// chunkCutStats describes one cut. The periodic-cut work fills it; a zero
// value means "not measured".
type chunkCutStats struct {
// 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 +496,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.