diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index 739f8fd76c..4ca4484725 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -78,7 +78,7 @@ type firstAttemptLayer struct { } func (l *firstAttemptLayer) Stats() storage.ChunkLayerStats { - return storage.ChunkLayerStats{DirtyChunks: 1} + return storage.ChunkLayerStats{DirtyChunks: 1, CutsFailed: uint64(l.calls.Load())} } func (l *firstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { select { @@ -89,6 +89,7 @@ func (l *firstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, er case <-l.release: case <-ctx.Done(): } + l.calls.Add(1) return storage.ChunkCutResult{}, context.DeadlineExceeded } func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { @@ -97,8 +98,10 @@ func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { done := make(chan struct{}) layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})} var cleaned atomic.Int32 - p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} - go p.chunkBackground(ctx, cancel, "dirty", layer, done, func() bool { return true }, nil, nil, nil) + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + kick := make(chan struct{}, 1) + kick <- struct{}{} + go p.chunkBackground(ctx, cancel, "dirty", layer, done, func() bool { return true }, nil, nil, kick) defer func() { cancel(); <-done }() time.Sleep(500 * time.Millisecond) synctest.Wait() @@ -111,7 +114,7 @@ func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { t.Fatalf("%d cleaning passes ran before the dirty start's first cut returned", n) } close(layer.release) - time.Sleep(time.Millisecond) + time.Sleep(2 * chunkSchedulePoll) synctest.Wait() if cleaned.Load() == 0 { t.Fatal("cleaning never ran after the first cut attempt") @@ -122,16 +125,21 @@ func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { type yieldingLayer struct { progressLoopLayer progressAt int32 + absent int + err error discarded atomic.Int32 } func (l *yieldingLayer) Stats() storage.ChunkLayerStats { - return storage.ChunkLayerStats{DirtyChunks: 1, StagedChunks: l.staged.Load()} + return storage.ChunkLayerStats{DirtyChunks: 1, StagedChunks: l.staged.Load(), CutsFailed: uint64(l.calls.Load()), AbsentChunks: l.absent} } func (l *yieldingLayer) Cut(context.Context) (storage.ChunkCutResult, error) { if l.calls.Add(1) == l.progressAt { l.staged.Add(1) } + if l.err != nil { + return storage.ChunkCutResult{}, l.err + } return storage.ChunkCutResult{}, context.DeadlineExceeded } func (l *yieldingLayer) DiscardStagedIfUnchanged(staged, seq uint64) bool { @@ -173,26 +181,85 @@ func TestStalledCutYieldsSessionToCleaning(t *testing.T) { } } -func TestCleaningNotDelayedForCleanOrAutomaticCutsDisabled(t *testing.T) { - for _, automatic := range []bool{false, true} { +func TestDirtyStartWithPeriodicCutsOffWaitsForRequestOrInterval(t *testing.T) { + for _, request := range []bool{false, true} { synctest.Test(t, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) - var layer storage.ChunkLayer = &progressLoopLayer{} // clean start - if !automatic { - layer = &yieldingLayer{} - } // dirty, but no automatic cut configured + layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})} var cleaned atomic.Int32 - p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} - if automatic { - p.cfg.ChunkCaptureInterval = time.Hour - } - go p.chunkBackground(ctx, cancel, "ordinary", layer, done, func() bool { return true }, nil, nil, nil) + p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Second, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + kick := make(chan struct{}, 1) + kick <- struct{}{} + go p.chunkBackground(ctx, cancel, "request", layer, done, func() bool { return true }, nil, nil, kick) defer func() { cancel(); <-done }() - time.Sleep(2 * time.Millisecond) synctest.Wait() - if cleaned.Load() == 0 { - t.Fatal("ordinary cleaning schedule was delayed") + if request { + go layer.Cut(ctx) + } + time.Sleep(400 * time.Millisecond) + synctest.Wait() + if cleaned.Load() != 0 { + t.Fatal("cleaning ran before any request cut finished or the interval elapsed") + } + if request { + close(layer.release) + } + time.Sleep(2 * chunkSchedulePoll) + synctest.Wait() + if request && cleaned.Load() != 1 { + t.Fatal("cleaning did not observe the request cut's completion") + } + if !request { + if cleaned.Load() != 0 { + t.Fatal("no-attempt fallback ran before the interval") + } + time.Sleep(500 * time.Millisecond) + synctest.Wait() + if cleaned.Load() != 1 { + t.Fatal("no-attempt fallback did not run after one interval") + } + } + }) + } +} + +func TestUnadmittedAttemptsDoNotDiscardStaging(t *testing.T) { + for _, skip := range []bool{false, true} { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &yieldingLayer{err: storage.ErrChunkCaptureRefused} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: 30 * 24 * time.Hour, ChunkMaintenance: func(context.Context, string) error { return nil }}} + var snapshots *snapshotSlot + wait := 8 * time.Second + if skip { + p.cfg.ChunkCaptureInterval = 0 + layer.absent = 1 + wait = 4 * time.Hour + p.cfg.ChunkScheduledSnapshot = func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + t.Error("restoring snapshot reached store") + return nil + } + snapshots = &snapshotSlot{s: newSnapshotSchedule("skip", 24*time.Hour, time.Now())} + snapshots.s.next = time.Now() + } + go p.chunkBackground(ctx, cancel, "unadmitted", layer, done, func() bool { return true }, snapshots, nil, make(chan struct{}, 1)) + defer func() { cancel(); <-done }() + time.Sleep(wait) + synctest.Wait() + if skip { + snapshots.mu.Lock() + n := snapshots.s.skipped[SnapshotSkipRestoring] + snapshots.mu.Unlock() + if n < 3 { + t.Fatal("did not exercise three snapshot skips") + } + } else if layer.calls.Load() < 3 { + t.Fatal("did not exercise three capture refusals") + } + if layer.discarded.Load() != 0 { + t.Fatal("unadmitted attempts discarded an unfinished session") } }) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 40df112281..ab889f13aa 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -952,23 +952,23 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca // Both background publishers share this in-process stall count. The layer // rechecks its counters under its capture lock before discarding anything. var attemptMu sync.Mutex - var first sync.Once - firstAttempt := make(chan struct{}) - zeroProgress := 0 - if p.cfg.ChunkCaptureInterval <= 0 || layer.Stats().DirtyChunks == 0 { - first.Do(func() { close(firstAttempt) }) + var firstAttempt *maintenanceStart + initial := layer.Stats() + if initial.DirtyChunks > 0 { + firstAttempt = &maintenanceStart{attempts: cutAttempts(initial), deadline: time.Now().Add(p.cfg.ChunkMaintenanceInterval)} } + zeroProgress := 0 attempted := func(before, after storage.ChunkLayerStats, err error) { attemptMu.Lock() defer attemptMu.Unlock() - first.Do(func() { close(firstAttempt) }) if err == nil || after.StagedChunks > before.StagedChunks || after.CutSeq != before.CutSeq { zeroProgress = 0 return } - if errors.Is(err, hostlimit.ErrSlotsHeld) { - return - } // no attempt ran + var skip *SnapshotSkip + if errors.Is(err, hostlimit.ErrSlotsHeld) || errors.Is(err, storage.ErrChunkCaptureRefused) || errors.As(err, &skip) { + return // no attempt against the store ran + } zeroProgress++ if zeroProgress < chunkZeroProgressLimit || p.cfg.ChunkMaintenance == nil { return @@ -1051,7 +1051,22 @@ func (p *DurableProvider) KickMaintenance(volumeID string) bool { return true } -func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt <-chan struct{}) { +// maintenanceStart bounds only the first cleaning of an initially dirty layer. +// Completion counters include periodic, scheduled, and operator-request cuts. +type maintenanceStart struct { + attempts uint64 + deadline time.Time +} + +func cutAttempts(st storage.ChunkLayerStats) uint64 { + n := st.CutsOK + st.CutsNoop + st.CutsFailed + for _, refused := range st.CutsRefused { + n += refused + } + return n +} + +func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt *maintenanceStart) { interval := p.cfg.ChunkMaintenanceInterval due := time.Now().Add(interval) if p.cfg.ChunkStagger { @@ -1075,10 +1090,16 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } } if firstAttempt != nil { - select { - case <-ctx.Done(): - return - case <-firstAttempt: + // The engine counters cover request cuts too, not just these workers. + // One interval bounds this scheduling wait; HEAD still decides safety. + for cutAttempts(layer.Stats()) == firstAttempt.attempts && time.Now().Before(firstAttempt.deadline) && !layer.Fenced() && current() { + pause := time.NewTimer(min(chunkSchedulePoll, time.Until(firstAttempt.deadline))) + select { + case <-ctx.Done(): + pause.Stop() + return + case <-pause.C: + } } firstAttempt = nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9d66a48f77..957da0af29 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -882,7 +882,7 @@ Notes: | `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` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | 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-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning follows cut attempt 1; K=3 stalled background attempts yield reusable staging, never a pending commit or an active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | +| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for any cut attempt or one maintenance interval. K=3 admitted stalled attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | 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 (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) 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-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 1dcab4a7db..c7eb2c2c45 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -706,11 +706,17 @@ when a failed attempt finished staging new chunks. An attempt with no new stagin keeps the ordinary doubling backoff. The per-attempt deadline is unchanged; retry progress is in-process, and a restart recovers objects by their content names. -When automatic cuts are enabled and the layer starts dirty, its first cleaning -pass waits for the first cut attempt to return. Clean starts and disabled automatic -cuts keep the ordinary cleaning schedule. After three consecutive failed background +When the layer starts dirty, its first cleaning pass waits for the first cut +attempt of any kind (periodic, scheduled or requested) to return, or for one +maintenance interval from startup, whichever comes first. This also applies when +periodic cuts are disabled; it does not enable them. Clean starts are unchanged. After three consecutive failed background attempts without staging progress, the holder drops its reusable staging session -and kicks cleaning. Progress or a successful cut resets that count. A running cut, +and kicks cleaning. Capture refusals, restoring-snapshot skips and host-slot refusals do not count: +no store attempt ran. Progress or a successful cut resets the count. K counts +attempts, not elapsed time: the first two zero-progress waits are 1 and 2 seconds +for automatic cuts, or 1 and 2 minutes for scheduled snapshots, plus the time spent +in each attempt. Discard permits cleaning to remove unreferenced uploads; the next +cut reuses only content-named chunks that cleaning left behind. A running cut, a newer completed cut or staging counter, and an unresolved commit prevent that discard. The kernel's session exclusion and conditional removal remain authoritative.