Repository navigation
fix(KVCache): keep the ChunkedKVCache offset and the MambaCache slots - #268
Merged
Merged
Conversation
The state of ChunkedKVCache came from KVCacheSimple. Its setter set the offset to the buffer length, which is smaller than the offset after maybeTrimFront(), so a loaded prompt cache had a wrong offset. The state now holds only the valid tokens, and the state and metaState setters keep offset - startPosition equal to the token count. The saved format does not change. MambaCache.extract(_:) went through state, which drops the empty slots. It now copies every slot, as ArraysCache.extract does. Fixes #239 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Oct 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implementation
Related issue: #239. Dependency stack: #214 -> #253 -> #268 (neutral references).
ChunkedKVCache.statesaves exactlyoffset - startPositionvalid rows. The state and metadata setters preserve absolute offset in either setter order.ArraysCache.extractSlots(_:to:)preserves empty slot positions; Mamba extraction retains its dynamic type and all optional slots.0...(-1); existing class metadata determines layer count, including empty middle/trailing layers. Empty fixed-arity caches skip their fatal nonthrowing state setter.PromptCacheValidation.swiftbefore nonthrowing restoration setters: reject malformed metadata arity, invalid numeric values, invalid array inventories and unsafe nested CacheList counts with a thrown error, not a fatal setter or silent numeric fallback.ArraysCache.advance()legitimately makes it negative; the loader now accepts signedIntpadding while retaining parse/range rejection and all other inventory/position guards. This fixes an introduced rejection on the earlier preparation headd4a75147.05cf778635eb3d940d394c68ce8a09a62f95db32). Diff over that parent contains only persistence/extraction runtime work, its tests and its fork-map topic.Runtime scope over updated parent:
Libraries/MLXLMCommon/KVCache.swiftandLibraries/MLXLMCommon/PromptCacheValidation.swift. No public signature changes or new file format.Storage Contract
Retains existing array keys
i.j, metadata keys0.i.j,1.key,2.i, Chunked metadata[chunkSize, startPosition], slot-aware Arrays/Mamba metadata and documented legacy compact state ([""]). Existing unrelated named arrays remain ignored as the legacy recording requires. The old valid Chunked and Mamba fixtures remain readable. Missing layers are reconstructed only from existing class declarations, not guessed.Left-padding entries accept signed integers, including legitimate negative values after
advance(). This does not relax nonnegative slot indices/counts, chunk positions, metadata arity, nested inventory bounds or integer parsing. Nonnumeric, overflowed and malformed comma-separated padding still throws.Historical Chunked files saved after trimming and a later update can contain padding indistinguishable from tokens. Their original valid token count cannot be recovered; this change does not invent a compatibility heuristic or claim to repair such data. Malformed declared state/metadata is now conservatively rejected. Direct in-memory nonthrowing setters retain their existing precondition behavior; validation is at the throwing file-loading boundary, not a claim of comprehensive hostile-file sandboxing.
Before
After
Fresh Validation (2026-10-03)
Head:
96d5f9761baa6055818af068a7f96bc5a9cdefbb, GitHub verificationverified=true, reasonvalid. Only this PR was updated for the signed-padding correction; parent heads remain unchanged.ruby cache-stack-validate.rb 268-padding-fixed;./268-padding-fixedon CPU andREVIEW_GPU=1 ./268-padding-fixedunder the shared mutex: 34 tests pass on each device. Actual authored copy, trim, Chunked/Mamba persistence suites; eleven durable validation tests; assertion-preserved cache recordings and prompt-file recordings through their serialization section.d4a75147all fail with invalid-cache errors (exit 1); parent05cf7786passes all three; corrected source passes. Additional malformed-padding cases still reject bad text, empty elements, mixed invalid signed text and integer overflow.readonly-cache-review-20261003-0924. Fresh differential and CPU/GPU logs are retained separately incache-stack-evidence/268-padding-*.logandpadding-results.json, collected bycache-stack-padding-evidence.rb. The older 31-test run did not cover advanced negative padding and was insufficient to establish that compatibility.e031bf20: unpopulated file test traps in0...(-1)(signal 5); malformed arity traps in Chunked metadata setter (signal 5); mixed/nested empty-layer test fails with cache-count mismatch (exit 1); numeric-only test fails with two missing-error expectations (exit 1). All pass after the fix.git diff --checkand strict Swift format lint on both new files pass. WholeKVCache.swiftstrict lint still reports seven pre-existing naming/forEach findings; it was not renamed broadly to hide baseline lint debt.0f4fe403, Cmlx core3fa8f25e, mlx-c02cf6f4d; owned immutable Metal SHA-2562129f6132794d84243c02631bc7478417dba0e0dbd10467beab56c11bf20bdd2. Local harness/evidence: isolatedheld-pr-prep-20261003/cache-stack-*scratch. Not a fresh full SwiftPM suite or provider/checkpoint qualification.Serving Risk And Stack Gates
Generic
ChatSession.saveCachecalls this serializer; consumers can restore vialoadPromptCache. Current library model constructors do not select ChunkedKVCache. Do not equate these SDK tests with canonical provider CBv2 qualification, which uses distinct cache paths.Base remains
fix/chunked-kvcache-trim. GitHub reports MERGEABLE against this parent, not independent main readiness. Exact new-head lint 37112426292 and fork-map 37112426301 pass; Fork Tests 37112426248 is in progress. Earlier-head checks are not substituted for these. Post-push refresh found no reviews, threads or comments; refresh again before merge. The independent negative-padding finding is addressed and differentially verified, not waived.Only after #214 actually merges may #253 be retargeted to main. Only after #253 actually merges may this PR be retargeted to main, with own-only diff/checks revalidated before merge. No merge, deploy, retarget or shipment is performed by this preparation.
Combined Integration Validation
On 2026-10-03, the current prepared heads of the twelve held PRs were composed
on a local-only validation branch based on main
3799b115, including thesigned-padding compatibility correction
96d5f976. No PR was merged.swift build --build-tests -j 4completed successfully.five optional fixture-dependent XCTest cases skipped. Advanced Arrays/Mamba
and nested signed-padding round trips passed in this composed build.
passed, with no failures or skips, covering paged backend, scheduler,
checkpoint engine, SSM bounds, Nemotron storage/priming, OpenAI service and
tool parser paths.
swift test --skip-build --filter ... --no-parallelunder the shared GPU mutex. This is focused integration validation, not a
full-package, real-weight or provider qualification. Exact compatible MLX
dependency tuple and immutable Metal artifact were verified before staging.
git diff --checkandpython3 scripts/check_forkdiff.pypassed.Existing assertions remain intact; this evidence does not waive required
latest-head CI, review, or parent-first retarget/revalidation gates.