You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "Astro-Han (via GitHub)" <gi...@apache.org> on 2026/08/21 04:43:22 UTC
[I] fix(runtime): context budget measures stored events, so hydrated image payloads count as zero [maka]
Astro-Han opened a new issue, #3372:
URL: https://github.com/apache/maka/issues/3372
## 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 `contextBudget` diagnostic: `estimatedTokensBefore: 67,193` against `maxHistoryEstimatedTokens: 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 stored `RuntimeEvent`s.
- `estimateRuntimeEventChars` (`context-budget-helpers.ts:27`) is an if/else allowlist over `content.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 *outgoing* `ModelMessage[]`, and it feeds `promptSegments` diagnostics only (`context-budget.ts:333`) — never a gate. In the failing turn `promptSegments` was `null`.
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.
1. **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.bytes` is `Buffer.byteLength(stableStringify(value))` at the provider seam (`packages/runtime/src/request-shape.ts:58`, `:461`). #2323 consumes those segments for the trace panel; the budget should consume the same numbers as a gate.
2. **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
1. Open a Desktop session on a vision-capable model (observed on `grok-4.6` via `xai-oauth`).
2. `Read` a large PNG — roughly 400 KB on disk, ~550 KB once base64-encoded — so the tool result is stored as a `session_file` ref.
3. Continue the turn.
4. The provider rejects the request; the turn fails as `context_overflow`, while the `contextBudget` diagnostic reports a comfortable `estimatedTokensBefore` that excludes the image entirely.
5. 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_compact` attempts timed out at 300 s; two more completed but produced unusable summaries — `grok-4.6` returned 57/62 output tokens with 922 reasoning tokens, failing the `orderedSectionsPresent` check from #3029 (`malformed_summary_missing_section`), and a relayed `deepseek-v4-flash` finished with `finishReason: tool_calls` and 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 #3341, which already tracks the recovery-hint criterion.
## Related
- #2323 — instruments the same `PreparedRequestSegment` capture for the trace panel (observability; this issue asks for a gate on the same data)
- #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
- #3164 — native PDF inputs, the next referenced payload kind that would hit this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [I] fix(runtime): context budget measures stored events, so hydrated image payloads count as zero [maka]
Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on issue #3372:
URL: https://github.com/apache/maka/issues/3372#issuecomment-5366039605
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.bytes` migration out of scope. Please assign this issue to me if that scope looks right.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [I] fix(runtime): context budget measures stored events, so hydrated image payloads count as zero [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han closed issue #3372: fix(runtime): context budget measures stored events, so hydrated image payloads count as zero
URL: https://github.com/apache/maka/issues/3372
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [I] fix(runtime): context budget measures stored events, so hydrated image payloads count as zero [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on issue #3372:
URL: https://github.com/apache/maka/issues/3372#issuecomment-5365455215
## 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`) is `JSON.stringify(messages).length` over the **hydrated** `ModelMessage[]` — 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:
```js
if (
(options.stepNumber >= 1 || state.capacity.source === 'policy_fallback') &&
!state.exhaustedDetail
) {
```
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
1. **history budget** — owns step 0 by assumption; counts images as exactly 0.
2. **mid-turn capacity check** — measures the hydrated payload correctly; starts at step 1.
3. **`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, then `empty_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.bytes` into a new admission gate — is more than this defect requires. The gate already exists; it is fenced off at step 0.
1. **Drop the step-0 exemption**, so the capacity check covers a turn's first request. The measurement, the capacity (`resolveContextBudgetCapacity`), and the over-limit handling (reentry → fold → `context_budget_exhausted`) are all already in place on that path.
2. **Add one non-LLM rung to the reduction ladder** — drop or downscale the oldest image attachments. This session proves the LLM-summary rung can fail, and it is currently the only rung; a ladder whose sole step depends on a model completion has no floor.
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 a `JSON.stringify` approximation — 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.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [I] fix(runtime): context budget measures stored events, so hydrated image payloads count as zero [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on issue #3372:
URL: https://github.com/apache/maka/issues/3372#issuecomment-5366223372
## Correction: disregard the fix I suggested earlier
[My previous comment](https://github.com/apache/maka/issues/3372#issuecomment-5365455215) recommended dropping the step-0 capacity exemption. **Don't.** I implemented it, measured it, reverted it.
One calculation settles it:
```
rejected request = 889,002 chars
verdict estimator = chars / 4 → ≈ 222,250 tokens
contextWindow = 500,000
```
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_response` result, so the estimator sees the few-hundred-byte ref; and the step-0 fold pool isn't empty either, prior turns are in it via `ai-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, then `empty_summary`, then `malformed_summary_missing_section`. Nothing below it.
Add a mechanical rung *before* the summary rung: collect image-bearing tool results from `state.priorContentEvents`, and in `currentMessages` replace their base64 `file` parts 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, so `ContextLength` falls into the catch-all `没有执行工具,可直接重试`. Recovery is latched to once per `send()` (`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**.*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org