Repository navigation
perf(provider): keep busy engines' MLX buffer pool and paged KV segments warm - #1545
Conversation
The proactive MLX cache sweep ran synchronize + clearCache under the eval lock every capacity tick whenever the pool exceeded 2 GiB, between busy engines' steps, and every flush reported device activity. It now waits for five seconds of whole-Mac idleness and flushes without reporting activity; busy engines flush only when the pool crowds out admission headroom. A refused engine-owned KV charge signals the shortfall-gated reclaim that request reservations already use. DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0 restores the old sweep. Segmented paged pools retain up to min(2 GiB, grant / 8) of free segments across requests and allocate new ones from zero-fill-on-demand host pages. DARKBLOOM_TTFT_SEGMENT_RETENTION=0 restores release-time trimming and device fills; DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0 keeps retention with device fills. Pins libs/mlx-swift-lm to the paired SDK branch (segment retention, the release request and the retained-bytes gauge) on the SDK commit master pins; libs/mlx-swift and libs/mlx stay at master's commits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Shortfall reclaims (request and engine-owned refusals), pressure-window sweeps and macOS memory-pressure events now also ask every engine to drop its retained free KV segments, which no cache flush reaches. A shortfall the MLX cache cannot cover still releases them. Adds the idle-sweep tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Busy engines now keep the reusable MLX pool up to its cache limit, and the load gate counts that pool as used. Both load paths (ProviderLoop's evictUntilAvailable, StandaloneServer's headroom gate) now flush the pool and resample once before unloading a resident model for room, so a pool-inflated box does not evict a model it could keep. Follows DARKBLOOM_TTFT_IDLE_CACHE_SWEEP (=0 keeps evict-first). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retained free paged segments are allocator-active memory, so load admission treated them as used. Count them as reclaimable (the process-wide retained-bytes gauge comes from the paired SDK change), and in the ProviderLoop and standalone load paths and the fast pre-accept self-heal request their release and wait briefly for engines to drop them before the pool flush and resample, ahead of evicting a resident model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
StandaloneServer.ensureMemoryHeadroomForLoad releases retained free KV segments and drops the MLX buffer pool once before it evicts or refuses. Cover the refusing path: a gate that may not evict still waits for the engine to drop its parked segment backing, then refuses without unloading or shutting down the resident model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Describe the busy-engine cache sweep window, retained free segments and host-zeroed growth in the inference architecture, the load gate's release of retained segments before eviction in the memory model, and the standalone load headroom path in direct mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
launchd does not inherit the installing shell, so a DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0, DARKBLOOM_TTFT_SEGMENT_RETENTION=0 or DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0 export reached only a foreground provider: the background provider job kept the idle-gated sweep and the retained, host-zeroed KV segments, and restarts and watchdog recovery reuse its saved plist. Name the three keys and add them to LaunchAgent.inferencePassthroughEnvKeys, so darkbloom start persists them into the provider plist. The watchdog plist stays without them: it never runs inference. The changelog now says what the old segment growth waited for: queued GPU work drained under the process-wide MLX eval lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
releaseRetainedKVSegments polled with `try? Task.sleep(for:)`. In a cancelled load the sleep threw at once and the loop swallowed it, so the task spun until its 250 ms deadline. The loop also used the generic sleep overload that TaskSleep.swift tells ProviderCore to avoid in release builds. Sleep through taskSleep and return on cancellation; the release request stays posted for the engines' next steps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…weep flushIfDue took its flush as a parameter named clearCache, which shadowed the stored clearCache, so `clearCache()` inside it silently meant the argument (the idle or the device flush). Name it `flush`. The sweep's entry point (proactiveReclaimSweep) and its ProviderLoop driver still said the sweep returns freed buffers instead of letting them accumulate. Busy engines now keep the pool, up to the cache limit, while admission headroom is healthy. Say so, and why engine-owned refusals now signal a reclaim. No behavior change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ion order No test read the segmented factory's retention settings. The min(2 GiB, grant / 8) cap, the 30 s idle release that the docs quote and the DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS rollback were unchecked. Build backends from the factory under each environment and read their pool configuration. retainedSegmentsReleaseBeforeEviction checked the parked bytes only after evictUntilAvailable returned. The final nothing-evictable refusal also releases them, so the test passed even without the release before the eviction. Record the parked bytes when the resident model shuts down; makeInertStubBridge gains an optional onShutdown hook for that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- inference.md: admission no longer waits for queued GPU work (it never stalled the queue itself). The eval lock is the process-wide part, not the stream synchronize. Host pages are wrapped only for segments that are a whole number of VM pages. The sweep flushes between busy engines' steps when the pool crowds out headroom, which "never ... unless" contradicted. - hardware-support.md: shortfall reclaims and pressure sweeps ask engines to drop retained segments even when they do not flush. - configuration.md: cold loads release retained segments before evicting or refusing; the page-granular condition for host pages. - changelog: the sweep still flushes busy engines under headroom pressure; cold loads also release retained segments before refusing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Threat model review — advisoryReviewed head Review not completed for this head. Previous findings are superseded, not confirmed resolved. Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging. Failure diagnostics: Coverage: 127/181 source units; cross-file integration pending. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned. Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 0 reused batch(es), 0 provider cache-hit tokens. Saved findings and earlier report · Historical findings are not confirmed resolved. Bedrock: 30 request(s), 1472351 uncached + 0 cache-read + 0 cache-write input / 26360 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately. |
Layr-Labs/mlx-swift-lm#328 squash-merged as 07b48961 ("perf(cbv2): retain free paged KV segments and grow new ones from host-zeroed pages (#328)"). Move the gitlink from the PR branch head 4cb9a532 to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9b1354a78f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Refresh before review: master moved (Nemotron Super and SDK pin updates; it now pins SDK 889fe3cc, mlx-swift 67dc7528 and MLX ad4745a2). Keep master's mlx-swift and MLX pins and pin libs/mlx-swift-lm to . Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bac7955cce
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bd3b96746c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…rges A refused native MiMo media charge added its extra OS reserve to the reclaim shortfall unconditionally, but ProcessMemoryLedger narrows only the OS-available side with that reserve, never the cap. When the cap bound (the usual case on large Macs) the shortfall overshot by the whole reserve, so KVPoolReclaimer skipped a buffer-cache flush that would have let the retry fit. A refused engine-owned paged charge in commitment debt had the opposite error: it ignored the debt and under-reported. ProcessMemoryLedger.capacityShortfall now computes, under the ledger lock, outstanding + growth - headroom with the same min(cap, system - extra) - reserve arithmetic admission uses, and both owners report it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ProcessMemoryLedger.capacityShortfall subtracted the admission headroom, which floors at zero once active plus cache memory reaches the activation reserve below the cap, or OS-available memory falls below the reserves. That is where refusals cluster, and there it reported only the outstanding commitment plus growth. KVPoolReclaimer then flushed the buffer cache whenever the cache covered that figure, even when the flush could not admit the retry, stalling busy engines for nothing. The shortfall is now the larger of the cap-side and OS-side deficits, neither floored: exactly what usage must fall by for the charge to fit. It is unchanged wherever headroom is positive. The MiMo reservation's onRefusal doc no longer calls the signal an upper bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a60cbd26ae
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…il released
ProviderLoop.reclaimableMemoryBytes added the live retained-segment gauge
(CBv2RetainedKVSegments.retainedBytes) to every eviction and pre-accept
feasibility check. A busy engine drops its segments only at its next
step, which can outlast the 250 ms wait in releaseRetainedKVSegments,
and it can park more meanwhile. After the one-time release the gates
still counted those bytes, so evictUntilAvailable and
evictUntilNemotronSuperFits could pass their feasibility check, evict an
idle model, and then refuse the load anyway ("all loaded models are
actively serving"). Pre-accept could also admit on the same bytes.
Retained segments now count only to decide whether that release could
make room. After the release, eviction credit is the idle models'
weights and the buffer cache, and the memory sample shows what the
release returned. The ordinary pre-accept and the managed Super
pre-accept (nemotronSuperLoadIsCertainToFail, now async) run the same
release-and-resample when nothing is idle or when only retained
segments could close the gap. They decide on the room that remains and
re-check the request's verdicts after the suspension. Segments are still
released before any eviction or refusal.
Regression tests use a RetainingEngineStub that does not step within
the wait, with the unreleased bytes as the margin. They cover the
ordinary gate and pre-accept and the Super gate and pre-accept. A Super
pre-accept whose engine does step is still admitted. Docs and the
changelog fragment describe the narrower credit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The load gates refuse at once, without releasing retained KV segments, when not even those segments and every idle model's weights could make room. Pre-accept also releases when nothing is idle, not only when the segments alone could close the gap. State both in the hardware-support memory notes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # docs/provider/cli-reference.md # provider-swift/Sources/ProviderCore/Inference/Performance/WholeMacServiceBudget.swift # provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift # provider-swift/Tests/ProviderCoreTests/Service/LaunchAgentRestartTests.swift
Move the ensureMemoryHeadroomForLoad sentence ahead of the preload_models precedence sentence so it no longer edits the line next to the shape-warmup rewrite of the standalone self-test sentence. Pure move with rewrapping; the sentence text is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
If a retained native MiMo fault or unretired closing transaction appears during the new retained-segment/cache-release suspension, the nativeMiMoRefusesRequest(modelId) result checked before that suspension is stale. This retry block rechecks retirement and residency only, so when the resampled memory is reachable it can return false and accept a cold request even though the process-wide native MiMo fence now refuses all cold loads; the authoritative load then fails after acceptance. Re-run nativeMiMoRefusesRequest after the suspension, as the Super branch does.
AGENTS.md reference: AGENTS.md:L110-L112
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Summary
This PR removes two GPU stalls that serving engines hit while they are busy.
synchronizeplusclearCacheunder the process-wide MLX eval lock, between busy engines' steps, and reported device activity. The engines then re-allocated the pool they had just lost.WholeMacServiceBudget.performIfIdle, under the admission lock. A request that arrives during the flush is admitted after it, not started on a pool that is being emptied.KVPoolReclaimer.proactiveWindow).GlobalKVCacheBudget.directChargeRefusalSignal). These are engine-owned KV growth and native MiMo media reservations.min(2 GiB, grant / 8)per pool.releaseReclaimableMemoryForLoad) before they evict a resident model or refuse.Three rollbacks restore the old behavior, and
darkbloom startnow forwards them to the launchd provider job.2994a3f01Keep busy engines' MLX buffer pool and paged KV segments warm4cb9a532,libs/mlx-swift81f58d79,libs/mlx71271f08). The merges below superseded those moves, and none is in the final difff648a3ba9Reclaim retained KV segments on memory pressureKVPoolIdleSweepTests5bc489590Drop the MLX buffer pool before evicting a model for a cold loadProviderLoop.evictUntilAvailableandStandaloneServer.ensureMemoryHeadroomForLoadflush the pool and resample once before they unload a resident model5f55449ceRelease retained KV segments before a cold load evicts or refuses89fee7f14Test that the standalone headroom gate releases retained KV segments121bf1c9cdocs: idle-gated cache sweep and retained paged KV segmentsarchitecture/inference.md,architecture/hardware-support.md,provider/direct-mode.md,reference/configuration.mdddc7214cdfix(provider): forward the serving-stall rollbacks to launchdLaunchAgent.inferencePassthroughEnvKeys, a test,provider/cli-reference.mdbd8756520Stop waiting for retained KV segments once a load is cancelledtaskSleepand returns on cancellation. AddscancelledLoadReleaseStopsWaitinga639da76brefactor(provider): name the reclaimer flush; describe the windowed sweep6004c57fdtest(provider): pin segment-retention wiring and release-before-eviction order9b1354a78docs: match the serving-stall wording to the codeinference.md,hardware-support.md,configuration.mdand the changelog fragmente0af12748Re-pin libs/mlx-swift-lm to the merged SDK change (#328)4cb9a532to its squash commit07b48961. Superseded by the next mergebac7955ccMerge master889fe3cc/67dc7528/ad4745a2);889fe3cccontains07b48961. The message reads "pin libs/mlx-swift-lm to ." because the SHA is missing. The pin it kept is889fe3cc5a3debea4Merge master (8f6958689)git show --remerge-diffis empty); pins unchanged78cf584d7fix(provider): signal a shortfall reclaim on refused native MiMo media chargesa36bb33edfix(provider): keep engine-refusal reclaim signals on while segments are retainedd99cdd309fix(provider): release retained KV segments in the Nemotron Super load gateac5180a6afix(provider): reclaim retained KV segments before skipping a startup preload87ec8456dfix(provider): make the idle cache flush atomic with request admission5a11393f9docs(provider): describe exactly which load paths release retained KV segmentsconfiguration.md,hardware-support.md,inference.mdbd3b96746refactor(provider): tidy the serving-stalls review follow-ups558c02506fix(provider): report the exact ledger deficit for refused direct chargesa60cbd26afix(provider): count usage inside the reserve in the refusal shortfall558c02506, see below83efeeadcfix(provider): count retained KV segments as eviction credit only until released0c84ac4d5docs(provider): note which refusals skip the retained-segment release83efeeadc, docs onlyThe changelog fragment is
changelog.d/serving-stalls.md.Merging current master
GlobalKVCacheBudget.swift: kept master'sconfigReserveBytes,flushCache(and its fenced clear in the test initializer),reservationBytesSnapshot()andreturnCachedBuffers()alongside this branch's idle-sweep window, refusal signal and retained-segment release.ProviderLoop+ModelLoading.swift: kept master'sreclaimableMemoryBytessplit, which the Nemotron Super gate also uses. Sinced99cdd309,reclaimableMemoryBytesitself counts retained segments, because every gate that plans with it now releases them. Since83efeeadc, it counts them only when the caller asks (countingRetainedKVSegments:), which the gates do only before their one-time release.Before
flowchart TB subgraph PB["Behavior: while engines serve"] direction LR tb["Capacity tick<br/>(2 s in ProviderLoop)"]:::input --> cb{"MLX buffer pool<br/>at least 2 GiB?"}:::decide cb -- "yes" --> fb["Flush: synchronize + clearCache<br/>under the MLX eval lock,<br/>reported as device activity"]:::slow fb --> sb["Busy engines wait, then<br/>re-allocate the pool<br/>Gemma: 10 flushes in 70 s, 13-35 ms each"]:::slow ab["Paged admission"]:::input --> gb["New KV segments: zero fill,<br/>eval and fence each time"]:::slow rb["Refused engine-owned KV growth<br/>or native MiMo media charge"]:::input --> nb["No reclaim signal"]:::code end subgraph LB["Code flow: load short of memory"] direction LR lb["evictUntilAvailable /<br/>ensureMemoryHeadroomForLoad /<br/>evictUntilNemotronSuperFits"]:::code --> eb["Evict an idle model"]:::slow lb -. "nothing evictable" .-> xb["clearCache, resample<br/>once, else refuse"]:::code sp["StartupPreloader:<br/>free sample short"]:::code --> kb["Skip the preload"]:::code end PB ~~~ LB style PB fill:#f8fafc,stroke:#64748b,color:#0f172a style LB fill:#f8fafc,stroke:#64748b,color:#0f172a classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a classDef code fill:#e0e7ff,stroke:#4338ca,color:#1e1b4b classDef decide fill:#fef3c7,stroke:#b45309,color:#78350f classDef slow fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d linkStyle default stroke:#64748b,stroke-width:1.5px linkStyle 8 stroke:none,stroke-width:0pxAfter
flowchart TB subgraph PA["Behavior: while engines serve"] direction LR ta["Capacity tick<br/>(2 s in ProviderLoop)"]:::input --> ca{"MLX buffer pool<br/>at least 2 GiB?"}:::decide ca -- "yes" --> wa{"proactiveWindow"}:::decide wa -- "Mac idle for 5 s" --> ia["Idle flush inside performIfIdle:<br/>admission waits for it,<br/>no device activity reported"]:::new wa -- "busy, headroom healthy" --> ka["Keep the pool warm<br/>Gemma: 0 flushes in 70 s"]:::new wa -- "pool crowds headroom" --> pa["Flush + release<br/>retained KV segments"]:::release ra["Refused engine-owned KV growth<br/>or native MiMo media charge"]:::input --> sa["directChargeRefusalSignal:<br/>shortfall reclaim +<br/>release retained segments"]:::release ma["macOS memory pressure"]:::input --> na["Release retained<br/>segments + clearCache"]:::release end subgraph LA["Code flow: load short of memory"] direction LR la["evictUntilAvailable /<br/>ensureMemoryHeadroomForLoad /<br/>evictUntilNemotronSuperFits:<br/>retained bytes count as reclaimable<br/>only until the release runs"]:::code --> oa["Once: releaseReclaimableMemoryForLoad<br/>(release retained segments, wait<br/>up to 250 ms, flush the pool), resample"]:::new oa --> ea["Still short: evict an idle model<br/>(credit: idle weights + cache,<br/>never still-parked segments), or refuse"]:::code sp["StartupPreloader:<br/>free sample short"]:::code --> rp["reclaimBeforeSkip, re-resolve<br/>the requirement, resample"]:::new rp --> kp["Still short: skip<br/>(preload never evicts)"]:::code end subgraph FA["Engine factory and rollbacks"] direction LR fa["Segmented backend: retain<br/>min(2 GiB, grant / 8),<br/>host-zeroed segments"]:::new ks["IDLE_CACHE_SWEEP, SEGMENT_RETENTION,<br/>SEGMENT_HOST_ZEROS = 0 rollbacks<br/>forwarded to the launchd job"]:::changed end PA ~~~ LA LA ~~~ FA style PA fill:#f8fafc,stroke:#64748b,color:#0f172a style LA fill:#f8fafc,stroke:#64748b,color:#0f172a style FA fill:#f8fafc,stroke:#64748b,color:#0f172a classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a classDef code fill:#e0e7ff,stroke:#4338ca,color:#1e1b4b classDef decide fill:#fef3c7,stroke:#b45309,color:#78350f classDef new fill:#dcfce7,stroke:#15803d,color:#14532d classDef release fill:#ffedd5,stroke:#c2410c,color:#7c2d12 classDef changed fill:#ccfbf1,stroke:#0f766e,color:#134e4a linkStyle default stroke:#64748b,stroke-width:1.5px linkStyle 11,12 stroke:none,stroke-width:0pxLegend:
Flush counts are from the quiet Gemma 4 run in the first table.
Evidence (M5 Ultra, 80-core GPU)
The implementer measured these on pre-rebase builds. Those builds carried two measurement-only commits, which this branch drops: a stall trace, and a 2 s standalone sweep cadence that matches ProviderLoop's
heartbeat / 2. Both builds used the samemlx.metallib(SHA-256fb1ba8f9…c85c).Load shape:
Arms: off =
DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0 DARKBLOOM_TTFT_SEGMENT_RETENTION=0; on = defaults.Logs are under
scratchpad/stalls/, wherescratchpadis/private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpadon the M5 Ultra.Quiet GPU (no other job held a GPU slot in any sample; load average about 2-3):
hold-q1.log)hold-q4.log)Shared GPU (other agents' jobs held GPU slots in 100% of samples). These runs show the mechanism only. Their end-to-end ITL and TTFT moved in both directions between pairs.
hold-q2.log)h3-q7.log)h3-q9.log)h3-q1.log,h3-q2.log)Each switch alone (Gemma 4, quiet,
hold-q5.log):Decode (Gemma 4,
darkbloom benchmark --sweep, 8,192-token context, 192 tokens, 2 iterations per arm; on ran first;h3-q10.log):The SDK PR has the isolated growth microbenchmark. Behind co-resident GPU work, steady growth p50 fell from 894.91 ms to 0.65 ms (
growth-bench-1.log).What this does not show.
Review follow-ups
Fixed:
d99cdd309.evictUntilNemotronSuperFitsruns the one-time release-and-flush pass before its first eviction and before refusing with nothing idle.reclaimableMemoryBytescounts retained segments, andnemotronSuperLoadIsCertainToFailcounts them in both branches. Tests:retainedSegmentsReleaseBeforeSuperEviction,superRefusalReleasesRetainedSegmentsFirst,superPreAcceptCountsRetainedSegments(replaced in83efeeadc, next-but-one row)87ec8456d. The clear runs insideWholeMacServiceBudget.performIfIdleunder the admission lock. Only a flush that actually ran stampslastReclaimAtand records telemetry. Tests:idleOperationHoldsOffAdmission,declinedIdleFlushLeavesRateLimitOpena36bb33ed.signalsEngineRefusalsfollowsbusyEnginesKeepReclaimableMemory(idle sweep or retention on). The productionGlobalKVCacheBudget.inittakes a defaultedenvironment, so the test covers the real wiring. Test:engineRefusalSignalFollowsKillSwitchesac5180a6a.StartupPreloader.Dependencies.reclaimBeforeSkip: release, re-resolve the requirement, resample, then skip. ProviderLoop and StandaloneServer wire it toreleaseReclaimableMemoryForLoad. Tests:shortSampleReclaimsBeforeSkipping,shortSampleReleasesRetainedSegmentsBeforeSkipping78cf584d7.MiMoV26ManagedMediaReservationtakesonRefusalfromdirectChargeRefusalSignal(). EveryinsufficientCapacityrefusal signals a shortfall reclaim; the next row makes that shortfall exact. Test:testCapacityRefusalSignalsShortfallReclaim5a11393f9. The docs now name the exact paths and say that the post-load KV headroom guard does not release them.inference.mdcites repo paths plus symbolsbd3b96746)558c02506,a60cbd26a.ProcessMemoryLedger.capacityShortfall(growthBytes:additionalSystemReserveBytes:)returns, under the ledger lock with a fresh usage read, how far usage must fall for(charged - materialized) + growthto fit the headroom admission checks. That is the larger of the cap-side deficitneeded + reserve + (active + cache) - capand the OS-side deficitneeded + reserve + extra - systemAvailable. The extra OS reserve counts only when the system side binds, usage already inside the reserve counts too, and overflow saturates.MiMoV26ManagedMediaReservation.signalShortfallandEngineProcessMemoryOwner.replaceboth report it, which also fixes the engine owner's under-report while in commitment debt. Admission and the unified-memory, activation and KV safeguards are unchanged; only the reclaim gate's input moves. Tests:testCapBoundRefusalSignalsOnlyTheCapDeficit,engineRefusalInDebtSignalsWholeDeficit,processLedgerCapacityShortfallIsTheBindingDeficita60cbd26a)83efeeadc, docs0c84ac4d5.reclaimableMemoryBytes(from:countingRetainedKVSegments:)counts the retained-segment gauge only to decide whether the one-time release could make room. After it, eviction credit is the idle models' weights plus the buffer cache; the post-release memory sample already includes what the release returned, so segments a busy engine has not dropped within the 250 ms wait, or has parked since, earn nothing.evictUntilAvailableandevictUntilNemotronSuperFitspass!poolDropped, so neither can evict an idle model for room the load never gets.fastAdmissionRejectandnemotronSuperLoadIsCertainToFail(now async) release and resample when nothing is idle or when only retained segments could close the gap, judge the room that remains, and re-check the request's verdicts after the suspension. A gate still refuses at once, without releasing, when not even the segments plus every idle model could make room. No reserve, headroom or KV safeguard changed. Tests:unreleasedRetainedSegmentsAreNoEvictionCredit,fastAdmissionRejectsOnUnreleasedRetainedSegments,unreleasedRetainedSegmentsAreNoSuperEvictionCredit,superPreAcceptRefusesOnUnreleasedRetainedSegments,superPreAcceptAdmitsTheRoomTheReleaseReturns(replacessuperPreAcceptCountsRetainedSegments, which asserted the old credit)Follow-ups (deferred, not in this PR):
reclaimIfNeededmeasures and flushes before engines honor the release at their next step.DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0, or segment sizes that are not page-granular. Default host-zeroed segments are unmapped on release.GlobalKVCacheBudget.recordReservationRefusalunder-reports its shortfall. The request-reservation path is unchanged from master and outside this PR's diff. It still reportsbytes - snapshot().remainingBytes, which omits commitment debt and usage already inside the reserve. A low figure errs only toward a flush that cannot admit the retry, never toward skipping one that would. Planned fix: reportprocessLedger.capacityShortfall(growthBytes: bytes), the helper the direct charges now use.83efeeadc, pre-accept also runs it when only retained segments could close the gap, and rejects (the coordinator reroutes) if a busy engine has not dropped them by then. Busy engines re-park segments, so the wait usually runs its full length. Waiting for a per-pool release epoch, or for a byte delta, would shorten it.83efeeadc, non-blocking, predates this round). In the ordinaryfastAdmissionRejectpath, the re-check after the release omitsnativeMiMoRefusesRequest, which the Super branch re-checks, and the final slot-cap check reuseshasEvictablefrom before the suspension.83efeeadcadds that suspension, up to 250 ms, when only idle weights plus retained segments could make room. The load path still enforces both checks, so the worst case is accept-then-503 within that window. Planned fix: re-resolve both after the suspension, with its own race regression test.performIfIdleholds the service-budget lock whileMLX.Memory.clearCache()takes MLX'sevalLock. There is no reverse lock order, so this cannot deadlock. An uncharged GPU eval that starts between the fence and the clear could delay admission for that eval's duration.Validation
This round, at
0c84ac4d5(Apple M3 Ultra, 512 GB, same daemon-state isolation as below). Full CI runs on the pushed head. The previous head,a60cbd26a, was green: Provider Unit Tests, Provider Tests, Provider SDK Tests, Provider Prompt Parity, Release Integrity, Docs Lint, Docs Impact and Commit Signatures all passed.cd provider-swift && swift build --build-tests -j 12, then../scripts/stage-test-metallib.sh .build/out/Products/Debugswift test --skip-build --no-parallel --filter 'ModelLoadEvictionAndAdmissionTests|NemotronSuperManagedSlotTests|KVPoolIdleSweepTests'ProviderLoop+ModelLoading.swiftandProviderLoop+NemotronSuperAdmission.swiftreverted toa60cbd26a, rebuilt, then the five new testssuperPreAcceptAdmitsTheRoomTheReleaseReturnsfails only onparkedBytes == 0, since the old pre-accept never released. With the fix restored, all passModelLoad|NemotronSuper|KVPoolIdleSweep|StartupPreload|StandaloneServerModelAdmission|Autopilot|Qwen4MemoryRetirement|NativeMemoryRetirement|ProcessMemoryLedger|GlobalKVCacheBudget|KVPoolReclaimer|Qwen4ReclaimAdmissionTests|RetirementGateTests|ServiceReservationHandlerTests|AudioInputRejectionTests|FlintReasoningVisibilityTests|OuterPrefixCacheReceiptTests|ProviderCancelledPrefixCacheTests, skippingmimoProviderStartupPlanUsesScannerNativeLoadandstandaloneMiMoStartupPlanUsesNativeLoadEnvelopeMIMO_V26_SERIAL_LOAD_FIXTURESis not set on this host (MiMoDiscoveryFixture.copyTiny); unrelated to this change. CI's explicit MiMo selections cover themmake docs-check;make docs-impact-check BASE=origin/master;make changelog-check190 file(s) OK;33 changed file(s), coverage OK;45 valid fragment(s)git log --show-signature83efeeadcand0c84ac4d5Previous round, at
a60cbd26a(Apple M3 Ultra, 512 GB). The test daemon state was isolated withDARKBLOOM_STATE_FILEandDARKBLOOM_LOADED_MODELS_FILE, asscripts/run-provider-tests.shdoes. The head before it,bd3b96746, was green: Provider Unit Tests, Provider Tests, Provider SDK Tests, Provider Prompt Parity, Docs Lint, Docs Impact and Commit Signatures all passed.cd provider-swift && swift build --build-tests -j 12, then../scripts/stage-test-metallib.sh "$(swift build --show-bin-path)"156f2624…)swift test --skip-build --no-parallel --filter 'testCapBoundRefusalSignalsOnlyTheCapDeficit|testCapacityRefusalSignalsShortfallReclaim|engineRefusalInDebtSignalsWholeDeficit|engineRefusalSignalsShortfall|processLedgerCapacityShortfallIsTheBindingDeficit'signalShortfallandEngineProcessMemoryOwner.replaceformulas restored, new tests kepttestCapBoundRefusalSignalsOnlyTheCapDeficitgot [6000, 7000, 5000] instead of [2000, 3000, 1000];engineRefusalInDebtSignalsWholeDeficitgot 1 GiB instead of 2 GiB. The system-bindingtestCapacityRefusalSignalsShortfallReclaimandengineRefusalSignalsShortfallstill passed, as expected558c02506capacityShortfallbody restored, the saturated-regime assertions keptprocessLedgerCapacityShortfallIsTheBindingDeficitfailed with 2 issues: expected 810, got 800; expected 1,820, got 800MiMoV26ManagedMediaReservationTests|KVPoolIdleSweepTests|processLedger|GlobalKVCacheBudget|KVPoolReclaimer|SystemMemoryAdmission|ProcessMemoryLoadConstraint|ProcessHostBufferReservation|ProcessMemoryPreparation|ProcessMemoryTelemetry|MiMoMemoryAdmission|MiMoV26MediaPhaseAdmission|KVPoolSweepWiring|SegmentedProductionGrant, skipping the three cases that need their own runners (next rows)558c02506anda60cbd26a. XCTest: 12 tests, 0 failures. Swift Testing: 99 tests in 7 suitesscripts/run-nested-suite.sh processLedgerCannotCombineOldUsageWithNewMaterializationCredit --no-parallel558c02506:scripts/run-nested-suite.sh ProcessMemoryNativeIntegrationTests --no-parallel, andscripts/run-exclusive-native-gpu-test.sh evaluatedPagesAvoidDoubleTaxAndRetainedAliasKeepsPressureemptyNativePoolTeardownUsesActualRetiredAdapterpassed. The nested runner's skip guard tripped only because the exclusive allocator test skips withoutDARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST; run through its own script, it passed (1 test)558c02506:swift test --skip-build --no-parallel --filter 'MiMoV26NativeLoadTransactionTests|MiMoV26EncodedAudio|MiMoV26ManagedAudioProvider|MiMoV26EncodedAudiovisualIngress'MiMoV26NativeLoadTransactionTestscases needMIMO_V26_SERIAL_LOAD_FIXTURES, which is not set on this host, and stopped withFixtureError.fixtureRequired. CI's explicit MiMo selections cover themmake docs-check;make docs-impact-check BASE=origin/master;make changelog-check;git diff --check190 file(s) OK;33 changed file(s), coverage OK;45 valid fragment(s); no whitespace errorsRound before that, at
bd3b96746(same host and isolation). The head before it,bac7955cc, was green: Provider Unit Tests ran 5,120 tests in 705 suites.cd provider-swift && swift build --build-tests -j 8, then../scripts/stage-test-metallib.sh "$(swift build --show-bin-path)"156f2624…)swift test --skip-build --no-parallel --filter 'KVPoolIdleSweepTests|KVPoolReclaimerTests|KVPoolReclaimerNativeGateTests|KVPoolSweepWiringTests|GlobalKVCacheBudgetSelfHealTests|GlobalKVCacheBudgetTests|GlobalKVCacheBudgetProcessTests|MiMoV26ManagedMediaReservationTests|MiMoV26MediaPhaseAdmissionTests|StartupPreloaderTests|StartupPreloadGateTests'GlobalKVCacheBudget*test functions, plusNemotronSuperManagedSlotTests|ModelLoadEvictionAndAdmissionTests|StandaloneServerModelAdmissionTests|GlobalKVCacheBudgetAuditTests|ProcessMemoryLedgerTests|LaunchAgentRestartTestsMiMoV26Encoded*,MiMoV26ManagedMediaReservationTests,MiMoV26MediaPhaseAdmissionTests,PrefillEvidenceRecoveryTests,UnboundedDeviceWork,Deadline*,ProcessMemoryLedgertestCapacityRefusalSignalsShortfallReclaim). After restoring the fixes, all passKVPoolIdleSweepTests|KVPoolReclaimerTests|GlobalKVCacheBudgetSelfHealTests|StartupPreloaderTests|StartupPreloadGateTests|MiMoV26ManagedMediaReservationTests|NemotronSuperManagedSlotTests|ModelLoadEvictionAndAdmissionTests|StandaloneServerModelAdmissionTests|LaunchAgentRestartTestsperformIfIdlebody outside the lock, failsidleOperationHoldsOffAdmission./scripts/docs-check.sh;DOCS_IMPACT_BASE=origin/master python3 scripts/docs-impact-check.py;python3 scripts/changelog.py check190 file(s) OK;31 changed file(s), canonical documentation coverage OK;45 valid fragment(s)mmdcon the two figures aboveEarlier rounds (M5 Ultra, on the pre-merge pins: SDK PR head
4cb9a532, mlx-swift81f58d79, MLX71271f08). The stagedmlx.metallibwas byte-identical to the one the measured builds used. At9b1354a78, after the first refactor pass:cancelledLoadReleaseStopsWaitingandsegmentedFactoryAppliesRetentionRollbacks.DARKBLOOM_TTFT_SEGMENT_HOST_ZEROSread. The tests caught each removal.After the first master merge (
bac7955cc):KVPoolReclaimer|GlobalKVCacheBudget|LaunchAgentpassed 134 of 135 (1 opt-in skip);KVPoolReclaimerNativeGateTestspassed 3 of 3;KVPoolIdleSweep|ModelLoadEvictionAndAdmission|StandaloneServerModelAdmissionpassed 55 of 55;Logs are in
scratchpad/pr/stalls-work/logs/andscratchpad/pr/stalls-refactor/logs/on the M5 Ultra.Not run locally: the full suite (
make provider-test; CI runs it), and any end-to-end or decode measurement of the merged build.Kill switch
Each rollback takes an exact
0from the process environment, anddarkbloom startforwards it to the launchd provider job. A restart reuses the saved plist, so stop and start with the intended environment.DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0restores the threshold-only sweep, which flushes between busy engines' steps.hold-q5.log: 8 busy flushes, growth p50 0.156 ms).DARKBLOOM_TTFT_SEGMENT_RETENTION=0set, neither the refusal signal nor the release-and-flush pass runs (busyEnginesKeepReclaimableMemory).DARKBLOOM_TTFT_SEGMENT_RETENTION=0restores release-time segment trimming and device-filled segments.DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0keeps retention but grows new segments with the device fill plus fence.Interface and capacity effects
reclaimableMemoryBytescounts retained segments as reclaimable only until the one-time release has run; after it, only the memory the release actually returned counts. The release happens in the provider, standalone and managed Nemotron Super load gates (before they evict, or refuse when the segments could have made the difference) and in startup preload (before it skips).min(2 GiB, grant / 8)of retained segments per paged pool. The load gates drop both once before they unload a resident model. That costs one extra flush, plus a wait of up to 250 ms, on a load that is short of memory, and on a pre-accept that only the retained segments could decide.free_for_load_gb,load_usable_gbandfree_for_load_no_evict_gbcount that kept pool and the retained segments as used. Cold-load routing, capacity quotes and the autopilot therefore see a more conservative figure while engines serve. The schema is unchanged; the values move.Limitations
benchmark --sweepdecode ABBA plus a short load A/B with the stall pair. This round's tests ran on M3 Ultra, but they test correctness, not performance.scratchpad/stalls/r3-*/*.json). One Gemma off run's server died. The quiet runs had no errors. The cause was not determined.Landing notes
LaunchAgent.inferencePassthroughEnvKeysandLaunchAgentRestartTests. Against perf(provider): warm first-use kernel shapes before serving #1537, the Swift files merge cleanly, and the only conflicts are indocs/provider/cli-reference.mdanddocs/provider/direct-mode.md. Whichever PR lands second resolves its conflicts and re-runs CI.Refactor pass
First pass (independent; commits
bd8756520to9b1354a78). It reviewed the code, tests, docs, changelog and figures, and checked every number in this description against its log.Task.sleep(for:)overload thatTaskSleep.swifttells ProviderCore to avoid. It now sleeps throughtaskSleepand returns on cancellation.flushIfDue's parameter shadowed the storedclearCache. The sweep comments still described the sweep from before the window.Second pass, on this round's follow-ups (independent reviewer; commit
bd3b96746, no behavior change).performIfIdlechecks idleness under the admission lock, with no reverse lock order;busyEnginesKeepReclaimableMemory;busyEnginesKeepReclaimableMemorycomment now names every direct charge that signals a reclaim.idleOperationHoldsOffAdmissionasserts ordered events instead of reusing a pool-size field as a flag.DARKBLOOM_TTFT_*names follow the sibling TTFT PRs.Third pass, on the exact shortfall (independent reviewer of
558c02506; fix commita60cbd26a).capacityShortfallchecks(charged - materialized) + growthagainst the same headroom thatinstallandrecheckChargeadmit against, under the ledger lock with a fresh usage read;EngineProcessMemoryOwner.replacepass matches what admission charged;MiMoV26ManagedMediaReservation.onRefusalcomment no longer calls the signal an upper bound.docs/architecture/hardware-support.mddescribes the exact shortfall with a path + symbol citation; the changelog fragment needed no change.recordReservationRefusal) is listed under Follow-ups above.Fourth pass, on the eviction-credit fix (independent reviewer of
83efeeadc; docs commit0c84ac4d5).evictUntilAvailableandevictUntilNemotronSuperFitscannot evict before their one-time release (or both rollbacks are set, so retention is off and the gauge is 0), so still-parked segments can no longer justify an eviction;fastAdmissionRejectkeeps its old verdicts for the plain idle-weights case and for the case no credit can rescue, and releases only when nothing is idle or only retained segments close the gap;nemotronSuperLoadIsCertainToFailmirrors its gate, and its caller re-checks the MiMo, Super and retirement refusals and residency after the suspension;docs/architecture/hardware-support.mdnow says a gate refuses at once, without releasing, when not even the segments plus every idle model could make room, and that pre-accept also releases when nothing is idle (matchingdocs/architecture/inference.md).docs/reference/configuration.mdkeep their summary-level wording.🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need.