Skip to content

[DO NOT MERGE] Continuous batching: integrated stack (whole-diff CI + review) - #23

Draft
ronaldmannak wants to merge 56 commits into
mainfrom
claude/continuous-batching-pr-review-2w9fl3
Draft

ronaldmannak wants to merge 56 commits into
mainfrom
claude/continuous-batching-pr-review-2w9fl3

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Jul 2, 2026 •

Copy link
Copy Markdown
Owner

Proposed changes

Draft on purpose — this PR is never merged. It exists so CI and code review run against the whole integrated diff of the continuous-batching stack, catching cross-PR seam issues that the individual PRs cannot surface.

This is the integration branch: the full cb2-1…cb2-8 chain (PRs #24–#31) plus the content deliberately kept out of the upstreamable PRs — BatchQuantizedKVCache and its suites (deferred until the engine can construct quantized batched caches), the quantized factory branch, and the review records under reviews/.

Update 2026-07-13 — rebuilt from the audit-hardened chain. A 40-agent audit (report: reviews/continuous-batching-audit-2026-07-13.md) verified every finding of the 2026-07-02 readiness review against HEAD and ran a fresh adversarially-verified hunt. All fixes are folded into their chain PRs (each PR's description lists its share); this branch = chain tip + quantized extras (now with the M-15 trim clamp and the extract pad clamp it was missing) + review docs. Highlights:

Reviewers, please focus on Libraries/MLXLMCommon/Batching/ and the diffs to KVCache.swift, Gemma2.swift, Gemma3nText.swift, Mistral3Text.swift, ModelContainer.swift. The reviews/ directory is review reporting, not product code.

Known-open items deliberately not addressed here (flagged in the audit report §4–§7): public-surface demotion of the engine/cache strata (decide @_spi(Batching) vs internal before upstreaming — downstream forks may link these types), PromptCaching insert-snapshot symmetrization and sync-vs-async, upstream coordination with ml-explore PR ml-explore#335 (deprecates ModelContainer) for PRs 6–8.

Checklist

  • I have read the CONTRIBUTING (github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

🤖 Generated with Claude Code

https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn

@gemini-code-assist

Copy link
Copy Markdown

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

Copy link
Copy Markdown
Owner Author

/gemini review


Generated by Claude Code

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces continuous-batching and prompt-caching infrastructure to the MLX language model common library, including the batch generation engine, an inference scheduler with single-to-batch auto-upgrading, and batched KV cache implementations. The review feedback highlights several critical correctness and performance improvements: falling back to the zero-overhead single-stream path instead of the batch engine when the joining request is the only active one (such as when the single task finishes, is already done, or has an unsupported cache topology); optimizing queue draining in InferenceScheduler to avoid O(N^2) array operations; and correcting a precondition in PrefillBatch.extend that currently prevents merging active requests.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +1191 to +1197
guard let liveBox else {
// The single task finished before it could deposit state. Its
// stream is already (or about to be) closed by its own loop; start
// the joining request fresh.
await admitToBatch(joining)
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

When the single task finishes before depositing state, the joining request is the only active request. Starting it via admitToBatch runs it on the batch engine, introducing unnecessary batching overhead. It should instead be started on the zero-overhead single-stream path using startSingleAfterUpgradeFallback.

        guard let liveBox else {
            // The single task finished before it could deposit state. Its
            // stream is already (or about to be) closed by its own loop; start
            // the joining request fresh.
            startSingleAfterUpgradeFallback(joining)
            return
        }

Comment on lines +1265 to +1281
if liveTokenIsStop || remainingBudget <= 1 {
// The original is already done: EOS reached, or delivering the live
// token reaches `budgetLimit` (no room for the batch to add another
// without overshooting). Finalize it cleanly (delivering the final
// non-stop token only when one is actually undelivered) and run the
// joining request through the batch.
finishUpgradedSingle(
handler: single.handler,
lastToken: liveFinalToken,
promptTokenCount: single.inputTokens.count,
generatedCount: liveGeneratedTokenIds.count,
submitTime: single.submitTime,
reason: liveTokenIsStop ? .stop : .length
)
await admitToBatch(joining)
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

When the original request is already finished (EOS reached or budget exhausted), the joining request is the only active request. Starting it via admitToBatch runs it on the batch engine, introducing unnecessary batching overhead. It should instead be started on the zero-overhead single-stream path using startSingleAfterUpgradeFallback.

        if liveTokenIsStop || remainingBudget <= 1 {
            // The original is already done: EOS reached, or delivering the live
            // token reaches `budgetLimit` (no room for the batch to add another
            // without overshooting). Finalize it cleanly (delivering the final
            // non-stop token only when one is actually undelivered) and run the
            // joining request through the batch.
            finishUpgradedSingle(
                handler: single.handler,
                lastToken: liveFinalToken,
                promptTokenCount: single.inputTokens.count,
                generatedCount: liveGeneratedTokenIds.count,
                submitTime: single.submitTime,
                reason: liveTokenIsStop ? .stop : .length
            )
            startSingleAfterUpgradeFallback(joining)
            return
        }

Comment on lines +1285 to +1303
guard let batchedCaches = Self.migrateCaches(live.cache) else {
// Migration unsupported for this cache topology. The original's KV
// cannot be carried into the batch, so finalize it cleanly
// (delivering its last token + completion info — never truncate
// silently) and run the joining request fresh.
// TODO(PR4 auto-upgrade): extend fromSingle to SSM/composite so this
// fallback is unreachable for those models.
finishUpgradedSingle(
handler: single.handler,
lastToken: liveCurrentToken,
promptTokenCount: single.inputTokens.count,
generatedCount: liveGeneratedTokenIds.count,
submitTime: single.submitTime,
reason: .length
)
await admitToBatch(joining)
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

When cache migration is unsupported for the active single request, the original request is finalized and the joining request is started fresh. Since the joining request is the only active request, starting it via admitToBatch runs it on the batch engine, introducing unnecessary batching overhead. It should instead be started on the zero-overhead single-stream path using startSingleAfterUpgradeFallback.

        // Migrate the live caches LAST (consumes `live.cache`). After this point
        // `live` must not be read.
        guard let batchedCaches = Self.migrateCaches(live.cache) else {
            // Migration unsupported for this cache topology. The original's KV
            // cannot be carried into the batch, so finalize it cleanly
            // (delivering its last token + completion info — never truncate
            // silently) and run the joining request fresh.
            // TODO(PR4 auto-upgrade): extend fromSingle to SSM/composite so this
            // fallback is unreachable for those models.
            finishUpgradedSingle(
                handler: single.handler,
                lastToken: liveCurrentToken,
                promptTokenCount: single.inputTokens.count,
                generatedCount: liveGeneratedTokenIds.count,
                submitTime: single.submitTime,
                reason: .length
            )
            startSingleAfterUpgradeFallback(joining)
            return
        }

Comment on lines +438 to +443
var boxes: [SendableBox<GenerationRequest>] = []
boxes.reserveCapacity(requests.count)
var remaining = requests
while !remaining.isEmpty {
boxes.append(SendableBox(remaining.removeFirst()))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using removeFirst() in a loop results in O(N^2) complexity because removeFirst() shifts all subsequent elements in the array. Reversing the array once and using removeLast() (which is an O(1) operation) achieves the same FIFO order in O(N) total time.

        var boxes: [SendableBox<GenerationRequest>] = []
        boxes.reserveCapacity(requests.count)
        var remaining = Array(requests.reversed())
        while !remaining.isEmpty {
            boxes.append(SendableBox(remaining.removeLast()))
        }

Comment on lines +1463 to +1467
// cannot be sent while the array stays reachable, so each request is
// boxed and consumed at the `sending` boundary.
var boxes: [SendableBox<ScheduledRequest>] = []
boxes.reserveCapacity(queuedRequests.count)
while !queuedRequests.isEmpty {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using removeFirst() in a loop results in O(N^2) complexity because removeFirst() shifts all subsequent elements in the array. Reversing the array once and using removeLast() (which is an O(1) operation) achieves the same FIFO order in O(N) total time.

        var boxes: [SendableBox<ScheduledRequest>] = []
        boxes.reserveCapacity(queuedRequests.count)
        var remaining = Array(queuedRequests.reversed())
        queuedRequests.removeAll()
        while !remaining.isEmpty {
            boxes.append(SendableBox(remaining.removeLast()))
        }

Comment on lines +245 to +250
public func extend(_ other: PrefillBatch) {
precondition(
uids.isEmpty && other.uids.isEmpty,
"PrefillBatch.extend currently only supports merging two empty batches"
)
uids.append(contentsOf: other.uids)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The precondition uids.isEmpty && other.uids.isEmpty prevents merging any actual requests because uids represents the requests in the batch. To restrict merging to batches before prefill has run (as described in the comment), the precondition should instead check that the caches are empty (e.g., using innerState().isEmpty). Note that promptCache also needs to be re-allocated or merged to match the new combined batch size.

Suggested change
public func extend(_ other: PrefillBatch) {
precondition(
uids.isEmpty && other.uids.isEmpty,
"PrefillBatch.extend currently only supports merging two empty batches"
)
uids.append(contentsOf: other.uids)
public func extend(_ other: PrefillBatch) {
precondition(
(promptCache.first?.innerState().isEmpty ?? true) && (other.promptCache.first?.innerState().isEmpty ?? true),
"PrefillBatch.extend currently only supports merging two batches before prefill has run"
)

ronaldmannak pushed a commit that referenced this pull request Jul 2, 2026
- Upgrade fallback paths (single finished before deposit, original
  finished at handshake, migration unsupported) now start the joining
  request on the zero-overhead single path instead of the batch engine
  when it is alone — matching the existing ensureDriver-nil precedent —
  guarded on driver.hasWork so a third request already batching keeps
  the engine path (a single beside an active batch would decode
  concurrently with it). (Gemini review, 3x high)
- Boxing loops in submitBatch/drainQueuedRequests use reversed()/
  removeLast() instead of O(n^2) removeFirst(). (Gemini review, 2x)
- BatchModelRegressionTests: rms_norm_eps 1e-5 -> 1e-6; main's Gemma4
  fused decode path preconditions eps == 1e-6 and the old value crashed
  the xctest process (the remaining CI failure).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S

Copy link
Copy Markdown
Owner Author

Review feedback addressed in 99d3aa5:

  • 3× high (upgrade fallbacks batch a solo request): valid — these paths were inconsistent with the existing ensureDriver == nil precedent. All three now start the joining request via startSingleAfterUpgradeFallback, with one refinement over the suggestion: guarded on driver.hasWork, so a third request that was already admitted to the batch during the upgrade window keeps the engine path (starting a single beside an active batch would decode concurrently with it).
  • 2× medium (O(N²) removeFirst loops): applied the reversed()/removeLast() pattern in submitBatch and drainQueuedRequests.
  • 1× medium (PrefillBatch.extend precondition): intentionally not changed — this API has no production caller (the engine merges via DecodeBatch.extend) and is slated for removal in the re-cut chain rather than semantic repair; see the same finding triaged on Continuous batching (2/5): explicit batch engine (rebased on main) #19.

Same commit also fixes the remaining CI failure: BatchModelRegressionTests used rms_norm_eps: 1e-5 in its random-weight Gemma4 configs, which trips main's fused-decode precondition (Gemma4Text.swift:442, requires 1e-6) and crashed the test process — a cross-PR seam between cb-2's tests and current main that exactly this integrated PR exists to catch.


Generated by Claude Code

Fix Python finfo.min port in quantized attention masking
…ask fix (chain 1/6)

Neutral KVCache.swift plumbing for continuous batching (leftPadding in
createCausalMask, batched-cache routing in the legacy mask overload,
ArraysCache row extraction hooks, quantizedScaledDotProductAttention
GQA broadcast for 4-D batched masks — the fill-value fix itself landed
via #17), plus the Gemma2 attention-mask change it requires. Fork CI
builds the package.

NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics
(boolean mask added to logits -> where/-1e9); it needs a pinning test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
claude added 2 commits July 17, 2026 00:44
Delete the dangling TEMPORARY HOME block left behind when 996bacd removed
the local maskFill extension (the comment now sits over no code and falsely
tells a reader that fresh package resolution is broken), and drop the stale
'e.g. Gemma2' example from the legacy createAttentionMask overload -- Gemma2
was migrated to the modern single-cache overload.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
This branch changes ArraysCache.prepare(lengths:) to store absolute end
positions (lengths + leftPadding) instead of raw counts; the existing
KVCacheTests assertions still expected the old counts and fail on the full
test bundle at every branch of this chain -- invisibly, because the previous
per-branch CI filters never executed these free-function tests. Fold the
updated expectations (with their derivations) into the same PR that changes
the semantics, so the branch's own test bundle is green standalone.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
@ronaldmannak
ronaldmannak force-pushed the claude/continuous-batching-pr-review-2w9fl3 branch 3 times, most recently from c017c00 to db0ee7d Compare July 17, 2026 01:35
claude added 4 commits July 17, 2026 01:53
Replace the per-branch -only-testing filters (and this branch's build-only
job) with an unfiltered run of the whole MLXLMTests bundle. The bundle is
self-contained at every point in the chain (no model downloads), and an
unfiltered run is the only way to execute legacy free-function tests such as
KVCacheTests, which have no @suite type name for -only-testing to match --
the old filters hid exactly such a regression on every branch.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
This branch changes Gemma2's single-stream attention-mask numerics (the
boolean mask was previously ADDED to the logits as 0/1, so multi-token
prefill ran with no causal masking at all; masks are now applied via where
with a finite fill). Pin the corrected behavior in the same PR: prefill
causality (trailing-token edits leave earlier positions unchanged),
incremental-decode parity with full prefill, and softcap boundedness under
extreme weight scales. The batched-parity half of this suite lands with the
batched cache PR, which introduces BatchKVCache.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
The full-attention batched KV cache with left-padding row semantics,
the BatchedCache protocol + BatchedCacheList composite + SSM adapter,
and the topology factory (simple caches only in this PR; rotating lands
next, quantized is deferred). CI runs the cache/factory/mask suites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ve span in trimBatched

extend() reconciled neither side's pending prepare(rightPadding:) cycle:
a stale [B_old]-shaped _rightPadding surviving a batch-growing extend makes
the later finalize() roll fail with a broadcast shape error (or, for a
batch-1 receiver, silently broadcast one row's padding over every appended
row), and a prepared other's pending padding was dropped with its right-pad
columns left permanently unmasked. filter() already reconciles the field on
every row-set change; extend now preconditions that both sides are
finalized. Engine paths pair prepare/finalize inside one prefill call and
cannot hit this -- the guard closes the public-API seam.

trimBatched(perRow:) rolled the full step-rounded buffer where finalize()
deliberately rolls only the populated ..<_idx head slice; for a small batch
on a freshly grown buffer that is up to ~25x wasted gather work per layer
and it parked relocated dead-draft garbage in the spare tail. Mirror
finalize()'s head-slice roll.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
@ronaldmannak
ronaldmannak force-pushed the claude/continuous-batching-pr-review-2w9fl3 branch from db0ee7d to 63377d4 Compare July 17, 2026 01:54
claude added 28 commits July 17, 2026 02:04
Trie-based cross-request prompt cache (exact/shorter/longer prefix
matching, LRU + byte-budget eviction) behind the PromptCaching
protocol, plus the PromptCachePolicy hook on LanguageModel. Disk
persistence is deliberately NOT included — storage policy is an
app-level concern (annotated reference implementation preserved in
the integration branch under reviews/reference/).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
The longer-prefix branch of `search` walked the divergence node's
subtree with a DFS that rebuilt the accumulated token path for every
pushed node (`extra + [tok]`), O(N²/2) array copies over a long stored
tail. The walk runs inside `state.withLockUnchecked` on the driver
actor's hot path, so a new conversation diverging from a stored
multi-thousand-token entry stalled all decoding for up to seconds.

Replace it with a breadth-first walk: BFS dequeues nodes in increasing
depth, so the first cached node found is the shallowest — exactly the
"shortest cached descendant" the DFS selected (ties between same-depth
candidates were dictionary-order arbitrary before and remain so).
Descent still stops at the first cached node per path (cached nodes
never have their children enqueued). Parent links are recorded in a
temporary ObjectIdentifier-keyed dictionary and the token path is
reconstructed once, only for the winner, making the walk O(nodes
visited) — and BFS stops at the answer's depth instead of exhausting
the long tail.

Adds a divergence-fetch test with a 2008-token stored chain plus a
10-token sibling sharing an 8-token prefix, asserting the shorter
descendant wins (value-fingerprinted), pinning the selection semantics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
`fetchNearestCacheResult` ran the entire hit path — including
`deepCopy` → `materializedCopy` → `eval` of every layer's KV state —
inside `state.withLockUnchecked`. Deep-copying a long entry is GPU work
that can take seconds, and the lock is taken on the driver actor's
decode hot path, so a single large fetch stalled all concurrent
fetch/insert traffic.

Split the operation: under the lock, `lookupNearestCache` now does only
the trie search, LRU touch, and capture of the matched entry's stored
caches plus hit metadata (a new file-private `Lookup`); the deep copy,
the longer-hit `trimPromptCache`, and the `eval` run after the lock is
released. This is safe because stored entries are immutable after
insert (updates replace the whole `CacheEntry`) and ARC keeps the
captured arrays alive even if the entry is concurrently evicted — a
fetch racing an eviction may return a just-evicted entry, which is
acceptable cache semantics and documented at the copy site.

Public API and result semantics are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
The longer-prefix fetch branch deep-copied the FULL stored entry
(`materializedCopy` with `tokenCount: nil` copies every row) and then
only logically trimmed it — `trimPromptCache` just decrements offsets —
so the request carried the entire oversized backing buffer for its
lifetime, and `BatchKVCache.extend` padded the whole batch out to that
width.

Pass the matched prefix length as `tokenCount:` into the copy instead
(the same normalization the insert path already uses): `KVCacheSimple`
rows are sliced to the prefix by `stateSnapshot`, and linear
`RotatingKVCache` rows are trimmed and physically re-detached by
`normalizeRotating`. The explicit `trimPromptCache` pass is dropped —
the copy already lands at the prefix, so it would double-trim. Wrapped
rotating entries (where `normalizeRotating` would degrade to an empty
cache) never reach this path: `isTrimmable` is false once a rotating
cache wraps, so the existing `canTrimPromptCache` gate keeps refusing
them, as before.

The now-unused `deepCopy` helper is removed (it was just
`materializedCopy(_, tokenCount: nil)`).

Adds a test asserting the returned layers' `innerState()` buffers are
prefix-width (the `state` getter slices to `..<offset` and cannot see
an oversized buffer), pinning the physical truncation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Pre-upstream API slimming: the protocol carried two requirements the
library never exercises, baking one conformer's storage policy into
every conformer.

- `trim(nSequences:nBytes:)` was never called through the protocol
  (only LRUPromptCache itself and tests use it). It is removed from the
  protocol and kept as a concrete public method on LRUPromptCache,
  still forwarding to `trimTo(nSequences:nBytes:)`.
- The `checkpoint:` parameter on `insertCache` encodes LRUPromptCache's
  dual-pool eviction and was `false` at all three library call sites.
  The requirement is now `insertCache(model:tokens:promptCache:salt:)`;
  LRUPromptCache keeps the `checkpoint:`-taking overload as concrete
  API and adds a witness that forwards with `checkpoint: false`.

The protocol-extension default-argument helpers now only supply
`salt: 0`; the scheduler/driver call sites drop their `checkpoint:
false` arguments; the protocol doc spells out that eviction policy
(limits, checkpoint pools, trim scheduling) is deliberately conformer
policy, not contract. The conformance test exercises the slimmed
existential surface and the concrete-only trim/checkpoint API.

This narrows what alternate PromptCaching implementations (e.g. a
future block/paged cache) must implement to the two operations the
library actually drives: fetch on admission, insert on write-back.

(The two scheduler-layer call sites adapt in the scheduler PR of this chain,
where those files are introduced.)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
…API (chain 6/8)

The policy scheduler (idle -> single -> upgrading -> batched),
EngineDriver executor, GenerationRequest, and the
ModelContainer.generate / generateBatched entry points. ChatSession is
deliberately NOT scheduler-aware (decision 2026-07-02): batching is a
server-facing API; sessions keep their single-request KV path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
The protocol dropped its checkpoint: parameter in the prompt-cache PR
(always false at every library call site; checkpoint pools are
LRUPromptCache eviction policy, not part of the conformance contract).
Drop the argument at the scheduler/driver call sites introduced here.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Convenience front door for continuous batching: optional overloads of
loadModelContainer / loadContainer that install an InferenceScheduler
(and optional prompt cache) at load time, instead of requiring manual
ModelContainer(context:scheduler:promptCache:) construction. Pure
composition in one new file -- no existing declaration changes, and
`scheduler` has no default value so the plain loaders keep resolving
exactly as before (zero-overhead default untouched).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
Batched requests now reuse cached prompt KV: on admission the driver
fetches the nearest prefix from the request's prompt cache, migrates the
deep-copied hit into batch-1 batched caches (same fromSingle path the
single->batch upgrade uses), prefills only the remainder, and splices
the row into the running batch via makeAdoptedBatch/adoptActiveBatch.
Exact hits trim the final token's KV and re-feed it as the seed
(single-path parity). The topology salt mixed into promptCacheSalt
guarantees a hit's cache types always match the engine's factories.

Tests: warm-vs-cold token parity plus forward-pass width assertions
(a cache-hit admission never runs a full-prompt-width prefill).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
route() checks single.contextEpoch == contextEpoch before starting an
upgrade, but upgrade() then suspends at the withCheckedContinuation
handshake. A refreshContext (public ModelContainer.update) landing in
that window swaps the model and bumps the epoch, and the resume path
never re-checked — old-model KV was migrated into an engine built from
the new context (K/V computed by the old weights, decoded by the new
model), and the finalize paths wrote that KV back to the prompt cache
under a model name update() may not have changed.

- Capture the epoch before the suspension and re-validate right after
  the deposit is consumed; on mismatch, finalize the single cleanly on
  its already-produced tokens (never adopt, never truncate silently)
  and start the joining request fresh on the current context.
- Gate writeBackUpgradedSingle on the epoch too: update() can swap
  weights without renaming the configuration, so the captured modelName
  cannot be trusted to isolate a stale entry — skipping the write-back
  is the only safe choice. This also covers finalize paths reached via
  ensureDriver, which suspends and can observe a refresh mid-flight.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
…down driver

Three stale-driver gaps around refreshContext:

- ensureDriver never consulted driverStale: any existing driver was
  reused forever, so batches after a context refresh kept decoding with
  the old model whenever the deferred teardown was missed. Now a stale
  driver is returned only while it still drains (in-flight rows finish
  on the model they started with — the documented continuity rule);
  once idle it is torn down and rebuilt from the current context.
- The deferred teardown in batchLoopFinished sat BELOW the
  'guard case .batched' early return, so whenever a concurrent path had
  already moved the state machine on, the stale driver survived — idle —
  indefinitely. The teardown now runs before that guard (the driver is
  already confirmed idle and unraced at that point).
- ensureDriver assigned self.driver before its setMaxBatchSize awaits;
  a refreshContext during those suspensions nils/replaces the field,
  and returning the local would resurrect the discarded instance. It
  now re-checks identity after the awaits and returns whatever is
  current (possibly nil — callers already handle that).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Actors are not FIFO mailboxes: batchLoopFinished's 'await driver.hasWork'
can be served BEFORE a suspended admitToBatch's pending driver.submit, so
the admission-epoch guard passes (the bump happens on the scheduler, but
the submit has not landed on the driver yet) and the scheduler idles
under a row that is about to go live — subsequent lone requests would
then start 'single' beside an active batch.

Make the submit side self-healing: after driver.submit returns (in both
admitToBatch and the upgrade's phase-3 join), re-assert '.batched' if a
stale loop-finish idled the state meanwhile — never clobbering a
'.single'/'.pendingUpgrade' installed concurrently, whose request the
state machine still tracks — and restart the loop. EngineDriver.drain is
ownership-idempotent ('if draining { return false }'), so the redundant
restart is a no-op when the loop survived.

Also apply the same never-clobber rule to batchLoopFinished's driver-nil
branch, which unconditionally forced '.idle' over any concurrent state.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
…context

attachSchedulerIfNeeded keys the binding on the container's
ObjectIdentifier, but nothing ever cleared attachedOwner: once the
container died the scheduler stayed schedulerAlreadyAttached forever —
or worse, an identity recycled onto a NEW container could pass the
owner equality check and be silently served the dead container's
retained context (old model, old tokenizer).

- Add InferenceScheduler.detach(owner:): clears the binding, bumps the
  context epoch, and marks any driver stale, so nothing built from the
  retained context (a driver, an in-flight single's upgrade) survives.
  The context itself is kept for still-running requests.
- ModelContainer.deinit calls it. deinit is nonisolated: the identity
  and scheduler reference are captured before hopping to the actor.
- attach() now REPLACES the stored context (and prompt cache) when a
  NEW owner binds after a detach, with the same epoch/stale
  invalidation — the old keep-first-context behavior would have
  generated the new container's requests with the previous model. The
  same-owner idempotent path is preserved.
- Tests: attach A -> steal fails -> detach wrong owner no-ops ->
  detach A -> attach B succeeds and replaces the context; same-owner
  re-attach keeps the first context. New attachedModelName test probe.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Two windows where a consumer dropping its stream was a silent no-op:

- M-7: '.upgrading' carries no request reference, so cancel(requestID:)
  matched neither the deposited single nor the joining request for the
  whole handshake. Add a pendingCancels set: cancel() records the id
  when the driver also does not know the token yet, and the upgrade
  path consumes the entry at each point a request becomes cancellable —
  right after adoptMigrated registers the upgraded single, right after
  driver.submit registers the joining request (both in upgrade() and in
  admitToBatch), and when the joining request settles on the fallback
  single path. Finalize paths (finishUpgradedSingle, the task-finished
  fallback) drop stale entries, and admission honors a recorded cancel
  before handing the request to the driver. Ids are monotonic and never
  reused, so a consumed entry can never hit a different request.
- SCHED-5: drainQueuedRequests moved the whole queue into local boxes
  up front, making every undrained request invisible to cancel() during
  the per-element route suspensions. It now pops one request per
  iteration, bounded by the initial count so route()'s legitimate
  re-appends (behind a new non-upgradeable single) cannot respin the
  loop.

startSingleAfterUpgradeFallback becomes async to replay a recorded
cancel once the fallback single task is tracked.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Three failure paths finished only the failing request and left
state == .idle without touching queuedRequests, permanently stranding
every request held behind a non-upgradeable single (their streams never
close, their consumers hang):

- startSingleIfIdle's catch (iterator prefill failed on the
  batched-path fallback),
- startSingleAfterUpgradeFallback's catch (same, after an upgrade
  window), and
- startSingle's 'guard let context' bail-out, which does not even throw
  (reachable after a detach with no re-attach).

Each now drains the queue after settling at idle. The recursion through
route() back into these paths is bounded: every drain pass removes or
finishes at least one queued request. startSingle/startSingleIfIdle
become async for the drain call; startSingle still builds the iterator
before returning (same-actor call, no suspension on the throw path), so
route()'s synchronous init-error semantics for the primary idle route
are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
…rite-back

Three correctness gaps when an upgraded single finalizes without joining
the batch:

- The delivered final token's disposition was discarded
  ('_ = handler.processToken(lastToken)'), so a token that completed a
  configured stop string at the remainingBudget <= 1 site still reported
  '.length'. Capture it and report '.stop', mirroring
  EngineDriver.deliver's reportedReason (single-path parity: the stop
  check runs before the length fallback); the token stays counted.
- The migration-failure fallback delivered liveCurrentToken a second
  time (it was already delivered before migration was attempted) and
  was the only finalize site skipping writeBackUpgradedSingle. It now
  passes lastToken: nil while still counting the delivered token, and
  writes the un-migrated caches back — safe because a failed
  migrateCaches only READ the source caches (fromSingle copies).
- promptTime was hardcoded 0 in finishUpgradedSingle (folding prefill
  into decode time and deflating tokens/sec) and in EngineDriver's
  zero-budget early return. The finalizer now splits at the single
  path's real first token (LiveIteratorState.firstTokenAt threaded
  through), matching runSingle/EngineDriver.deliver; the zero-budget
  return reports elapsed-since-submit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Since the seeded key chains were unified (c55543b), a single-path
TopPSampler and a batched SamplerKeyHolder consume the SAME split chain
for the same seed. The upgrade path built a fresh makeRowSampler(seed:)
whose holder restarted at MLXRandom.key(seed), bit-identically REPLAYING
the keys that produced tokens 1..N — a seeded upgraded request repeated
its own sampling history instead of continuing it.

Draw accounting (verified against TokenIterator and DecodeBatch): the
single iterator consumes one draw in prepare (the pump) plus one per
next() call, so at deposit time liveTokenCount + 1 draws are gone and
the pending handoff token is draw liveTokenCount + 1. The adopted
batch's priming step (DecodeBatch.init -> step()) performs the next
draw, so the fresh sampler is advanced by liveTokenCount + 1 and its
first draw is draw liveTokenCount + 2 — bitwise what the single path
would have sampled next. Prefix-fetch adoptions consumed no draws and
advance by 0 (the default).

- SamplerKeyHolder.advance(by:) fast-forwards the chain (state-only
  splits, evaluated once so no deep lazy graph), threaded through
  makeRowSampler(advancedBy:) and InferenceScheduler.rowSampler.
- Fix the stale comments claiming the chains differ (rowSampler) and
  that LiveIteratorState carries a LogitSampler (it carries KV only).
- Tests: advance(n) == n consumed draws at draw n+1; advance(0)
  identity; unseeded holders stay keyless.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
…idation

migrateCaches([]) returned a non-nil empty array, so canUpgrade approved
upgrading singles running on cacheless models — but
BatchGenerationEngine.init's !probe.isEmpty guard then rejects exactly
that topology, ensureDriver swallows the throw, and the RUNNING request
was finalized '.length' mid-generation, recurring for every concurrent
pair. An empty topology now fails migration, routing such models onto
the existing graceful serialize path. (This also makes an empty
prefix-fetch hit fall through to the cold insert instead of adopting a
zero-layer row.)

InferenceScheduler.Configuration.init now preconditions
completionBatchSize / prefillBatchSize / prefillStepSize > 0, mirroring
BatchGenerationEngine.validateConfiguration exactly: the engine's own
throw fires inside ensureDriver — mid-flight, where it is swallowed and
requests silently degrade — so failing loudly at construction is the
only place the mistake is visible. maxBatchSize stays exempt (the
driver documents clamping it).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Both driver cancel paths — cancel(token:) on consumer stream-drop and
the '.cancelled' disposition in deliver (which routes through
cancel(uid:)) — used the non-capturing engine.cancel(uid:), discarding
the row's prompt + partial-generation KV. The single path writes back
even on cancellation (runSingle's insertCache runs after a .cancelled
outcome), so a batched consumer dropping its stream silently lost cache
state the next request could have reused.

cancel(uid:) now uses the capturing engine cancel and writes back,
gated on the same destination-cache existence check as
finishOnSemanticStop (writeBackToPromptCache && a per-record or
driver-level cache exists), with the write-back running before the
record is removed so the model-name/salt key is still available.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Batched write-back ignored PromptCachePolicy: EngineDriver.admit set
writeBackToPromptCache from a bare 'promptCache != nil' test, and
upgraded rows could resurrect a policy-disabled write-back through
writeBack's 'record.promptCache ?? promptCache' driver-level fallback.
The single path already made one canUsePromptCache decision for both
fetch and write-back; the batched paths did not.

The scheduler now computes eligibility ONCE at submit
(promptCacheEligible -> LRUPromptCache.canUsePromptCache against the
bound model) and threads it through:

- SchedulerRequest.cacheEligible (default true so direct constructors —
  tests — keep opt-in-by-nil behavior; the scheduler always passes its
  decision): gates EngineDriver.admit's write-back flag and replaces
  admitViaPrefixFetch's re-derived canUsePromptCache check, so the
  fetch and write-back flags can never disagree.
- SingleRequest.writeBackToPromptCache is now policy-gated too, so an
  ineligible single that upgrades carries a false flag into
  AdoptedRecord and the driver-level fallback can no longer resurrect
  its write-back.
- stepOnce's capture predicate now matches finishOnSemanticStop's
  (flag AND destination), skipping cache extraction when no row will
  actually write back.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Parity: makeRowSampler and InferenceScheduler.rowSampler treated
'temperature <= 0' as greedy, but GenerateParameters.sampler()
special-cases only exact zero — a single-path request with a negative
temperature samples the inverted distribution, while the same request
silently went argMax when batched. Both gates are now '== 0' / '!= 0',
with a test asserting a negative temperature yields a real sampler.

Hygiene, all verified stale:
- RequestRecord.tokensIncludePrompt was true at all three creation
  sites (cold insert, prefix-fetch admission, adoption — adopted rows
  have carried prompt-inclusive histories since the penalty-seeding
  change), so the field, its stale generated-only doc, and writeBack's
  dead 'record.inputTokens + finished.allTokens' branch are gone;
  generationCount always subtracts the prompt. RequestRecord/
  AdoptedRecord.inputTokens existed only for that dead branch and are
  removed too.
- setMaxBatchSize's doc no longer names the 'Layr' fork (the file
  header already credits server-shaped forks generically).
- startSingle's comment claimed batched-path prefix fetch 'is not
  wired yet'; it is (EngineDriver.admitViaPrefixFetch).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Follow-up closing a window at the seam of the epoch re-validation and
the stale-driver handling: a single request started AFTER a context
refresh carries the CURRENT epoch, so the upgrade epoch gates pass —
but if the stale driver is still draining old-context rows, ensureDriver
(by design) keeps returning it, and adoption would splice current-model
KV into an engine that caches the previous model's weights.

Gate the route-time upgrade decision on !driverStale: the new request
queues behind the running single instead (the existing pendingUpgrade
path) and is drained once it finishes, by which time
batchLoopFinished/ensureDriver has torn the stale driver down and
rebuilt from the current context. A driver that turns stale
mid-handshake always comes with an epoch bump, which upgrade()'s
re-validation already catches — so route-time is the only spot that
needed the extra gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Nothing in the bundle drove two concurrent requests through
InferenceScheduler.route/upgrade end to end; SchedulerUpgradeParityTests
adds that coverage through the PUBLIC front door (ModelContainer +
InferenceScheduler over a deterministic fixture model), patterned after
PrefixFetchTests' instrumented-model approach:

- token parity: request A runs solo for a baseline, then A + B run
  concurrently, forcing the .single -> .upgrading -> .batched handshake
  (live-state deposit, cache migration, engine adoption). A's full
  decoded stream must be IDENTICAL to its solo run and B's to its own --
  any dropped/duplicated/reordered token at the handoff (handoff-token
  delivery, adopted-row budget accounting) breaks the equality;
- completion infos: promptTokenCount/generationTokenCount correct for
  both rows, stop reasons .length, promptTime finite and non-negative,
  tokens/sec finite (no +inf from a zero generation window);
- cancellation: B's stream is dropped after its first token; A must
  still complete with full parity and the scheduler must return to idle
  (activeRequestCount == 0);
- an upgrade witness (max forward batch width == 2) proves the requests
  actually decoded in one batch rather than serializing.

Determinism: the fixture's next token is (previous + 1) mod 16, so
baselines are exactly known, and interleaving is gated -- the model
BLOCKS on an armed forward call until the test releases it, with an
instrumented newCache (the scheduler's canUpgrade topology probe)
signalling when B has reached the upgrade path. No sleep-race timing;
the gate has a safety timeout so a failure cannot hang CI.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
This integration branch carries, on top of the full cb2 chain, the content
deliberately kept out of the upstreamable PRs: BatchQuantizedKVCache and its
suites (deferred until the engine can actually construct quantized batched
caches), the quantized branch of the batched-cache factory, and the
readiness-review records under reviews/.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Port 34ca30a's trim clamp to the quantized batch cache, which was skipped
when BatchKVCache and BatchRotatingKVCache received it. `trim(_ n:)` used
`min(_idx, n)` with no min-live-row clamp, so on a ragged batch (e.g.
leftPadding [4, 0], _idx 6) a trim(5) drove the shorter row's batchOffsets
negative ([-3, 1]), leaving its leftPadding larger than the new _idx --
a later extract slices `padding ..< _idx` with an invalid range and decode
sees invalid RoPE positions. Mirror BatchKVCache.trim exactly (this cache
is left-padding based like the simple batch cache): clamp the trim to
`min(n, _idx, max(0, batchOffsets.min()))` and return the clamped amount.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Port 7e2ae88's BatchKVCache.extract fix to the quantized batch cache,
which was skipped when the sibling received it. `extract(idx:)` read the
row's leftPadding unclamped and sliced `padding ..< _idx`: a row still
inside its left-padding prefix (legitimately preserved by `filter`'s
`_idx >= minLeftPad` guard during chunked prefill) has padding > _idx,
so the slice range is invalid and extraction traps. Clamp the pad start
to _idx so such a row extracts as an empty single-row cache instead; the
metaState offset write (`_idx - padding`) is then 0 for the empty case,
mirroring BatchKVCache's fixed behavior.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
The existing trimRewinds test uses a single zero-padding row, a shape that
cannot detect a missing min-live-row clamp. Add the quantized siblings of
BatchCacheTests' trimClampsToMinimumLiveRow coverage:

- Ragged-padding trim: leftPadding [4, 0], prefill 6, trim(5) must clamp
  to the min live row length (2) so no batchOffsets entry goes negative,
  and both rows still extract with valid slices afterwards.
- Extract after the filter guard: chunked prefill (prepareBatched left
  padding 4, first chunk of 2) plus filter leaves a preserved row with
  leftPadding > _idx; extracting it must yield an empty cache (offset 0,
  zero-width quantized state) instead of trapping on an invalid range.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
40-agent audit of the integration branch and the 8-PR chain: verification
of every 2026-07-02 review finding against HEAD, a fresh adversarially
verified bug hunt (the Gemma3n batched-mask fatal, the hot-swap epoch
cluster, the LRU quadratic search, and the smaller parity items fixed in
the accompanying commits), API-surface and PR-split assessments, and the
upstream MaterializedArray coordination analysis.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
@ronaldmannak
ronaldmannak force-pushed the claude/continuous-batching-pr-review-2w9fl3 branch from 63377d4 to c4573f2 Compare July 17, 2026 02:04
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