From 3eda912af857a962e86e70ae889ff5f520a76add Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 02:41:45 -0800 Subject: [PATCH] fix: scope upload pacing and degraded cut admission honestly --- seaweed-block/cmd/blockvolume/host_limit.go | 4 +-- .../core/frontend/durable/host_limit_test.go | 35 +++++++++++++++++++ .../core/frontend/durable/provider_chunk.go | 2 +- .../core/host/volume/chunk_control.go | 4 ++- seaweed-block/core/hostlimit/limiter.go | 25 ++++++++++--- seaweed-block/core/hostlimit/limiter_test.go | 6 ++-- .../docs/design/agent-workspace-design.md | 2 +- seaweed-block/docs/design/invariants.md | 4 +-- seaweed-block/docs/spec/HostBudget.tla | 2 ++ 9 files changed, 70 insertions(+), 14 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go index 188ceeafcc..7eba88af39 100644 --- a/seaweed-block/cmd/blockvolume/host_limit.go +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -14,7 +14,7 @@ func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { fs.IntVar(&c.IdleSlots, "host-limit-idle-slots", c.IdleSlots, "host idle-work slots") fs.Int64Var(&c.PayloadBytes, "host-limit-payload-bytes", c.PayloadBytes, "maximum cut payload per slot") fs.Int64Var(&c.COWBytes, "host-limit-cow-bytes", c.COWBytes, "maximum saved COW bytes per slot") - fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "aggregate background upload rate across cut slots") - fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "static-share divisor when the pool is unavailable; shared cap is not enforced") + fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap") + fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "urgent-fallback per-process divisor; coordinated host cap is not enforced") fs.DurationVar(&c.MaxHold, "host-limit-max-hold", c.MaxHold, "cut lease timeout; expiration aborts but waits for admitted I/O before release") } diff --git a/seaweed-block/core/frontend/durable/host_limit_test.go b/seaweed-block/core/frontend/durable/host_limit_test.go index 7ef1670004..e4b38a628b 100644 --- a/seaweed-block/core/frontend/durable/host_limit_test.go +++ b/seaweed-block/core/frontend/durable/host_limit_test.go @@ -58,3 +58,38 @@ func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) { t.Fatal("refused cut published") } } + +func TestHostUnusablePoolExplicitDurabilityUsesUrgent(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir() + "/missing") + lim, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer lim.Close() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + s := openRecovered(t, p) + if _, err = s.Write(0, block(0x6a)); err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if _, err = p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("background cut bypassed missing pool: %v", err) + } + if err = p.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { + t.Fatalf("explicit durability was not urgent: %v", err) + } + head, err := remote.GetHead(context.Background()) + if err != nil || head.RemoteLSN < 1 { + t.Fatalf("explicit durability did not publish: %+v %v", head, err) + } + if st := lim.Snapshot().(hostlimit.Stats); st.Fallback != 1 || st.SkippedByClass[hostlimit.Normal] != 1 { + t.Fatalf("wrong durability/periodic policy: %+v", st) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index d0963b1471..040dc4bbe5 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -810,7 +810,7 @@ func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID if err != nil { return err } - return layer.MakeRemoteDurable(ctx, lsn) + return layer.MakeRemoteDurable(hostlimit.WithClass(ctx, hostlimit.Urgent), lsn) } // chunkFenced refuses a volume whose layer attached fenced: HEAD belongs to diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 43db86794e..c762f4d5f1 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -19,6 +19,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -546,7 +547,8 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } - r, err := c.p.CutVolume(ctx, volumeID, 0) + // A named seal is urgent even without a minimum LSN. + r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) if err != nil { return chunkstore.SnapshotInfo{}, err } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index dd64160fc8..ebbc76fe95 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -1,5 +1,6 @@ // Package hostlimit coordinates background cuts across cooperating host processes. -// Guest I/O never acquires a slot. A missing pool degrades to static rate sharing. +// Guest I/O never acquires a slot. An unavailable pool skips background work; +// urgent seals may use explicitly uncoordinated per-process limits. package hostlimit import ( @@ -257,7 +258,19 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) ( } return 0, err } - fallback := err != nil // A is deliberately degraded: no shared memory/spill cap. + if err != nil && c != Urgent { + l.mu.Lock() + warn := l.stats.LastPoolError != err.Error() + l.stats.LastPoolError = err.Error() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + if warn { + log.Printf("hostlimit: shared pool unavailable; background work skipped: %v", err) + } + return 0, errors.Join(ErrBusy, err) + } + fallback := err != nil // Urgent fallback has no coordinated host resource/rate bound. l.mu.Lock() if l.closed || ctx.Err() != nil || len(l.live) >= l.cfg.NormalSlots+l.cfg.UrgentSlots+l.cfg.FillSlots+l.cfg.IdleSlots { l.stats.Skipped++ @@ -394,8 +407,12 @@ func (l *Limiter) releaseLoop() { func (l *Limiter) Snapshot() any { l.mu.Lock(); defer l.mu.Unlock(); return l.stats } // WaitUpload paces background payload PUTs, including parallel uploader workers. -// Static shares trade utilization for a conservative aggregate rate. It never -// paces local WAL flushing, COW reads, or demand hydration. +// One process spaces reservations by the previous payload/rate. Its first +// payload is immediate; debt survives its leases but resets on a new process. +// For a constant share r and maximum payload B, one process reserves at most +// r*T+B bytes over T. Fresh processes each add a new B; neither process/slot +// churn nor uncoordinated fallback has a fixed host-rate bound. Wire overhead +// is excluded. Local WAL flushing, COW reads and demand hydration bypass it. func (l *Limiter) WaitUpload(ctx context.Context, n int) error { if n < 0 { return ErrBusy diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go index da572bdf1a..255f575a3b 100644 --- a/seaweed-block/core/hostlimit/limiter_test.go +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -170,7 +170,7 @@ func TestFallbackAndConfigMismatch(t *testing.T) { } c.Directory += "-missing" f := newTest(t, c) - x, e = f.Admit(context.Background(), 1, nil) + x, e = f.Admit(WithClass(context.Background(), Urgent), 1, nil) if e != nil { t.Fatal(e) } @@ -327,7 +327,7 @@ func TestFallbackLogDoesNotHoldCOWAccountingLock(t *testing.T) { defer log.SetOutput(before) defer close(gate.release) done := make(chan struct{}) - go func() { _, _ = l.Admit(context.Background(), 1, nil); close(done) }() + go func() { _, _ = l.Admit(WithClass(context.Background(), Urgent), 1, nil); close(done) }() select { case <-gate.entered: case <-time.After(5 * time.Second): @@ -343,7 +343,7 @@ func TestHealthyAdmissionDoesNotHideOlderFallbackLease(t *testing.T) { c := testConfig(t) c.Directory = filepath.Join(c.Directory, "late-pool") l := newTest(t, c) - x, e := l.Admit(context.Background(), 1, nil) + x, e := l.Admit(WithClass(context.Background(), Urgent), 1, nil) if e != nil { t.Fatal(e) } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 5a5ab705a4..8b1152d2cd 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -402,4 +402,4 @@ stateDiagram-v2 Joined --> Free: descriptor closed ``` -Guest I/O never acquires a slot. Static fallback reports that the shared cap is not enforced. +Guest I/O never acquires a slot. An unavailable pool skips background cuts; urgent and named seals may use per-process fallback with an alarm. Active coordinated reservations exclude orphaned crash spill. Upload pacing debt survives leases in one process, but a new process starts fresh, so arbitrary process turnover has no fixed host-rate bound. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9b846e4bac..e4b68c4837 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -311,7 +311,7 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Missing pools use static fallback with an alarm and no shared-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. ## Part B. Invariant ledger @@ -460,7 +460,7 @@ Notes: | `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 | | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | | `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | -| `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Missing-pool fallback is explicitly degraded and cannot claim the shared bound. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE | +| `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE | | `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | diff --git a/seaweed-block/docs/spec/HostBudget.tla b/seaweed-block/docs/spec/HostBudget.tla index b2cea0fe8e..bae8554b27 100644 --- a/seaweed-block/docs/spec/HostBudget.tla +++ b/seaweed-block/docs/spec/HostBudget.tla @@ -1,4 +1,6 @@ ----------------------------- MODULE HostBudget ----------------------------- +\* Active coordinated reservations only: fallback, pacing, RSS and retained +\* crash scratch bytes are outside this abstraction. Crash frees active slots. EXTENDS Integers, FiniteSets, TLC CONSTANTS N, SlotCount, Payload, Spill, EarlyRelease, AtomicConfig Owners == 1..N