Merge pull request #529 from seaweedfs/fix/cut-stats-staging

fix: a cut's payload time counts staging; the layer counts staged chunks
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-23 18:39:05 -08:00
commit 7892b305b7
8 files changed
+137 -15

No files matched your search

+1 -1
View File
@@ -621,7 +621,7 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec
}
}
order := hotChunkKeys(indices, recent)
out, intents, err := l.streamCutPayloads(ctx, order, head, func(ctx context.Context, idx uint64) (capturedChunk, error) {
out, intents, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) {
c, ok, err := l.copyCOWEntry(w, idx)
if err != nil {
return capturedChunk{}, err
@@ -41,7 +41,10 @@ func hotChunkKeys(indices map[uint64]bool, recent map[uint64]uint64) []uint64 {
// image through PUT/retry, then reads its next candidate independently of slow
// workers. One durable intent covers all candidate keys before the first PUT;
// unused keys are harmless and retain no payload memory.
func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) {
//
// staging says the batch is a staging round (before the barrier): each chunk
// it finishes is counted in Stats.StagedChunks as it finishes.
func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, staging bool, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) {
out := make([]capturedChunk, len(batch))
keys := make([]string, len(batch))
for i, idx := range batch {
@@ -74,7 +77,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
}
}
l.rememberPayload(c, head.Gen)
l.rememberPayload(c, head.Gen, staging)
c.data = nil
out[i] = c
return nil
@@ -86,7 +89,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
}
func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) {
out, intents, err := l.streamCutPayloads(ctx, batch, head, func(ctx context.Context, idx uint64) (capturedChunk, error) {
out, intents, err := l.streamCutPayloads(ctx, batch, head, true, func(ctx context.Context, idx uint64) (capturedChunk, error) {
data, err := l.readChunk(idx)
if err != nil {
return capturedChunk{}, err
@@ -114,11 +117,16 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64,
// until this version is superseded or a confirmed HEAD makes it reachable.
// This cache belongs to one layer/owner lifetime. Generation equality is not
// a reuse proof across reopen or takeover; those require content-hash matching.
func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64) {
// A staged chunk is counted in Stats.StagedChunks here, when it is
// remembered, so an interrupted round counts what it finished.
func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64, staged bool) {
c.data = nil
l.stMu.Lock()
defer l.stMu.Unlock()
if staged {
l.stats.StagedChunks++
}
if l.reusable == nil {
l.reusable = make(map[uint64]stagedChunk)
}
+1 -3
View File
@@ -778,9 +778,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if !guestFrozen {
staged, intents, err = l.stage(ctx, &st, spill.bytes)
}
if st.UploadedBytes > 0 {
st.PayloadNs += time.Since(stageStart).Nanoseconds()
}
st.PayloadNs += time.Since(stageStart).Nanoseconds()
if err != nil {
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, err
@@ -202,7 +202,7 @@ func TestCutPayloadReadsOverlapEarlierUploadsWithinBudget(t *testing.T) {
t.Cleanup(func() { cancel(); free(); cowWaitSignal(t, done, "overlap cleanup") })
go func() {
defer close(done)
_, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, func(_ context.Context, idx uint64) (capturedChunk, error) {
_, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) {
if idx == 2 {
close(readThird)
}
@@ -233,7 +233,7 @@ func TestCutPayloadIntentCountLargeCandidateSets(t *testing.T) {
for i := range batch {
batch[i] = uint64(i)
}
_, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, func(_ context.Context, idx uint64) (capturedChunk, error) {
_, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) {
data := makeBlock(ctBlockSize, byte(idx%255+1))
return capturedChunk{idx: idx, data: data, sum: sha256.Sum256(data)}, nil
})
+13 -3
View File
@@ -489,8 +489,17 @@ type chunkCutStats struct {
// results whose outcome stayed unresolved after the HEAD re-read.
// - PendingUnresolved: an unresolved proposal is held now.
// - DirtyChunks is the number of chunks dirty since the last HEAD now
// (the C11 bitmap popcount); the cut scheduler's threshold reads it.
// Chunks still awaiting reconciliation are not counted.
// (the C11 bitmap popcount): the next cut's candidates, not its
// progress (it does not fall while a cut runs or across failed
// attempts); the cut scheduler's threshold reads it. Chunks still
// awaiting reconciliation are not counted.
// - StagedChunks counts the chunks staging finished (read, hashed,
// uploaded when not zero, and remembered for reuse) in every cut
// attempt of this layer: a failed attempt and an interrupted round
// count what they finished. It only grows: a chunk staged again (after
// a guest write re-dirtied it, or in a later cut) counts again; it is
// in-process (a restart starts at 0). The progress a cut retried after
// its deadline has made.
// - Reconciling: the dirty set is being reconciled against HEAD; no cut
// publishes until it is done. ReconcileDone of ReconcileTotal chunks
// are compared.
@@ -508,7 +517,8 @@ type chunkLayerStats struct {
CASConflicts uint64 // HEAD CAS precondition failures
CASUnknown uint64 // HEAD CAS results still unresolved after the re-read
PendingUnresolved bool // an unresolved HEAD proposal is held now
DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation)
DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress
StagedChunks uint64 // chunks staged by every cut attempt, failed ones included (in-process)
Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile
ReconcileDone int // chunks compared so far
ReconcileTotal int // chunks to compare
@@ -0,0 +1,104 @@
package storage
import (
"context"
"errors"
"testing"
"time"
)
// zeroStagedLayer is a layer past its zero baseline cut with n chunks
// rewritten with zeros: candidates that staging reads and hashes but never
// uploads. The spill cap of two chunks makes the cut stage them.
func zeroStagedLayer(t *testing.T, n int) (*fakeChunkRemote, *chunkLayerImpl) {
t.Helper()
s, f, l, w := precopyLayer(t, 1, 0)
l.cfg.COWSpillLimit = 2 * ctChunkBytes
for c := 0; c < n; c++ {
w.write(t, s, uint32(c*ctChunkBlocks+2), 0)
}
return f, l
}
// The payload time of a cut counts its staging rounds even when they
// upload nothing (every staged chunk was zero), so a first cut that spent
// its time reading and hashing shows it.
func TestChunkStage_PayloadTimeCountsStagingWithoutUploads(t *testing.T) {
_, l := zeroStagedLayer(t, 6)
// Staging takes measurable time on any clock resolution.
l.testAfterStageHook = func(int) { time.Sleep(20 * time.Millisecond) }
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
st := r.Stats
if st.StageRounds == 0 || st.StagedChunks == 0 {
t.Fatalf("cut stats %+v; want staging rounds", st)
}
if st.UploadedBytes != 0 {
t.Fatalf("uploaded %d bytes; want none (every staged chunk is zero)", st.UploadedBytes)
}
if st.PayloadNs < int64(20*time.Millisecond) {
t.Fatalf("payload time %d ns with %d chunks staged; want the staging time", st.PayloadNs, st.StagedChunks)
}
}
// The layer counts every chunk staged by any cut attempt, a failed one
// included, so a first cut retried after its deadline shows the progress
// its earlier attempts made; the last successful cut's stats do not move.
// An attempt that staged all 6 candidates counts exactly 6.
func TestChunkStage_StagedChunksCountsFailedAttempts(t *testing.T) {
_, l := zeroStagedLayer(t, 6)
before := l.Stats()
ctx, cancel := context.WithCancel(context.Background())
l.testBeforeBarrierLockHook = cancel
if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) {
t.Fatalf("cut: %v; want it cancelled before the barrier", err)
}
l.testBeforeBarrierLockHook = nil
after := l.Stats()
if got := after.StagedChunks - before.StagedChunks; got != 6 {
t.Fatalf("a failed attempt that staged all 6 candidates counted %d", got)
}
if after.CutSeq != before.CutSeq || after.LastCut.StagedChunks != before.LastCut.StagedChunks {
t.Fatal("a failed attempt changed the last successful cut")
}
// A retry stages nothing again (the chunks are reused) and counts nothing.
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if got := l.Stats().StagedChunks - after.StagedChunks; got != 0 {
t.Fatalf("the retry counted %d staged chunks; want 0 (every chunk reused)", got)
}
}
// A round that fails partway counts the chunks it finished, each remembered
// for reuse, and not the ones it did not: one upload worker stages the five
// zero chunks (the most recent writes go first), then the non-zero chunk's
// upload fails at its intent.
func TestChunkStage_StagedChunksCountsAnInterruptedRound(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 0)
l.cfg.COWSpillLimit = 2 * ctChunkBytes
l.cfg.UploadConcurrency = 1
w.write(t, s, uint32(0*ctChunkBlocks+2), 0x5a) // oldest write: staged last
for c := 1; c <= 5; c++ {
w.write(t, s, uint32(c*ctChunkBlocks+2), 0)
}
f.mu.Lock()
f.failPutIntent = errors.New("intent refused")
f.mu.Unlock()
before := l.Stats().StagedChunks
l.stMu.Lock()
reusedBefore := len(l.reusable)
l.stMu.Unlock()
if _, err := l.Cut(ctTimeout(t)); err == nil {
t.Fatal("cut succeeded; want the staging round to fail at the intent")
}
l.stMu.Lock()
remembered := len(l.reusable) - reusedBefore
l.stMu.Unlock()
got := l.Stats().StagedChunks - before
if got != 5 || uint64(remembered) != got {
t.Fatalf("interrupted round counted %d staged chunks, remembered %d; want 5 and 5", got, remembered)
}
}
+2 -1
View File
@@ -497,7 +497,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
319 rows: 248 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 new.
320 rows: 249 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 303 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -820,6 +820,7 @@ Notes:
| `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 |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE |
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `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 |
+2 -1
View File
@@ -227,7 +227,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures |
| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read |
| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now |
| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation) |
| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation): candidates, not progress |
| `Volumes[].Chunk.Stats.StagedChunks` | uint64 | chunks staged by every cut attempt, failed ones included (in-process) |
| `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile |
| `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far |
| `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare |