fix: retain partial cut work and failed preparation timings

This commit is contained in:
pingqiu committed 2026-11-29 11:38:47 -08:00
1 parent 9c87c66b5d
commit c60d320f48
8 files changed
+242 -5

No files matched your search

@@ -347,6 +347,7 @@ func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
// under their own bound, each completed segment reported as progress, and
// no bound on the read as a whole (the segment count grows with the volume).
func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[uint64]layout.Ref, error) {
defer storage.MeasureCutWork(ctx, storage.CutManifestRead)()
if af, ok := storage.AttachFetchFrom(ctx); ok {
m, err := boundedManifest(ctx, l.r, rn, af)
if err != nil {
@@ -674,6 +675,7 @@ func (l *LayoutRemote) manifests(ctx context.Context, h layout.Head, next storag
// writeRootLocked writes next's segments and root in this session, so the
// commit finds them prepared.
func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) error {
defer storage.MeasureCutWork(ctx, storage.CutSegmentWrites)()
root, segs, err := layout.Build(next)
if err != nil {
return err
@@ -0,0 +1,118 @@
package durable
import (
"bytes"
"context"
"errors"
"log"
"path"
"regexp"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
type cutWorkFiler struct {
*chunkstore.MemFiler
active, prepared atomic.Bool
mode string
}
func (f *cutWorkFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
if f.active.Load() {
p := path.Join(dir, name)
if strings.Contains(p, "/root/") || strings.Contains(p, "/seg/") {
time.Sleep(20 * time.Millisecond)
if f.mode == "manifest" {
return nil, errors.New("manifest read interrupted")
}
}
if f.prepared.Load() && strings.Contains(p, "/pool/") {
time.Sleep(20 * time.Millisecond)
return nil, errors.New("commit lookup interrupted")
}
}
return f.MemFiler.LookupEntry(ctx, dir, name)
}
func (f *cutWorkFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error {
if f.active.Load() && strings.Contains(path.Join(dir, e.Name), "/seg/") {
time.Sleep(20 * time.Millisecond)
f.prepared.Store(true)
if f.mode == "segments" {
return errors.New("segment write interrupted")
}
}
return f.MemFiler.CreateEntry(ctx, dir, e, excl)
}
func TestFailedLayoutCutLogsRepeatedPreparationTime(t *testing.T) {
for _, mode := range []string{"manifest", "segments", "commit"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
f := &cutWorkFiler{MemFiler: chunkstore.NewMemFiler(), mode: mode}
b := &kzLayoutBlobs{b: map[string][]byte{}}
cat, err := chunkstore.NewBCatalog(f, b, "/cut-work")
if err != nil {
t.Fatal(err)
}
id, err := layout.NewVolumeID()
if err != nil {
t.Fatal(err)
}
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 256 * 4096, BlockSize: 4096, ChunkBytes: 16 * 4096}); err != nil {
t.Fatal(err)
}
p := kzProvider(t, t.TempDir(), &kzLayout{cat: cat, ref: ref, blobs: b})
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if _, err := p.Backend("v1").Write(ctx, 0, bytes.Repeat([]byte{0x11}, 4096)); err != nil {
t.Fatal(err)
}
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if _, err := p.Backend("v1").Write(ctx, 0, bytes.Repeat([]byte{0x42}, 4096)); err != nil {
t.Fatal(err)
}
old := log.Writer()
var out bytes.Buffer
log.SetOutput(&out)
defer log.SetOutput(old)
f.active.Store(true)
if _, err := p.CaptureVolume(ctx, "v1"); err == nil || !strings.Contains(err.Error(), "interrupted") {
t.Fatalf("cut error=%v", err)
}
line := out.String()
for _, field := range []string{"manifest_read_ms", "segment_writes_ms", "commit_check_ms"} {
match := regexp.MustCompile(field + `=([0-9.]+)`).FindStringSubmatch(line)
if len(match) != 2 {
t.Fatalf("missing %s: %s", field, line)
}
ms, err := strconv.ParseFloat(match[1], 64)
if field == "segment_writes_ms" && mode == "manifest" {
if err != nil || ms != 0 {
t.Fatalf("unstarted span %s=%v: %s", field, ms, line)
}
continue
}
if err != nil || ms < 20 {
t.Fatalf("%s=%v error=%v: %s", field, ms, err, line)
}
}
if !strings.Contains(line, "compared=1") || !strings.Contains(line, "uploaded=1") {
t.Fatalf("failed check lost work: %s", line)
}
})
}
}
@@ -172,3 +172,41 @@ func TestAbortedCutLogsEachCompletedCompareAndUpload(t *testing.T) {
}
}
}
type cancelCutAfterPut struct {
*fakeChunkRemote
cancel context.CancelFunc
done int
}
func (r *cancelCutAfterPut) Put(ctx context.Context, key string, data []byte) error {
err := r.fakeChunkRemote.Put(ctx, key, data)
if err == nil {
r.done++
if r.done == 3 {
r.cancel()
}
}
return err
}
func TestAbortedStagingLogsCompletedWork(t *testing.T) {
old, flags := log.Writer(), log.Flags()
t.Cleanup(func() { _ = logging.Configure("info"); log.SetOutput(old); log.SetFlags(flags) })
_, remote, layer, _ := precopyLayer(t, 1, 5)
layer.cfg.UploadConcurrency = 1
ctx, cancel := context.WithCancel(ctTimeout(t))
defer cancel()
layer.remote = &cancelCutAfterPut{fakeChunkRemote: remote, cancel: cancel}
var out bytes.Buffer
log.SetOutput(&out)
_ = logging.Configure("info")
if _, err := layer.Cut(ctx); err == nil {
t.Fatal("aborted staging published")
}
line := out.String()
for _, field := range []string{"level=INFO", "noop=false", "candidates=5", "compared=3", "uploaded=3", "staged=3"} {
if !strings.Contains(line, field) {
t.Fatalf("lost staged work %s: %s", field, line)
}
}
}
@@ -0,0 +1,40 @@
package storage
import (
"context"
"sync/atomic"
"time"
)
// CutWorkSpan identifies diagnostic work that may be repeated by a cut retry.
// Spans include time spent before a failure; they never decide a cut outcome.
type CutWorkSpan uint8
const (
CutManifestRead CutWorkSpan = iota
CutSegmentWrites
CutCommitCheck
cutWorkSpanCount
)
type cutAttemptObservation struct {
compared, staged, uploaded atomic.Int64
spans [cutWorkSpanCount]atomic.Int64
}
type cutObservationKey struct{}
func cutObservation(ctx context.Context) *cutAttemptObservation {
w, _ := ctx.Value(cutObservationKey{}).(*cutAttemptObservation)
return w
}
// MeasureCutWork records elapsed work on return, including errors and
// cancellation. Outside a cut attempt it is a no-op. Adapter spans may nest.
func MeasureCutWork(ctx context.Context, span CutWorkSpan) func() {
w := cutObservation(ctx)
if w == nil || span >= cutWorkSpanCount {
return func() {}
}
start := time.Now()
return func() { w.spans[span].Add(time.Since(start).Nanoseconds()) }
}
@@ -58,6 +58,10 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
if err != nil {
return err
}
work := cutObservation(ctx)
if work != nil {
work.compared.Add(1)
}
ref, had := head.Chunks[c.idx]
if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) {
c.key, c.size = l.keyFor(c.idx, c.sum, keys[i]), len(c.data)
@@ -69,6 +73,14 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
}
}
if work != nil {
if c.key != "" {
work.uploaded.Add(1)
}
if staging {
work.staged.Add(1)
}
}
l.rememberPayload(c, head.Gen, staging)
if !staging {
l.markEqualNow(c, head)
+13 -4
View File
@@ -785,6 +785,8 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
start := time.Now()
recoveredPublication := l.pending != nil
var st chunkCutStats
work := &cutAttemptObservation{}
ctx = context.WithValue(ctx, cutObservationKey{}, work)
persistCapturedMap := func(versions map[uint64]uint64) {
l.cutPhase("settle")
start := time.Now()
@@ -836,11 +838,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
// HEAD exchange); report observations, never add them into a new total.
// Pending recovery can write HEAD even when normal publication is a no-op.
emit := func(format string, args ...any) { log.Printf("level=INFO "+format, args...) }
if err == nil && res.Noop && !recoveredPublication && st.CandidateChunks == 0 && st.UploadedChunks == 0 {
if err == nil && res.Noop && !recoveredPublication && st.CandidateChunks == 0 && st.UploadedChunks == 0 && work.compared.Load() == 0 && work.staged.Load() == 0 && work.uploaded.Load() == 0 {
emit = logging.Debugf
}
emit("storage: cut phases phase_scope=publication volume=%q holder=%q epoch=%d h=%d noop=%t candidates=%d uploaded=%d candidates_ms=%.3f compare_prepare_ms=%.3f upload_ms=%.3f commit_ms=%.3f head_write_ms=%.3f settle_ms=%.3f total_ms=%.3f err=%q",
l.cfg.VolumeID, l.cfg.Holder, l.cfg.Epoch, res.H, res.Noop, st.CandidateChunks, st.UploadedChunks,
emit("storage: cut phases phase_scope=publication work_scope=attempt volume=%q holder=%q epoch=%d h=%d noop=%t candidates=%d compared=%d staged=%d uploaded=%d manifest_read_ms=%.3f segment_writes_ms=%.3f commit_check_ms=%.3f candidates_ms=%.3f compare_prepare_ms=%.3f upload_ms=%.3f commit_ms=%.3f head_write_ms=%.3f settle_ms=%.3f total_ms=%.3f err=%q",
l.cfg.VolumeID, l.cfg.Holder, l.cfg.Epoch, res.H, res.Noop, st.CandidateChunks, work.compared.Load(), work.staged.Load(), work.uploaded.Load(),
float64(work.spans[CutManifestRead].Load())/1e6, float64(work.spans[CutSegmentWrites].Load())/1e6, float64(work.spans[CutCommitCheck].Load())/1e6,
float64(st.CandidateNs)/1e6, float64(st.PublishPrepareNs)/1e6, float64(st.UploadNs)/1e6,
float64(st.CASNs)/1e6, float64(st.CASWriteNs)/1e6,
float64(st.HeadReadbackNs+st.CommitStateNs+st.MapPersistNs)/1e6, float64(st.TotalNs)/1e6, errorText)
@@ -1155,7 +1158,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
put := l.beginPutRound(len(uploads))
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
u := uploads[i]
return l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) })
err := l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) })
if err == nil {
work.uploaded.Add(1)
}
return err
}); err != nil {
l.requeueCut(all)
return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
@@ -1461,6 +1468,7 @@ func sameProposal(cur, next chunkHead) bool {
// passes. A precondition or fence goes on to the CAS, which answers it from
// HEAD (before any lookup) and resolves it as without the check.
func (l *chunkLayerImpl) checkCommitFirst(ctx context.Context, expected chunkHeadVersion, next chunkHead) error {
defer MeasureCutWork(ctx, CutCommitCheck)()
c, ok := l.remote.(chunkCommitChecker)
if !ok {
return nil
@@ -1729,6 +1737,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap
head := copyHead(l.head)
l.stMu.Unlock()
st.StageRounds++
st.CandidateChunks = max(st.CandidateChunks, len(batch))
roundChunks, err := l.stagePayloadRound(ctx, batch, vers, head, st)
if err != nil {
return nil, err
+1
View File
@@ -910,6 +910,7 @@ Notes:
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
| `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE |
| `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE |
| `INV-CUT-ATTEMPT-OBSERVED-001` | A failed cut logs completed compares, staging results and uploads instead of discarding partial batch work. Manifest reads, root/segment preparation and commit checks retain elapsed time on failure. These observations never authorize publication. | M5 diagnostics (no transition) | `core/storage/chunk_cut_observation.go`; `chunk_cut_payload.go`; `chunk_layer.go`; `core/frontend/chunkstore/layout_remote.go` | `TestAbortedCutLogsEachCompletedCompareAndUpload`; `TestAbortedStagingLogsCompletedWork`; `TestFailedLayoutCutLogsRepeatedPreparationTime` | — | ACTIVE |
| `INV-CUT-READ-LOGICAL-001` | Every cut read of a chunk (COW copy, COW save and pre-copy staging) resolves each block through the dirty map first, validates the whole WAL record it read and re-resolves on a mismatch, and reads the extent only for a block with no dirty entry; no cut path reads the extent region directly. | M5 Stage / Copy | `core/storage/chunk_cut_cow.go` `readCOWChunk`, `readLocalBlock`; `core/storage/chunk_layer.go` `readChunk`; `core/storage/walstore_v3.go` `readDirtyV3Into` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`); `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
| `INV-CUT-HOOK-BEFORE-APPEND` | The COW hook owns/saves the at-H image before a read-visible WAL mutation, under shared capture admission. | M1 Write / M5 Save | `walstore.go` `Write`, `WriteBatch`; `chunk_cut_cow.go` `beforeChunkMutation` | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 SaveStart before Write | ACTIVE |
| `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE |
+18 -1
View File
@@ -49,7 +49,24 @@ this path, then finish as a no-op: that recovery cost appears in `total_ms`,
not necessarily in `commit_ms` or `head_write_ms`. `noop` does not mean the
invocation made no remote call.
Spans are completion-dependent and rounded to three decimal places in
The same line carries attempt work even if it aborts: `candidates` is the
planned set at the last staging/barrier step reached; `compared` counts completed
chunk reads/hashes compared against HEAD, including repeated staging work;
`staged` counts completed reusable staging results; `uploaded` counts payload
PUTs completed or resolved by exact-byte readback in this attempt. A failed batch
retains the work its workers finished. These are observations, not persistence
proofs or runner verdict inputs; `noop=true` only says no new image was published.
`work_scope=attempt` applies to the new elapsed work spans: `manifest_read_ms`
measures root/segment manifest reads; `segment_writes_ms` measures building and
preparing segments plus their root (including reuse/tag checks); `commit_check_ms`
measures the commit-check call, including its manifest/root preparation. They
record elapsed time on errors as well as success, add repeated calls within the
attempt, and can nest or overlap. They include pending-recovery work when it
reaches those paths. An unstarted work span is zero; millisecond values are
rounded to three decimals. Do not sum these spans.
The older publication spans are completion-dependent and rounded to three decimal places in
milliseconds: zero can mean
unfinished or unmeasured work, or rounding, rather than no work. A failed
session begin or upload can consume time without its completion span being