Repository navigation
Recreate the chat backend context after a decode failure - #2226
Conversation
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]>
Code Review SummaryThis 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 I traced the borrow-checker shape at all three call sites, verified FindingsCritical IssuesNone. Suggested Improvements🟡 Important —
That said, the actual state-invalidation contract this fix depends on — 🟢 Suggestion — repeated OOM on the same oversized prompt is now a fast failure loop, not a fix 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
Verification Notes (for reviewer confidence, not action items)
Requirements CheckAgainst issue #2172's "Suggested direction" (bullets 1-2 in scope for this PR; 3-4 explicitly deferred per PR description):
RecommendationAPPROVE The core fix is correct: I independently verified the borrow-checker reasoning at all three call sites, confirmed |
malibio
left a comment
There was a problem hiding this comment.
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.
Addressed review feedback✅ Addressed:
⏭️ Skipped (with reasoning):
Quality checks and full test suite ( Re-Review DecisionDecision: 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. |
Summary
Closes #2172 for the two defects it identifies as separable and directly fixable:
ChatLlamaStatecached the sameLlamaContextfor the engine's lifetime, so every decode after the first failure hit the identical poisoned backend.ctx.decode()call sites (prefill, and both per-token generation retries) now surface a distinctChatError::BackendDecodeFailedinstead of the genericInferenceError, 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_decodedoes return a non-zero status on this failure (GGML_STATUS_FAILED→-3), which thellama-cpp-2binding already turns intoErr(DecodeError)— not swallowed at the FFI boundary.generate_blocking→generate_streaming→LlamaChatInferenceEngine::generate→agent_loop::run_turnall propagate theErrcorrectly via?.local_agent_service.rs(daemon) already appends a visiblerole: assistanterror 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 cachedLlamaContextand the KV-cache prefix (cached_prompt) it invalidates, so the next call toget_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)
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.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 passedcargo test -p nodespace-daemon— 155 passedbun run test:all— 227 frontend files / all Rust workspace tests passedbun run quality:fix— cleanbun 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]