Skip to content

Metal OOM on large prefill poisons the backend permanently: agent silently returns zero tool calls until daemon restart #2172

Closed

Description

@malibio

Summary

A sustained multi-turn agent workload exhausts Metal GPU memory on a 16 GB machine, and the failure is unrecoverable: once the first command buffer fails, the backend enters a permanent error state and every subsequent turn returns zero tool calls until the daemon is restarted.

The daemon does not crash and reports no fatal error. It keeps serving turns that silently do nothing.

Found while running bun run eval:agent against a freshly-built daemon on an isolated database. No code changes; origin/main at 4e669f42.

Impact: a passing-looking eval from a dead environment

The matrix reported 5/16 with a formatted results table, the correct commit, and the correct model. It looks like a legitimate — alarming — regression against the ~6–7/12 baseline. It is not a result at all.

Every failure from the OOM onward reads identically:

✗ 5   Expected 'search_nodes' exactly once, got 0 (tools: )
✗ 6   Expected sequence [resolve_query,update_node] as a subsequence, got:
✗ 9   Expected 'update_node' exactly once, got 0 (tools: )
... (11 scenarios, all `got 0`, all empty tool lists)

Scenarios 1, 2, 3, 4, 7 passed — they ran before the first OOM. Everything after failed with the same empty signature.

This is the same class the eval docs already warn about ("a plausible partial result from an environment where nothing worked, and it took reading daemon logs to notice"), but preflight cannot catch it: the environment was healthy at load and degraded under load.

Root cause: prefill of a large accumulated prompt

Turn-by-turn prefill sizes, from the daemon log:

turn prompt chars tokenized delta decoded
1 3,470 743 —
2 3,478 746 10
3 3,586 769 33
4 29,425 6,953 6,948
5 30,152 7,123 170
6 3,881 846 841
7 32,139 7,606 7,601
8 32,527 7,726 120
9 3,922 881 876
10 35,552 8,518 8,513 ← OOM here

The matrix runs scenario groups in a shared chat node, so history accumulates. By turn 10 the prompt is 35.5 KB / 8,518 tokens, and KV-cache reuse contributes only 5 prefix tokens — so essentially the entire prompt is re-prefilled.

Metal then fails:

error: Insufficient Memory (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)
ggml_metal_synchronize: error: command buffer 0 failed with status 5
ggml_metal_graph_compute: backend is in error state from a previous
    command buffer failure - recreate the backend to recover
graph_compute: ggml_backend_sched_graph_compute_async failed with error -1

84 OOM errors total. The "recreate the backend to recover" instruction is never acted on — nothing recreates it, so the poisoned state persists for the daemon's lifetime.

What this is NOT (each checked and refuted)

Recorded so nobody re-derives them:

  • NOT n_batch pinned to n_ctx. Cap the prefill batch and budget chat context against total RAM, not free pages #1762 fixed that. PREFILL_BATCH_TOKENS = 2048 / PREFILL_UBATCH_TOKENS = 512 are fixed constants, explicitly decoupled from n_ctx.
  • NOT an under-budgeted context window. On this machine fit_n_ctx_to_budget yields 16 GB − 4.97 (weights) − 2.0 (OS reserve) − 1.5 (compute reserve) = 7.53 GB budget, against an actual KV cache of 1.75 GB (512 MiB non-SWA + 1280 MiB SWA at 32K). Four-fold headroom. The arithmetic was conservative, not wrong.
  • NOT embedding-model contention. Zero embedding operations in the 200 log lines preceding the OOM.
  • NOT a second database's model manager. One database, one Chat context created, one model load.
  • NOT a background job colliding. A periodic task fires every 4 minutes (20:50:20, 20:54:20, 20:58:21, …), but the eval's last turn was 20:46:22 and the OOM 20:46:37 — no overlap. Worth noting separately: that task keeps running inference against an already-poisoned backend.
  • NOT host RAM exhaustion. memory_pressure reported 33% free; only one process >1 GB RSS.

Two defects, separable

1. The prefill of a large prompt exceeds what Metal will allocate. COMPUTE_RESERVE_BYTES (1.5 GiB) is a fixed reserve, but the peak transient allocation scales with the prefill size actually submitted. A 2048-token n_batch bounds each chunk, yet an 8.5K-token prefill still submits four back-to-back chunks whose combined graph exceeds what the GPU will give.

2. The error state is permanent and silent — arguably the worse half. llama.cpp says "recreate the backend to recover" and nothing does. The daemon continues accepting turns, generating nothing, and reporting no error to the caller. A user's agent simply stops working until they restart the daemon, with no indication why.

Suggested direction

  • Recover from the poisoned backend. Detect ggml_backend_sched_graph_compute_async failed / status-5 command-buffer failure and recreate the context rather than serving dead turns forever. This is the part that turns a transient allocation failure into a silent outage.
  • Surface the failure. A turn that dies in the backend should reach the caller as an error, not as a successful turn with no tool calls. (Trim #2161/#2164 tool-schema bloat; surface turn-level inference failures #2168 recently began surfacing turn-level inference failures — this may be adjacent.)
  • Bound peak prefill, or account for it in the memory budget. The current reserve is a constant while the cost scales with prompt size.
  • Consider history compaction. A 35 KB prompt with 5 tokens of KV reuse means summarization is not engaging on this path; the shared-chat-node pattern accumulates unboundedly.

Reproduction

cargo build --release -p nodespace-daemon -p nodespace-cli
rm -rf /tmp/nodespaced-test && mkdir -p /tmp/nodespaced-test
NODESPACED_HEADLESS=1 NODESPACE_HOME=/tmp/nodespaced-test \
NODESPACED_SOCKET=/tmp/nodespaced-test/daemon.sock RUST_LOG=debug \
  target/release/nodespaced > /tmp/nodespaced-test/daemon.log 2>&1 &
target/release/nodespace --socket /tmp/nodespaced-test/daemon.sock model load gemma-4-e4b-q4km
NS_BIN=target/release/nodespace NODESPACED_SOCKET=/tmp/nodespaced-test/daemon.sock \
NS_LOG=/tmp/nodespaced-test/daemon.log NS_MODEL=gemma-4-e4b-q4km NS_TIMEOUT_MS=240000 \
  bun run eval:agent e4b /tmp/rep1.json

Machine: 16 GB M-series, macOS. Model: gemma-4-e4b-q4km (5.0 GB), granted n_ctx 32768.

grep -c kIOGPUCommandBufferCallbackErrorOutOfMemory /tmp/nodespaced-test/daemon.log   # 84

Why this matters beyond the eval

The eval is just the first workload heavy enough to hit it. Any user with a long agent conversation on a 16 GB machine reaches the same prompt sizes — and gets an agent that silently stops calling tools with no error and no indication a restart is needed.

It also blocks matrix measurement on this hardware, which is currently the only non-circular check on the prompt work in #2118/#2120/#2122.

Activity

  1. added
    bug
    on Aug 19, 2026
  2. malibio commented on Aug 21, 2026

    @malibio
    CollaboratorAuthor

    Related: #2197 and #2201 are the same failure chain

    Two issues filed since this one describe the segment before and after it. Whoever picks any of the three should read all three — they compose.

    #2197  history budget undercounts real prompt
              ↓ summarizer never fires, prompt grows unbounded
    #2172  prefill exceeds what Metal will allocate → OOM, backend poisoned  (this issue)
              ↓ decode errors on every subsequent turn
    #2201  cached_prompt left stale on decode-error paths → KV prefix corruption
    

    #2197 is the most likely upstream cause. maybe_summarize_history counts only msg.content, so assistant tool-call arguments_json (up to ~2,048 tokens per ReAct round), the tool-definitions JSON, and per-message template overhead are never counted. Its early return then skips summarization even when system+history already exceeds the window.

    That matches what this issue measured exactly: prefill climbing 743 → 6,953 → 7,606 → 8,518 tokens across a shared-chat-node scenario group, with KV reuse contributing 5 tokens on the failing turn. A summarizer that should have engaged and didn't produces precisely that curve.

    #2201 is the aftermath, and already cites this issue by number — it names "the decode-failure class core#2172 shows is real" as its trigger. Once the Metal backend is poisoned here, every later call returns Err after the KV trim, leaving cached_prompt describing the old prompt while the KV cache holds the new one. Silent prefix corruption across chats.

    What this implies for sequencing

    Fixing #2197 may substantially reduce how often #2172 fires, without addressing it: correct accounting keeps prompts inside the window, so the oversized prefill becomes rare rather than impossible. This issue's second defect — that the failure is permanent and silent, with llama.cpp's own "recreate the backend to recover" never acted on — is independent of prompt size and would survive a perfect summarizer.

    So #2197 is the higher-leverage fix, and #2172's recovery half is the one that turns a transient allocation failure into an indefinite outage where the agent accepts turns, calls no tools, and reports no error.

    Correction to this issue's own framing

    The reproduction here used RUST_LOG=debug per the eval docs. A later run at RUST_LOG=info, same scenarios and machine, completed with zero OOMs. So debug-level logging — ~10MB written in ~90 seconds — is part of the trigger condition, and this issue overstates it as prefill size alone. The prefill numbers stand; the threshold is lower than stated when debug logging is on.

  3. malibio commented on Aug 21, 2026

    @malibio
    CollaboratorAuthor

    Frontend: 4794 passed (227 files)

  4. self-assigned this
    on Aug 21, 2026
  5. mstomar125 commented on Sep 3, 2026

    @mstomar125
    Contributor

    Independently re-verified before starting today's drain, along with the linked chain (#2197, #2201): PR#2226 added ChatLlamaState::poison_context() + ChatError::BackendDecodeFailed (confirmed live in packages/nlp-engine/src/chat/mod.rs, wired at every decode-failure call site) — the backend-recovery half. PR#2227/#2231 addressed the prefill-bounding half (compute-buffer reserve retuning + PREFILL_STABILITY_CEILING, confirmed live in agent_loop.rs). Both defects this issue described are fixed. Board status was stuck on Todo despite the real GitHub closure — fixing that now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

backendbughigh-priority

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions