Repository navigation
cb2-8 (chain 8/8): prefix-cache fetch on batched admission + audit hardening - #31
ronaldmannak wants to merge 15 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a prefix-cache admission hook (admitViaPrefixFetch) in EngineDriver to reuse cached prompt KV, prefilling only the remainder of the prompt instead of the full prompt. It also adds corresponding behavioral tests in PrefixFetchTests.swift to verify that cached prompt prefixes are correctly reused and exact-hit admissions are handled properly. There are no review comments, so I have no feedback to provide.
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.
5ff107c to
d8bfc13
Compare
bdfb7ca to
6b53f63
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bdfb7cac1a
ℹ️ 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".
| tokens: [request.inputTokens] | ||
| ) | ||
| guard let uid = uids.first else { return nil } | ||
| engine.adoptActiveBatch(batch) |
There was a problem hiding this comment.
Honor completionBatchSize for cache-hit admissions
In the default configuration (maxBatchSize == nil), freeSlots is unbounded and regular inserts are still constrained by BatchGenerationEngine.admitFromQueue using completionBatchSize; this new cache-hit path bypasses that queue and calls adoptActiveBatch immediately. A burst of cached prompts can therefore grow generationBatch past the configured concurrent decode limit (e.g. completionBatchSize = 2 with three prefix hits), defeating the memory/concurrency cap that non-hit requests obey.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. admitViaPrefixFetch now bails to the normal insert path when the engine is at completionBatchSize (activeCount + queuedCount), so cache-hit admissions respect the same decode cap as cold inserts. The request loses only prefix reuse when the batch is full, and insert queues it under the cap.
Generated by Claude Code
| modelName: request.modelName, | ||
| promptCacheSalt: request.promptCacheSalt, | ||
| promptCache: request.promptCache, | ||
| submitTime: Date.timeIntervalSinceReferenceDate, |
There was a problem hiding this comment.
Capture submit time before cached prefill
For prefix-cache hits this timestamp is recorded only after the cache lookup, suffix prefill loop, and makeAdoptedBatch priming decode have already completed. Completion info later computes promptTime as firstTokenAt - submitTime, so cached batched requests under-report their actual admission/prefill latency, unlike the single path and cold batched path that start timing before prefill work begins.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. submitTime is now captured at admit entry and used by both paths, so a hit's promptTime covers the fetch, remainder prefill, and priming step exactly like the cold path's covers its prefill.
Generated by Claude Code
| let chunk = MLXArray( | ||
| prefillTokens[index ..< (index + n)].map { UInt32($0) } | ||
| ).reshaped([1, n]) | ||
| _ = engine.model.callAsFunction(chunk, cache: batched.map { $0 as any KVCache }) |
There was a problem hiding this comment.
Apply wired-memory limits to cached suffix prefill
When a prompt-cache-hit request supplies a wiredMemoryTicket, this forward pass runs synchronously during submit before activeWiredMemoryTicket is recorded, so the caller's memory limit is not applied to cached suffix prefill. Cold batched admissions do their prefill inside drain under stepOnceWired; with a large cache remainder this path can exceed the memory cap the request asked the scheduler to enforce.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed, conservatively. You were right that setting the ticket property earlier is a non-fix -- the limit only applies inside withWiredLimit step scopes. Ticketed requests now skip prefix-fetch admission entirely and take the cold path, whose prefill runs inside the drain loop's ticketed scopes, preserving the memory guarantees at the cost of prefix reuse for ticketed requests only. Deferring hit admission into the drain loop, which would restore reuse under the ticket, is noted in the guard comment as the follow-up design.
Generated by Claude Code
d8bfc13 to
0f0daf3
Compare
6b53f63 to
c78a03c
Compare
0f0daf3 to
55b17a0
Compare
c78a03c to
187011c
Compare
55b17a0 to
7ab7720
Compare
187011c to
7c913ec
Compare
7ab7720 to
2b60e84
Compare
7c913ec to
490b848
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 490b8485e6
ℹ️ 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".
| index += n | ||
| } | ||
|
|
||
| let (batch, uids) = engine.makeAdoptedBatch( |
There was a problem hiding this comment.
Keep cache-hit admission inside active wired limits
When a ticketed row is already in the batch, activeWiredMemoryTicket stays set until drain finishes, but a later cache-hit request without its own ticket can still reach this adoption path because the guard only checks request.wiredMemoryTicket. makeAdoptedBatch performs the priming decode immediately from submit (and the preceding suffix-prefill loop does the same), so that GPU work runs outside stepOnceWired; cold admissions instead queue into engine.next() and are covered by the active wired limit. This still lets mixed batches exceed the memory cap whenever an unticketed cached request joins while a ticketed request is draining.
Useful? React with 👍 / 👎.
| // into the live batch, bypassing the completion-capacity queue that | ||
| // cold inserts go through. At capacity, fall through to `insert`, | ||
| // which queues under the cap (the request loses only prefix reuse). | ||
| guard engine.activeCount + engine.queuedCount < engine.completionBatchSize else { |
There was a problem hiding this comment.
Preserve FIFO behind queued cold rows
When an older cold request is already sitting in the engine queue (for example, multiple submitOne calls happen before the detached drain task gets to run), this condition still passes as long as active+queued is below completionBatchSize. The cached request then primes and splices itself into generationBatch immediately, so it can run and deliver ahead of the older queued row; a non-hit request would have gone through engine.insert and preserved FIFO in the queue. Gate this path on queuedCount == 0 or enqueue the adopted row to avoid newer cache hits jumping older submissions.
Useful? React with 👍 / 👎.
2b60e84 to
a1fe6db
Compare
490b848 to
06f7038
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 06f70387eb
ℹ️ 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".
| if await existing.hasWork { | ||
| return existing |
There was a problem hiding this comment.
Defer new-owner requests until the stale driver is idle
When a container is destroyed while one of its batched streams is still decoding, detach permits a new container to attach and marks the old driver stale, but this branch returns that old driver while it has work. A request from the new owner therefore enters the previous container's engine and is decoded with the wrong model (and may mix the new owner's prompt-cache state with it). Hold new-owner requests until the stale driver drains and is rebuilt from the newly attached context.
Useful? React with 👍 / 👎.
| guard let scheduler else { return } | ||
| let owner = ObjectIdentifier(self) | ||
| Task { await scheduler.detach(owner: owner) } |
There was a problem hiding this comment.
Make scheduler detachment deterministic before reuse
If client code releases one container and immediately calls generate on a new container sharing the scheduler, this unstructured task is not guaranteed to run before the new container checks currentOwner. The new call can therefore nondeterministically see the dead container's owner and throw schedulerAlreadyAttached, despite this change intending to make scheduler reuse possible. Provide an awaitable/ordered release mechanism rather than relying solely on a deinit-scheduled task.
Useful? React with 👍 / 👎.
| guard contextEpoch == epochAtHandshake else { | ||
| finishUpgradedSingle( |
There was a problem hiding this comment.
Continue the original request after an epoch change
If ModelContainer.update(_:) lands after route starts an upgrade but before the live-state handshake returns, this guard finalizes the original request immediately with .length, even when it has substantial token budget remaining and encountered no stop condition. This contradicts the documented behavior that an in-flight single request keeps its original model reference and causes output length to depend on a narrow update/upgrade race; abort the upgrade while allowing the deposited request to continue on its original context instead of reporting a false length completion.
Useful? React with 👍 / 👎.
06f7038 to
9084bf4
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9084bf4ba7
ℹ️ 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".
| let fetch = cache.fetchNearestCacheResult( | ||
| model: request.modelName, tokens: request.inputTokens, | ||
| salt: request.promptCacheSalt) | ||
| guard let fetched = fetch.cache else { return nil } |
There was a problem hiding this comment.
Disable prefix-cache adoption into stale drivers
When ModelContainer.update refreshes the context while a batch is active, ensureDriver intentionally keeps returning the stale driver until its old-model rows drain, while a newly submitted request carries the refreshed context's model name, topology salt, and prompt cache. This lookup can therefore return KV produced by the new model, which admitViaPrefixFetch subsequently adopts into an engine still backed by the old model, producing invalid output and potentially poisoning cache write-back. Cache-hit admission needs to be disabled for requests routed to a stale driver or keyed against the driver's own context.
Useful? React with 👍 / 👎.
| let removed = await driver?.cancel(token: requestID) ?? false | ||
| if !removed, upgradingWindow { |
There was a problem hiding this comment.
Record upgrade cancellations before consulting the driver
With three concurrent requests, the third request can enter admitToBatch during the first two requests' handshake and change scheduler state from .upgrading to .batched before either hidden request is registered in the driver. Cancelling the original or joining stream then makes driver.cancel return false while upgradingWindow is false, so no pending cancellation is recorded and the request still performs migration/prefill and priming work until a later token delivery notices the terminated stream. Track the two upgrading request IDs independently of the mutable scheduler state, and record cancellation before the suspending driver call.
Useful? React with 👍 / 👎.
a1fe6db to
a3197df
Compare
9084bf4 to
5c8a2ae
Compare
a3197df to
a5db974
Compare
5c8a2ae to
25f6495
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 25f6495fc3
ℹ️ 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".
| // time reaching admission (e.g. waiting for a batch | ||
| // slot); report elapsed-since-submit as prompt time | ||
| // rather than a hardcoded 0. | ||
| promptTime: max(0, Date.timeIntervalSinceReferenceDate - submitTime), |
There was a problem hiding this comment.
Timestamp zero-budget requests before capacity queuing
When maxBatchSize is full, submit stores the request in waiting, but submitTime is created only later when admitWaitingIfPossible calls admit; consequently this new elapsed-time calculation remains near zero and excludes the entire capacity wait it explicitly intends to report. Capture the timestamp when submit first receives the request and carry it through PendingSubmission so zero-budget completion metrics include queue latency.
Useful? React with 👍 / 👎.
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
a5db974 to
6fa7071
Compare
25f6495 to
4f63b10
Compare
Chain 8/8 — stacked on #30. Closes the batched path's prompt-cache gap, then carries the scheduler/driver hardening from the 2026-07-13 audit (which needs the driver's final form and therefore lands here rather than on #29).
Prefix fetch (original scope)
On
EngineDriver.admit, a request that opted into prompt caching now:fromSinglepath the single→batch upgrade uses;makeAdoptedBatch/adoptActiveBatch.Exact hits trim the final token's KV and re-feed it as the seed, matching
startSingle. Any ineligibility falls through to the normal full-prefillinsert.PrefixFetchTestsdrives a realEngineDriverdrain end-to-end: warm-vs-cold token parity, completion-info checks, and forward-pass width assertions via an instrumented model.Audit hardening (2026-07-13, all adversarially verified — details in
reviews/continuous-batching-audit-2026-07-13.mdon the integration branch)contextEpochre-validated after the upgrade-handshake suspension (aModelContainer.updatelanding in that window previously spliced old-model KV into a new-model engine and poisoned the prompt cache via write-back);ensureDriverhonorsdriverStalewith identity re-checks;batchLoopFinished's stale-driver teardown can no longer be skipped; submit-side self-heal closes the non-FIFO-actor stale-idle residue; upgrades gate on!driverStale.detach(owner:)+ModelContainer.deinitdetach;attachreplaces the context for a new owner after detach (previously a scheduler was permanentlyschedulerAlreadyAttachedafter its container died, or could serve a recycled identity with the old model)..upgradingwindow (M-7);drainQueuedRequestspops per-iteration so undrained requests stay cancellable; failure paths drain the queue instead of stranding it.finishUpgradedSinglehonors a stop-string disposition (.stop, not.length), no longer double-delivers the handoff token on migration failure, adds the missing write-back, and reports realpromptTime(as does the driver's zero-budget return).PromptCachePolicyon all paths (fetch eligibility decided once at submit); negative temperature samples the same distribution as the single path;canUpgraderejects empty cache topologies instead of truncating the running request;Configuration.initvalidates like the engine does.SchedulerUpgradeParityTests: the first end-to-end auto-upgrade test — solo-vs-concurrent token parity for both requests through the publicModelContainerfront door, with a deterministic decode-probe fixture, completion-info checks, and a cancellation case.🤖 Generated with Claude Code
https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn