Repository navigation
fix(provider): checkpoint KV restore reservation leaks/races (0.6.5 blocker; review of #325) - #326
Conversation
…eview of #325) Three reservation-correctness bugs in the prefix/KV checkpoint restore path (found reviewing #325), each of which broke the '#324 worst case = cold prefill, never OOM' guarantee: 1. Reservation leak on materialize fallback: when materialize fell back to a cold prefill, the request kept the restore-sized charge in BOTH the scheduler token budget (bridge.reservedTokens) and the global KV byte budget for its whole life -> admission starvation under the OOM pressure that triggers restore failures. materializeRestoredCheckpoint now returns Bool; a shared finalizeRestore helper (used by both submit paths) downgrades both systems to the cold footprint on fallback. Adds GlobalKVCacheBudget.reduceReservation (atomic shrink-only; release+reserve would be non-atomic and could strand the request with no reservation). 2. Use-after-release race: a cancel/timeout during the materialize await could release KV + drop the bridge while the RAM-copy/SSD-decrypt was in flight. materialize now re-checks the bridge is still present after the await and discards the materialized caches (returns false) if the request was cancelled. 3. Under-reserved restore: reserveKVForRequest downgraded a failed restore-sized reservation to cold but still returned success, and the submit path materialized the restore anyway -> restore-sized KV against a cold reservation -> OOM under the exact pressure that caused the downgrade. It now reports .restoreReserved / .coldReserved / .failed; the restore is materialized only when the restore-sized reservation actually held. Provider-side only; no coordinator changes. swift build clean; tests: BatchSchedulerBudget 21/21 (8 new), PrefixCache 96/96, BatchScheduler 51/51.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This PR fixes a KV-cache reservation accounting bug; the changes are internally consistent, no mitigations are weakened, and one latent memory-safety issue that could have become a cross-tenant data boundary is closed. Trust Boundaries Touched
Threat AnalysisT-028 — Residual inference data in GPU memory (Information Disclosure) ✅ Strengthens mitigation The old code had a use-after-release gap: T-041 — Cross-tenant prefix-cache TTFT timing oracle (Information Disclosure) ℹ️ Neutral (accounting fix, not sharing boundary) The T-007 / T-027 — Provider serves manipulated model outputs (Tampering) ℹ️ Neutral
New Attack Surface / FindingsTest seam in production actor — low severity, flag for review
Open SEC Findings ResolvedNone resolved by this PR. SEC-007, SEC-016, SEC-035 remain open and are unaffected. 🔐 Threat model: |
Layr-Labs/mlx-swift-lm#326 squash-merged as f2eb29b8 ("fix(gptoss): keep bf16 activations through the expert SwiGLU clamp (#326)"). Move the gitlink from the PR branch head 4aaf012c to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings master through #1516 (GLM-5.3-Flash) and pins mlx-swift-lm main 889fe3cc, which contains #322 (Flint) as merged plus #324 and #326-#330. Conflicts keep Flint and GLM side by side: sampling defaults honor Flint and the exact GLM identities; backend preparation passes Flint's model type and keeps GLM's paged target; the advertised context is GLM's for a GLM target, else Flint's, else the existing limits; request validation runs Flint's policy beside GLM's controls and MiMo's tool restoration; native tool failures name GLM, Flint or MiMo; both sampling-default tests stay. The DiffusionGemma Responses expectation takes master's form.
#1539) * fix(gptoss): pin the SDK that keeps GPT-OSS activations and KV in bf16 Pin libs/mlx-swift-lm to the GPT-OSS bf16 activation fix (741d2d0c, on top of mlx-swift-lm c17693f5, #316). The SDK's expert SwiGLU clamp used float32 `MLXArray` bounds, which promoted every layer after layer 0 of a bf16 gpt-oss-20b checkpoint to float32 activations and K/V. Scalar bounds keep the checkpoint dtype. Provider sizing already reads the observed native K/V types, so the gpt-oss-20b native full-attention rate falls from 49,152 to 24,576 bytes per token in admission, paged storage and the heartbeat without a logic change. The `fullRowsUseFP32` fallback stays: production slots always supply observed types, and the fallback over-reserves rather than under-reserves. Its comments and the EngineV2KVSizing header now say so. Complete-checkpoint identity binds per-layer dtypes, so float32-era GPT-OSS SSD checkpoints land in another namespace and are never restored; matching prompts prefill cold until new checkpoints exist. Docs: the prefix-cache checkpoint sizes, the inference `gpt_oss` row, the provenance of the gpt-oss-20b activation floor and the constant-cast cache row. The fleet geometry fixture's GPT-OSS row is bf16 on every layer. Adds changelog.d/gptoss-bf16-activations.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(gptoss): correct the remaining float32 GPT-OSS sizing notes Pin libs/mlx-swift-lm to 4aaf012c, one test-and-comment commit on top of 741d2d0c on the SDK pin branch. The SDK's catalog window reservation test now prices gpt-oss-20b with bf16 K/V (4,462,452 bytes reserved per checkpoint instead of the float32 7.6 MB), and the staged-window budget comment quotes that ~4.5 MB reserved figure rather than the 3.15 MB logical window. SDK library behavior is unchanged. The `EngineV2Bridge.kvBytesPerToken` comment still said contiguous GPT-OSS adds an fp32 owning-full-row delta and that paged slots stay fp16. Ordinary CBv2 slots price the observed native per-layer K/V types through `EngineV2SlotFactory.slotKVBytesPerToken`; the comment now says so. The changelog fragment says "every layer after the first" instead of the gpt-oss-20b-specific "layers 1-23", and that admission, paged storage and checkpoint identity use the observed native K/V types instead of sizing from them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Pin libs/mlx-swift-lm to the SDK change on master's SDK commit The paired SDK PR branch (ttft/gptoss-bf16-activations) was published on SDK main 0351444e, which also carries mlx-swift-lm #323 and #325 that d-inference master does not pin yet. Pin ttft/gptoss-bf16-activations-pin (c4947f7a) instead: the same commits cherry-picked onto 0351444e, the SDK commit master pins, so this PR adds only this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Revert "Pin libs/mlx-swift-lm to the SDK change on master's SDK commit" d-inference master now pins SDK main 0351444e (#1531), the base the paired SDK PR branch (ttft/gptoss-bf16-activations) was published on, so the PR head is already the right pin and the cherry-picked ttft/gptoss-bf16-activations-pin copy is redundant. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-pin libs/mlx-swift-lm to the merged SDK change (#326) Layr-Labs/mlx-swift-lm#326 squash-merged as f2eb29b8 ("fix(gptoss): keep bf16 activations through the expert SwiGLU clamp (#326)"). Move the gitlink from the PR branch head 4aaf012c to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(provider): cite the gpt-oss-20b activation-floor measurement The floor's float32-activation basis was asserted without evidence. Cite the 2026-07-10 sweep report that sized it and the SDK history showing that revision still clamped the expert SwiGLU with float32 bounds (51ea0c4b until f2eb29b8). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(provider): restamp the GPT-OSS bf16 docs hardware-support.md, inference.md, prefix-cache.md and configuration.md changed for the bf16 GPT-OSS activations; set their freshness stamps to the UTC date of the change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The PR's own KV-subtracted activation probe at eight rows of 32,768-token prompts, inside the floors' measurement range of eight rows at 4k tokens or more, shows 2,048 / 4,096 pushing GPT-OSS from its 3.5 GiB floor to 3.62 GiB and Qwen3.5-9B from 5.73 to 6.03 GiB against the 5.5 GiB default. No margin absorbs that: UnifiedMemoryCap.liveKVHeadroomBytes grants KV until MLX usage plus the reserve reaches the cap, so activation above the reserve lands past the cap once the KV budget is full. Floors are measured constants that move only with platform admission, so they stay unchanged here. usesWidePrefillChunk now selects Gemma 4 alone (3.73 GiB at 32k against 5.5). GPT-OSS and dense Qwen3.5/3.8, including the unmeasured Qwen3.8-27B, keep 512 / 2,048 and their stripes; DARKBLOOM_CBV2_PREFILL_CHUNK=2048 with DARKBLOOM_CBV2_STEP_TOKENS=4096 still opts them in for measurement. Tests pin GPT-OSS and dense Qwen to the SDK geometry and drive the GPT-OSS busy-engine and pool-lockstep cases through the opt-in. The GPT-OSS and Qwen live checkpoint fixtures no longer need to pin the SDK geometry and return to master's form; prefix-cache.md returns to master because no recurrent family takes the wide chunk by default. The report gains a default-scope section with the per-cell margins and names the SDK revision the probes ran on (cef662176, before SDK #326's GPT-OSS bf16 activations). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Raise CBv2 mixed-step prefill geometry for GPT-OSS, dense Qwen and Gemma 4 With one partial prefill a busy engine prefills only its plain chunk beside decode rows, so production fed every mixed step 512 prompt tokens. GPT-OSS, dense Qwen3.5/3.8 and Gemma 4 now default to a 2,048-token plain chunk and a 4,096-token step budget (EngineV2Factory.prefillGeometry). The chunk replaces the 2,048-token GPT-OSS and Gemma stripes and stays below dense Qwen's 4,096-token stripe, so paged ring sizes, KV charges and load quotations are unchanged. Other families keep 512 / 2,048. Gemma 4 image and video requests keep 512-token chunks through the SDK's new bidirectionalMediaPrefillChunkCeiling (libs/mlx-swift-lm moves to the commit that adds it): a paged span-bearing chunk attends in one unblocked call, so its score tensor grows with the chunk length times the history. DARKBLOOM_CBV2_PREFILL_CHUNK and DARKBLOOM_CBV2_STEP_TOKENS override the geometry for every family and reach the launchd provider job; 512 / 2048 rolls back. Scheduler-prefill receipts record the geometry (schema 5), the decision live runner pins its simulated geometry, and fixtures that pin a stripe also pin the SDK chunk. Docs, a dated measurement report and a changelog fragment record the load, inter-token latency and activation evidence and its limits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Document the Gemma 4 block ring bound and tighten geometry comments Behavior-preserving refactor-pass follow-up to the prompt geometry change. - inference.md invariant 9: a Gemma 4 block chunk stays within the 2,048-token ring because Gemma4Processor delimits every image and video frame, not because submit validation bounds blocks, which now admits them up to the 4,096-token step. - configuration.md: a solo stripe that does not exceed the plain chunk, including an equal one, is disabled. - productionSchedulerConfig: the media ceiling comment names bidirectional media, which is all the ceiling applies to. - SegmentedFleetGeometry: window rings follow the largest schedulable chunk, which for GPT-OSS and Gemma is now the plain chunk, not a stripe. - libs/mlx-swift-lm moves to the SDK commit that files the ceiling tests under Unit/Scheduling, matching SDK main; no library change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Record why the Gemma benchmark wrapper schema stays at 6 Raw scheduler-prefill schema 5 adds the plain chunk and step budget. Like the raw sweep 8 / arrival 6 note, say why the wrapper schema does not move: the default workload's prompts each fit one chunk and no step exceeds 2,048 tokens, so the Gemma 4 geometry change does not alter its chunking; longer prompts beside decode rows do not compare across the change. Comment only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: untangle the recurrent-bank paragraph after the master merge The merge kept both sides of the conflicting prefix-cache.md paragraph, which repeated two sentences. Keep this branch's 2,048-token plain chunk and master's Nemotron Super alignment sentence once each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-pin libs/mlx-swift-lm to the merged SDK change (#331) Layr-Labs/mlx-swift-lm#331 squash-merged as c8dce97d ("Add an opt-in plain-chunk ceiling for bidirectional media requests (#331)"). Move the gitlink from the PR branch head 204771c4 to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-pin the SDK to f77b384c and adapt to its tool-call delta type The previous pin, c8dce97d (#331), also carries SDK #332: chunk deltas now carry [OpenAIToolCallDelta] and MLXServerGenerationEvent gains .toolCallDelta, so ProviderLoop+SSEParser.swift no longer compiled. Pin f77b384c, the merged SDK main commit that adds #333's MLXLMServerTests build fix on top of #331 (same library tree). The SSE parser and the six test-file hunks are copied byte for byte from #1549 (ttft/stream-auto-tool-calls), so whichever of the two lands second merges cleanly. They change types only; this branch does not request streamed fragments, so complete calls hash and encode as before. Flint response-format code added by master's #1552 also switches over MLXServerGenerationEvent; it ignores .toolCallDelta like .toolCall, and its tests count a completed delta as a call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Fill the schema-5 geometry in the merged prompt-mode receipt test Master's #1535 added SchedulerPrefillPromptTests against schema 4. After the merge its receipt fixture omitted this branch's new required prefillChunkTokens and maxBatchedTokensPerStep and expected schema 4 from a current-version report, so the test target failed to compile. The fixture now records the SDK geometry and expects the current schema; the legacy case decodes a faithful schema-4 payload without the geometry fields. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Carry the schema-5 prompt geometry into gptoss_profile summaries summarize_cell copied only soloPrefillStripeTokens from a scheduler-prefill receipt. Under the wide plain chunk a nil stripe no longer means 512-token chunks, so derived summaries could not tell a default run from an explicit chunk or step-budget arm. Prefill rows now also keep prefillChunkTokens and maxBatchedTokensPerStep (None for schema-4 receipts, which lack them). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the wide prompt geometry default for Gemma 4 only The PR's own KV-subtracted activation probe at eight rows of 32,768-token prompts, inside the floors' measurement range of eight rows at 4k tokens or more, shows 2,048 / 4,096 pushing GPT-OSS from its 3.5 GiB floor to 3.62 GiB and Qwen3.5-9B from 5.73 to 6.03 GiB against the 5.5 GiB default. No margin absorbs that: UnifiedMemoryCap.liveKVHeadroomBytes grants KV until MLX usage plus the reserve reaches the cap, so activation above the reserve lands past the cap once the KV budget is full. Floors are measured constants that move only with platform admission, so they stay unchanged here. usesWidePrefillChunk now selects Gemma 4 alone (3.73 GiB at 32k against 5.5). GPT-OSS and dense Qwen3.5/3.8, including the unmeasured Qwen3.8-27B, keep 512 / 2,048 and their stripes; DARKBLOOM_CBV2_PREFILL_CHUNK=2048 with DARKBLOOM_CBV2_STEP_TOKENS=4096 still opts them in for measurement. Tests pin GPT-OSS and dense Qwen to the SDK geometry and drive the GPT-OSS busy-engine and pool-lockstep cases through the opt-in. The GPT-OSS and Qwen live checkpoint fixtures no longer need to pin the SDK geometry and return to master's form; prefix-cache.md returns to master because no recurrent family takes the wide chunk by default. The report gains a default-scope section with the per-cell margins and names the SDK revision the probes ran on (cef662176, before SDK #326's GPT-OSS bf16 activations). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Raise undersized Gemma 4 chunk overrides to cover a whole media block A Gemma 4 chunk that starts at a bidirectional media block extends over the whole block, and submit validation bounds blocks only by the step budget, but the paged window rings hold max(chunk, stripe) tokens. With DARKBLOOM_CBV2_PREFILL_CHUNK=256 and DARKBLOOM_CBV2_SOLO_PREFILL_STRIPE=0 the rings held 256 tokens and a 280-token image block tripped the PagedSequenceKV precondition, killing the provider. prefillGeometry now raises a Gemma 4 chunk to 1,120 tokens, the vision family's largest image budget, whenever the override leaves max(chunk, stripe) below it. The default 2,048-token chunk, the documented 512 / 2,048 rollback (its 2,048-token stripe re-arms) and other families are unchanged. A geometry test pins the raised values; an engine test prefills a 300-token block beside decode under chunk 256 with the stripe off. With the guard disabled the first fails and the second stops on "windowed update of 300 tokens exceeds maxPrefillChunk 256". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Record the prompt geometry the built engines actually ran in receipts The scheduler-prefill receipt took prefillChunkTokens, maxBatchedTokensPerStep and soloPrefillStripeTokens from EngineV2Factory.prefillGeometry before production applied later policy: glm5NextServingScheduler (2,048 / 2,048, stripe off), the calibrated Nemotron clamp and any dedicated scheduler policy. A GLM or Nemotron run could therefore be attributed to the generic geometry. ProductionBuild now carries prefillGeometry, taken from the scheduler configuration assembleProductionBuild hands the engine. The benchmark records the warm-up engine's value and fails the run if a measured engine was built with different geometry, so one report-level field never describes samples it does not cover. A test builds a tiny paged GPT-OSS engine with and without a scheduler policy that narrows the chunk, step and stripe, and checks the build reports the narrowed geometry rather than prefillGeometry(model:). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Count only completed tool-call deltas in the Flint test helpers, as #1549 does FlintResponseFormatTests counted every .toolCallDelta event as a call, so it disagreed with FlintAnswerStopTests and with #1549 (ttft/stream-auto-tool-calls), which count a delta only when it completes a call. Both helpers now match #1549's files byte for byte, so this branch and #1549 merge without conflicts in either file. Behavior is unchanged: this branch does not request streamed fragments, so its engines emit only whole .toolCall events. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Raise undersized Gemma 4 step budgets to cover a whole media block e19f138 kept the windowed rings at least one Gemma 4 media block wide, but submit validation also refuses a block longer than the step budget (CBv2MultimodalPlan.validate). With a chunk below the block, a stripe that already covers it and an explicit step budget equal to the small chunk (for example 256 / 1,120 / 256), the ring guard did not fire and every image request failed with spanTooLong although the rings could hold the block. prefillGeometry now raises a Gemma 4 step budget below 1,120 tokens (gemma4MaximumMediaBlockTokens) to 1,120. Defaults, the 512 / 2,048 rollback and other families are unchanged. A geometry test pins the raised budget and that other families keep theirs. A real paged Gemma 4 engine test submits a 300-token block under chunk 256, stripe 1,120 and step 256. With the clamp removed, the geometry test fails and the engine test catches .spanTooLong(blockTokens: 300, maxBatchedTokensPerStep: 256). inference.md invariant 9 records the budget bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Name the families whose policy replaces the prompt geometry overrides The prompt-geometry docs said an explicit DARKBLOOM_CBV2_PREFILL_CHUNK applies to every family. Three later policies replace or cap it: glm5NextServingScheduler sets GLM5Next's own 2,048-token chunk and step; NemotronSuperLocalPrefill.Policy.apply sets Nemotron Super local serving's chunk (DARKBLOOM_NEMOTRON_SUPER_PREFILL_CHUNK) and step; and calibratedPrefillTokenLimit caps calibrated Nemotron chunks. inference.md and the configuration rows now name these exceptions, and point to the receipts' built geometry. The STEP_TOKENS row also records the Gemma 4 media-block budget raise. The changelog said solo prefill is unchanged. Solo chunking is, but the 2,048-token Gemma stripe used to shrink to 512 tokens once when KV could not be reserved, and a plain chunk does not. On contiguous KV (Gemma 4 artifacts other than the catalog's paged gemma-4-26b-qat-4bit, or with paging disabled), such a prompt now waits or is preempted. The fragment now says so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Place prefill-geometry passthrough test apart from sibling PRs' insertions Move forwardsPrefillGeometryRollbackToProviderJob up beside forwardsPrefillOperationalControlsUnchanged, mirroring the key order in inferencePassthroughEnvKeys, so it no longer shares an insertion point with the serving-stalls test after the deadline-admission test. Pure move; the test body is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Why
Code review of #325 (and tracing the path) surfaced three reservation-correctness bugs in the prefix/KV checkpoint restore path. Each breaks the core promise of #324/#325 — "the worst case of a restore is a cold prefill (recompute), never a crash, never an OOM." These must land before v0.6.5 is cut (the fleet is still on 0.6.4, so this is a release-blocker, not a live-fire issue).
The three bugs (all provider-side, all in the restore path)
materializeRestoredCheckpointfell back to cold prefill, the request kept the restore-sized charge in both the scheduler token budget (bridge.reservedTokens) and the global KV byte budget for its whole lifetime → progressive admission starvation under the OOM pressure that triggers restore failures. Fix:materializeRestoredCheckpointnow returnsBool; a sharedfinalizeRestorehelper (used by both submit paths) downgrades both systems to the cold footprint on fallback. NewGlobalKVCacheBudget.reduceReservationdoes an atomic shrink (release-then-reserve would be non-atomic and could strand the request with no reservation).materializeawait could release KV + drop the bridge while the RAM-copy/SSD-decrypt was still in flight. Fix:materializere-checks the bridge is still present after the await and discards the materialized caches if the request was cancelled.reserveKVForRequestdowngraded a failed restore-sized reservation to cold but still returned success, and the submit path materialized the restore anyway → restore-sized KV against a cold reservation → OOM under the exact pressure that caused the downgrade. Fix: it now reports.restoreReserved/.coldReserved/.failed; the restore is materialized only when the restore-sized reservation actually held.Verification
Provider-side only — no coordinator changes.
swift buildclean; tests: BatchSchedulerBudget 21/21 (8 new regression tests pinning all three fixes + the shrink-only contract), PrefixCache 96/96, BatchScheduler 51/51. Reviewed by codex + an independent reviewer; happy-path / no-budget / normal-cold paths confirmed byte-equivalent.Follow-up to #324 (
broadcast_shapes/metal::malloccrash guards) and #325 (plan/materialize split). Bundle this into the v0.6.5 provider release.🤖 Generated with Claude Code
Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.