server: uncaught exception in extract_cache kills the generation thread while the HTTP listener keeps accepting — all subsequent requests hang forever with no error
Summary
When extract_cache raises inside mlx_lm.server's generation thread, the server does not crash. The worker thread dies silently, the HTTP listener keeps accepting connections, and every subsequent request hangs forever with zero bytes returned and no error of any kind reaching the client.
This is distinct from #854 and #1390, which describe the server process crashing/aborting on Metal OOM. Here the process stays alive and healthy-looking — which is arguably worse, because nothing downstream can detect the failure.
Environment
mlx-lm0.31.3,mlx0.32.2- macOS 26.3.1, Apple M4, 16 GB
- Model used in the repro:
mlx-community/Qwen3-4B-4bit
The code path
mlx_lm/models/cache.py — KVCache.extract() does a real Metal allocation/copy, and is where a genuine OOM RuntimeError surfaces:
def extract(self, idx):
cache = KVCache()
padding = self.left_padding[idx].item()
cache.keys = mx.contiguous(self.keys[idx : idx + 1, :, padding : self._idx])
cache.values = mx.contiguous(self.values[idx : idx + 1, :, padding : self._idx])
cache.offset = cache.keys.shape[2]
return cachemlx_lm/generate.py — PromptProcessingBatch.extract_cache, GenerationBatch.extract_cache and BatchGenerator.extract_cache all call into it unguarded.
mlx_lm/server.py — ResponseGenerator.__init__ starts the batch loop as a plain Thread:
self._generation_thread = Thread(target=self._generate)
self._generation_thread.start()Inside _generate's main loop:
caches = batch_generator.extract_cache(eos_ids)There is no try/except around this call. The only guarded regions in _generate are self._tokenize(...) and self.model_provider.load(...).
So an exception here propagates out of the thread target. Python prints it via threading.excepthook and the thread dies. The ThreadingHTTPServer accept loop is a separate thread and is completely unaffected — it keeps LISTENing. Meanwhile every request handler is blocked on its per-request result queue's .get(), and with _generate dead nothing ever .put()s again or drains the incoming request queue. Handlers block forever; new connections are accepted and then also hang.
Reproduction
python -m venv /tmp/mlx-repro-venv && source /tmp/mlx-repro-venv/bin/activate
pip install mlx-lm # 0.31.3 / mlx 0.32.2
python run_repro_server.py & # see below; serves on 127.0.0.1:8811
# Request 1 — system + user message, so the request has more than one
# cacheable segment and hits the extract_cache(eos_ids) branch:
curl -s --max-time 30 -X POST http://127.0.0.1:8811/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"mlx-community/Qwen3-4B-4bit","messages":[
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"Say hi in one word."}],"max_tokens":16}'
lsof -iTCP:8811 -sTCP:LISTEN # still listening
# Request 2 — fresh, independent:
curl -sv --max-time 12 -X POST http://127.0.0.1:8811/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"mlx-community/Qwen3-4B-4bit","messages":[{"role":"user","content":"hello"}],"max_tokens":8}'run_repro_server.pyimport sys, threading, logging, importlib
logging.basicConfig(level=logging.INFO)
generate_mod = importlib.import_module("mlx_lm.generate")
def _make_boom(name):
def _boom_extract_cache(self, idx):
raise RuntimeError(
"[metal::Device] Command buffer execution failed: Insufficient Memory "
"(00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)"
)
return _boom_extract_cache
generate_mod.PromptProcessingBatch.extract_cache = _make_boom("PromptProcessingBatch")
generate_mod.GenerationBatch.extract_cache = _make_boom("GenerationBatch")
def _thread_excepthook(args):
print(f"[REPRO] THREAD DIED: thread={args.thread.name} exc={args.exc_value}", flush=True)
threading.excepthook = _thread_excepthook
sys.argv = ["mlx_lm.server", "--model", "mlx-community/Qwen3-4B-4bit",
"--host", "127.0.0.1", "--port", "8811", "--log-level", "INFO"]
from mlx_lm.server import main
main()Honest caveat about this repro: I did not force a genuine multi-GB Metal OOM — reliably exhausting GPU memory on a 16 GB daily-driver machine was impractical. Instead I monkeypatched the exact call sites (the installed package was never modified) to raise the same RuntimeError text Metal produces on OOM. That isolates precisely the behavior in question — how an exception at this call site propagates — which is the part that differs from #854/#1390. That OOM genuinely occurs at this call site is already established by those two issues; the propagation path above is read directly from the shipped source, not inferred.
Observed
- Server starts, model loads,
:8811LISTENing. - Request 1 triggers
extract_cache→RuntimeError→THREAD DIED: thread=Thread-1 (_generate). lsofimmediately after: port still LISTENing, process alive.- Request 2: TCP connects, request sent, then
Operation timed out after 12011 milliseconds with 0 bytes received(curl exit 28). It would hang indefinitely without the client-side timeout. No new line appears in the server log at all — the handler never reaches its logging call.
Expected
Either of these would be a big improvement over hanging:
- Wrap the batch-stepping region of
_generateintry/except, fail the in-flight request(s) with an HTTP 500 and a useful message, and either keep serving or shut down deliberately. - At minimum, if the generation thread dies, make the server stop accepting or immediately fail queued/new requests rather than leaving them blocked on a queue nobody will ever feed.
Happy to put up a PR for the try/except + 500 path if that's the direction you'd want.
Investigated with AI assistance; all code quotes and observations were taken from a running 0.31.3 install.
Source: ml-explore/mlx-lm