Skip to content

fix(computer): classify local model KV pool and context overflow failures - #669

Open
oldwinter53 wants to merge 1 commit into
mainfrom
fix/local-model-kv-pool-full-recovery
Open

oldwinter53 wants to merge 1 commit into
mainfrom
fix/local-model-kv-pool-full-recovery

Conversation

@oldwinter53

@oldwinter53 oldwinter53 commented Nov 24, 2026 •

Copy link
Copy Markdown

Summary

Hardens product error classification and diagnostics preservation when a local model (llama-server behind Bifrost) exhausts its shared KV pool or context window during a long Agent session or concurrent multi-slot load.

Root Cause

  1. Pi interactive runs lost structured API diagnostics: piTurn only stored raw error text and overwrote Outcome.Diagnostics with processExitDiagnostics (exitCode: 0), never extracting structured HTTP status codes or JSON error code/type fields. As a result, ClassifyExecutionFailure reported generic execution_failed for llama.cpp exceed_context_size_error (400), request_too_large (413), unavailable_error / server_error (503/500 non-SSE shared KV pool full), and rate_limit_exceeded (429). This also prevented RunnerOperations from emitting an overload signal to ModelQueue to back off concurrency.
  2. Pi compaction_end events were ignored: Pi emits compaction_end rather than auto_compaction_end, so overflow compaction failures were not mapped to context_too_long and successful compactions were not counted.
  3. Structured API error parsing rejected llama.cpp numeric codes and unwrapped OpenAI SDK bodies: API error parsing expected string-only JSON code fields and required body.Code != "" on top-level objects, failing on real llama-server responses formatted by @earendil-works/pi-ai (400: {"code":400,"type":"exceed_context_size_error",...}, 503: {"code":503,"type":"unavailable_error",...}). Background model_invoke calls fell back to generic failed, which runtime-model-call.ts treated as retryable instead of failing fast.
  4. Codex HTTP 400 local-gateway errors stayed unclassified: codexErrorDiagnostics kept httpConnectionFailed (400) without inspecting embedded structured API error codes such as exceed_context_size_error.

What Changed

  • Shared structured API error parser (apps/computer/local-daemon/internal/provider/native/diagnostics.go): Added ParseStructuredAPIError and APIErrorDiagnostics parsing only structured signals (HTTP status prefixes, JSON error code/type fields accepting numeric 4xx/5xx status codes and top-level unwrapped bodies, and POSIX network errnos).
  • Pi & Codex native adapters (pi_events.go, pi_run.go, pi_finish.go, codex_events.go): Handle both compaction_end and auto_compaction_end, mark failed overflow recovery as context_too_long, log auto_retry_start/auto_retry_end/failed compaction_end, preserve structured Diagnostics (Code, StatusCode) alongside ExitCode/Signal, and enrich Codex HTTP 400 httpConnectionFailed with embedded structured API error codes.
  • Single-source failure classification & logging (execution_failure.go, model_invoke.go, pi_model_invoke.go, executor.go, daemon/operations.go): Map structured context-overflow, capacity/server, rate-limit, auth, model-not-found, and POSIX network codes (plus HTTP 413) in ClassifyExecutionFailure; route both classifyModelInvokeFailureWithDiagnostics and classifyPiModelInvokeFailure through ClassifyExecutionFailure and a shared failure-code switch (rate_limited -> ModelInvokeRuntimeUnavailable); log classified failure_code, diagnostic_code, and http_status in Daemon and local diagnostic logs.
  • Cross-stack tests: Added real pinned-Pi tests against a mock local gateway (pi_local_error_test.go, covering HTTP 400 exceed_context_size_error, HTTP 503 unavailable_error, HTTP 500 server_error, and bounded settlement for mid-stream HTTP 200 SSE errors), deterministic Pi/Codex/Daemon/failure-classification unit tests, and a Node Services RunnerOperations overload-backoff + diagnostics preservation test.

Scope Note on Mid-Stream HTTP 200 SSE Errors

  • Mid-stream HTTP 200 SSE error chunks (data: {"error":{"code":500,"type":"server_error","message":"..."}}) remain out of scope for structured classification in this PR and continue to settle boundedly as execution_failed / ModelInvokeFailed.
  • Verified against pinned @earendil-works/pi-coding-agent@1.5.2 / @earendil-works/pi-ai and openai@6.49.0: openai/core/streaming.mjs throws new APIError(undefined, data.error, undefined, response.headers) (leaving status === undefined), and @earendil-works/pi-ai/dist/utils/error-body.js (formatProviderError) drops norm.body whenever norm.status === undefined, forwarding only raw error prose in errorMessage. Because Linger never classifies failures by matching natural-language prose, structured classification of mid-stream SSE errors requires upstream pi-ai to preserve norm.body when status is absent.

Verification

  • go test -v -race -count=2 on all touched/new tests in ./internal/provider, ./internal/provider/native, and ./internal/daemon (including real pinned Pi 1.5.2 local gateway tests)
  • make -C apps/teamhub lint-go-daemon BASE=origin/main (0 issues)
  • GOOS=windows GOARCH=amd64 go build ./... (apps/computer/local-daemon)
  • pnpm --filter @linger/node-services typecheck && pnpm --filter @linger/node-services lint
  • pnpm --filter @linger/node-services exec vitest run tests/agent/runner-gateway/runner-operations-public.test.ts (63/63 passed)
  • pnpm --filter @linger/web test src/features/rooms/runtime-status/runtime-failure-message.test.ts (22/22 passed)
  • make check-repository && make check-repository-gate BASE=origin/main

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Request changes (1 P1, 1 P2, 1 P3)

Scope: base main, merge base 94ada676. Reviewed 1 commit (400981e0) touching 21 files. I followed the rules from the coderbook (sections 2, 3 and 5), ponytail-review (sections 1–3) and karpathy-guidelines (sections 2–3) skills from memory; I did not load them in this session. The review ran in a separate session.

Findings

P1

apps/computer/local-daemon/internal/provider/execution_failure.go:44 — the provider error-code classification now exists in two copies, and they already disagree

  • diagnosticFailureCode now contains the full llama.cpp/OpenAI/Anthropic code lists: context overflow, auth, rate limit, server/unavailable, and POSIX errnos.
  • The same lists also live in isContextTooLongErrorCode, isAuthErrorCode and isUnavailableErrorCode (internal/provider/model_invoke.go:922-944). This PR extends both copies in parallel.
  • classifyPiModelInvokeFailure (internal/provider/pi_model_invoke.go:75-88) adds a third copy of the status rules: 401/403 → auth, 413 → context, 429/≥500 → unavailable. diagnosticFailureCode already encodes those rules.
  • The copies already diverge. rate_limit_exceeded, rate_limit_error and rate_limit become rate_limited in one place and "unavailable" in the other. model_not_found is a branch in one and a list entry in the other.
  • The POSIX errno regex is also duplicated: posixNetworkErrnoPattern exists in model_invoke.go:916 and again in native/diagnostics.go:139. parseStructuredAPIError (model_invoke.go:918) is a one-line passthrough to native.ParseStructuredAPIError.
  • Failure scenario: the next code anyone adds (say a new llama.cpp type) goes into one list. Interactive Runs and background model_invoke then report different outcomes for the same gateway response, and the Agent Service either backs off or retries depending on the path.
  • Fix:
    • Have classifyPiModelInvokeFailure build native.APIErrorDiagnostics(answer.Error) and send it through ClassifyExecutionFailure. It can then reuse the same switch classified.Code that classifyModelInvokeFailureWithDiagnostics (model_invoke.go:972-984) already uses, mapping rate_limited to ModelInvokeRuntimeUnavailable there.
    • Then delete the code lists that become redundant, use the native errno pattern in one place, and drop the passthrough wrapper.

P2

apps/computer/local-daemon/internal/provider/pi_local_error_test.go:72 — KV-pool exhaustion during decode is still unclassified, and the test name says otherwise

  • The PR body lists "server_error (503/500 shared KV pool full)" among the codes it now classifies.
  • But the mid-stream SSE case ({"error":{"code":500,"type":"server_error","message":"shared KV pool full during decode"}}) asserts wantFailureCode: "execution_failed", an empty wantDiagnosticCode, and ModelInvokeFailed.
  • The case is named "mid-stream SSE error preserves server diagnostics", yet it asserts that no diagnostics are kept.
  • During long sessions with concurrent slots, this is a likely way for the shared KV pool to run out. Such failures still reach users as generic execution_failed and send no overload signal to ModelQueue. Background calls are classified failed and retried.
  • Fix either way:
    • classify the mid-stream error (find out what Pi puts in errorMessage for it), or
    • rename the case and state in the PR description that mid-stream errors stay out of scope.

P3

apps/web/src/features/rooms/runtime-status/runtime-status.messages.ts:149 — runtime-agnostic copy now carries local-model-only advice

  • failureContextTooLong and failureModelServiceError are shown for every runtime. A cloud Codex or Claude context_too_long would now also say the problem may be "available memory" and suggest "reduce concurrent runs". Neither applies to a hosted model.
  • Fix: put the memory/concurrency wording behind a local-model condition, or keep it generic.

Verified as fine

  • Pi 1.2.0 event shape: in the pinned @earendil-works/pi-coding-agent@1.2.0, dist/core/agent-session.js:2420-2425 and :2596-2602 emit compaction_end with reason, result: undefined, aborted, willRetry: false and errorMessage when overflow recovery fails. auto_retry_start (:3073-3078) carries attempt, maxAttempts and errorMessage. These match the new piEventFrame fields and the overflowFailed branch in native/pi_events.go:113-129.
  • overflowFailed locking: it is written under t.mu in pi_events.go, reset at applyMessageEnd (pi_events.go:181), and read under t.mu in pi_finish.go:204-206. The new and touched native tests passed with -race -count=2.
  • pi_finish.go:203-214: exit code and signal are still added only when the Daemon did not cause the failure. The structured API diagnostics are added next to them instead of being overwritten by processExitDiagnostics.
  • codexFailureDiagnostics (native/codex_events.go:308-322): it falls back to message parsing only for an empty code, other, or httpConnectionFailed with status 400. A Codex 400 with no embedded code keeps httpConnectionFailed + 400, so it still classifies as before.
  • ParseStructuredAPIError (native/diagnostics.go:146):
    • Numeric code values are read as an HTTP status only within 400–599. String codes still pass through.
    • Codes that reach Sanitized() are limited by diagnosticCodePattern, so free-form text cannot get into diagnostics.
  • Breaker impact of 503/429 → runtime_unavailable for background calls: these now count toward the breaker (isAvailabilityRuntimeFailure, apps/node-services/src/runtime-model-call.ts:449; threshold 2, 30 s doubling up to 30 min). This matches the PR's stated "fail fast" intent.
  • Language checks: the commit message contains no CJK, and outside zh-CN.json no added line contains CJK.

Unverified: whether TestPiLocalGatewayCapacityAndContextErrors actually ran in CI rather than skipping. CI installs with --ignore-scripts and does not run Go tests with -v, so the log cannot tell. Pi is not installed in my worktree, so I did not run it.

Process notes

  • One conventional commit; no merge commits and no fixup commits.
  • Merge state is BLOCKED, waiting on required review.

CI

  • All checks that ran passed: computer-go, computer-go-windows, web, web tests, web-static, desktop, repository-gate and CodeQL. No check (node-services) job appears in the PR's checks, so the new runner-operations-public.test.ts case was not exercised by CI.
  • I ran go test -race -count=2 on TestPiStructuredFailureDiagnosticsAndCompactionEvents, TestAPIErrorDiagnosticsParsing and TestCodexFailedTurnExtractsStructuredAPIErrorOnHTTP400 in ./internal/provider/native. They passed.

Automated review by Claude Code


Automated review of 400981e by Claude Code.

…ures

Extract structured HTTP status and JSON API error codes from Pi and Codex local-model failures (including llama.cpp numeric error codes and unwrapped OpenAI SDK bodies), deduplicate interactive and background failure classification through ClassifyExecutionFailure, track Pi overflow compaction failures, and preserve structured diagnostics in logs and wire frames.
@oldwinter53
oldwinter53 force-pushed the fix/local-model-kv-pool-full-recovery branch from 400981e to efcf3b9 Compare November 26, 2026 19:05
@oldwinter53

Copy link
Copy Markdown
Author

Rebased onto latest main (6a511c15) and addressed all three review findings in efcf3b9e:

  • P1 (Deduplicate provider error-code classification): Routed both classifyPiModelInvokeFailure (pi_model_invoke.go) and classifyModelInvokeFailureWithDiagnostics (model_invoke.go) through native.APIErrorDiagnostics + ClassifyExecutionFailure + a single shared modelInvokeResultForFailureCode switch (mapping rate_limited -> ModelInvokeRuntimeUnavailable). Removed the duplicated isContextTooLongErrorCode / isAuthErrorCode / isUnavailableErrorCode helpers, duplicate posixNetworkErrnoPattern, and one-line parseStructuredAPIError wrapper, and added unit coverage across both paths.
  • P2 (Mid-stream HTTP 200 SSE error scope & test): Verified against pinned @earendil-works/pi-coding-agent@1.5.2 / @earendil-works/pi-ai and openai@6.49.0 that openai/core/streaming.mjs throws APIError(undefined, data.error, ...) and pi-ai's formatProviderError drops norm.body whenever norm.status === undefined, leaving only raw prose in errorMessage. Rather than matching prose, added a real-Pi HTTP 500 JSON server_error test case (model_service_error / ModelInvokeRuntimeUnavailable), renamed the mid-stream HTTP 200 SSE case accurately to reflect bounded settlement as execution_failed / ModelInvokeFailed, and documented the out-of-scope note in the PR description.
  • P3 (Runtime-agnostic Web copy): Reverted the PR's edits to runtime-status.messages.ts, runtime-failure-message.test.ts, and zh-CN.json in favor of main's concise, runtime-agnostic failure copy, so no local-model-specific advice appears on hosted runtimes.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approve (0 findings)

Follow-up on 400981e. The PR was force-pushed and rebased, so I compared the two versions with git range-diff and then re-reviewed the full merge-base diff (6a511c15, 1 commit, 19 files).

Previous findings

  • Resolved: duplicated failure-code rules. classifyModelInvokeFailureWithDiagnostics and classifyPiModelInvokeFailure now both go through ClassifyExecutionFailure → modelInvokeResultForFailureCode (internal/provider/model_invoke.go:930, internal/provider/pi_model_invoke.go:71). The single code list is in diagnosticFailureCode (internal/provider/execution_failure.go:53).
  • Resolved: mid-stream SSE KV-pool-full errors. The PR body and the test comment now say these are out of scope, and the test case is renamed to match (internal/provider/pi_local_error_test.go).
  • Resolved: local-only advice in the generic Web copy. The Web change is no longer part of the PR.

Verified as fine

  • rate_limited now maps to runtime_unavailable (model_invoke.go:938). In Node, runtime_unavailable is not retried and counts toward the background breaker (apps/node-services/src/runtime-model-call.ts:456,471,882). Repeated 429s or full-KV-pool failures therefore back off instead of being retried. The PR body declares this change.
  • Pi failed turns now keep the structured Code and StatusCode, keep ExitCode and Signal only on a real process exit, and set context_too_long only after a failed overflow compaction. overflowFailed is guarded by t.mu and cleared on each message_end (native/pi_finish.go:206-218, native/pi_events.go:119-135,234).
  • The Codex 400 httpConnectionFailed wrapper is enriched only when Codex's own info is generic (native/codex_events.go:308).

CI: desktop, computer-go-windows, web, repository-gate and CodeQL passed; check (computer-go) was still pending. I ran go test -race -count=1 with focused -run filters on ./internal/provider and ./internal/daemon, and both passed. The pinned-Pi gateway test skipped because Pi is not installed locally. The focused ./internal/provider/native run with -race produced no output within its 300 s limit, so I have no result for that package.

Automated review by Claude Code


Automated review of efcf3b9 by Claude Code.

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.

2 participants