Repository navigation
Description
Summary
Summary
mlxcel-server reliably crashes with a C++ std::invalid_argument exception from mx.squeeze on the third turn of a multi-turn chat conversation against Qwen3-Coder-30B-A3B-Instruct (8-bit MLX), provided the prompt-prefix cache is enabled (default). The crash occurs immediately after the cache successfully serves a prefix hit on Turn 2.
Disabling the cache (--prompt-cache-enabled=false) eliminates the crash entirely; all turns complete cleanly. This isolates the bug to the cache-resume / cache-replay codepath, not to thinking-mode handling, model packaging, or anything else.
The crash reproduces identically across two independent packagings of the same underlying weights:
mlx-community/Qwen3-Coder-30B-A3B-Instruct-8bitlmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit
Environment
- mlxcel version:
0.1.2 - OS: macOS
26.5(Apple Silicon) - Hardware:
M3 Max, 96 GB unified memory - Install method: Homebrew
- Model: Qwen3-Coder-30B-A3B-Instruct (8-bit MLX, both packagings tested)
Reproduction
-
Start mlxcel-server with defaults (prompt cache enabled, all other defaults):
mlxcel-server \ -m <path-to-Qwen3-Coder-30B-A3B-Instruct-8bit-or-MLX-8bit> \ --port 8000 --host 127.0.0.1
-
Send a 5-turn chat conversation where each turn appends a user message to the growing conversation history (standard chat-template accumulation). A minimal reproducer is a Node script that sends sequential
/v1/chat/completionscalls, each carrying the full prior history. (Happy to attach the full script — it's ~150 LOC, no deps, Node 22+.) -
Observe Turn 2 hits the cache (
cached=N/M prompt tokenslog line with N ≈ 90%+ of M). -
Observe Turn 3 crashes with the exception below.
The conversation that triggered the crash was about TypeScript error handling — pretty ordinary content, no special characters. System prompt was "You are a senior TypeScript engineer. Be concise and specific. Use markdown code blocks for code." Five sequential user messages of growing context.
Crash output
libc++abi: terminating due to uncaught exception of type std::invalid_argument: [squeeze] Cannot squeeze axis 1 with size 0 which is not equal to 1.
[1] 87234 abort mlxcel-server -m --port 8000 --host 127.0.0.1
Relevant startup log
INFO mlxcel::server::startup: Tokenizer recognizes a think marker pair; defaulting chat_template kwarg `enable_thinking=true` (issue #590, upstream PR #1114) think_start=Some("<think>") think_end=Some("</think>") think_start_tokens_len=1 think_end_tokens_len=1
INFO mlxcel::server::startup: Prompt-prefix KV cache store enabled (epic #416 / issue #419 + APC #552) capacity_bytes=2147483648 max_entries=1024 ttl_seconds=3600 min_prefix_tokens=32 apc_enabled=false apc_block_size=16 apc_hash=sha256
Note: mlxcel auto-enables enable_thinking=true because the Qwen3-Coder tokenizer has <think>/</think> markers. Also worth noting:
INFO mlxcel::server::chat_request: prompt cache on + preserve_thinking unset: defaulting preserve_thinking=true for prefix stability (override via chat_template_kwargs.preserve_thinking=false) session=__mlxcel_anon__
mlxcel itself flags the cache + thinking interaction as needing special handling. That comment may be load-bearing here — it sounds like the cache-resume path makes an assumption about the shape of preserved thinking tokens that the actual tensor breaks.
Turn-by-turn behavior (cache ON, crashes)
| Turn | prefix chars | TTFT | cached tokens | result |
|---|---|---|---|---|
| 1 | 97 | 587 ms | 0/99 (cold) | OK |
| 2 | 1775 | 112 ms | 425/455 (93%) | OK |
| 3 | 2340 | — | — | 💥 crash mid-prefill |
The Turn 2 cache hit rate of 93% is high enough that the cache is clearly working as designed; the crash is on the next prefill, where mlxcel apparently tries to extend the cached state with new tokens.
Isolation: cache OFF, no crash, all 5 turns complete
With --prompt-cache-enabled=false and otherwise identical inputs, the same 5-turn conversation completes cleanly:
| Turn | prefix chars | TTFT | cached tokens |
|---|---|---|---|
| 1 | 97 | 551 ms | 0/99 |
| 2 | 1775 | 613 ms | 0/455 |
| 3 | 2340 | 875 ms | 0/593 |
| 4 | 4152 | 1252 ms | 0/1046 |
| 5 | 5169 | 1548 ms | 0/1286 |
TTFT scales sub-linearly with prefix length, no crashes. So the cache-disabled codepath is healthy. This rules out:
- The model itself (same model, no crash)
- The chat template + thinking-mode handling (same template active, no crash)
- Any tokenization/encoding issue
- Memory pressure (machine has 96 GB; resident stays well below)
Hypothesis
Looking at the startup log's mention of preserve_thinking=true as "needed for prefix stability," my guess is:
- The cache stores a KV state at the end of an assistant turn that contains
<think>...</think>boundaries - On the next user turn, mlxcel tries to resume from the cached state and append new tokens
- Somewhere in that "detach + adopt" or "merge" path (mentioned in
docs/turbo-kv-cache.md), a tensor is being squeezed on an axis that's expected to be size-1 but is actually size-0 — likely because the boundary between the cached prefix and the new user tokens leaves a degenerate axis somewhere in attention or position-embedding handling
The exception type (std::invalid_argument from mx.squeeze, not a Rust panic from mlxcel-core's own checks) suggests the bad shape gets handed down to the MLX kernel as-is — i.e., mlxcel-core's cache code constructs the shape, doesn't validate, and MLX C++ rejects it.
A possible cheap mitigation while a proper fix is investigated: validate the resumed tensor shapes in the cache-replay path before passing to MLX kernels, and either reject the resume (fall back to full prompt eval) or fix the shape inline.
What I'd suggest as next debugging steps
- Reproduce against any Qwen3-Coder variant with cache enabled
- Add a trace log right before each
mx.squeezecall in the cache replay path to dump the input tensor shape - The bad shape is probably visible at the boundary where cached KV is being extended
Happy to provide the full Node chat-bench script if useful — it's small and reproduces deterministically.
Reproduction steps
## Reproduction
1. Start `mlxcel-server` with defaults (prompt cache enabled — no extra flags needed):
mlxcel-server \
-m <path-to-Qwen3-Coder-30B-A3B-Instruct-8bit> \
--port 8000 --host 127.0.0.1
2. Save this as `repro.mjs` (Node 22+, no dependencies):
const URL = process.env.URL ?? 'http://localhost:8000/v1/chat/completions';
const MODEL = process.env.MODEL ?? 'Qwen3-Coder-30B-A3B-Instruct-MLX-8bit';
const SYSTEM = 'You are a senior TypeScript engineer. Be concise and specific. Use markdown code blocks for code.';
const TURNS = [
'Review this TypeScript function and identify which I/O errors it silently swallows. Be specific about each one.\n\n\nasync function fetchUserData(userId: string): Promise<UserData> {\n const response = await fetch(`https://api.example.com/users/${userId}`);\n const data = await response.json();\n return data;\n}\n',
"Show the full revised function with handling for all the errors you identified. Don't change the signature.",
'Write Vitest unit tests for the revised function. Cover all the error paths you added in the previous turn.',
];
async function call(messages) {
const res = await fetch(URL, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ model: MODEL, messages, max_tokens: 1024, stream: true, temperature: 0 }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let answer = '', buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl;
while ((nl = buf.indexOf('\n')) !== -1) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith('data:')) continue;
const p = line.slice(5).trim();
if (!p || p === '[DONE]') continue;
try {
const d = JSON.parse(p).choices?.[0]?.delta?.content;
if (typeof d === 'string') answer += d;
} catch {}
}
}
return answer;
}
const messages = [{ role: 'system', content: SYSTEM }];
for (let i = 0; i < TURNS.length; i++) {
messages.push({ role: 'user', content: TURNS[i] });
process.stderr.write(`Turn ${i + 1}/${TURNS.length}... `);
try {
const answer = await call(messages);
messages.push({ role: 'assistant', content: answer });
console.error(`OK (${answer.length} chars)`);
} catch (e) {
console.error(`CRASH: ${e.message}`);
process.exit(1);
}
}
3. Run:
node repro.mjs
4. **Observed behavior**:
- **Turn 1** (cold): succeeds. Server log shows `cached=0/N` (cold).
- **Turn 2** (cached): succeeds. Server log shows `cached=425/455 prompt tokens` (93%+ cache hit).
- **Turn 3**: client gets `TypeError: terminated` (the server hangs up mid-stream). Server process aborts with:
libc++abi: terminating due to uncaught exception of type std::invalid_argument:
[squeeze] Cannot squeeze axis 1 with size 0 which is not equal to 1.
5. **Expected behavior**: Turn 3 should complete like Turn 2, with the server extending the cached prefix by the new turn's tokens.Expected behavior
Don't crash :)
Actual behavior
Crash
mlxcel version
0.1.2
Install method
Homebrew (lablup/tap)
Platform
macOS (Apple Silicon)
Model checkpoint
mlx-community/Qwen3-Coder-30B-A3B-Instruct-8bit or lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit
Relevant logs
Additional context
No response
Pre-submission checks
- I searched existing issues and did not find a duplicate
- This is not a security vulnerability (those go to SECURITY.md instead)
Activity
fix: harden chunked prefill range handling
fix: finish chunked prefill when first chunk reaches prompt end (#179)
fix: finish chunked prefill when first chunk reaches prompt end (labl…