Skip to content

Add fixed-batch token and decoded generation streams - #97

Open
ronaldmannak wants to merge 16 commits into
codex/quantized-batch-kvcachefrom
codex/batched-generation-streams
Open

ronaldmannak wants to merge 16 commits into
codex/quantized-batch-kvcachefrom
codex/batched-generation-streams

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Nov 5, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #94. Optional benchmark tooling remains separate in #93.

Closes #96.

What changed

  • Adds batchGenerateTokens and batchGenerateText, with task-returning variants for cancellation and deterministic MLX cleanup. Events identify the prompt by its zero-based UID.
  • Each row has its own decoder, reasoning/tool parser and stop policy. Model/cache failures propagate through AsyncThrowingStream.
  • BatchCompletionInfo reports prompt and emitted token counts, stop reason, time to first model token and elapsed batch time. Streams buffer losslessly; callers stopping early should cancel and await the returned task.
  • Request queues, admission policy, prefix reuse, prompt-cache ownership and budgets remain the caller's.
  • Producer cancellation completes unfinished rows as .cancelled, including cancellation observed between prefill chunks. A model-thrown CancellationError still propagates when the producer task is not cancelled.

Prefill cancellation follow-up

CancellationError completes unfinished rows as .cancelled only when the producer task is cancelled. Other errors retain their stream-failure behavior. Both paths still remove iterator rows, synchronize queued device work and finish the continuation.

The regression runs raw-token and decoded-text streams through the real PrefillParameters.forEachChunk cancellation check. It cancels after one CPU prefill forward and verifies one completion per row, zero generated tokens, nil first-token time and no later forwards. Control cases verify that an uncancelled model throwing CancellationError still fails the stream. Every case awaits producer cleanup, including the negative run.

Both actual-cancellation cases fail on the previous implementation. The focused fixed run passes 50 Swift tests and 15 XCTest cases. The restacked candidate 76993b3 passes 58 targeted Swift tests across 3 suites and 15 XCTest cases; CI-pinned swift-format 603 checks pass. These are local results; fork CI remains skipped.

Evidence

Earlier validation (71f07c2), including the streaming suite this PR adds and the Qwen VL tests from #94:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/BatchGenerationTests \
  -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite BatchGenerationTests passed after 0.303 seconds.
Suite QwenVLBatchedPositionTests passed after 0.320 seconds.
Suite BatchTokenIteratorTests passed after 2.003 seconds.
Test run with 48 tests in 3 suites passed after 2.003 seconds.
** TEST SUCCEEDED **

An earlier whole MLXLMTests run reported in #98: 1600 Swift Testing tests and 869 XCTest cases. That earlier run's only failure is the pre-existing EmbeddingGemmaMaskTests G7 (output in #98).

Codex's earlier validation of this patch reported DocC for all 11 library products with warnings as errors and zero diagnostics. DocC was not re-run for this restack. Origin-fork GitHub Actions jobs are skipped by the workflow's repository-owner condition; the results above are local (M5 Max).

Restack (2026-11-06c)

Both commits are rebased unchanged onto #94's new head (5254d24), which carries #90's recurrent offset fix: the streaming patch and the cancellation follow-up (d484159, now f716203). At this head (f716203):

-only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/BatchGenerationTests
-only-testing:MLXLMTests/QwenVLBatchedPositionTests
Suite BatchGenerationTests passed after 0.337 seconds.
Suite QwenVLBatchedPositionTests passed after 0.344 seconds.
Suite BatchTokenIteratorTests passed after 2.073 seconds.
Test run with 53 tests in 3 suites passed after 2.073 seconds.
** TEST SUCCEEDED **

Rebased onto main 4ab2679 (2026-11-07)

Rebased from c8dabc6 onto main 4ab2679, which adds seven commits (22bdf2c..4ab2679): surrogate-pair escapes, weight-loading progress, LFM2.5, chat-session steering, VLM image prompts out of float32, LFM3, and Qwen 3.5 VLM YaRN. Git applied every commit of the stack without conflicts. git range-diff shows the earlier commits unchanged.

Main's chat-session steering adds a Generation.steering case, so the test helper BatchStreamTextResult.append (added by this PR) no longer compiled: its switch over Generation was not exhaustive. New commit e361606 adds the case and records it as an issue, as the helper already does for an embedded .info: the batch streams take no steering control and never emit it. The library code needs no change.

At this head (e361606):

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/BatchGenerationTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite BatchGenerationTests passed after 0.303 seconds.
Suite QwenVLBatchedPositionTests passed after 0.314 seconds.
Suite BatchTokenIteratorTests passed after 1.970 seconds.
Test run with 53 tests in 3 suites passed after 1.971 seconds.
** TEST SUCCEEDED **

Batch row operations move to BatchableKVCache (2026-11-07b)

Rebased onto #94's a5b9179 (the BatchableKVCache change in #88-#94; see #88). This PR's commits are unchanged (git range-diff); the generation streams use no row operation.

At this head (e40c18a, was e361606):

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/BatchGenerationTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite BatchGenerationTests passed after 0.316 seconds.
Suite QwenVLBatchedPositionTests passed after 0.319 seconds.
Suite BatchTokenIteratorTests passed after 1.963 seconds.
Test run with 54 tests in 3 suites passed after 1.963 seconds.
** TEST SUCCEEDED **

Merge validation and padding-only extraction (2026-11-07c)

Rebased onto #94's 13957b4 (the round 8 changes in #88-#94). This PR's other commits are unchanged (git range-diff); the only new commits in the stack are #88's 1c399b0, #89's 081b109, #90's a35cbe2 and #94's 13957b4.

At this head (84a3adf, was e40c18a):

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/BatchGenerationTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite BatchGenerationTests passed after 0.306 seconds.
Suite QwenVLBatchedPositionTests passed after 0.320 seconds.
Suite BatchTokenIteratorTests passed after 2.018 seconds.
Test run with 54 tests in 3 suites passed after 2.018 seconds.
** TEST SUCCEEDED **

Batch cleanup synchronizes the captured stream (2026-11-07d)

Merged #94 (which carries #90's e222aa2), then new commit 316cacd; head 316cacd, was 84a3adf. No rebase. It answers the Codex finding on the batch worker's cleanup:

  • The batch task now captures StreamOrDevice.default.stream when it is created and synchronizes that stream in cleanup, as generateLoopTask in Evaluate.swift does, instead of reading Stream.defaultStream at the end.
  • No test fails without it, because the two name the same stream today. MLX's default stream is task-local: Stream.withNewDefaultStream, Device.withDefaultDevice and using(device:) all bind it with @TaskLocal, and task locals carry into the Task and through the GenerationWorker actor hop. So Stream.defaultStream read at cleanup already resolves to the stream the iterator submitted its work to, even inside withNewDefaultStream (worked out from MLX's Stream.swift and the worker; no such test was run). The change keeps the two generation paths alike and the stream explicit.

At 316cacd:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchGenerationTests -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite BatchGenerationTests passed after 0.302 seconds.
Suite QwenVLBatchedPositionTests passed after 0.319 seconds.
Suite BatchTokenIteratorTests passed after 1.970 seconds.
Test run with 54 tests in 3 suites passed after 1.971 seconds.
** TEST SUCCEEDED **

54 tests here; 54 at 84a3adf.

Driver on iterator events, with emission recording (2026-11-07e)

Merged #94, which carries #91's event API (head 058907f, was 316cacd; no rebase). The merge commit moves BatchGeneration.swift onto the events:

  • .token goes to the row's handler. .finished(stopToken:) takes the path a stop-token Response took before. .finished(.length) completes the row after its last token.
  • .failed failed the stream with that error, after the step's other output. That kept this PR's contract, which an admission throw used to trigger. 522d71c (below) replaces this with a per-row failure event.
  • The driver calls recordEmittedToken(id:token:) exactly where it counts a token, before the handler sees it, as the single-sequence loop does. Generated tokens are always recorded; stop tokens (EOS or a protocol stop) only with includeStopToken. Tokens after a consumer stops partway through a step are never recorded.
  • Cleanup removes every row of the batch, including rows that ended in the last step, so each processor is finalized exactly once however the stream ends.

New BatchGenerationTests cover the lifecycle with a ThinkingBudgetProcessor behind a recording processor. Each row's log must be its delivered tokens, in order, then exactly one finalization, and the finalized reasoning count must match a single-sequence ThinkingBudgetProcessor that emitted the same tokens. The tests cover:

  • EOS, with and without includeStopToken (the stop token is recorded only when delivered)
  • the row limit
  • a stop string (the completing token counts; the row is removed)
  • a protocol stop token (.atem)
  • a consumer that stops partway through a step
  • task cancellation
  • rows that fail to join

The same six tests with the driver's recordEmittedToken calls removed and the old cleanup (iterator.remove(iterator.ids)):

Test "Raw rows record their delivered tokens and finalize once at EOS or their limit" with 2 test cases failed after 0.032 seconds with 4 issues.
Test "A stop string records the token that completes it, then finalizes the row once" failed after 0.003 seconds with 2 issues.
Test "A protocol stop token ends its row without being recorded" failed after 0.003 seconds with 2 issues.
Test "A consumer that stops partway through a step leaves the rest unrecorded" failed after 0.001 seconds with 1 issue.
Test "Task cancellation records the delivered tokens and finalizes every row once" failed after 0.002 seconds with 2 issues.
Test "Rows that fail to join finalize once and record nothing" failed after 0.001 seconds with 2 issues.
Test run with 6 tests in 1 suite failed after 0.046 seconds with 13 issues.

At 058907f:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchGenerationTests -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite QwenVLBatchedPositionTests passed after 0.329 seconds.
Suite BatchGenerationTests passed after 0.351 seconds.
Suite BatchTokenIteratorTests passed after 2.097 seconds.
Test run with 64 tests in 3 suites passed after 2.097 seconds.
** TEST SUCCEEDED **

That is 64 tests here; 54 at 316cacd. The additions are #91's 4 iterator tests and these 6.

Then merged #91's follow-up ca604a2 through #94 (head 2eb1b49): 65 tests, all passing.

Per-row failures in the stream (2026-11-07f)

New commit 522d71c, made at the maintainer's request.

  • BatchGenerationEvent gains failed(uid:_:). A row that cannot join ends with that event after its handler finishes, and the other rows carry on to their own info events. Before, the first such row ended the whole stream with its error. A row can fail this way when its supplied cache does not match the batch, its prefill throws, or the model's state allows only one row.
  • Every row now ends with exactly one info or failed event.
  • A prefill stopped by the task's own cancellation still completes its row as .cancelled. An error from a batched model step still ends the stream.
  • This is a breaking change for callers that switch exhaustively over BatchGenerationEvent. The guide's example in using.md now handles the new case.

With the driver changed back to throwing the row's error, the affected tests fail:

Test "A row that cannot join fails alone while the others finish" with 2 test cases failed after 0.003 seconds with 2 issues.
Test "Cancellation between prefill chunks completes raw and decoded rows without a model error" with 4 test cases failed after 0.033 seconds with 4 issues.
Test "A preparation failure ends its row with a failed event, not the stream" failed after 0.001 seconds with 1 issue.
Test "Rows that fail to join finalize once and record nothing" failed after 0.001 seconds with 1 issue.
Test run with 4 tests in 1 suite failed after 0.040 seconds with 8 issues.

The cancellation failures are only in its two cancelTask: false cases (the model throws CancellationError on its own); the cancelTask: true cases pass both ways.

At 522d71c:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchGenerationTests -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite BatchGenerationTests passed after 0.608 seconds.
Suite QwenVLBatchedPositionTests passed after 0.587 seconds.
Suite BatchTokenIteratorTests passed after 2.444 seconds.
Test run with 66 tests in 3 suites passed after 2.444 seconds.
** TEST SUCCEEDED **

That is 66 tests, up from 65: rowFailureLeavesOtherRows, with raw and decoded cases.

GenerateParameters and cancellation merged in (2026-11-07g)

Pushed one commit at a time; Codex gave each a thumbs up before the next went out.

Head 8eb03f3: 73 tests, all passing.

Resumable prefill merged in (2026-11-07h)

Merged #94 (05786a9), bringing #91's resumable prefill; Codex gave it a thumbs up. No changes in this PR. The stream drivers ignore .prefill. Head 05786a9: 76 tests, all passing.

Two-chunk prefill merged in (2026-11-07j)

Merged #94 (2aef5be), which brings #91 at 6dd7f3c. 15 more model families opt into resumable prefill, the family test seeds its weights, and two prefill chunks stay in flight (6dd7f3c): a batch of one now reaches its first token as fast as a single run. The merge was clean.

BatchTokenIteratorTests + BatchGenerationTests + QwenVLBatchedPositionTests at 2aef5be:

** TEST SUCCEEDED **
Test run with 78 tests in 3 suites passed after 3.405 seconds.

Merged #94 again (9fcb0d3). It brings:

The merge was clean. Focused suites at 9fcb0d3, two more tests than before, both from #94:

** TEST SUCCEEDED **
Test run with 80 tests in 3 suites passed after 3.926 seconds.

#91's marker and layer-count fixes merged in (2026-11-08)

Merged #94 (65d8b65). It brings #91 at 3ac324a:

  • 6c28e8c: each prefill chunk now has one marker that owns its memory. Before, its markers were views of the cache buffers, which forced every in-place chunk to copy its buffer.
  • 3ac324a: a first row whose supplied cache has fewer layers than the model now fails with KVCacheError instead of trapping in the model.

The merge was clean. Focused suites at 65d8b65:

** TEST SUCCEEDED **
Test run with 82 tests in 3 suites passed after 3.504 seconds.

Merged #94 again (9f75ec3), which brings #91's c9145a2. The prefill chunk marker is now a single element: one element of the last cache array instead of every array's. That removes the ~10 ms that 6c28e8c added to a batch of four's first-row TTFT on 2048-token prompts, and the marker still owns its memory. The merge was clean. Focused suites at 9f75ec3:

** TEST SUCCEEDED **
Test run with 82 tests in 3 suites passed after 3.374 seconds.

Not done on purpose

  • No regression test for the stream capture: none can fail without it while MLX's default stream is task-local (see 2026-11-07d).
  • Scheduling, admission policy and prefix reuse stay with the caller, as above.

Test changes

  • 2026-11-08 (merge 9f75ec3): no test changes.
  • 2026-11-08 (merge 65d8b65): no test changes.
  • 2026-11-08 (merge 9fcb0d3): no test changes.
  • 2026-11-07j (merge 2aef5be): no test changes.
  • 2026-11-07f (522d71c), for per-row failures:
    • preparationFailuresPropagate expected the stream to throw the preparation error. It now expects that row's failed event and a normal end, and is renamed "A preparation failure ends its row with a failed event, not the stream". It still checks for no output.
    • prefillCancellation (cancelTask: false) expected the model's own CancellationError to end the stream. It now expects every row to end with failed carrying a CancellationError, with still no info, output, progress or forward. The cancelTask: true expectations are unchanged.
    • emissionAtFailure (added in 2026-11-07e) expected a throw. It now reads both rows' failed events; its lifecycle check is unchanged.
    • rawModelFailurePreservesPriorOutput and the collectBatchStreamTokens and BatchStreamTextResult helpers handle the new case: a row ends exactly once with info or failed, and emits nothing after it. No assertion was removed.
    • Added: rowFailureLeavesOtherRows.
  • 2026-11-07e: none of this PR's existing tests changed; the six lifecycle tests are new.
  • None in 2026-11-07d.
  • BatchStreamTextResult.append in BatchTokenIteratorTests.swift gains a .steering case that records an issue (e361606), so the helper compiles against main's new Generation case. No existing assertion changes.
  • Existing assertions are unchanged. BatchGenerationTests gains the four-case prefill-cancellation regression; its existing model fixture and locked probe gain optional chunked-prefill/cancellation modes.

AI assistance: implementation, tests, documentation and stack cleanup were prepared with Codex at the maintainer's request for this origin fork. The earlier restack was made with Claude Code. Codex prepared the cancellation follow-up and its regression coverage for this origin fork.

🤖 Generated with Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T05:09:19.525478Z 9f75ec3 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from 3fc905b to 3394218 Compare November 6, 2026 03:54
@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch 2 times, most recently from 09aa9fc to 4b236d1 Compare November 6, 2026 04:23
@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from 3394218 to 05bdca8 Compare November 6, 2026 04:23
@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from 05bdca8 to 71f07c2 Compare November 6, 2026 20:41
@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch from 4b236d1 to 045c21d Compare November 6, 2026 20:41
@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch 2 times, most recently from dd7bdff to fe57954 Compare November 6, 2026 21:18
@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch from 825bb5a to 46e5197 Compare November 6, 2026 21:18

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fe57954d5e

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

@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from d484159 to f716203 Compare November 6, 2026 22:22
@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch from 46e5197 to 5254d24 Compare November 6, 2026 22:22
@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from f716203 to e361606 Compare November 7, 2026 05:11
@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch from 5254d24 to 472604a Compare November 7, 2026 05:11

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e3616060c5

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

}
iterator.remove(iterator.uids)
// Cache owners and consumers may proceed only after queued device work settles.
Stream.defaultStream.synchronize()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Synchronize the stream used by the batch worker

When generation runs with an overridden MLX execution stream, BatchTokenIterator submits its pipelined asyncEval work to that stream, but cleanup synchronizes Stream.defaultStream instead. The producer can therefore finish while its queued device work is still running, violating the task API's cleanup guarantee when callers await task.value before reusing resources. Capture StreamOrDevice.default.stream and synchronize it here, as the existing generateLoopTask in Evaluate.swift does.

Useful? React with 👍 / 👎.

@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch from 472604a to a5b9179 Compare November 7, 2026 06:25
@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from e361606 to e40c18a Compare November 7, 2026 06:25
ronaldmannak and others added 3 commits November 6, 2026 23:50
Treat CancellationError as task cancellation only while the producer is cancelled, finish unfinished rows once, and retain the common cache/device cleanup. Preserve error propagation for actual model failures and uncancelled model-thrown CancellationError. Exercise real between-chunk cancellation and the error control in raw and decoded streams.

AI assistance: implemented, reviewed and validated with Codex for this origin fork.
Main added Generation.steering for chat-session steering. The batch
streams take no steering control and never emit it, so the helper records
it as unexpected, as it does an embedded info event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ronaldmannak
ronaldmannak force-pushed the codex/batched-generation-streams branch from e40c18a to 84a3adf Compare November 7, 2026 08:11
@ronaldmannak
ronaldmannak force-pushed the codex/quantized-batch-kvcache branch from a5b9179 to 13957b4 Compare November 7, 2026 08:11
ronaldmannak and others added 4 commits November 7, 2026 06:19
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The batch generation task now captures StreamOrDevice.default.stream when it
is created and synchronizes that stream in cleanup, as the single-sequence
generateLoopTask does, instead of reading Stream.defaultStream at the end.

MLX's default stream is task-local (withNewDefaultStream, withDefaultDevice
and using(device:) all bind it with TaskLocal), and task locals carry into
the Task and through the GenerationWorker hop, so both expressions name the
same stream today. The change makes the stream explicit and keeps the two
generation paths alike; it has no observable effect, so there is no test
that fails without it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PR 91 changed BatchTokenIterator.next() to return events, so the stream
driver in BatchGeneration.swift now consumes them:

- .token goes to the row's handler; .finished(stopToken:) takes the stop
  path that a stop-token Response took before; .finished(.length) completes
  the row after its last token; .failed fails the stream with that error
  after the step's other output, as an admission throw did before.
- Each token the driver counts is recorded with recordEmittedToken(id:token:)
  before its handler sees it, as the single-sequence loop does: generated
  tokens always, stop tokens (EOS or a protocol stop) only with
  includeStopToken. Tokens after a consumer stops partway through a step
  are never recorded.
- Cleanup removes every row of the batch, including rows that ended in the
  last step, so each processor is finalized exactly once however the
  stream ends.

New BatchGenerationTests check that lifecycle with a ThinkingBudgetProcessor
behind a recording processor, for EOS (with and without includeStopToken),
length, a stop string, a protocol stop token, a consumer that stops
partway through a step, task cancellation and failed rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ronaldmannak and others added 2 commits November 7, 2026 11:26
BatchGenerationEvent gains failed(uid:_:). A row that cannot join the batch
(its supplied cache does not match, its prefill throws, or the model's state
allows one row) now ends with that event after its handler finishes, and
the other rows carry on to their own info events. Before, the first such
row ended the whole stream with its error. Every row ends with exactly one
info or failed event. A prefill stopped by the task's own cancellation still
completes its row as .cancelled. An error from a batched model step still
ends the stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48f689afdb

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

Comment on lines +230 to +232
// Cancellation is checked before next(), which pipelines more MLX work.
while !Task.isCancelled, !terminated {
guard let events = try iterator.next() else { break }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop admission before decoding when prefill is cancelled

If cancellation occurs during a later prompt's chunked prefill after an earlier row was admitted, checking cancellation only before iterator.next() does not prevent new GPU work. BatchTokenIterator.admit() catches the later row's CancellationError, then samples the previously admitted rows, and next() proceeds into decode() despite the cancelled task. The new .failed handling runs only after those forwards have been submitted; with maxTokens: 1, the earlier row even completes as .length instead of .cancelled. Ensure cancellation interrupts admission before sampling or batched decoding, while still finalizing all unfinished rows and synchronizing already-submitted work.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed at the source in PR 91 (1e95cae), merged into this PR. A CancellationError from a prefill while the current task is cancelled now stops admission at once: the rows that have not failed go back to the queue, failures already recorded arrive with the next call, and next() throws before any sampling or decoding, so this driver completes the rows as .cancelled. cancelledAdmissionStopsBeforeSampling fails on acebd0b (7 issues) and passes on 1e95cae.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed at the source in PR 91 (1e95cae), merged into this PR. A CancellationError from a prefill while the current task is cancelled now stops admission at once: the rows that have not failed go back to the queue, failures already recorded arrive with the next call, and next() throws before any sampling or decoding, so this driver completes the rows as .cancelled. cancelledAdmissionStopsBeforeSampling fails on acebd0b (7 issues) and passes on 1e95cae.

ronaldmannak and others added 7 commits November 7, 2026 12:24
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The scenario Codex reported on this PR: the first row is prefilled and the
task is cancelled during the second row's chunked prefill. With PR 91's
fix, merged in, no row decodes, no decode forward is submitted, and both
rows complete as .cancelled. Before it, the first row decoded and
completed as .length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

1 participant