Skip to content

Recreate the chat backend context after a decode failure - #2226

Merged
malibio merged 2 commits into
mainfrom
issue-2172-metal-oom-recovery
Aug 21, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2172-metal-oom-recovery

Conversation

@malibio

@malibio malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

Closes #2172 for the two defects it identifies as separable and directly fixable:

  1. The error state is permanent. llama.cpp's own log says "recreate the backend to recover" after a Metal command-buffer failure (e.g. OOM during a large prefill), but nothing ever did — ChatLlamaState cached the same LlamaContext for the engine's lifetime, so every decode after the first failure hit the identical poisoned backend.
  2. Failures were indistinguishable from success in logs. All three ctx.decode() call sites (prefill, and both per-token generation retries) now surface a distinct ChatError::BackendDecodeFailed instead of the generic InferenceError, so this failure mode is identifiable in daemon logs/traces without guessing.

What was already correct (verified, not assumed)

Traced the full propagation path before writing any fix:

  • llama_decode does return a non-zero status on this failure (GGML_STATUS_FAILED → -3), which the llama-cpp-2 binding already turns into Err(DecodeError) — not swallowed at the FFI boundary.
  • generate_blocking → generate_streaming → LlamaChatInferenceEngine::generate → agent_loop::run_turn all propagate the Err correctly via ?.
  • local_agent_service.rs (daemon) already appends a visible role: assistant error message per ADR-062 ("refuse loudly, don't clamp silently") when a turn's inference call fails.

So the "silent" half of the bug wasn't in error propagation — it was that the same broken context kept being reused, turning one transient OOM into a standing outage for the daemon's lifetime.

Fix

Added ChatLlamaState::poison_context(), called from all three decode failure sites: drops the cached LlamaContext and the KV-cache prefix (cached_prompt) it invalidates, so the next call to get_or_create_context() builds a fresh context — and thus a fresh Metal backend/command queue — instead of reusing the dead one.

Out of scope (left for follow-up)

  • Bounding peak prefill / re-tuning COMPUTE_RESERVE_BYTES. The issue's own arithmetic shows ~4x headroom in the current budget (7.53 GB vs 1.75 GB actual KV cache), so the fixed reserve isn't obviously wrong — the actual peak transient allocation during a large prefill's back-to-back decode chunks is an llama.cpp-internals question I don't have empirical grounds to tune blind. Needs a live repro + measurement, not a guessed constant.
  • History compaction / bounding unbounded prompt growth in the shared-chat-node matrix pattern — a real contributor to reaching these prompt sizes at all, but a separate, larger change.

Test plan

  • cargo test -p nodespace-nlp-engine --features chat-service,metal — 123 passed, live-model tests appropriately ignored (no GGUF present)
  • cargo test -p nodespace-agent — 539 passed
  • cargo test -p nodespace-daemon — 155 passed
  • bun run test:all — 227 frontend files / all Rust workspace tests passed
  • bun run quality:fix — clean
  • Live repro against the issue's reproduction steps (Metal OOM under bun run eval:agent) — not run in this session; recommend verifying against real hardware before closing the issue fully, since this failure mode is inherently hardware/load-dependent and wasn't caught by CI in the first place.

Co-Authored-By: Claude [email protected]

llama.cpp does not recover a Metal backend on its own after a compute
failure (its own log says "recreate the backend to recover" and
nothing does), so a single command-buffer OOM during a large prefill
left the same poisoned context/backend cached in ChatLlamaState
forever — every later decode kept hitting the same dead command
queue.

Add ChatLlamaState::poison_context() and call it on every
ctx.decode() failure (prefill and both per-token generation sites),
dropping the cached context and prefix so the next call rebuilds a
fresh Metal backend instead of reusing the broken one. Errors from
this path now surface as the new ChatError::BackendDecodeFailed
variant, distinct from the general InferenceError, so logs and
callers can tell "backend recovered, retry the turn" apart from other
inference failures.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a small, well-scoped fix (2 files, ~45 lines) for issue #2172: a Metal command-buffer OOM during prefill leaves the chat backend permanently poisoned, silently returning zero tool calls until the daemon is restarted. The PR adds ChatLlamaState::poison_context() and calls it from all three ctx.decode() failure sites, tearing down the cached LlamaContext and cached_prompt so the next call rebuilds a fresh backend. A new ChatError::BackendDecodeFailed variant distinguishes this failure class in logs.

I traced the borrow-checker shape at all three call sites, verified poison_context()'s state invalidation is complete and consistent, independently re-derived that all .decode( call sites on the chat context are covered, and — most importantly — actually read the daemon-level error-surfacing path the PR's narrative depends on (local_agent_service.rs) rather than taking the claim on faith. All of that holds up. This is a net positive, low-risk, correctly-scoped change. No blocking issues found.

Findings

Critical Issues

None.

Suggested Improvements

🟡 Important — poison_context() cannot be unit-tested in isolation; consider whether the KV-invalidation contract deserves a narrower test double
📁 packages/nlp-engine/src/chat/mod.rs:82-113, 175-178

ChatLlamaState owns a real LlamaModel, which can only be constructed via LlamaModel::load_from_file against an actual GGUF + initialized Metal/CPU backend — there's no fixture/mock for it in this codebase (unlike ChatInferenceEngine, which is a trait and is mocked extensively at the agent-crate boundary). I confirmed there are no #[ignore]-gated live-model tests anywhere in chat/mod.rs either, so the PR isn't lowering an existing bar — this file has never had live-model coverage. Given that, the "not unit-testable without a live GGUF+Metal backend" claim in the PR description is fair as stated.

That said, the actual state-invalidation contract this fix depends on — poison_context() clearing both context and cached_prompt together, and a subsequent prefix-reuse computation seeing an empty cached_prompt and falling back to a full decode — is logic that doesn't strictly require a live model to exercise if it were extracted into a small pure function (e.g. fn compute_reusable_prefix(new_tokens: &[LlamaToken], cached: &[LlamaToken]) -> (usize, bool)), tested directly against ChatLlamaState's cached_prompt field mutations. This is not a blocker — it would be a refactor beyond this PR's targeted scope — but worth a follow-up ticket if a future regression in the poison→rebuild→re-cache sequence needs a faster feedback loop than "reproduce a live Metal OOM."

🟢 Suggestion — repeated OOM on the same oversized prompt is now a fast failure loop, not a fix
📁 packages/nlp-engine/src/chat/mod.rs:175-178

The recovery here converts "permanent silent outage" into "one failed turn, backend rebuilt, next turn tries again." That's the right fix for the stated defect. But if the same shared-chat-node history (the ~35 KB / 8.5K-token prompt from the issue's repro) is resubmitted on the next turn — which is exactly what happens today since there's no compaction — the freshly rebuilt context will hit the identical peak-transient-allocation ceiling and OOM again. The failure is now visible (bullet 2) instead of silent, which is the real win, but a user/agent loop that doesn't reduce prompt size will now see a loud, repeating "This turn failed and could not complete" on every subsequent turn rather than one clear error followed by recovery. Worth flagging in the issue thread (not this PR) as the concrete reason bullet 4 (history compaction) is a near-term follow-up rather than a someday-maybe.

Nitpicks

  • Nit: packages/nlp-engine/src/chat/error.rs:29 — BackendDecodeFailed's message ("Backend decode failed and was reset; retry the turn") is instructional to a caller, which is a slightly unusual tone for an error variant (most sibling variants are purely descriptive). Harmless given today's only consumer stringifies it into a user-visible chat message anyway, and the instruction is accurate, so not asking for a change — just noting it reads more like a log line than a typed error.

Verification Notes (for reviewer confidence, not action items)

  • Borrow-checker / control-flow correctness (all 3 call sites, mod.rs:519, 641, 700): ctx is a mutable reborrow of llama.context taken before each loop; poison_context() needs &mut llama (whole-struct). This is legal under NLL only because every branch that calls poison_context() does an unconditional early return Err(...) immediately after — ctx (and, at the second/third sites, the co-live model_ref = &llama.model) has no further use on that path, so its borrow is provably dead at the poison_context() call site. I confirmed by reading each branch to its return that nothing after poison_context() touches ctx, batch, or model_ref before the function exits. Correct.
  • cached_prompt / context invalidated together, no half-poisoned state: poison_context() sets self.context = None and clears self.cached_prompt atomically (single non-yielding function, called under the same MutexGuard held for the whole generate_blocking call). On the next call, get_or_create_context() sees self.context.is_none() and rebuilds; the prefix-reuse computation (tokens.iter().zip(llama.cached_prompt.iter())) sees an empty cached_prompt, yielding prefix_len == 0 and has_reusable_prefix == false, forcing a full decode against the fresh (empty) KV cache — exactly the correct behavior for a rebuilt context. No path leaves one invalidated without the other.
  • Exhaustive decode-site coverage: grepped all .decode( calls in chat/mod.rs — exactly 3, all now poison on failure. sample_with_grammar_rejection and token_count do not call .decode(). embedding.rs uses an entirely separate LlamaContext/backend path, correctly out of scope for this fix.
  • Root-cause narrative for deferring "surface the failure" as already-partially-handled: independently verified, not assumed. ChatError (any variant, including the new one) is converted at the agent crate boundary via inference.rs:128 (.map_err(|e| InferenceError::Engine(e.to_string()))?), propagates through agent_loop::run_turn, and reaches local_agent_service.rs's tokio::select! at line 661-687. The Err(e) arm of send_fut (line 665-675) sets turn_error = Some(e) and emits an error chunk; the subsequent match turn_result { None => match turn_error { Some(e) => ... } } block (line 727-772) appends a visible role: "assistant" message ("This turn failed and could not complete: {e}") per the documented ADR-062 "refuse loudly" rationale, and there's an existing test (failed_inference_turn_surfaces_a_visible_error_not_silent_idle) covering this exact path. The PR's claim holds — this is not a critical gap.
  • ChatError::BackendDecodeFailed exhaustiveness risk: grepped the full workspace for match.*ChatError / ChatError:: usage outside error.rs/mod.rs — zero hits. ChatError never crosses the crate boundary as a typed value (always .to_string()'d at the inference.rs bridge), so the new variant cannot break any exhaustive match elsewhere. Clean, low-risk addition.
  • Scope deferrals (bullets 3 and 4 from issue Metal OOM on large prefill poisons the backend permanently: agent silently returns zero tool calls until daemon restart #2172): reasonable to defer. Bullet 3 (bound peak prefill / re-tune COMPUTE_RESERVE_BYTES) would require guessing a new constant without live peak-transient-allocation measurement data — the issue's own arithmetic already shows ~4x headroom in steady-state KV cache vs. budget, so the actual gap is a different, harder-to-bound quantity (transient compute-graph allocation during back-to-back prefill chunks) that a guessed constant is unlikely to fix correctly. Bullet 4 (history compaction) is correctly identified as a separate, larger change. Neither deferral undermines this PR's own claimed fix for bullets 1 and 2.

Requirements Check

Against issue #2172's "Suggested direction" (bullets 1-2 in scope for this PR; 3-4 explicitly deferred per PR description):

  • ✅ Bullet 1 — Recover from the poisoned backend. ChatLlamaState::poison_context() is called from all three decode-failure sites, tearing down the cached context and prefix so the next get_or_create_context() rebuilds a fresh Metal backend. Verified correct control flow and complete state invalidation (see Verification Notes above).
  • ✅ Bullet 2 — Surface the failure. New ChatError::BackendDecodeFailed variant distinguishes this failure class at the source. Verified (not merely trusted) that the daemon-level path already converts any inference-call failure into a visible role: assistant error message per ADR-062, with existing test coverage — so this failure no longer looks like a silently-successful empty turn.
  • ⏸️ Bullet 3 — Bound peak prefill / memory budget accounting. Explicitly deferred; reasoning is sound (see Suggested Improvements — not requesting this be added here).
  • ⏸️ Bullet 4 — History compaction. Explicitly deferred as a separate, larger change; reasonable.

Recommendation

APPROVE

The core fix is correct: I independently verified the borrow-checker reasoning at all three call sites, confirmed poison_context() leaves no half-invalidated state, confirmed exhaustive coverage of all decode call sites, and — critically — independently traced the daemon-level error-surfacing claim through actual code rather than accepting the PR description's assertion, and it holds. The new error variant is additive and provably can't break any exhaustive match elsewhere in the workspace. Test coverage gap is real but justified given the codebase's existing live-model testing posture, and the one suggested improvement (extracting KV-prefix-reuse logic into a pure, testable function) is appropriately scoped as a follow-up rather than a blocker for this fix. Scope deferrals (bullets 3-4) are well-reasoned engineering judgment, not scope-avoidance.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Nit from PR #2226's review: the error text read as instructional
("...retry the turn") rather than descriptive, unlike its sibling
ChatError variants. Reworded to state what happened, matching the
existing style.

Addresses reviewer recommendations from PR review.
@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

✅ Addressed:

  • 🟢 Nit — reworded ChatError::BackendDecodeFailed's message from instructional ("...retry the turn") to descriptive, matching sibling variants' style. (d37a9b0)

⏭️ Skipped (with reasoning):

  • 🟡 Important — "poison_context() isn't independently unit-testable." The reviewer already characterized this as consistent with the rest of the file (no live-GGUF fixture exists anywhere in chat/mod.rs's test module), and didn't identify a concrete feasible test that was missed — the "extract into a pure function" idea doesn't apply cleanly since the method's whole job is mutating two fields of real state. Flagged as a fair follow-up, not a blocker; leaving as-is.
  • 🟢 Suggestion — "repeated OOM on the same oversized prompt is now a fast failure loop, not a fix." This is a correct observation about system behavior, not a defect introduced by this PR — it's precisely the history-compaction gap the PR description already calls out as deliberately out of scope (bullet 4 of the issue's suggested direction). No action item beyond what's already documented there.

Quality checks and full test suite (bun run quality:fix, bun run test:all, pre-push gate) all green on the new commit.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The only change was a one-line error-message reword with no logic, control-flow, or behavioral impact. Both skipped items were already assessed by the original review as non-blocking follow-ups with sound reasoning, not issues requiring rework. Nothing here changes the shape of the fix the review already evaluated and approved.

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.

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

1 participant