Skip to content

refactor: session API - #48

Merged
Brooooooklyn merged 112 commits into
mainfrom
feat/qwen35-chat-session
Apr 17, 2026
Merged

Brooooooklyn merged 112 commits into
mainfrom
feat/qwen35-chat-session

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Note

Medium Risk
Medium risk because it changes core chat/streaming/tool-call flows and server request normalization, which can break multi-turn behavior or tool-result ordering if edge cases are missed.

Overview
Migrates chat to a session-first API. Removes legacy model.chat() / model.chatStream() usage in favor of a cross-model ChatSession wrapper (send, sendStream, sendToolResult, reset, plus cold-replay helpers) driven by native chatSessionStart/chatSessionContinue/chatSessionContinueTool.

Reworks streaming plumbing. Renames the callback→AsyncGenerator bridge to _runChatStream, adds AbortSignal fast-abort + double-cancel protection, and ensures model wrappers (including Gemma4Model) override chatStreamSession* with async generators so they satisfy SessionCapableModel.

Tightens tool-result and Anthropic message mapping invariants. mapAnthropicRequest now enforces tool_result blocks as a contiguous prefix, rejects unrepresentable nested-image tool results, constrains trailing text/image shapes after tool results, and encodes tool_result.is_error=true content in a JSON envelope.

Tests/docs updated. Adds large hermetic ChatSession unit coverage, updates Qwen3 integration tests to session entry points, adds Gemma4 loader regression tests, extends stream bridge tests, and refreshes README/CLAUDE.md to reflect the new session API; also downgrades @types/node in .yarnrc.yml.

Reviewed by Cursor Bugbot for commit 8be7f98. Bugbot is set up for automated code reviews on this repo. Configure here.

Brooooooklyn and others added 30 commits April 12, 2026 21:00
Factor the post-prefill pipeline (penalty -> sample -> compiled init ->
decode loop -> cache export -> save -> finalize) out of chat_sync into
a shared helper so it can be driven by the upcoming session delta path.
Pure refactor: chat_sync behavior is preserved byte-for-byte.

Also add Qwen3Tokenizer::im_end_id() for resolving the <|im_end|> id
from the tokenizer vocab (needed by the session path, where the raw
eos_token_id from config.json is the wrong sentinel to stop on).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Scaffolding for the session-based chat path:
- Qwen35Cmd::ChatTokensDelta variant wired into handle_qwen35_cmd
- Qwen35Inner::chat_tokens_delta_sync: text-only delta prefill on top
  of an existing session's KV caches, driving chat_with_caches_inner
- Uses <|im_end|> (from tokenizer vocab) as eos instead of the raw
  config.eos_token_id, giving clean cache boundaries for Phase 2's
  multi-turn TS session class

No NAPI exposure yet — Phase 1 is internal Rust scaffolding only.
Guard errors cover: no active session, empty delta, image session.
Phase 1 hardcodes enable_thinking=Some(true); Phase 2 will plumb it
through from ChatConfig.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds crates/mlx-core/tests/qwen3_5_delta_chat.rs, an integration test
that:
- loads a real Qwen3.5 dense checkpoint pointed at by MLX_TEST_MODEL_PATH
- runs turn 1 via chat()
- runs turns 2-4 via chat_tokens_delta_blocking() with a manually
  constructed <|im_end|>\n<|im_start|>user\n...<|im_start|>assistant\n
  delta
- asserts that turn-4 TTFT stays within 1.5x of turn-1 TTFT, proving
  that the new session path actually reuses the KV caches and only pays
  for delta prefill (the pre-Phase-1 path would re-prefill the entire
  accumulating history)

The test is #[ignore]d by default and early-returns if
MLX_TEST_MODEL_PATH is unset, so plain `cargo test -p mlx-core` still
passes without a model on disk. Run it with:

  MLX_TEST_MODEL_PATH=./.cache/models/qwen3.5-0.8b-mlx-bf16 \\
      cargo test -p mlx-core --test qwen3_5_delta_chat \\
      -- --ignored --nocapture

Also adds a non-NAPI `Qwen3_5Model::chat_tokens_delta_blocking` bridge
method so the test (external to the crate) can reach the new command
without requiring any TS-visible export. The method lives in a separate
`#[doc(hidden)] impl` block so it can't accidentally get picked up by
napi-derive.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The delta path is a session-reuse operation by construction: it prefills
a pre-tokenized delta on top of the existing KV caches. Silently accepting
`reuse_cache = Some(false)` would use the session for prefill and then
let `save_cache_state_direct` wipe both the caches and
`cached_token_history` at the end — confusing behavior that also breaks
the next turn's delta.

Reject early (before any state mutation) next to the other guards
(no caches, empty delta, images cached, missing <|im_end|>).

Also tighten a few phase-1 markers:
- FIXME(phase2) next to the hardcoded `enable_thinking = Some(true)`
  pointing at `config.reasoning_effort`
- TODO(phase2) next to `#[allow(dead_code)]` on `Qwen35Cmd::ChatTokensDelta`
- "to be removed in Phase 2" note on `chat_tokens_delta_blocking` doc

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Two fixes to the gated delta TTFT test:

1. Runtime deadlock hazard. `chat_tokens_delta_blocking` calls
   `oneshot::Receiver::blocking_recv()` internally, and blocking on a
   `flavor = "current_thread"` tokio runtime is a documented deadlock
   hazard — it only works today because the reply comes from a separate
   OS thread and nothing else is scheduled. Switch to
   `flavor = "multi_thread", worker_threads = 2` so any ambient task
   scheduled while the bridge is waiting won't starve.

2. Missing structural assertions. The previous test only checked
   `ttft_turn4 < ttft_turn1 * 1.5` plus a trivially-true
   `prompt_tokens >= delta_tokens.len()`. A regressed delta path that
   silently re-prefilled the full history would pass on a fast machine.
   Record a per-turn `TurnSnapshot { ttft_ms, prompt_tokens }` and
   assert:
     - `prompt_tokens` strictly grows across turns 1..=4 (proves the
       session accumulates history instead of being reset)
     - turn 4 TTFT < 1.5x turn 1 TTFT (existing flatness check, kept)
     - turn 4 TTFT < 2x turn 2 TTFT (catches gradual slowdown across
       deltas that an only-vs-turn-1 bound would miss)

Also:
- Extract the ChatML wire format to a module-level `DELTA_FORMAT_TEMPLATE`
  constant so Phase 2's TS session class has one place to grep for.
  Render via a small `render_delta` helper.
- Replace the useless `let _ = im_end_id;` with a real assertion that
  the delta does not contain `<|im_end|>` — any encoding mismatch now
  surfaces as a clear failure instead of a silent 0-token generation.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…puts

`chat_with_caches_inner` had grown to 23 positional parameters and was
leaning on `#[allow(clippy::too_many_arguments)]`. Phase 2 will need to
plumb at least `enable_thinking` from `config.reasoning_effort`, which
would push the count higher.

Pack the arguments into a new `ChatDecodeInputs` struct with named
fields grouped by concern (prefill outputs, compiled-path state, token
bookkeeping, tokenizer/reasoning state, profiler/perf, MLX state).
Update both callers — `chat_sync` and `chat_tokens_delta_sync` — to
construct the struct literal. This is a pure refactor: the helper
destructures in one shot and the downstream body is unchanged.

Remove the `#[allow(clippy::too_many_arguments)]` attribute now that
the signature is a single struct parameter.

Also replace the terse `let _ = y;` workaround with a named
`let _final_sampled_token = y;` plus a comment explaining which clippy
lint it suppresses and why the `decode_loop!` macro repetition hides
the usage pattern from the lint.

Verified: `cargo test -p mlx-core --lib` still green at 1004 passing,
`cargo clippy --all-targets -- -D warnings` clean, `cargo fmt --check`
clean.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Phase 2 of replacing the broken prompt-cache prefix-matching path for
Qwen3.5 Dense multi-round chat. Exposes the session path through NAPI:

- `chat_session_start_sync` — text-only jinja render with `<|im_end|>`
  as eos. Establishes a clean ChatML cache boundary so subsequent deltas
  append without re-rendering the template. Resets caches up-front.
- `chat_session_continue_sync` — builds a raw ChatML user/assistant
  delta on top of the session cache, tokenizes it, delegates to
  `chat_tokens_delta_sync`. Sanitizes the user message via the same
  role/content injection guard as the jinja path.
- `chat_sync_core` — shared internal helper driving both `chat_sync`
  and `chat_session_start_sync`, parameterized by `eos_override`.
  Legacy `chat_sync` passes `None` and is byte-for-byte identical to
  before.
- `Qwen35Cmd::ChatSessionStart` / `::ChatSessionContinue` variants
  wired into `handle_qwen35_cmd`.
- `#[napi] pub async fn chat_session_start` / `chat_session_continue`
  on `Qwen3_5Model`. `index.d.cts` regenerated with the new methods.

Phase 1 cleanup:
- `chat_tokens_delta_sync` now resolves `enable_thinking` via
  `chat_common::resolve_enable_thinking(&config)`. The Phase 1
  `Some(true)` hardcode and FIXME(phase2) comment are gone.
- The `chat_tokens_delta_blocking` non-NAPI bridge is removed. The
  gated integration test migrates to the async NAPI methods directly,
  dropping the delta wire-format constant and its `Qwen3Tokenizer`
  loader.

The legacy `chat_sync` / `chat_stream_sync` paths are unchanged — no
VLM touch, no prefix-verification touch.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Phase 2 of the Qwen3.5 Dense multi-round chat fix. Builds a small
ergonomic TypeScript class on top of the new native session entry
points:

- `new Qwen35Session(model, { system, defaultConfig })` — holds a
  turn counter and routes `send()` through `chatSessionStart` on
  turn 1 and `chatSessionContinue` on subsequent turns. Forces
  `reuseCache: true` regardless of caller config because the session
  path is a session-reuse operation by construction.
- Rejects concurrent `send()` calls on the same session with a
  clear error (the native model has a single worker thread that
  serializes cache mutation; a concurrent in-flight send would race
  the first's cache-save step).
- `reset()` clears the underlying model caches and resets the turn
  counter so the next `send()` goes through `chatSessionStart`.

Unit tests use `vi.fn()` mocks so they run in CI without booting MLX.
The gated Rust integration test at
`crates/mlx-core/tests/qwen3_5_delta_chat.rs` covers the real native
path end-to-end.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Mirror the symmetric guard in chat_tokens_delta_sync. Without this,
a direct NAPI caller passing reuseCache:false to chatSessionStart
would decode successfully but then have save_cache_state_direct wipe
the caches, causing the next chatSessionContinue to fail with a
cryptic "missing session" error. The TypeScript Qwen35Session wrapper
already forces reuseCache:true, but the native surface should fail
fast for other direct consumers.
Lock in an async-friendly signature so future async reset
implementations don't break callers. The body is unchanged — the
underlying resetCaches() is synchronous today, but returning
Promise<void> matches the rest of the session API and works
transparently with `await session.reset()` patterns.
Red-phase tests that exercise the streaming session path we're about
to add. They cover the same turn-routing, inFlight, reuseCache, and
exception semantics as the existing sync `send()` tests but over the
AsyncGenerator surface, plus the Phase-3-specific rule that
`turnCount` must only increment when the final `done: true` chunk is
yielded (so a caller who breaks mid-stream stays on the same turn and
the next stream re-routes through `chatStreamSessionStart`).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Red-phase test for Phase 3 streaming session path. Mirrors the
existing non-streaming TTFT test but drives the upcoming
`chat_stream_session_start_for_test` / `chat_stream_session_continue_for_test`
helper methods and asserts:
- prompt_tokens grows turn over turn (history accumulates),
- ttft stays flat across delta turns (caches are being reused),
- cancellation mid-stream still emits a final done chunk with
  finish_reason="cancelled" AND leaves the session consistent so the
  next continue succeeds.

The `_for_test` helpers expose the underlying mpsc receiver directly
so the test can drive the streaming path without constructing a
`ThreadsafeFunction` from outside a NAPI host. These helpers are
added in the subsequent implementation commit; this commit intentionally
fails to compile until then.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Phase 3 of the chat-session migration: adds the streaming analogs of
the Phase-2 non-streaming session API.

Rust model side:
- `Qwen35Inner::chat_stream_tokens_delta_sync` — mirrors the
  non-streaming `chat_tokens_delta_sync` guards (reject `reuse_cache=
  false`, no active session, empty delta, image session), then runs
  the streaming decode path. Cache state is saved unconditionally
  (even on cancellation) so the session stays consistent for the
  next turn.
- `Qwen35Inner::chat_stream_session_start_sync` — resets caches,
  resolves `<|im_end|>`, and delegates to `chat_stream_sync_inner`
  with the eos override. Guards send a final `done=true` chunk with
  `finish_reason="error"` on violation rather than returning an Err.
- `Qwen35Inner::chat_stream_session_continue_sync` — builds the same
  ChatML delta as the non-streaming path and forwards to
  `chat_stream_tokens_delta_sync`.
- `chat_stream_sync_inner` now takes `eos_override: Option<u32>` so
  both the streaming session-start path and the legacy `chat_stream`
  path can share the prefill + decode pipeline. The existing
  `chat_stream` caller passes `None` for byte-for-byte compatibility.

Command plumbing:
- New `Qwen35Cmd::ChatStreamSessionStart` / `ChatStreamSessionContinue`
  variants and dispatcher arms in `handle_qwen35_cmd`.
- New NAPI methods `chat_stream_session_start` /
  `chat_stream_session_continue` on `Qwen3_5Model` that create the
  unbounded mpsc, forward the command, spawn the callback bridge
  task, and return a `ChatStreamHandle`.
- `#[doc(hidden)]` test helpers `chat_stream_session_start_for_test`
  / `chat_stream_session_continue_for_test` that expose the raw mpsc
  receiver so the gated integration test can drive the streaming
  path without constructing a `ThreadsafeFunction`.

With these, the previously red `crates/mlx-core/tests/qwen3_5_delta_chat.rs`
file now compiles; both new streaming tests remain `#[ignore]`-gated
on `MLX_TEST_MODEL_PATH`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Wires the streaming session NAPI entry points added in b7b872a into
the TypeScript layer.

- Add `Qwen35Model.chatStreamSessionStart` and
  `Qwen35Model.chatStreamSessionContinue` AsyncGenerator overrides
  over the callback-based native methods. Refactors the internal
  pump into `_runChatStream(startCall)` so the session wrappers and
  the legacy `_createChatStream` share one queue/yield/cancel
  implementation.
- Add `Qwen35Session.sendStream(userMessage, config)` with turn-1
  vs. turn-N routing mirroring `send()`, shared `inFlight` guard
  against concurrent use, and forced `reuseCache: true`.
- `turnCount` only advances when the final `done: true` chunk has
  been yielded — caller break / mid-stream exceptions leave the
  counter untouched so the session stays consistent on restart.
- Sync packages/core/index.d.cts with the new NAPI signatures.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The streaming session entry points (chat_stream_session_start_sync,
chat_stream_session_continue_sync, chat_stream_tokens_delta_sync)
previously reported pre-decode guard failures by emitting a fake
final ChatStreamChunk with done=true and finish_reason="error".
The TypeScript Qwen35Session.sendStream wrapper only checked
event.done to decide whether to advance turnCount, so a guard
violation bricked the session: turnCount went to 1 and future
sendStream() calls routed through chatStreamSessionContinue, which
itself immediately tripped the no-session guard and produced more
error chunks ad infinitum.

Replace send_stream_error_chunk with send_stream_error, which sends
napi::Error::from_reason through the mpsc. The NAPI forwarder
invokes the TS callback with (err, null), _runChatStream throws,
and Qwen35Session.sendStream catches the throw in its try/finally
so inFlight clears, sawFinal stays false, turnCount is not
incremented, and the exception re-throws to the caller.

Also add a belt-and-suspenders finishReason !== "error" check in
the session wrapper: even if a future code path were to emit a
done:true error chunk as a regular event, the session must refuse
to advance.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ream

Two new cases in the sendStream describe block:

1. Guard-violation errors thrown from the underlying async generator
   must NOT advance turnCount. The next sendStream() call then
   re-routes through chatStreamSessionStart instead of the bricked
   continue path. Exercises the exception path that
   send_stream_error now triggers on the Rust side.

2. A done:true chunk with finishReason="error" (hypothetical future
   code path) must ALSO not advance turnCount. Exercises the
   belt-and-suspenders defensive check in session.ts.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The cancellation integration test asserted finish_reason was
exactly "cancelled" after handle.cancel(), but the decode loop can
naturally reach stop/length on the very next step before the
cancellation flag is observed. Accept any terminal finish_reason
(cancelled | stop | length) so the assertion doesn't race with
natural completion. The cache-consistency follow-up continue check
remains the real invariant under test.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Route the Qwen3.5 dense text multi-round chat branch through the new
server-side `Qwen35Session.sendStream` API instead of the legacy
`model.chat(messages, ...)` prefix-matching cache-reuse path. The old
path hit a Metal GPU watchdog hang on turn 4 because:
  1. `finalize_chat_result` strips `<think>`/`</think>` from rawText,
     breaking re-render consistency across turns, and
  2. `config.json eos_token_id = 248044` vs the tokenizer_config
     `<|im_end|> = 248046` mismatch produces a cache boundary no jinja
     template can cleanly continue from.

The session API owns the KV cache on the native side and builds a raw
ChatML delta on top of a cache that ends on `<|im_end|>`, so each turn
only prefills the new user message.

Adds a TTFT summary table + asserts turn4/turn1 < 1.5 and
turn4/turn2 < 2.0 to guard against prompt-prefill regressions that
would indicate the cache reuse is broken. End-to-end run on
`qwen3.5-0.8b-mlx-bf16` produces TTFTs 50/22/21/25 ms (turn4/turn1 =
0.51), confirming the session path avoids the watchdog hang and the
cache boundary is correct.

Gemma4, Qwen3 (legacy), Qianfan-OCR, and the VLM image branch stay on
the legacy `chat()` path — they don't hit the Qwen3.5-specific bug and
the session API is currently text-only.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Move image hashing, stream error signaling, ChatML delta builders, and
the IMAGE_CHANGE_REQUIRES_SESSION_RESTART error prefix from the dense
model into chat_common so MoE, LFM2, Qwen3, Gemma4, and Qianfan-OCR can
share the same session machinery in upcoming steps.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Relax the text-only guard on chat_session_start / chat_stream_session_start
so VLM callers can prime a session with image content (the downstream
chat_sync_core path already supports VLM prefill). chat_session_continue /
chat_stream_session_continue now accept an optional images argument and
reject any non-empty value with an IMAGE_CHANGE_REQUIRES_SESSION_RESTART:
typed error — callers must restart the session to change the image.

Add chat_session_continue_tool / chat_stream_session_continue_tool entry
points that build a raw ChatML <tool_response> delta via the shared
build_chatml_tool_delta_text helper (extended with enable_thinking for
parity with the user-continue helper) and replay it through the existing
chat_tokens_delta / chat_stream_tokens_delta paths. This gives Step 2 a
first-class tool-result round-trip on top of a live session cache without
reinventing the delta pipeline.

Wire the new entry points through Qwen35Cmd / handle_qwen35_cmd and the
NAPI surface, regenerate index.d.cts, and pass null through from the TS
wrappers (Qwen35Session.send + stream.ts chatStreamSessionContinue) so the
existing text-only callers keep compiling. Update the gated integration
test with three new assertions: continue-with-image rejection (error
reason starts with the typed prefix), tool-result round-trip, and a VLM
session-start success gated on MLX_TEST_VLM_MODEL_PATH +
MLX_TEST_VLM_IMAGE_PATH.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Mirrors the dense model's chat_sync_core factoring: the legacy chat_sync
and chat_stream_sync entry points become thin wrappers that forward to
chat_sync_core / chat_stream_sync_core with eos_override = None. The
factored cores take an Option<u32> eos_override parameter so Step 2b can
add chat_session_start_sync methods on top of this scaffolding without
re-editing the body. Zero behavior change for legacy callers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…eaming)

Port the Qwen3.5 Dense chat-session primitives to the MoE model as an
additive surface on top of the existing chat / chat_stream entry points.
Adds `chat_session_start`, `chat_session_continue`, `chat_session_continue_tool`,
`chat_tokens_delta_sync`, and the four streaming variants (plus three
`#[doc(hidden)]` test-only helpers) so the TypeScript `Qwen35Session`
layer can reuse cached KV state across turns on MoE checkpoints the
same way it already does on dense. Legacy `Chat` / `ChatStream` arms
and NAPI methods stay in place; removal is deferred to a later step.

The decode loop is inlined rather than factored through a shared helper
because MoE's forward path takes an extra `fa_idx` argument and uses
MoE-specific compiled entry points (`mlx_qwen35_moe_forward`,
`mlx_qwen35_moe_export_caches`, `MoeResetGuard`) that can't cleanly
share code with dense. All shared ChatML / cache / sampling helpers
come from `qwen3_5::chat_common`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Pure refactor in preparation for Step 3b (LFM2 session API surface).
Adds an `eos_override: Option<u32>` parameter threaded through both
sync paths so session methods can pass a custom EOS token (e.g.
`<|im_end|>` for Qwen-style ChatML delimiters). Every existing caller
passes `None`, so behavior is unchanged.

Also adds `cached_image_key: Option<u64>` to `Lfm2Inner` for
structural uniformity with VLM-capable models — always `None` for
text-only LFM2, reset to `None` in `reset_caches`.

No new Cmd variants, no new NAPI methods, no behavior change.
All 1004 mlx-core lib tests pass.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…aming)

Mirrors the Qwen3.5 MoE session surface (commit bc2942b) on LFM2:
adds chat_session_start, chat_session_continue, chat_session_continue_tool
and their streaming variants, plus reset_caches. Session continue paths
prefill a raw ChatML delta on top of live KV/conv caches so turns do not
re-render the jinja template, keeping TTFT flat across a conversation.

LFM2 is text-only, so chat_session_continue takes an opt-in images guard
that returns the IMAGE_CHANGE_REQUIRES_SESSION_RESTART: prefix when
non-empty — this lets the TypeScript ChatSession layer uniformly route
image changes back through chat_session_start across every backend.

Tool continuations use LFM2's plain <|im_start|>tool ... <|im_end|>
delta format (no <tool_response> wrapper) since the LFM2 chat template
identifies tool responses positionally. build_chatml_continue_delta_text
is always called with enable_thinking=Some(false) because the LFM2
template does not inject a <think>\n prefix — the model emits its own
reasoning tags.

Also adds gated integration tests in tests/lfm2_session.rs (10 tests,
env var MLX_TEST_LFM2_MODEL_PATH) covering:
  * TTFT flatness across 4 turns, streaming and non-streaming
  * mid-stream cancellation preserving cache for the next turn
  * image-guard restart prefix for both streaming and non-streaming
  * tool-result round-trips
  * session-not-started and reuse_cache=false guards
  * reset_caches determinism
  * stream vs non-stream byte-for-byte parity

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Pure refactor in preparation for Step 4b (Qwen3 streaming path) and
Step 4c (Qwen3 session API). Adds an `eos_override: Option<u32>`
parameter threaded through `chat_sync_core` so session methods can
pass a custom EOS token (e.g. `<|im_end|>` for ChatML-delimited
session turns). Every existing caller passes `None`, so behavior is
unchanged.

Also adds `cached_image_key: Option<u64>` to `Qwen3Inner` for
structural uniformity with VLM-capable models — always `None` for
text-only Qwen3, reset to `None` in both existing cache-reset paths.

No new Cmd variants, no new NAPI methods, no behavior change.
All 1004 mlx-core lib tests pass.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Introduces first-ever streaming path for the Qwen3 legacy model. Qwen3
previously had zero streaming code — no ChatStreamChunk, no StreamTx,
no chat_stream_* methods. This commit lands the compute core behind
`#[allow(dead_code)]`; Step 4c will wire the `Qwen3Cmd::ChatStream`
dispatch + NAPI `chat_stream` entry point and retire the legacy
non-streaming `chat_sync` / `Qwen3Cmd::Chat` / `chat` NAPI method in a
single coordinated commit.

- Adds `Qwen3Inner::chat_stream_sync_core` mirroring Qwen3.5 Dense's
  `chat_stream_sync_inner` reference but adapted to the Qwen3 forward
  path: `Qwen3Model::forward_fused` with explicit
  kv_keys/kv_values/cache_idx/rope_offsets/left_padding plumbing,
  chunked prefill, zero-delta replay, and the existing cache-reuse
  verification.
- Adopts `chat_common::ReasoningTracker` + `apply_all_penalties` +
  `extract_chat_params` + `parse_thinking_and_tools` +
  `compute_performance_metrics`, and drives the token loop through the
  shared `chat_common::decode_loop!` macro with the streaming block so
  Qwen3 shares the same pipelining, budget enforcement, cancellation,
  incremental detokenization, and is_reasoning tagging as dense/MoE.
- Wraps errors from the core via `chat_common::send_stream_error` in a
  thin `chat_stream_sync` wrapper that delegates with `eos_override =
  None`.
- Adds a Qwen3-local `StreamSender` adapter matching the one used by
  dense/MoE so the shared `decode_loop!` macro's `.call(result, mode)`
  callback surface is satisfied by the dedicated-thread mpsc sender.
- Text-only: Qwen3 legacy has no vision encoder, so the forward closure
  and cache bookkeeping skip image processing entirely. The structural
  `cached_image_key` field always stays `None`.

Post-commit state: 1004 Rust lib tests passing (matches post-4a
baseline), `cargo clippy --all-targets -- -D warnings` clean, `cargo
fmt --check` clean, `yarn build:native` green.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Two targeted fixes to chat_stream_sync / chat_stream_sync_core on the
Qwen3 legacy path:

- compute_performance_metrics now receives the real prefill delta (from
  prefill_input_ids.shape_at(1), or 1 on a zero-delta replay) instead of
  the full rendered prompt length. Cache-hit turns no longer inflate
  prefill_tokens_per_second. Mirrors chat_sync_core's actual_prefill_count
  idiom and qwen3_5 dense's prefill_tokens.len() usage.
- chat_stream_sync wrapper now returns () and forwards errors directly
  via stream_tx.send(Err(e)), matching dense/MoE/LFM2. Drops the
  chat_common::send_stream_error call that was flattening napi::Error
  status codes through to_string().

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…eaming)

Replaces the monolithic `Qwen3Model::chat` NAPI surface with a
session-oriented API that matches the LFM2 / Qwen3.5 shape:

* `chat_session_start` — fully resets the caches and drives the
  `chat_sync_core` / `chat_stream_sync_core` core paths with
  `<|im_end|>` as the stop token so the KV cache ends on a clean
  ChatML boundary.
* `chat_session_continue` — builds a raw ChatML user/assistant delta
  via `chat_common::build_chatml_continue_delta_text`, tokenizes it,
  and delegates to the new `chat_tokens_delta_sync` /
  `chat_stream_tokens_delta_sync_inner` helpers which prefill the
  delta on top of the live session caches (extending `cached_kv_keys`,
  `cached_kv_values`, `cached_cache_idx` in place) and decode the
  reply. Qwen3 is text-only; `images` is an opt-in guard that
  surfaces an `IMAGE_CHANGE_REQUIRES_SESSION_RESTART:`-prefixed error
  so the TS `ChatSession` layer can route image-changes back through
  a fresh `chat_session_start` uniformly across all backends.
* `chat_session_continue_tool` — same mechanics but using the
  Qwen3.5-style `<tool_response>`-wrapped delta builder so the shared
  `chat_common::build_chatml_tool_delta_text` helper can be reused
  verbatim.
* `chat_stream_session_*` — streaming variants of the three methods
  above, plumbed through `StreamTx<ChatStreamChunk>` and driven by
  the existing `decode_loop!` macro with a `DecodeOps::forward`
  closure that threads local `kv_keys` / `kv_values` / `cache_idx`
  (hoisted out of `self` via `std::mem::take` to keep the borrow
  checker happy alongside the immutable `layers` / `final_norm` /
  etc. references).
* `reset_caches` — exposes the existing `reset_kv_caches_sync` helper
  so tests and session orchestration code can return to a known
  clean baseline between turns.

Seven new `Qwen3Cmd` variants wire the NAPI methods through the
existing `handle_qwen3_cmd` dispatcher; the old `Qwen3Cmd::Chat`
variant, the `chat_sync` / `chat_stream_sync` outer wrappers, and
the `chat` NAPI method are deleted (`chat_sync_core` and
`chat_stream_sync_core` remain as the reused core engines). The
`chat_tokens_delta_sync` save-step drops the final generated token
when `finish_reason != "length"` so `cached_token_history` always
ends on the same `<|im_end|>` boundary — matching `chat_sync_core`'s
existing bookkeeping.

All training and paged attention code paths are preserved verbatim.

The `__test__/models/qwen3-chat.test.ts` suite is rewritten to
exercise the new session API (15 tests covering basic send, multi-turn
continuation, image rejection, tool-definition acceptance, finish
reasons, and generation config). The regenerated
`packages/core/index.d.cts` reflects the new Qwen3Model surface.

Gates:
- `cargo test -p mlx-core --lib`: 1004 passed
- `cargo clippy --all-targets -- -D warnings`: clean
- `cargo fmt --check`: clean
- `yarn build:native`: success
- `yarn build:ts`: success
- `vp test`: 601 passed / 4 skipped across 46 files
- `vp test __test__/models/qwen3-chat.test.ts`: 15 passed

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replaced `std::mem::take` with `.clone()` in both `chat_tokens_delta_sync`
and `chat_stream_tokens_delta_sync_inner`. The previous code hoisted
`cached_kv_keys` / `cached_kv_values` out of `self` into owned locals before
`forward_fused` — if any `?` operator propagated an error between the hoist
and the save-back block (OOM, sampling failure, etc.), the function
returned with `self.cached_kv_keys` / `cached_kv_values` emptied but
`cached_token_history` still populated, so the next `chat_session_continue`
call passed the session-started guard and then dispatched forward_fused
with zero-length KV arrays → FFI UB.

The fix mirrors the existing `chat_sync_core` precedent at model.rs:1421:
clone the Vecs at the top (cheap — `MxArray` clones are ref-count bumps on
the Metal side), work on the locals, write back on success. Errors now
leave `self` at its pre-call state automatically because the clones are
dropped without touching `self`.

Also added two tests to `__test__/models/qwen3-chat.test.ts`:
- `chatSessionContinueTool extends the session with a tool-result message`
  — first coverage for `chatSessionContinueTool`, exercises the delta
  path three ways (start → continue_tool → continue) to prove the cache
  stays consistent across tool-result turns.
- `resetCaches restores a clean slate (determinism canary)` — proves the
  happy-path hoist-and-save-back is clean by checking that
  `resetCaches + chatSessionStart` twice produces identical output.

Streaming and cancellation test coverage deferred to Step T2 when the
TypeScript `ChatSession` wrapper lands and the streaming event plumbing
has a natural home.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Delete Gemma4ChatConfig struct in favor of the unified ChatConfig used
  by dense, MoE, LFM2, and Qwen3 legacy.
- Route enable_thinking through chat_common::resolve_enable_thinking so
  Gemma4 follows the repo-wide reasoning_effort → Option<bool> mapping.
- Plumb ChatConfig.tools through apply_chat_template_sync in both the
  jinja path and the manual fallback template render sites.
- Document which unified ChatConfig fields are silent no-ops on the
  current Gemma4 chat entry points (penalties, thinking_token_budget,
  reuse_cache, report_performance). Several become supported in 5b/5c.
- TS side: drop Gemma4ChatConfig from packages/lm/src/stream.ts and
  index.ts, switch the Gemma4Model.chatStream override to ChatConfig.

Step 5a of the chat-session refactor. 5b (cache state migration) and
5c (session methods + NAPI) follow.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Brooooooklyn and others added 3 commits April 17, 2026 10:53
Codex iter-57 finding: getEarliestExpiresAtMs() fell back to the raw
hardTimedOut entry without applying the TTL + absoluteExpiresAt liveness
check that isHardTimedOut() uses. A marker whose TTL had lapsed (or whose
absoluteExpiresAt had been crossed) would return the future scalar, driving
the classification path to retryable 503 even when the retry window was
already closed. This broke MLX_HARD_TIMEOUT_MARKER_TTL_MS=0 semantics and
produced 503 -> 404 flip-flops on the same unrecovered write.

Fix: factor isMarkerLive() and gate the fallback by it. The refresh +
move-to-tail side effects stay localized to isHardTimedOut() so the
classification-path read stays side-effect-free. sweepExpired() remains
the authoritative reaper; the fallback just refuses to expose scalars for
markers that would fail liveness.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…okup

Codex iter-58 finding: getEarliestExpiresAtMs() returned undefined for
dead hard-timeout markers, which the consumer (responses.ts:2204-2227)
treated as "no expiry metadata" — skipping the 404 guard and falling
through to retryable 503 sendStorageTimeout. This regressed the
already-expired case: before iter-58, a past absoluteExpiresAt would trip
the Date.now() >= earliestMs check to produce 404; after iter-58 it became
undefined and produced 503.

Fix: return 0 (sentinel for "already expired") instead of undefined for
dead markers. Date.now() >= 0 is always true, so the consumer's 404 guard
trips correctly. Live markers still return absoluteExpiresAt; no-data
cases still return undefined.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Session TTL stays at 30 min (warm KV cache is GPU memory), but the
stamped `expires_at` on stored response rows is now governed by a
separate `responseRetentionSec` knob (default 7 days, env override
`MLX_RESPONSE_RETENTION_SECONDS`). Previously both used the same 1800s
constant, so `previous_response_id` cold-replay via
`reconstructMessagesFromChain` + `startFromHistory` became impossible
the moment the warm session was evicted. Rows now outlive the warm
cache, making disk-backed recovery within the retention window the
default behaviour.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: 1797cf283c

ℹ️ 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 thread packages/lm/src/stream.ts Resolved
Brooooooklyn and others added 2 commits April 17, 2026 15:03
Collapse multi-paragraph iteration narratives and Codex-review
bookkeeping into concise invariant-level comments across
packages/server/src and __test__/server. Preserves load-bearing
"why" content (race windows, ordering constraints, cross-file
coupling pointers) and all test-name strings — those are historic
regression anchors. Net ~3,400 lines removed, all comment-only; no
code, identifiers, or test behaviour changed. 336/336 server tests
pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…etention, queue backpressure

Four additive fixes to the session/persistence surface; all opt-in-safe
for existing clients.

1. Restart-safe chain continuation. Stamp a `serverBootId` into
   `configJson` alongside `modelInstanceId`; continuations whose stored
   boot id doesn't match the live process fall through to name-based
   resume instead of 400. Within-process hot-swap protection unchanged.
   Makes 7-day row retention actually recoverable across restarts.

2. X-Session-Cache observability. Emit `X-Session-Cache: hit |
   cold_replay | fresh` on both /v1/responses and /v1/messages so
   clients can distinguish warm reuse, SQLite cold-replay, and new
   sessions. `SessionRegistry.getOrCreate` now returns
   `{ session, hit }`.

3. Per-request retention override. Accept `metadata.retention_seconds`
   on /v1/responses; clamped to [60, 7776000]. Falls through to the
   server-level `responseRetentionSec` when omitted.

4. Queue-depth backpressure. `ServerConfig.maxQueueDepthPerModel`
   (env: `MLX_MAX_QUEUE_DEPTH_PER_MODEL`); default unbounded.
   `SessionRegistry.withExclusive` throws `QueueFullError` when
   waiters exceed the cap; endpoints respond HTTP 429 with
   `Retry-After: 1`.

360/360 server tests pass (+24 new). Lint/typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: aefeec5b65

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

Brooooooklyn and others added 2 commits April 17, 2026 16:40
- collapsible_match: inline `if` guards into match arms (mlx-tui)
- unnecessary_sort_by: switch to sort_by_key + Reverse (paddleocr_vl)
- useless_conversion: drop redundant .into_iter() (optimizers, foreign_weights, qwen3)
- unnecessary_min_or_max: drop .max(0) on unsigned subtraction (attention_vjp_test)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Refactors 9 hard-timeout breaker tests in handler.test.ts from real
setTimeout waits (150ms-3200ms each) to `vi.useFakeTimers()` +
`vi.advanceTimersByTimeAsync(n)`. Eliminates a flaky CI failure
(`iter-54 hard-timeout marker clamps to earliest expiresAt`) where
the real-timer budget between "mark row expiring in 1s" and
"assert marker is live" collapsed under load.

Handler soft-timeout internally does `Promise.race([settled,
setTimeout(N)])`, so fake-timer tests can't `await handler(...)`
directly — pattern is now `const p = handler(...); await
vi.advanceTimersByTimeAsync(N); await p;`.

handler.test.ts suite 12s -> 0.85s; full repo suite 48s -> 40s.
144/144 tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 8c47953. Configure here.

Comment thread packages/lm/src/models/model-loader.ts Resolved

@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: 8c47953b2d

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

Brooooooklyn and others added 3 commits April 17, 2026 16:59
…Generator streaming

The native Gemma4Model exposes callback-based
`chatStreamSessionStart(msgs, cfg, cb) -> Promise<ChatStreamHandle>`; the
wrapper in stream.js overrides these with `AsyncGenerator<ChatStreamEvent>`
so `for await` inside ChatSession works. The model-loader was importing
the raw native class, so loadModel/loadSession for Gemma4 returned
instances with callback-based streaming that didn't conform to
SessionCapableModel. All other session-capable models (Qwen3, Qwen3.5
dense/MoE, Lfm2) were already imported from stream.js; Gemma4 was the
lone outlier. Flagged by Cursor Bugbot.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…reserve empty instructions

Two regressions flagged by Codex review:

1. Warm-session continuations whose last message role was assistant or
   system threw 500 ("unsupported last message role on hot path") out of
   runSessionNonStreaming / runSessionStreaming, even though mapRequest
   accepts the shape. Outcome depended on cache state — same payload
   returned 200 under a cold miss, 500 under a warm hit. Gate the hot
   path: single non-user/non-tool continuations now clear the warm entry
   and fall through to the cold-replay branch (primeHistory +
   startFromHistory*), reported as X-Session-Cache: cold_replay.

2. Instructions inheritance gate dropped stored `""`, so a chain that
   explicitly cleared instructions re-resolved to null on every
   continuation and mismatched the cached entry — forcing cold replay
   every turn. Relaxed gate to `typeof === 'string'`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
triggerAbort already calls `handle.cancel()` when the signal fires; the
finally block then called it again unconditionally. Surrounding doc
comments already acknowledged that some native backends throw on
double-cancel, so an aborted stream could surface a native error
instead of terminating cleanly through the synthetic aborted marker —
most visibly on client-disconnect paths. Route both sites through a
`cancelOnce` helper that flips a local flag and swallows any native
throw. Flagged by Codex review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: 8f1d9f0b14

ℹ️ 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 thread packages/lm/src/chat-session.ts Resolved
Assistant history entries were committed as `{role: 'assistant',
content}` with no `toolCalls`, even when the model had just emitted
tool calls. The Jinja chat template (`tokenizer.rs:958`) renders
`ChatMessage.toolCalls` on cold replay, so on image-change restart
or any `startFromHistory` path, the replayed conversation contained
orphan `role: 'tool'` messages with no preceding assistant call —
structurally corrupt, and model behaviour shifted accordingly.

All 8 commit paths routed through a shared `buildAssistantMessage`
helper: `send` / `sendStream` delta, `sendToolResult` /
`sendToolResultStream`, `startFromHistory` /
`startFromHistoryStream`, and the turn-0 / image-change
`runStartPath` / `runStartStreamPath`. Helper filters to ok-status
entries and stringifies Record-shaped arguments so `ChatResult`'s
shape maps cleanly onto `ChatMessage`'s. Flagged by Codex review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: a964d28a9b

ℹ️ 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 thread packages/server/src/server.ts Resolved
Brooooooklyn and others added 2 commits April 17, 2026 17:44
…thPerModel=0

`config.maxQueueDepthPerModel` was forwarded to `ModelRegistry` without
the positive-integer validation applied to the env var. A caller passing
`0` or negative dropped the model offline immediately —
`SessionRegistry.withExclusive` evaluates `queuedCount >= limit` which is
true at 0 on every call, so every request synchronously throws
`QueueFullError` and returns 429. `responseRetentionSec = 0` has the same
failure shape (stamps `expires_at = now`; next cleanup sweep deletes
every row).

Added `normalizePositiveIntConfig` that runs before env fallback and
throws on non-integer / non-finite / NaN / `<= 0` for both knobs, so a
bogus explicit config surfaces instead of masking. Flagged by Codex
review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two-part fix for the intermittent iter-54 failure under load:

1. Root cause at iter-54 was NOT a setTimeout-registration race as
   first hypothesized — the setTimeout did fire and the marker did
   install. The test used `Math.floor(Date.now()/1000) + 1` for the
   shortened row expiry; depending on where in the real second the
   test started, the marker's `absoluteExpiresAt` could land only
   0-1000ms ahead of "now", and the subsequent
   `advanceTimersByTimeAsync(200)` could cross that cap so
   `isHardTimedOut()` auto-deleted the expired marker on read before
   the assertion. Switched `Math.floor` → `Math.ceil` (guarantees
   ≥1000ms margin) and bumped the compensating wall-clock advance at
   the "A ages out" step from 1200 → 2200ms.

2. Audit of sibling tests with the pattern `const p = handler(...);
   await advance(N>0); await p;` surfaced 12 sites that could exhibit
   a genuine setTimeout-registration race (handler hadn't reached
   the persist branch before the clock advanced). Hardened each with
   `while (mock.calls.length < N) await advance(0)` polling — flushes
   microtasks until the wedged persist signal, then advances.

Stability: iter-54 passed 20/20 runs (baseline 16/20). Full suite
892 passed / 4 skipped / 0 failed, 10 consecutive handler-suite runs
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: 3b5dfdfe9a

ℹ️ 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 thread packages/server/src/server.ts Resolved
Comment thread packages/server/src/server.ts Resolved
`parseEnvSeconds` and `parseEnvPositiveInt` did `Math.floor(parsed)` on
positive non-integers, so `MLX_RESPONSE_RETENTION_SECONDS="1.5"` was
accepted as 1 second — rows expire almost immediately,
`previous_response_id` chains break silently. Same class of bug in
`MLX_MAX_QUEUE_DEPTH_PER_MODEL`: "1.5" would clamp the queue to 1.

Both parsers now reject non-integers via `Number.isInteger(parsed)` and
return `undefined` so callers fall through to their documented defaults
(7-day retention / unbounded queue). Permissive by design — env is set
by orchestrators and a startup crash on a typo is harsh; falling through
to the default is safer than silently truncating. The explicit config
path (`normalizePositiveIntConfig`) keeps its throw-on-invalid
semantics — different contract (caller intent is explicit). Flagged by
Codex review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: f0b4668d34

ℹ️ 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 thread packages/server/src/session-registry.ts Resolved
`withExclusive` synchronously incremented `queuedCount` on every entry
before the cap check. In burst `Promise.all([handler(a), handler(b)])`,
both callers enter the admission path in the same microtask — Call 1
bumps queuedCount to 1, Call 2 sees 1 >= maxQueueDepth=1 and throws
QueueFullError even though Call 1 is about to become the runner, not
a waiter. Impact: any pipelined / batched fanout against a single
model (agent frameworks, speculative prefetching) had to inflate the
cap by 1 to compensate.

Added `initialLock` sentinel; `execLock` starts at / resets to it when
the chain drains. Admission now: `asWaiter = execLock !== initialLock`.
Cap check + `queuedCount++` only on the waiter path. The runner-slot
caller never touches `queuedCount`. Synchronous throw contract
preserved (shell stays non-async; async work in `_runExclusive`).
Flagged by Codex review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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: 8be7f98216

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

@Brooooooklyn
Brooooooklyn merged commit 0e095f0 into main Apr 17, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/qwen35-chat-session branch April 17, 2026 12:48
Brooooooklyn added a commit that referenced this pull request May 2, 2026
… task #48)

Adds a `cache_salt: u64` parameter to the four allocator hashing-loop
functions (`find_longest_cache_hit`, `find_longest_cache_hit_per_block`,
`cache_full_blocks`, `cache_full_blocks_per_block`) and the six
adapter wrappers (`find_cached_prefix`, `find_cached_prefix_per_block`,
`register_full_blocks_for_reuse`, `register_full_blocks_for_reuse_per_block`,
`finalize_turn_keep_live`, `finalize_turn_keep_live_per_block`). The salt is
mixed into the FIRST block's hash only when non-zero, matching vLLM's
`cache_salt` composition (`vllm/v1/core/kv_cache_utils.py:521-531`):

    cache_salt_keys = [request.cache_salt] if (start_token_idx == 0
                                               and request.cache_salt) else []
    extra_keys      = lora + mm + cache_salt_keys + prompt_embeds

`cache_salt = 0` is the well-defined "no salt" sentinel — byte-equal to
pre-task-#48 behavior. All in-tree production call sites (Qwen3,
Qwen3.5 dense + MoE, LFM2, Gemma4 model adapters) and existing tests
pass `0u64` so no observable behavior changes.

Adds two focused tests proving first-block-only semantics:

- `cache_salt_only_affects_first_block_hash` (allocator unit test):
  registering a chain under `salt = A` and looking up under `salt = B`
  misses on block 0 and (since the chain breaks on block 0) returns no
  hits — proving cross-tenant first-block isolation. Also confirms
  `salt = 0` is byte-equal to the pre-change behavior, and that the
  salt is NOT mixed at `n > 0` (chained blocks remain reachable when
  the first block matches).
- `cache_salt_isolates_prefix_lookup_first_block` (adapter integration
  test): same property end-to-end through the public adapter API
  (`register_full_blocks_for_reuse` with salt A; `find_cached_prefix`
  with salt B misses; with salt A hits fully).

The implementation routes through a tiny `hash_block` helper that
collapses to `hash_tokens(tokens, parent_hash, extra_keys)` (no extra
allocation) when `cache_salt == 0` or `block_index != 0`. Only the
leading block of a salted chain pays the cost of building a small
effective `extra_keys + [salt]` Vec.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn added a commit that referenced this pull request May 2, 2026
…nic + hot-path Vec

Address codex code-quality findings on task #48:

1. (HIGH) Each adapter wrapper now documents the cache_salt contract
   independently — 0 is the no-salt sentinel, salt is mixed only at
   block n == 0, aligning with vLLM kv_cache_utils.py:521-531. No
   more transitive "see find_cached_prefix" pointers.
2. (MEDIUM) cache_salt_isolates_prefix_lookup_first_block now
   panics with the underlying pool error + an explicit "this test
   intentionally fails instead of skipping because..." reason.
3. (LOW) hash_block: no longer heap-allocates for the salted
   leading-block path — drives the Hasher directly instead of
   materializing an extra_keys + [cache_salt] Vec; bit-equal to the
   prior path (covered by the existing salt-mixing tests).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn added a commit that referenced this pull request May 2, 2026
Three files in `crates/mlx-core/src/models/qwen3_5/` (sparse_moe.rs,
switch_glu.rs, switch_linear.rs) were never declared in the parent
mod.rs — orphaned during the Feb 2026 dense/MoE split. The live MoE
implementations live under `qwen3_5_moe/`. 544 LOC removed; cargo
check + clippy + tests unchanged.

Also refresh the cold-start flow doc-comment in qwen3/model.rs:2016
to show the post-task-#48/#49 4-arg signature
`find_cached_prefix(prompt_tokens, &[], 0, false)` instead of the
stale 2-arg form.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
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