Skip to content

perf(cbv2): retain free paged KV segments and grow new ones from host-zeroed pages - #328

Merged
Gajesh2007 merged 4 commits into
mainfrom
ttft/serving-stalls
Oct 22, 2026
Merged

Gajesh2007 merged 4 commits into
mainfrom
ttft/serving-stalls

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Paired provider PR: Layr-Labs/d-inference#1545.

Update for publication (2026-10-21, evening): replayed onto current main 19634dd8 (adds #318 and #314), which d-inference master now pins. Validation below ran on 66f556b7.

Summary

Paged admission on a segmented pool allocated, zero-filled, evaluated and stream-synchronized every new 64 MiB KV segment, because row release dropped every fully free segment. The fill's eval and Stream.synchronize() both run under the process-wide MLX eval lock. Every admission therefore waited for the engine's queued GPU work, and other engines' evals waited behind it. This PR adds two pool options, both off by default (the provider turns them on), and a process-wide release request with a gauge.

  • PagedKVPoolConfig.retainedFreeSegmentBytes: release parks free segment backings up to this many bytes. Parked backing leaves the committed set exactly like a trim (grant, floor and ledger coverage are released), and the next growth of the same size class reinstalls it without allocating, filling or fencing.
  • PagedKVPoolConfig.hostZeroedSegments: a new segment wraps zero-fill-on-demand anonymous pages as its Metal buffer, without a copy (MLXArray.cbv2ZeroFilledPages). Growth schedules no stream work, takes no eval lock and waits on no fence.
  • CBv2RetainedKVSegments: a process-wide release request (an epoch that each pool honors at its engine's next step, so pools stay engine-queue confined) and a retained-bytes gauge. The provider uses both to reclaim parked backing on memory pressure and before a cold load evicts a model.

Parked backing is also dropped on a refused admission or allocation, and after retainedFreeSegmentIdleSeconds (30 s) of engine idleness.

Commit Change
51c1ec63 style(paged): format PagedKVSegments.swift Format-only. Two expressions from #316 were not formatted on main, and the Lint job formats every file a PR touches
d95ab76e Retain free paged KV segments across requests; allocate new ones without a stream fence Retention, host-zeroed growth, the idle hook in EngineLoopV2, tests
a50ec95a Drop retained KV segments on a process-wide release request CBv2RetainedKVSegments.requestRelease(), the step hook in EngineLoopV2
4cb9a532 Gauge retained paged KV segment bytes process-wide CBv2RetainedKVSegments.retainedBytes (park, reinstall, release, group teardown)

The paired provider PR is Layr-Labs/d-inference branch ttft/serving-stalls. It enables the options and pins this branch.

Before

flowchart TB
  subgraph SB["Behavior: paged admission on a segmented pool"]
    direction LR
    rb["Row released"]:::input --> tb["Every fully free 64 MiB<br/>segment is dropped"]:::slow
    ab["Next admission"]:::input --> zb["Each new segment:<br/>device zero fill"]:::slow
    zb --> eb["eval under the<br/>MLX eval lock"]:::slow
    eb --> fb["Stream synchronize under<br/>the eval lock: waits for<br/>queued GPU work"]:::slow
    fb --> gb["Growth per admission<br/>Gemma: p50 7.1 ms, max 12.7 ms"]:::slow
  end
  subgraph CB["Code flow"]
    direction LR
    pb["PagedKVPool<br/>trimFreeSegments"]:::code --> kb["PagedKVGroup.trimSegments<br/>drops the backing"]:::code
    qb["PagedKVPool+Segments<br/>growth"]:::code --> hb["PagedKVGroup<br/>prepareGrowth"]:::code
    hb --> sb["PagedKVSegment.init<br/>zeros, evaluate, fence"]:::code
  end
  SB ~~~ CB
  style SB fill:#f8fafc,stroke:#64748b,color:#0f172a
  style CB fill:#f8fafc,stroke:#64748b,color:#0f172a
  classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
  classDef code fill:#e0e7ff,stroke:#4338ca,color:#1e1b4b
  classDef slow fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d
  linkStyle default stroke:#64748b,stroke-width:1.5px
  linkStyle 8 stroke:none,stroke-width:0px
Loading

After

flowchart TB
  subgraph SA["Behavior: paged admission on a segmented pool"]
    direction LR
    ra["Row released"]:::input --> ta["Free segments parked up to<br/>retainedFreeSegmentBytes:<br/>no grant, floor or ledger charge"]:::new
    aa["Next admission"]:::input --> qa{"Parked backing of<br/>the same size class?"}:::decide
    qa -- "yes" --> ia["Reinstall under the new range:<br/>no allocation, fill or fence"]:::new
    qa -- "no" --> ha{"hostZeroedSegments and<br/>a page-granular size?"}:::decide
    ha -- "yes" --> wa["Wrap zero-fill-on-demand pages<br/>without a copy: no eval,<br/>no fence, no eval lock"]:::new
    ha -- "no" --> da["Device zero fill, eval, fence<br/>(unchanged path)"]:::stock
    ia --> ga["Growth per admission<br/>Gemma: p50 0.16 ms, max 0.26 ms"]:::new
    wa --> ga
  end
  subgraph RA["Code flow: parked backing is released"]
    direction LR
    xa["Refused admission<br/>or allocation"]:::release --> la["releaseRetainedSegments"]:::release
    ya["Engine idle for 30 s<br/>(EngineLoopV2 idle hook)"]:::release --> la
    za["CBv2RetainedKVSegments<br/>.requestRelease(): an epoch<br/>honored at the next step"]:::release --> la
    la --> ma["Process-wide gauge<br/>CBv2RetainedKVSegments<br/>.retainedBytes"]:::state
  end
  SA ~~~ RA
  style SA fill:#f8fafc,stroke:#64748b,color:#0f172a
  style RA fill:#f8fafc,stroke:#64748b,color:#0f172a
  classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
  classDef new fill:#dcfce7,stroke:#15803d,color:#14532d
  classDef decide fill:#fef3c7,stroke:#b45309,color:#78350f
  classDef stock fill:#e5e7eb,stroke:#4b5563,color:#111827
  classDef release fill:#ffedd5,stroke:#c2410c,color:#7c2d12
  classDef state fill:#ede9fe,stroke:#6d28d9,color:#3b0764
  linkStyle default stroke:#64748b,stroke-width:1.5px
  linkStyle 12 stroke:none,stroke-width:0px
Loading

Legend: blue marks inputs, indigo unchanged code, red the per-admission stall, amber decisions, green new behavior, grey the unchanged fallback, orange the release paths for parked backing, and purple the process-wide gauge. Growth figures are from the Gemma 4 runs in the evidence table.

Reconciliation with #316 (cbv2HostZeros)

#316 added hostMaterialized to PagedKVSegment.init for checkpoint imports. That path copies host zeros into a fresh allocator buffer (cbv2HostZeros) and relies on an evaluator that skips available arrays (evaluateUnavailable). Pool growth cannot reuse it unchanged:

  • The pool's growth evaluator (slabEval) evaluates unconditionally and takes the eval lock. A host-copied array would still wait for the lock.
  • cbv2HostZeros copies the whole segment, and briefly commits a second host buffer of the same size outside MLX's allocator.

This branch therefore leaves #316's lines unchanged and adds hostZeroed as an early return before evaluation. cbv2ZeroFilledPages maps anonymous pages and hands them to MLX's make_buffer without a copy. MLX counts the exact length as active memory. When Metal refuses the wrap, MLX itself falls back to a copied allocation. When the size is not page-granular, the helper returns nil and growth takes the device fill plus fence, as before; pool growth never passes hostMaterialized. Checkpoint staging is unchanged: it keeps #316's hostMaterialized copy and never passes hostZeroed. A checkpoint import's suffix growth (prepareImport) now goes through the same growth helper, so it can reinstall parked backing of the same size class, but it never wraps host pages.

Evidence (M5 Ultra, 80-core GPU)

All numbers were measured by the implementer on pre-rebase builds that carried a measurement-only trace commit, which this branch drops. Each provider run had 5 decode streams, plus a cold arrival every 2 s (2,048, 512 or 4,096 prompt tokens) for 70 s; the first 10 s are excluded. "off" sets DARKBLOOM_TTFT_SEGMENT_RETENTION=0 DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0; "on" is the default. The provider PR has the end-to-end tables.

KV segment growth per admission (provider stall trace) off p50 / max on p50 / max Source
Gemma 4 26B QAT, quiet GPU 7.122 / 12.654 ms 0.161 / 0.260 ms scratchpad/stalls/hold-q1.log
GPT-OSS 20B, quiet GPU 3.100 / 6.551 ms 0.052 / 0.121 ms scratchpad/stalls/hold-q4.log
Qwen3.5-9B, shared GPU 1.804 / 4.109 ms 0.029 / 0.098 ms scratchpad/stalls/hold-q2.log
Gemma 4 + Qwen3.5-9B co-resident, shared GPU, 3 pairs 5.043-6.532 / 96.6-396.2 ms 0.164-0.193 / 0.695-0.989 ms scratchpad/stalls/h3-q1.log, h3-q2.log
Isolated growth benchmark (20 segments per admission) Idle: steady growth p50 / max Behind co-resident default-stream work: p50 / max
Trim + device fill + fence (before) 12.63 / 19.91 ms 894.91 / 1,771.78 ms
Retain + device fill 0.68 / 6.36 ms 0.66 / 165.62 ms
Trim + host zeros 0.91 / 2.25 ms 0.90 / 2.03 ms
Retain + host zeros (this PR, as the provider configures it) 0.67 / 2.15 ms 0.65 / 1.88 ms

The benchmark is scratchpad/stalls/growth-bench-1.log, a Gemma-4-like geometry. In the configuration this PR enables, the first 2,048-token KV write into the grown backing was unchanged: p50 36.73 ms before and 36.52 ms after (idle). Host zeros without retention made that write slower, p50 43.55 ms idle, because fresh pages fault on first touch. The provider always pairs host zeros with retention. Row release behind co-resident work fell from p50 29.43 ms to 3.12 ms, because a pool that keeps its backing skips the empty-pool retirement synchronize.

scratchpad is /private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpad on the M5 Ultra.

Validation

Run on M5 Ultra in a fresh PR clone. Toolchain: Apple Swift 6.4 (Command Line Tools), XCTest from Xcode 27.1, and libs/mlx-swift 81f58d79 (nested MLX 71271f08).

Command Outcome
swift build --build-tests (debug, clean build directory) Build complete, 0 errors
../../scripts/stage-test-metallib.sh "$(swift build --show-bin-path)" mlx.metallib SHA-256 fb1ba8f9…c85c, from nested MLX 71271f08
swift test --skip-build --no-parallel --filter 'CBv2PagedSegmentRetentionTests|CBv2CheckpointAdmissionTransferTests|CBv2PagedGrantTests|CBv2PagedPoolGuardTests|CBv2PagedSegmentDispatchCacheExecutionTests|CBv2PagedSegmentDispatchCacheTests|CBv2PagedSegmentTests|CBv2PagedSlabCommitmentTests|PagedCompleteCheckpointCodecTests' (one exclusive GPU ticket) Passed: 73 tests in 9 suites, including all 8 retention tests (host-zeroed segments are zeroed, exactly sized and need no evaluation; reinstalled stale segments decode bit-identically to a direct slab)
swift format format --configuration .swift-format on the 6 changed files: swift-format 604.0.0 (Homebrew) and the Swift 6.4 Command Line Tools formatter No changes, at every commit of the series. The Lint job's Xcode 26 formatter was not available locally
python3 scripts/check_forkdiff.py Exit 0: 1,695 changed files, 1,695 described. The new test file falls under the existing Tests/MLXLMTests/CBv2* glob. The merge-base check needs upstream main and was skipped

Logs: scratchpad/pr/stalls-work/logs/build-sdk-tests-1.log and sdk-gpu-tests-1.log.

Not run here: the CBv2CompleteCheckpointTests XCTest suite, which exercises #316's import path. The Command Line Tools runner runs only Swift Testing. Also not run: the full SDK suite.

Compatibility

  • Public API additions only: three PagedKVPoolConfig fields, each with a defaulted initializer argument, and the CBv2RetainedKVSegments enum. Existing callers keep the old behavior.
  • PagedKVSegment.init (internal) gains hostZeroed: Bool = false next to hostMaterialized.
  • Memory accounting: a parked backing is uncommitted, so no grant, floor or ledger charge covers it. It is still allocator-active memory, so process headroom counts it as used until it is released. The provider counts it as reclaimable for loads and releases it on pressure. A reinstalled backing is covered by the new admission exactly as a fresh segment would be. A backing covered by another admission is dropped, not reused.
  • Reinstalled backing still holds the previous row's bytes, exactly like recycled free pages. Every read is bounded by the row's written length, and reinstalledStaleSegmentsDecodeLikeFreshStorage covers this.

Rollback

Leave the options at their defaults (off). In the provider, DARKBLOOM_TTFT_SEGMENT_RETENTION=0 turns off both retention and host zeros, and DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0 turns off host zeros only.

Limitations

  • Only measured on M5 Ultra. M3 Ultra, M4 Max and other chips are unmeasured. That includes how the GPU reads no-copy host-page buffers there.
  • Decode with host-zeroed KV. In one Gemma 4 decode sweep pair (8K context, 2 iterations per arm, provider PR), the "on" arm ran first and was 3.4% lower at B=1. That gap is within the 3.8% spread between the arm's own iterations, and B=8 was at parity. A repeated or ABBA decode run is still owed.
  • Retained memory. Each pool holds up to retainedFreeSegmentBytes of allocator memory while its engine serves, and for 30 s after it idles. The provider cap is min(2 GiB, grant / 8).
  • All measurements predate the rebase onto main (Stage provider checkpoint imports without the MLX eval lock #316 and the Nemotron Super commits). The retention and growth code is the same as in the measured build, apart from the Stage provider checkpoint imports without the MLX eval lock #316 reconciliation described above.

Landing order

Land this PR first. The provider PR then re-pins libs/mlx-swift-lm from this branch head to the merged commit on main.

Refactor pass

The independent refactor pass required by d-inference AGENTS.md reviewed this branch (six files, eight tests) and this description. It changed no code, so the provider PR's pin stays at 4cb9a532.

  • Names, boundaries and comment density match the surrounding paged-pool code. No dead code was added: the one-argument trimSegments(willRetire:) still serves native pool retirement. Refused admissions and failed allocations drop parked backing. The gauge stays exact through reinstall, release and group teardown.
  • Each retention test checks behavior that main lacks. All 8 pass in the run above.
  • This description made two claims that the code contradicts. Both are now corrected in the Stage provider checkpoint imports without the MLX eval lock #316 section: the non-page-granular fallback never takes the host copy, and checkpoint-import suffix growth can reinstall parked backing.
  • Nits not taken, because each is a comment-only change that would force a provider re-pin:
    • The EngineLoopV2 step-hook comment names only memory pressure as a release trigger. Any requestRelease() triggers it, including refused charges and cold loads.
    • retainedSegmentsTouchedNanos is documented as "parked or reinstalled", but any trim refreshes it.
  • Observation: if Metal refuses the no-copy wrap and MLX's fallback allocation then throws, cbv2ZeroFilledPages leaks its anonymous mapping. Only address space is lost, because the pages were never touched.

🤖 Generated with Claude Code

Gajesh2007 and others added 4 commits October 21, 2026 17:04
Format-only (`swift format`, repository `.swift-format`). The Lint workflow
formats every Swift file a pull request touches; two expressions added by
#316 were not formatted on main, and the next commit edits this file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…out a stream fence

Row release used to retire every fully free 64 MiB segment, so each
admission re-allocated, zero-filled, evaluated and stream-synchronized new
ones. A pool configured with retainedFreeSegmentBytes now parks those
evaluated backings outside the committed set (grant, floor and ledger
coverage released exactly as before) and reinstalls one of the same size
class, covered by the same admission, at the next growth without
allocating, filling or fencing. Retained backing is dropped on a refused
admission or allocation and after the engine idles.

hostZeroedSegments wraps zero-fill-on-demand host pages as the segment
buffer without a copy, so growth schedules no stream work, takes no MLX
eval lock and waits on no completion fence. It sits beside #316's
hostMaterialized import path: cbv2HostZeros copies into a fresh allocator
buffer for an evaluator that skips available arrays, while the pool's
growth evaluator takes the eval lock unconditionally, so a wrapped segment
returns before evaluation. Both options default off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retained free segments are live allocator memory outside every grant, so
neither a cache flush nor another engine's refused charge could reclaim them.
CBv2RetainedKVSegments.requestRelease() advances a process epoch; each pool
drops its retained backing at its engine's next step (pools stay engine-queue
confined).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retained free segments are allocator-active memory outside every grant.
Pools mirror their parked bytes into CBv2RetainedKVSegments.retainedBytes
(parking, reinstall, release and group teardown), so provider load
admission can count that backing as reclaimable and wait for engines to
drop it after a release request before evicting a resident model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T00:11:29.437981Z 4cb9a53 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Gajesh2007
Gajesh2007 merged commit 07b4896 into main Oct 22, 2026
5 of 6 checks passed
@Gajesh2007
Gajesh2007 deleted the ttft/serving-stalls branch October 22, 2026 00:31
Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 22, 2026
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>
Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 22, 2026
…nts warm (#1545)

* Keep busy engines' MLX buffer pool and paged KV segments warm

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>

* Reclaim retained KV segments on memory pressure

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>

* Drop the MLX buffer pool before evicting a model for a cold load

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>

* Release retained KV segments before a cold load evicts or refuses

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>

* Test that the standalone headroom gate releases retained KV segments

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>

* docs: idle-gated cache sweep and retained paged KV segments

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>

* fix(provider): forward the serving-stall rollbacks to launchd

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>

* Stop waiting for retained KV segments once a load is cancelled

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>

* refactor(provider): name the reclaimer flush; describe the windowed sweep

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>

* test(provider): pin segment-retention wiring and release-before-eviction 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>

* docs: match the serving-stall wording to the code

- 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>

* Re-pin libs/mlx-swift-lm to the merged SDK change (#328)

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>

* fix(provider): signal a shortfall reclaim on refused native MiMo media charges

MiMoV26ManagedMediaReservation charges the process ledger directly, so
its refusals never reached recordReservationRefusal or the engine-owner
callback. With busy engines keeping MLX's buffer pool and retained KV
segments, a media reservation a release or flush would fit could keep
failing until the Mac idled.

Each insufficientCapacity refusal (initial charge, decode working bytes,
native plan adoption, recheck) now signals the same shortfall-gated
reclaim. The ledger snapshot omits the media path's extra system
reserve, which can shrink headroom by at most its own size, so the
signalled shortfall is an upper bound: retained segments are always
asked back, and the cache is flushed only when it certainly covers the
refusal. GlobalKVCacheBudget.directChargeRefusalSignal builds the signal
for both direct-charge owners and is nil under the existing kill switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(provider): keep engine-refusal reclaim signals on while segments are retained

signalsEngineRefusals followed only the idle-sweep kill switch, so with
DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0 and segment retention still on, a
refused engine-owned growth no longer asked other pools to drop their
retained segments, which no cache flush reaches.

One predicate, busyEnginesKeepReclaimableMemory (idle sweep or
retention on), now drives both the refusal signal and the load gates'
one-time release-and-flush pass. The production budget takes its
environment as a defaulted parameter so the wiring is tested directly
rather than through the test initializer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(provider): release retained KV segments in the Nemotron Super load gate

Managed Super loads bypass evictUntilAvailable, so their gate neither
released retained free KV segments nor dropped the buffer pool busy
engines now keep before evicting an idle model or refusing, and its
pre-accept counted retained segments as used. Super loads could evict
needlessly, refuse a load that fits, or be fast-rejected.

evictUntilNemotronSuperFits now runs the ordinary gate's one-time
release-and-flush pass before its first eviction and before refusing
with nothing idle; reclaimableMemoryBytes counts retained segments, so
the reachable room both gates plan with includes them, and
nemotronSuperLoadIsCertainToFail counts them in its nothing-evictable
branch. The release-then-flush step is one helper,
releaseReclaimableMemoryForLoad, on ProviderLoop and StandaloneServer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(provider): reclaim retained KV segments before skipping a startup preload

A startup preload candidate whose shortfall the previous model's
retained segments (or the kept buffer pool) covered was skipped and left
cold until its first request, because the preloader compared free
memory without the release the load gates run.

StartupPreloader takes a reclaimBeforeSkip hook: on a short sample it
releases what a load reclaims without evicting, then resolves the live
requirement (Super's tracks its claim room) and samples free memory
again before skipping. ProviderLoop and StandaloneServer wire it to
releaseReclaimableMemoryForLoad. Preload still never evicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(provider): make the idle cache flush atomic with request admission

The idle sweep rechecked WholeMacServiceBudget.isIdle and then
synchronized and cleared, so a request admitted in between started on a
pool being emptied. When the recheck bailed out, flushIfDue still
stamped lastReclaimAt and recorded a reclaim, suppressing a real
shortfall reclaim for the rate-limit interval.

The idle flush now fences outside the budget, then clears inside
WholeMacServiceBudget.performIfIdle, which runs its body under the same
lock as admission and device-activity starts: a request admitted first
cancels the clear, and one arriving during it is admitted afterwards.
An idle Mac has no charged GPU work, so the clear does not wait on
evals while holding the lock. Flush callbacks report whether they ran,
and only a flush that ran records a reclaim and starts the next window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): describe exactly which load paths release retained KV segments

The changelog, configuration reference and hardware-support page said
cold loads release retained segments before evicting or refusing. Name
the paths that do (the provider, standalone and managed Nemotron Super
load gates, and the startup-preload check), state that the post-load
headroom guard measures without releasing them (that backing was already
counted as used when the gate admitted the load), and document the
idle flush's atomicity with admission and the direct-charge refusal
signal (native MiMo media included, on while retention is on).
inference.md now cites repo paths and symbols instead of bare file names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(provider): tidy the serving-stalls review follow-ups

Behavior-preserving cleanup from the independent refactor pass:

- busyEnginesKeepReclaimableMemory's comment now names every direct
  charge that signals a reclaim (directChargeRefusalSignal), not only
  engine-owned growth, since native MiMo media reservations use it too.
- idleOperationHoldsOffAdmission records the idle operation and the
  admission as ordered events instead of reusing a pool-size field as a
  flag, so the assertion states the ordering it checks.
- Rewrap two over-long lines in hardware-support.md and inference.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(provider): report the exact ledger deficit for refused direct charges

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>

* fix(provider): count usage inside the reserve in the refusal shortfall

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>

* fix(provider): count retained KV segments as eviction credit only until 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>

* docs(provider): note which refusals skip the retained-segment release

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>

* Place standalone load-headroom sentence apart from sibling PRs' edits

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>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant