Repository navigation
Description
What happened
A Desktop session on grok-4.6 (xai-oauth) entered a loop it cannot leave: every turn fails with context_overflow ("上下文窗口已超出限制") plus the recovery hint "没有执行工具,可直接重试", and automatic history compaction reports "Context summary failed" and keeps failing open. Retrying reproduces it exactly — the prompt is byte-identical on every attempt, so "retry directly" can never succeed.
The session had read three PNG screenshots with Read. From the captured provider request for the failing turn:
- prompt: 93 messages, 889,002 bytes serialized; tool schemas 27,154 bytes
- one single tool result: 554,762 bytes of base64 PNG; two more at 54,962 bytes each
- images are therefore ≈665 KB of an ≈889 KB prompt
- the same turn's
contextBudgetdiagnostic:estimatedTokensBefore: 67,193againstmaxHistoryEstimatedTokens: 500,000— the budget sees no pressure at all - provider outcome:
400 invalid-argument, "Context window exceeded" →errorClass: ContextLength
The control that isolates the images: the history_compact call on the same model and connection, which does not carry the image parts, completed normally at inputTokens: 71,082. Only the image-bearing main call is rejected.
Root cause
The budget does not measure what is sent.
Large payloads are stored by reference — the tool result persists as {"kind":"image","mimeType":"image/png","ref":{"kind":"session_file",...}}, about 360 bytes — and are hydrated into full base64 only when the provider request is built. That two-representation split is legitimate: session_message_chunks caps a chunk at 65,536 bytes, so a 554 KB payload has no business in the row.
The defect is which representation the budget authority reads:
estimateRuntimeEventsTokens(packages/runtime/src/context-budget-helpers.ts:45) is the authority, and it runs on storedRuntimeEvents.estimateRuntimeEventChars(context-budget-helpers.ts:27) is an if/else allowlist overcontent.kind:text,thinking,function_call,function_response,error.kind: "image"matches no branch and returns 0 — not an underestimate, exactly zero.estimateModelMessagesChars(context-budget.ts:344) is the only estimator that runs on the outgoingModelMessage[], and it feedspromptSegmentsdiagnostics only (context-budget.ts:333) — never a gate. In the failing turnpromptSegmentswasnull.
So no gate on this path has ever looked at the bytes that leave the process. Trimming never triggers, and compaction cannot help either: the images sit in the recent retained turns, and compaction folds historical text.
This stayed latent because for text the two representations are nearly the same size, so measuring the wrong one had no consequence. The budget carries an unwritten, never-verified assumption that stored ≈ sent. Images take the gap from ~0 to 554 KB.
Proposed boundary
Not a new else if for image. Adding one concedes the allowlist and the next referenced payload kind — audio, native PDF inputs (#3164), any future blob — reproduces this incident unchanged.
- Measure the request, not the store. The budget's input must be the hydrated payload, after hydration and before dispatch — the only point past which nothing changes the size. That seam already exists and is already captured per item:
PreparedRequestSegment.bytesisBuffer.byteLength(stableStringify(value))at the provider seam (packages/runtime/src/request-shape.ts:58,:461). Instrument prompt composition so the trace can answer "full of what" #2323 consumes those segments for the trace panel; the budget should consume the same numbers as a gate. - Unknown parts fall back to bytes, not zero. Whatever estimator survives must cost an unrecognized part by its serialized size, so an omission over-estimates instead of vanishing.
How to reproduce
- Open a Desktop session on a vision-capable model (observed on
grok-4.6viaxai-oauth). Reada large PNG — roughly 400 KB on disk, ~550 KB once base64-encoded — so the tool result is stored as asession_fileref.- Continue the turn.
- The provider rejects the request; the turn fails as
context_overflow, while thecontextBudgetdiagnostic reports a comfortableestimatedTokensBeforethat excludes the image entirely. - Every retry and every automatic compaction attempt reproduces it — the session cannot be recovered from the UI.
Environment
- Maka commit:
57e08d834 - OS: macOS 26.5.2 (Darwin 25.5.0)
- Surface: Desktop + Runtime Host
- Node.js: v26.7.0
- Provider/model:
xai-oauth/grok-4.6,contextWindow: 500000
Out of scope (separate defects seen in the same session)
- Compaction fail-open. Three
history_compactattempts timed out at 300 s; two more completed but produced unusable summaries —grok-4.6returned 57/62 output tokens with 922 reasoning tokens, failing theorderedSectionsPresentcheck from fix(runtime): history compaction accepts truncated/unstructured LLM summaries without validation #3029 (malformed_summary_missing_section), and a relayeddeepseek-v4-flashfinished withfinishReason: tool_callsand an empty body (empty_summary). Real defects, but not on this causal chain: correct budgeting would have handled the images before compaction was ever needed. - Misleading "retry directly" guidance on a failure whose next request is byte-identical. Same shape as provider capacity errors (code=resource-exhausted) surface as "Unknown error" + misleading "retry directly" guidance #3341, which already tracks the recovery-hint criterion.
Related
- Instrument prompt composition so the trace can answer "full of what" #2323 — instruments the same
PreparedRequestSegmentcapture for the trace panel (observability; this issue asks for a gate on the same data) - fix(runtime): bound a single oversized prior turn before the next model request #2371 — an oversized prior turn defeating the budget, where the estimate itself was accurate (~244k estimated vs ~1 MB sent); here the estimate is zero
- feat(runtime): materialize native PDF inputs for verified PDF-capable providers #3164 — native PDF inputs, the next referenced payload kind that would hit this
Activity
Astro-Han commentedon Aug 21, 2026
Correction: the hydrated size is already computed — step 0 just never acts on it
The issue body claims "no gate on this path has ever looked at the bytes that leave the process". That is not accurate, and the accurate version makes the fix considerably smaller.
midTurnRequestPayloadChars(packages/runtime/src/ai-sdk-compaction.ts:2239) isJSON.stringify(messages).lengthover the hydratedModelMessage[]— it sees the base64 in full. It is evaluated on every step, step 0 included (:1934). On step 0 the value is computed, stored as the next step's baseline (:2014), and compared against nothing:Note which way the exemption runs. Capacity is checked at step 0 only when the model's context window is unknown (
policy_fallback,context-budget-policy.ts:463). When the window is known —selected_model, which is this session (contextWindow: 500000) — step 0 is exempt. That encodes an explicit trust assumption: the history budget already bounded step 0, so re-checking here is redundant. The history budget is blind to images, so it did not.So the true value for the rejected request (≈889,002 chars) was computed, persisted as a baseline, and discarded without a comparison.
Three lines of defence, each assuming another owns step 0
recoverFromOverflowError(ai-sdk-compaction.ts:1772) — reactive, and already written for exactly this: "force the fold past the high water regardless of the (evidently under-counting) estimate." Its only lever is LLM summarisation, which failed here (3× 300 s timeout, thenempty_summary/malformed_summary_missing_section), leaving no lower rung.The loop closes because every layer defers step 0 to a layer that cannot see the payload.
Revised proposal (supersedes "Proposed boundary" in the body)
The original proposal — promote
PreparedRequestSegment.bytesinto a new admission gate — is more than this defect requires. The gate already exists; it is fenced off at step 0.resolveContextBudgetCapacity), and the over-limit handling (reentry → fold →context_budget_exhausted) are all already in place on that path.Two follow-ups that are real but not prerequisites for this fix:
PreparedRequestSegment.bytes(request-shape.ts:461) remains the more precise measure — true serialized bytes at the dispatch seam versus aJSON.stringifyapproximation — and is the natural convergence target once the step-0 gap is closed.chargeImageBudget's 12 MB cap (attachments.ts:58) should be re-labelled as what it is: a transport-payload guard, not a context budget. It passed this request at 665 KB / 12 MB while the context was the thing being exceeded.Sun-GLiang commentedon Aug 21, 2026
Hi, I'd like to work on this issue. I've reviewed the correction and plan to cover the step-0 admission gap, add a deterministic non-LLM fallback that omits the oldest hydrated images before relying on summarization, and add regression coverage for the provider-visible request and overflow-recovery paths. I'll keep the broader
PreparedRequestSegment.bytesmigration out of scope. Please assign this issue to me if that scope looks right.Astro-Han commentedon Aug 21, 2026
Correction: disregard the fix I suggested earlier
My previous comment recommended dropping the step-0 capacity exemption. Don't. I implemented it, measured it, reverted it.
One calculation settles it:
The estimator says pass. Removing the exemption changes nothing — and even crediting the images their full 665 KB still lands at ~222k. The provider's real image cost is far above bytes/4, and xAI publishes a text tokenizer only, with no multimodal preflight endpoint.
So: no client-side estimate stops this request at any precision. That also retires the "make the ref carry
byteLength" idea from the issue body — precision was never the binding constraint. The only reliable judge is the provider.(Two smaller corrections to the issue body, neither of which changes the above: images aren't counted as zero — they ride in a
function_responseresult, so the estimator sees the few-hundred-byte ref; and the step-0 fold pool isn't empty either, prior turns are in it viaai-sdk-compaction.ts:1278.)Where the fix belongs
A. The reduction ladder has one rung, and it depends on an LLM.
recoverFromOverflowError(ai-sdk-compaction.ts:1772) is already the right seam — reactive,ContextLength-triggered. But summarisation is its only lever, and here it failed 3× at a 300 s timeout, thenempty_summary, thenmalformed_summary_missing_section. Nothing below it.Add a mechanical rung before the summary rung: collect image-bearing tool results from
state.priorContentEvents, and incurrentMessagesreplace their base64fileparts with a placeholder naming the artifact (protocol structure and artifact intact, so the model can deliberately re-read). Key detail: record the omitted tool call IDs in state and re-apply on every later request, or the durable replay re-hydrates them next step. Don't touch the user's own attachments, the persisted events, or the artifacts.Deterministic, and needs no token arithmetic at all — it only runs after a rejection.
B. The UI recommends the one action that cannot work.
deriveFailedTurnRecovery(apps/desktop/src/renderer/session-status-presentation.ts:157-184) has no context-overflow branch, soContextLengthfalls into the catch-all没有执行工具,可直接重试. Recovery is latched to once persend()(retryAlreadyUsed), so the turn actually fails cleanly — what loops is the user following that hint, each 继续 rebuilding a byte-identical prompt. Independent of A and separately shippable.One open decision
If dropping images still overflows: split the retry latch in two (images once, fold once), or keep a single retry, drop all eligible images at once, and terminate honestly if it still fails? The two reviews disagreed. Implementer's call.
Not claiming this — handing over the analysis. Happy to expand on anything: hydration timing, the structural end-state, or the specific regressions from my exemption experiment.
Disclosure: produced with Claude Code (Claude Opus); two further model instances independently reviewed it against the source and caught the corrections above. I verified every cited file:line myself and ran the exemption experiment against
mid-turn-capacity-backend.test.ts. The fixes in A and B are not implemented or tested.fix(runtime): don't count image bytes as raw chars in the context-bud…
fix(runtime): don't count image bytes as raw chars in the context-bud…
fix(runtime): don't count image bytes as raw chars in the context-bud…
fix(runtime): don't count image bytes as raw chars in the context-bud…
fix(runtime): don't count image bytes as raw chars in the context-bud…
chore(nsh): sync upstream through a901baa2e (0.7.2)
chore(nsh): sync upstream through a901baa2e (0.7.2) (#7325)