Skip to content

perf(provider): keep busy engines' MLX buffer pool and paged KV segments warm - #1545

Merged
Gajesh2007 merged 27 commits into
masterfrom
ttft/serving-stalls
Oct 22, 2026
Merged

Gajesh2007 merged 27 commits into
masterfrom
ttft/serving-stalls

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

SDK dependency: done. The paired SDK PR, Layr-Labs/mlx-swift-lm#328, is merged as 07b48961. master's SDK pin 889fe3cc already contains it, so this PR changes no gitlinks. libs/mlx-swift-lm 889fe3cc, libs/mlx-swift 67dc7528 and libs/mlx ad4745a2 are identical to master. There is nothing to re-pin, and the SDK PR imposes no landing order.

Summary

This PR removes two GPU stalls that serving engines hit while they are busy.

  1. The proactive MLX cache sweep. Every capacity tick (2 s in ProviderLoop, 5 s in the standalone server), the sweep flushed the buffer pool whenever it held 2 GiB or more. Each flush ran synchronize plus clearCache under 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.
    • The sweep now waits for 5 s of whole-Mac idleness and flushes without reporting device activity.
    • The idle clear runs inside 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.
    • While engines serve, the sweep flushes only when the pool crowds out admission headroom (KVPoolReclaimer.proactiveWindow).
    • Refused direct charges now signal the same shortfall-gated reclaim that request reservations already use (GlobalKVCacheBudget.directChargeRefusalSignal). These are engine-owned KV growth and native MiMo media reservations.
  2. Per-admission paged KV segment growth. The SDK change (perf(cbv2): retain free paged KV segments and grow new ones from host-zeroed pages mlx-swift-lm#328, already in master's pin) lets segmented pools keep free 64 MiB segments across requests and grow new ones from host-zeroed pages. Growth needs no device fill, eval, fence or eval lock.
    • This PR turns that on with a cap of min(2 GiB, grant / 8) per pool.
    • It also wires the release paths. Retained segments are dropped on any refused charge, on a pressure sweep or a macOS memory-pressure event, and after 30 s of engine idleness.
    • The provider, standalone and managed Nemotron Super load gates release them once (releaseReclaimableMemoryForLoad) before they evict a resident model or refuse.
    • Startup preload releases them before it skips a model.
    • Load admission counts retained segments as reclaimable only to decide whether that one-time release could make room. After the release, only the memory it actually returned counts; segments a busy engine has not yet dropped earn no eviction credit.

Three rollbacks restore the old behavior, and darkbloom start now forwards them to the launchd provider job.

Commit Change
2994a3f01 Keep busy engines' MLX buffer pool and paged KV segments warm Idle-gated sweep window, the engine-refusal reclaim signal, segment retention and host zeros in the segmented backend factory. This commit also moved three gitlinks (SDK PR head 4cb9a532, libs/mlx-swift 81f58d79, libs/mlx 71271f08). The merges below superseded those moves, and none is in the final diff
f648a3ba9 Reclaim retained KV segments on memory pressure Shortfall reclaims, pressure sweeps and macOS memory-pressure events ask engines to drop retained segments. Adds KVPoolIdleSweepTests
5bc489590 Drop the MLX buffer pool before evicting a model for a cold load ProviderLoop.evictUntilAvailable and StandaloneServer.ensureMemoryHeadroomForLoad flush the pool and resample once before they unload a resident model
5f55449ce Release retained KV segments before a cold load evicts or refuses Retained bytes count as reclaimable. The ordinary and standalone gates and the pre-accept self-heal release them and wait up to 250 ms
89fee7f14 Test that the standalone headroom gate releases retained KV segments A gate that may not evict still releases parked backing, then refuses without unloading the resident model
121bf1c9c docs: idle-gated cache sweep and retained paged KV segments architecture/inference.md, architecture/hardware-support.md, provider/direct-mode.md, reference/configuration.md
ddc7214cd fix(provider): forward the serving-stall rollbacks to launchd Named keys, LaunchAgent.inferencePassthroughEnvKeys, a test, provider/cli-reference.md
bd8756520 Stop waiting for retained KV segments once a load is cancelled Refactor pass. The load-time wait sleeps through taskSleep and returns on cancellation. Adds cancelledLoadReleaseStopsWaiting
a639da76b refactor(provider): name the reclaimer flush; describe the windowed sweep Refactor pass, no behavior change
6004c57fd test(provider): pin segment-retention wiring and release-before-eviction order Refactor pass, tests only
9b1354a78 docs: match the serving-stall wording to the code Refactor pass. inference.md, hardware-support.md, configuration.md and the changelog fragment
e0af12748 Re-pin libs/mlx-swift-lm to the merged SDK change (#328) Moved the gitlink from the SDK PR head 4cb9a532 to its squash commit 07b48961. Superseded by the next merge
bac7955cc Merge master Took master's pins (889fe3cc / 67dc7528 / ad4745a2); 889fe3cc contains 07b48961. The message reads "pin libs/mlx-swift-lm to ." because the SHA is missing. The pin it kept is 889fe3cc
5a3debea4 Merge master (8f6958689) No conflict resolutions (git show --remerge-diff is empty); pins unchanged
78cf584d7 fix(provider): signal a shortfall reclaim on refused native MiMo media charges Review follow-up, see below
a36bb33ed fix(provider): keep engine-refusal reclaim signals on while segments are retained Review follow-up
d99cdd309 fix(provider): release retained KV segments in the Nemotron Super load gate Review follow-up
ac5180a6a fix(provider): reclaim retained KV segments before skipping a startup preload Review follow-up
87ec8456d fix(provider): make the idle cache flush atomic with request admission Review follow-up
5a11393f9 docs(provider): describe exactly which load paths release retained KV segments Changelog, configuration.md, hardware-support.md, inference.md
bd3b96746 refactor(provider): tidy the serving-stalls review follow-ups Independent refactor pass, no behavior change
558c02506 fix(provider): report the exact ledger deficit for refused direct charges Review follow-up, see below
a60cbd26a fix(provider): count usage inside the reserve in the refusal shortfall Independent review of 558c02506, see below
83efeeadc fix(provider): count retained KV segments as eviction credit only until released Review follow-up, see below
0c84ac4d5 docs(provider): note which refusals skip the retained-segment release Independent review of 83efeeadc, docs only

The changelog fragment is changelog.d/serving-stalls.md.

Merging current master

  • GlobalKVCacheBudget.swift: kept master's configReserveBytes, flushCache (and its fenced clear in the test initializer), reservationBytesSnapshot() and returnCachedBuffers() alongside this branch's idle-sweep window, refusal signal and retained-segment release.
  • ProviderLoop+ModelLoading.swift: kept master's reclaimableMemoryBytes split, which the Nemotron Super gate also uses. Since d99cdd309, reclaimableMemoryBytes itself counts retained segments, because every gate that plans with it now releases them. Since 83efeeadc, 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:0px
Loading

After

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:0px
Loading

Legend:

  • blue: inputs
  • indigo: unchanged code
  • amber: decisions
  • red: stalls
  • green: new behavior
  • orange: reclaim and release paths
  • teal: the forwarded rollbacks

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 same mlx.metallib (SHA-256 fb1ba8f9…c85c).

Load shape:

  • a standalone server with 5 decode streams;
  • a cold arrival every 2 s (2,048, 512 or 4,096 prompt tokens, 128 output tokens) for 70 s, with the first 10 s excluded;
  • 12 sequential cold idle probes before the load.

Arms: off = DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0 DARKBLOOM_TTFT_SEGMENT_RETENTION=0; on = defaults.

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

Quiet GPU (no other job held a GPU slot in any sample; load average about 2-3):

Gemma 4 26B QAT, off → on (hold-q1.log) GPT-OSS 20B, off → on (hold-q4.log)
KV segment growth per admission, p50 / max 7.122 / 12.654 → 0.161 / 0.260 ms 3.100 / 6.551 → 0.052 / 0.121 ms
Busy-engine cache flushes during the load 10, 13-35 ms each → 0 12, 8-25 ms each (first 10 listed) → 0
Growth at the 12 idle probes 5.32-16.27 → 0.10-0.35 ms 5.28-13.54 → 0.06-0.37 ms
ITL p99 of the running streams 125.0 → 126.3 ms 100.6 → 100.9 ms
Arrival TTFT p50, 512 / 2,048 / 4,096 tokens 152.4 / 474.8 / 846.6 → 155.4 / 475.0 / 843.9 ms 180.2 / 414.4 / 772.9 → 177.2 / 403.9 / 784.0 ms
Idle-probe TTFT p50, 512 / 2,048 / 8,192 tokens (n = 4 each) 107.2 / 224.7 / 835.1 → 101.9 / 212.9 / 805.1 ms 124.0 / 309.1 / 1,085.0 → 122.5 / 297.9 / 1,058.6 ms
Request errors 0 → 0 0 → 0

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.

Run Growth p50, off → on Growth max, off → on Busy flushes, off → on
Qwen3.5-9B (hold-q2.log) 1.804 → 0.029 ms 4.109 → 0.098 ms 23 → 0
Qwen3.5-9B, 2 pairs (h3-q7.log) 5.518, 2.299 → 0.031, 0.032 ms 12.092, 10.088 → 0.122, 0.145 ms 13, 20 → 0, 0
GPT-OSS 20B, 2 pairs (h3-q9.log) 4.693, 4.761 → 0.070, 0.051 ms 11.122, 7.666 → 0.246, 0.196 ms 7, 6 → 0, 0
Gemma 4 + Qwen3.5-9B co-resident, 3 pairs (h3-q1.log, h3-q2.log) 5.394, 5.043, 6.532 → 0.193, 0.178, 0.164 ms 96.557, 396.242, 224.791 → 0.695, 0.989, 0.933 ms 28, 33, 28 → 0, 0, 0

Each switch alone (Gemma 4, quiet, hold-q5.log):

  • Retention off, idle sweep on: growth p50 8.913 ms, 0 busy flushes.
  • Idle sweep off, retention on: growth p50 0.156 ms, 8 busy flushes.

Decode (Gemma 4, darkbloom benchmark --sweep, 8,192-token context, 192 tokens, 2 iterations per arm; on ran first; h3-q10.log):

Aggregate tok/s B = 1 B = 4 B = 8
on 127.1, 132.0 248.1, 259.4 292.1, 293.2
off 132.5, 135.8 253.0, 261.8 287.9, 298.3

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.

  • On a quiet, single-model M5 Ultra, end-to-end ITL p99 and TTFT are at parity. The removed stalls (milliseconds per admission, tens of milliseconds per flush) are small next to the arrivals' prefill chunks.
  • The large growth stalls (up to 396 ms) appeared only with co-resident GPU work. The TTFT effect of removing them is not demonstrated end to end.
  • None of these measurements were rerun after the master merges or the review follow-ups.

Review follow-ups

Fixed:

Review thread Fix
(P1) Reclaim retained segments before Nemotron Super admission d99cdd309. evictUntilNemotronSuperFits runs the one-time release-and-flush pass before its first eviction and before refusing with nothing idle. reclaimableMemoryBytes counts retained segments, and nemotronSuperLoadIsCertainToFail counts them in both branches. Tests: retainedSegmentsReleaseBeforeSuperEviction, superRefusalReleasesRetainedSegmentsFirst, superPreAcceptCountsRetainedSegments (replaced in 83efeeadc, next-but-one row)
(P2) Make the idle recheck atomic with the cache flush 87ec8456d. The clear runs inside WholeMacServiceBudget.performIfIdle under the admission lock. Only a flush that actually ran stamps lastReclaimAt and records telemetry. Tests: idleOperationHoldsOffAdmission, declinedIdleFlushLeavesRateLimitOpen
(P2) Keep refusal signaling enabled while segments are retained a36bb33ed. signalsEngineRefusals follows busyEnginesKeepReclaimableMemory (idle sweep or retention on). The production GlobalKVCacheBudget.init takes a defaulted environment, so the test covers the real wiring. Test: engineRefusalSignalFollowsKillSwitches
(P2) Reclaim retained segments before skipping a startup preload ac5180a6a. StartupPreloader.Dependencies.reclaimBeforeSkip: release, re-resolve the requirement, resample, then skip. ProviderLoop and StandaloneServer wire it to releaseReclaimableMemoryForLoad. Tests: shortSampleReclaimsBeforeSkipping, shortSampleReleasesRetainedSegmentsBeforeSkipping
(P2) Signal retained release for native media reservation refusals 78cf584d7. MiMoV26ManagedMediaReservation takes onRefusal from directChargeRefusalSignal(). Every insufficientCapacity refusal signals a shortfall reclaim; the next row makes that shortfall exact. Test: testCapacityRefusalSignalsShortfallReclaim
Docs overclaimed which load paths release retained segments 5a11393f9. The docs now name the exact paths and say that the post-load KV headroom guard does not release them. inference.md cites repo paths plus symbols
(P2) Compute media reclaim from the binding headroom (review of bd3b96746) 558c02506, a60cbd26a. ProcessMemoryLedger.capacityShortfall(growthBytes:additionalSystemReserveBytes:) returns, under the ledger lock with a fresh usage read, how far usage must fall for (charged - materialized) + growth to fit the headroom admission checks. That is the larger of the cap-side deficit needed + reserve + (active + cache) - cap and the OS-side deficit needed + 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.signalShortfall and EngineProcessMemoryOwner.replace both 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, processLedgerCapacityShortfallIsTheBindingDeficit
(P1) Exclude unreleased segments from eviction credit (review of a60cbd26a) 83efeeadc, docs 0c84ac4d5. 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. evictUntilAvailable and evictUntilNemotronSuperFits pass !poolDropped, so neither can evict an idle model for room the load never gets. fastAdmissionReject and nemotronSuperLoadIsCertainToFail (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 (replaces superPreAcceptCountsRetainedSegments, which asserted the old credit)

Follow-ups (deferred, not in this PR):

  • Flush after device-filled retained segments are released (review thread, P2). reclaimIfNeeded measures and flushes before engines honor the release at their next step.
    • This only matters where released backing is device-filled: the non-default DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0, or segment sizes that are not page-granular. Default host-zeroed segments are unmapped on release.
    • The rollback case matches master's freed-to-cache behavior, and the load gates wait for the release before they flush.
    • Planned fix: a follow-up flush once each pool has honored the release.
  • GlobalKVCacheBudget.recordReservationRefusal under-reports its shortfall. The request-reservation path is unchanged from master and outside this PR's diff. It still reports bytes - 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: report processLedger.capacityShortfall(growthBytes: bytes), the helper the direct charges now use.
  • The 250 ms release wait on the pre-accept reject path and on short-of-memory loads waits for the global gauge to reach zero. Since 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.
  • Ordinary pre-accept re-check after the release suspension (independent review of 83efeeadc, non-blocking, predates this round). In the ordinary fastAdmissionReject path, the re-check after the release omits nativeMiMoRefusesRequest, which the Super branch re-checks, and the final slot-cap check reuses hasEvictable from before the suspension. 83efeeadc adds 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.
  • Idle-flush lock hold. performIfIdle holds the service-budget lock while MLX.Memory.clearCache() takes MLX's evalLock. 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.

Command Outcome
cd provider-swift && swift build --build-tests -j 12, then ../scripts/stage-test-metallib.sh .build/out/Products/Debug Build complete, no errors or warnings in changed files
swift test --skip-build --no-parallel --filter 'ModelLoadEvictionAndAdmissionTests|NemotronSuperManagedSlotTests|KVPoolIdleSweepTests' Passed: 72 tests in 3 suites
Fails-without-fix check, run separately by the implementer and the independent reviewer: ProviderLoop+ModelLoading.swift and ProviderLoop+NemotronSuperAdmission.swift reverted to a60cbd26a, rebuilt, then the five new tests All five fail (10 issues). The ordinary and Super gates evict the idle model and the ordinary gate then refuses ("all loaded models are actively serving"); both pre-accepts admit; superPreAcceptAdmitsTheRoomTheReleaseReturns fails only on parkedBytes == 0, since the old pre-accept never released. With the fix restored, all pass
Broad affected suites: ModelLoad|NemotronSuper|KVPoolIdleSweep|StartupPreload|StandaloneServerModelAdmission|Autopilot|Qwen4MemoryRetirement|NativeMemoryRetirement|ProcessMemoryLedger|GlobalKVCacheBudget|KVPoolReclaimer|Qwen4ReclaimAdmissionTests|RetirementGateTests|ServiceReservationHandlerTests|AudioInputRejectionTests|FlintReasoningVisibilityTests|OuterPrefixCacheReceiptTests|ProviderCancelledPrefixCacheTests, skipping mimoProviderStartupPlanUsesScannerNativeLoad and standaloneMiMoStartupPlanUsesNativeLoadEnvelope Passed. Swift Testing: 497 tests in 62 suites plus 30 in 5. XCTest: 39 executed, 0 failures, 1 skipped. The reviewer's run of the same filter without the last four suites: 477 in 58 plus 30 in 5, XCTest 39 / 0 failures
The two skipped MiMo startup-plan tests, run unskipped Fail only because MIMO_V26_SERIAL_LOAD_FIXTURES is not set on this host (MiMoDiscoveryFixture.copyTiny); unrelated to this change. CI's explicit MiMo selections cover them
make docs-check; make docs-impact-check BASE=origin/master; make changelog-check 190 file(s) OK; 33 changed file(s), coverage OK; 45 valid fragment(s)
git log --show-signature Good ED25519 signatures on 83efeeadc and 0c84ac4d5

Previous round, at a60cbd26a (Apple M3 Ultra, 512 GB). The test daemon state was isolated with DARKBLOOM_STATE_FILE and DARKBLOOM_LOADED_MODELS_FILE, as scripts/run-provider-tests.sh does. 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.

Command Outcome
cd provider-swift && swift build --build-tests -j 12, then ../scripts/stage-test-metallib.sh "$(swift build --show-bin-path)" Build complete, no errors; metallib staged (156f2624…)
swift test --skip-build --no-parallel --filter 'testCapBoundRefusalSignalsOnlyTheCapDeficit|testCapacityRefusalSignalsShortfallReclaim|engineRefusalInDebtSignalsWholeDeficit|engineRefusalSignalsShortfall|processLedgerCapacityShortfallIsTheBindingDeficit' Passed. XCTest: 2 tests, 0 failures. Swift Testing: 3 tests
Mutation check: the previous signalShortfall and EngineProcessMemoryOwner.replace formulas restored, new tests kept testCapBoundRefusalSignalsOnlyTheCapDeficit got [6000, 7000, 5000] instead of [2000, 3000, 1000]; engineRefusalInDebtSignalsWholeDeficit got 1 GiB instead of 2 GiB. The system-binding testCapacityRefusalSignalsShortfallReclaim and engineRefusalSignalsShortfall still passed, as expected
Mutation check: the 558c02506 capacityShortfall body restored, the saturated-regime assertions kept processLedgerCapacityShortfallIsTheBindingDeficit failed with 2 issues: expected 810, got 800; expected 1,820, got 800
Memory and MiMo admission suites: MiMoV26ManagedMediaReservationTests|KVPoolIdleSweepTests|processLedger|GlobalKVCacheBudget|KVPoolReclaimer|SystemMemoryAdmission|ProcessMemoryLoadConstraint|ProcessHostBufferReservation|ProcessMemoryPreparation|ProcessMemoryTelemetry|MiMoMemoryAdmission|MiMoV26MediaPhaseAdmission|KVPoolSweepWiring|SegmentedProductionGrant, skipping the three cases that need their own runners (next rows) Passed at both 558c02506 and a60cbd26a. XCTest: 12 tests, 0 failures. Swift Testing: 99 tests in 7 suites
scripts/run-nested-suite.sh processLedgerCannotCombineOldUsageWithNewMaterializationCredit --no-parallel Passed at both commits: 1 test
At 558c02506: scripts/run-nested-suite.sh ProcessMemoryNativeIntegrationTests --no-parallel, and scripts/run-exclusive-native-gpu-test.sh evaluatedPagesAvoidDoubleTaxAndRetainedAliasKeepsPressure emptyNativePoolTeardownUsesActualRetiredAdapter passed. The nested runner's skip guard tripped only because the exclusive allocator test skips without DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST; run through its own script, it passed (1 test)
At 558c02506: swift test --skip-build --no-parallel --filter 'MiMoV26NativeLoadTransactionTests|MiMoV26EncodedAudio|MiMoV26ManagedAudioProvider|MiMoV26EncodedAudiovisualIngress' Non-fixture cases passed. Eight MiMoV26NativeLoadTransactionTests cases need MIMO_V26_SERIAL_LOAD_FIXTURES, which is not set on this host, and stopped with FixtureError.fixtureRequired. CI's explicit MiMo selections cover them
make docs-check; make docs-impact-check BASE=origin/master; make changelog-check; git diff --check 190 file(s) OK; 33 changed file(s), coverage OK; 45 valid fragment(s); no whitespace errors

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

Command Outcome
cd provider-swift && swift build --build-tests -j 8, then ../scripts/stage-test-metallib.sh "$(swift build --show-bin-path)" Build complete, exit 0; metallib staged (156f2624…)
swift test --skip-build --no-parallel --filter 'KVPoolIdleSweepTests|KVPoolReclaimerTests|KVPoolReclaimerNativeGateTests|KVPoolSweepWiringTests|GlobalKVCacheBudgetSelfHealTests|GlobalKVCacheBudgetTests|GlobalKVCacheBudgetProcessTests|MiMoV26ManagedMediaReservationTests|MiMoV26MediaPhaseAdmissionTests|StartupPreloaderTests|StartupPreloadGateTests' Passed. Swift Testing: 70 tests in 5 suites plus 1. XCTest: 11 tests, 0 failures
The 26 GlobalKVCacheBudget* test functions, plus NemotronSuperManagedSlotTests|ModelLoadEvictionAndAdmissionTests|StandaloneServerModelAdmissionTests|GlobalKVCacheBudgetAuditTests|ProcessMemoryLedgerTests|LaunchAgentRestartTests Passed. Swift Testing: 188 tests in 17 suites plus 6 in 5. XCTest: 5 tests, 0 failures. This includes the three new Super gate tests
MiMo media and deadline suites: MiMoV26Encoded*, MiMoV26ManagedMediaReservationTests, MiMoV26MediaPhaseAdmissionTests, PrefillEvidenceRecoveryTests, UnboundedDeviceWork, Deadline*, ProcessMemoryLedger Passed. XCTest: 37 executed, 9 skipped (native MiMo fixtures sit behind their own gates), 0 failures. Swift Testing: 43 passed
Mutation check: each of the eight fixes reverted in place, then the nine new regression tests run All nine fail (13 issues across 8 Swift Testing tests, plus testCapacityRefusalSignalsShortfallReclaim). After restoring the fixes, all pass
Independent reviewer, final tree: KVPoolIdleSweepTests|KVPoolReclaimerTests|GlobalKVCacheBudgetSelfHealTests|StartupPreloaderTests|StartupPreloadGateTests|MiMoV26ManagedMediaReservationTests|NemotronSuperManagedSlotTests|ModelLoadEvictionAndAdmissionTests|StandaloneServerModelAdmissionTests|LaunchAgentRestartTests Passed: 159 tests in 10 suites plus 1, 0 failures. A separate reviewer mutation, running the performIfIdle body outside the lock, fails idleOperationHoldsOffAdmission
./scripts/docs-check.sh; DOCS_IMPACT_BASE=origin/master python3 scripts/docs-impact-check.py; python3 scripts/changelog.py check 190 file(s) OK; 31 changed file(s), canonical documentation coverage OK; 45 valid fragment(s)
mmdc on the two figures above Both parse and render

Earlier rounds (M5 Ultra, on the pre-merge pins: SDK PR head 4cb9a532, mlx-swift 81f58d79, MLX 71271f08). The staged mlx.metallib was byte-identical to the one the measured builds used. At 9b1354a78, after the first refactor pass:

  • The 10 focused GPU suites passed: 118 tests, including cancelledLoadReleaseStopsWaiting and segmentedFactoryAppliesRetentionRollbacks.
  • The CPU suites passed: 76 tests in 9 suites.
  • The SDK focused suites passed: 73 tests in 9 suites.
  • A mutation check removed the old wait loop, the release before eviction and the DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS read. The tests caught each removal.

After the first master merge (bac7955cc):

  • the debug build had 0 errors;
  • KVPoolReclaimer|GlobalKVCacheBudget|LaunchAgent passed 134 of 135 (1 opt-in skip);
  • KVPoolReclaimerNativeGateTests passed 3 of 3;
  • KVPoolIdleSweep|ModelLoadEvictionAndAdmission|StandaloneServerModelAdmission passed 55 of 55;
  • master's three Super eviction tests passed 3 of 3.

Logs are in scratchpad/pr/stalls-work/logs/ and scratchpad/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 0 from the process environment, and darkbloom start forwards 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=0 restores the threshold-only sweep, which flushes between busy engines' steps.
    • With retention still on, refused direct charges keep signalling a reclaim, and the load gates keep their release-and-flush pass. Each of those sweeps also asks engines to drop their retained segments, which are parked again at the next release (hold-q5.log: 8 busy flushes, growth p50 0.156 ms).
    • With both this and DARKBLOOM_TTFT_SEGMENT_RETENTION=0 set, neither the refusal signal nor the release-and-flush pass runs (busyEnginesKeepReclaimableMemory).
  • DARKBLOOM_TTFT_SEGMENT_RETENTION=0 restores release-time segment trimming and device-filled segments.
  • DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0 keeps retention but grows new segments with the device fill plus fence.

Interface and capacity effects

  • No schema change. Protocol, telemetry, manifest and quotation schemas are unchanged.
  • Retained segments and accounting. Retained segments are uncommitted, so no grant, floor or ledger charge covers them. They are still allocator-active memory, which process headroom sees as used until they are released.
  • Load admission. reclaimableMemoryBytes counts 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).
  • Post-load guard. The post-load KV headroom guard re-measures after its cache flush without releasing retained segments. That backing was already counted as used when the gate admitted the load.
  • Busy-provider memory. A busy provider now keeps up to its MLX cache limit in the buffer pool, plus up to 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.
  • Heartbeat values. On a busy provider, free_for_load_gb, load_usable_gb and free_for_load_no_evict_gb count 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.
  • Platform capacity review. Idle and pressure reclaim are unchanged in kind. Busy engines hold more reusable memory between capacity ticks than before.

Limitations

  • Hardware. Everything was measured on M5 Ultra only. The fleet is mostly M3 Ultra, M4 Max and M5 Max, and no M3 Ultra A/B has run. Before relying on this on M3 Ultra, run a benchmark --sweep decode 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.
  • Decode. In the one Gemma 4 decode pair above, on was 3.4% lower at B = 1 (mean of 2 iterations). That is within the 3.8% spread between the on arm's own iterations, and B = 8 was at parity. A repeated, order-balanced decode A/B is still owed.
  • End-to-end TTFT gain unproven. The quiet runs are at parity. The shared-GPU runs show the stall mechanism removed, but their contended end-to-end numbers are not usable.
  • Contiguous-backend reservations. These reserve worst-case bytes up front. While busy, they see less headroom, because the pool is kept while remaining ≥ pool + 2 GiB. A refusal triggers the shortfall flush, so a retry fits. Watch the kv-budget refusal telemetry during rollout.
  • Errors in the shared-GPU runs. Those runs returned "Response generation failed" for some arrivals in both arms: off 8, 3 and 2 of 19 arrivals, on 1, 3 and 3 (scratchpad/stalls/r3-*/*.json). One Gemma off run's server died. The quiet runs had no errors. The cause was not determined.
  • Retained memory stays resident for up to 30 s after an engine idles, unless pressure, a refused charge, a load gate or a startup-preload check releases it first.

Landing notes

Refactor pass

First pass (independent; commits bd8756520 to 9b1354a78). It reviewed the code, tests, docs, changelog and figures, and checked every number in this description against its log.

  • Fix. A cancelled load's wait for retained segments spun until its 250 ms deadline, and it used the generic Task.sleep(for:) overload that TaskSleep.swift tells ProviderCore to avoid. It now sleeps through taskSleep and returns on cancellation.
  • Names and comments. flushIfDue's parameter shadowed the stored clearCache. The sweep comments still described the sweep from before the window.
  • Tests. The pass pinned the factory's retention wiring and made the release-before-eviction test record the parked bytes, so the test fails without the release.
  • Docs. The pass fixed four places where the docs disagreed with the code.

Second pass, on this round's follow-ups (independent reviewer; commit bd3b96746, no behavior change).

  • The pass verified all six fixes:
    • the Super gate releases once and counts retained bytes in every branch;
    • performIfIdle checks idleness under the admission lock, with no reverse lock order;
    • the refusal signal follows busyEnginesKeepReclaimableMemory;
    • the preload keeps its order and never evicts;
    • the MiMo shortfall is an algebraic upper bound (made exact this round, see below);
    • the master merge has an empty remerge diff, and its pins equal master's.
  • Cleanup:
    • The busyEnginesKeepReclaimableMemory comment now names every direct charge that signals a reclaim.
    • idleOperationHoldsOffAdmission asserts ordered events instead of reusing a pool-size field as a flag.
    • Two over-long doc lines are rewrapped.
  • Its non-blocking notes are listed under Follow-ups above.
  • Left as is.
    • The DARKBLOOM_TTFT_* names follow the sibling TTFT PRs.
    • The standalone server has no macOS memory-pressure monitor, so only the other release paths apply there.

Third pass, on the exact shortfall (independent reviewer of 558c02506; fix commit a60cbd26a).

  • The pass verified that:
    • capacityShortfall checks (charged - materialized) + growth against the same headroom that install and recheckCharge admit against, under the ledger lock with a fresh usage read;
    • the growth each MiMo call site (init, decode growth, native-plan adoption, recheck) and EngineProcessMemoryOwner.replace pass matches what admission charged;
    • wherever headroom is positive, the old formula is never lower than the new one, so nothing that was reclaimed before is now under-reported.
  • Fix. The first helper subtracted the admission headroom, which floors at zero once active + cache memory sits inside the activation reserve below the cap, or OS-available memory falls below the reserves. Refusals cluster there. The helper then reported only outstanding + growth, so the reclaimer could flush a cache that could not admit the retry. It now returns the larger of the unfloored cap-side and OS-side deficits; the result is identical wherever headroom is positive. New saturated-regime assertions pin 810 B and 1,820 B where the first helper returned 800 B.
  • Doc. The MiMoV26ManagedMediaReservation.onRefusal comment no longer calls the signal an upper bound. docs/architecture/hardware-support.md describes the exact shortfall with a path + symbol citation; the changelog fragment needed no change.
  • Its non-blocking note (recordReservationRefusal) is listed under Follow-ups above.

Fourth pass, on the eviction-credit fix (independent reviewer of 83efeeadc; docs commit 0c84ac4d5).

  • The pass traced each gate and confirmed:
    • evictUntilAvailable and evictUntilNemotronSuperFits cannot 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;
    • fastAdmissionReject keeps 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;
    • nemotronSuperLoadIsCertainToFail mirrors its gate, and its caller re-checks the MiMo, Super and retirement refusals and residency after the suspension;
    • no reserve, headroom or KV safeguard changed, and StandaloneServer, Autopilot and capacity reporting never used this credit.
  • It independently reproduced the fails-without-fix result (5 tests, 10 issues). The Swift change needed no cleanup.
  • Doc. docs/architecture/hardware-support.md now 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 (matching docs/architecture/inference.md).
  • Its non-blocking note on the ordinary pre-accept re-check is listed under Follow-ups above. The changelog fragment and docs/reference/configuration.md keep their summary-level wording.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

Gajesh2007 and others added 11 commits October 21, 2026 17:32
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>
@vercel

vercel Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Ready Ready Preview Oct 22, 2026 9:53pm UTC
d-inference-console-ui-dev Ready Ready Preview Oct 22, 2026 9:53pm UTC
d-inference-landing Ready Ready Preview Oct 22, 2026 9:53pm UTC
darkbloom-status Ready Ready Preview Oct 22, 2026 9:53pm UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 22, 2026 9:53pm UTC

Request Review

@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-22T21:58:14.066974Z 1d3ae2b New commits
ℹ️ 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.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head 1d3ae2b7312f against base b02d39e5aac3.

Review not completed for this head. Previous findings are superseded, not confirmed resolved.
Bedrock request allowance reached; no fallback around the limit

Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging.

Failure diagnostics: BEDROCK_CALL_LIMIT

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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Gajesh2007 and others added 2 commits October 22, 2026 02:00
…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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Gajesh2007 and others added 2 commits October 22, 2026 03:17
…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>
jonathan308
jonathan308 previously approved these changes Oct 22, 2026
Gajesh2007 and others added 2 commits October 22, 2026 14:41
# 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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

if isRefusedByRetirement(modelId) { // retirement began mid-retry

P2 Badge Recheck the native MiMo fence after releasing segments

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

@Gajesh2007
Gajesh2007 merged commit c6d4a57 into master Oct 22, 2026
31 checks passed
@Gajesh2007
Gajesh2007 deleted the ttft/serving-stalls branch October 22, 2026 22:06
@Gajesh2007 Gajesh2007 mentioned this pull request Oct 22, 2026
3 of 6 tasks

This branch was successfully deployed

5 active deployments
Preview – d-inference-console-ui-dev — 1d3ae2b7 Deployed Oct 22, 2026 by vercel[bot]
Preview – d-inference — 1d3ae2b7 Deployed Oct 22, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — 1d3ae2b7 Deployed Oct 22, 2026 by vercel[bot]
Preview – d-inference-landing — 1d3ae2b7 Deployed Oct 22, 2026 by vercel[bot]
Preview – darkbloom-status — 1d3ae2b7 Deployed Oct 22, 2026 by vercel[bot]
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.

2 participants