Repository navigation
Conversation
runCompression serializes the entire compress zone with buildMessageXML and sends it without checking the total input size. When a single tool result carries an unbounded line (e.g. a 170 KB one-line file read), the request meant to reduce context can itself exceed the provider's context limit. Bound the compress-zone input to MaxContextTokens x 4 bytes before serializing. The largest message is truncated first (with an explicit "... (truncated)" suffix) so small messages keep full content and the summarizer can see that source content was elided rather than silently pretending the full history was reviewed. Closes alibaba#1876.
|
🔍 OpenCodeReview found 2 issue(s) in this PR.
|
| if keep <= 0 { | ||
| return suffix | ||
| } | ||
| return text[:keep] + suffix |
There was a problem hiding this comment.
Slicing a Go string at an arbitrary byte offset (text[:keep]) can split a multi-byte UTF-8 rune, producing an invalid UTF-8 string. This malformed text is then embedded into XML via buildMessageXML and sent to the LLM provider, which may reject the request or produce unexpected behavior.
Use utf8.DecodeLastRuneInString to walk back from the cut point to a valid rune boundary, or use strings.ToValidUTF8 after slicing to clean up the result.
Suggestion:
| return text[:keep] + suffix | |
| // Avoid splitting a multi-byte rune at the cut point. | |
| for keep > 0 && !utf8.RuneStart(text[keep]) { | |
| keep-- | |
| } | |
| return text[:keep] + suffix |
| if text == out[largestIdx].ExtractText() { | ||
| break // no further reduction possible | ||
| } | ||
| out[largestIdx] = llm.NewTextMessage(out[largestIdx].Role, text) |
There was a problem hiding this comment.
When replacing a truncated message, NewTextMessage creates a message with only Role and Content, discarding ToolCalls, Native, and ReasoningContent from the original. Since buildMessageXML serializes ReasoningContent (lines 198–201), if the largest message is an assistant message with reasoning, that reasoning is silently dropped from the compression input. Consider preserving unmodified fields from the original message, e.g. by copying the struct and only replacing the Content field.
NanaseInori
left a comment
There was a problem hiding this comment.
The compression-input failure in #1876 is real, but the new bound does not cover the input that runCompression actually sends. Please address the payload-accounting issue below before merging.
I inspected both changed files, the surrounding buildMessageXML/runCompression path, the linked issue and existing bot findings. I also compared #1170: it addresses the same oversized-compression boundary by dropping older messages, whereas this PR truncates message text. #1885 addresses duplicate rejected requests and is a separate concern. Overlap alone is not the reason for this change request.
Validation: I ran an isolated Go reproduction of this PR's bounding/serialization functions with a minimal text-message stand-in, not the repository test suite. With a 4,096-byte budget, a message containing two visible bytes and 170 KiB of ReasoningContent produces 174,202 bytes of XML. A tool message with exactly 4,096 visible bytes produces 4,171 XML bytes even before the compression template is added. The current tests sum ExtractText lengths and therefore miss both failures.
This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.
|
|
||
| total := 0 | ||
| for _, m := range msgs { | ||
| total += len(m.ExtractText()) | ||
| } | ||
| if total <= inputBudgetBytes { |
There was a problem hiding this comment.
[P2] Enforce the budget on the rendered compression input
This early return only accounts for ExtractText(), but buildMessageXML also serializes ReasoningContent and adds per-message markup; runCompression then adds the compression-template text. For example, an assistant message with content "ok" and 170 KiB of ReasoningContent is returned unchanged for a 4,096-byte budget, and the resulting XML is 174,202 bytes. Even a tool message with exactly 4,096 visible bytes becomes 4,171 XML bytes. The compression request can therefore still cross the intended ceiling and be rejected by the provider—the failure #1876 explicitly asks to prevent.
Please budget the complete rendered prompt, including reasoning and fixed template/wrapper overhead, and either reduce it safely or return an explicit incomplete outcome before issuing an oversized request. Add a runCompression regression with a recording/rejecting fake client that measures the actual request messages, rather than only summing ExtractText().
Measure the request as sent, including reasoning, XML markup and template text, keep other message fields when truncating, cut on rune boundaries, and skip the request with an error when it cannot fit.
|
@fxia0018 license/claWaiting for status to be reported — Contributor License Agreement is not signed yet. |
|
@NanaseInori thanks for the review. Addressed in 10d3f11:
Could you take another look when you have time? |
|
@fxia0018 Thanks for the follow-up. I reviewed P2: Avoid repeatedly rendering the entire compression requestAt compression.go:287, every field truncation rebuilds all message XML and expands the complete template again. With N similarly sized, oversized fields of length L, this takes roughly N passes and processes O(N^2 * L) bytes. Multiple large tool results can trigger this in a single round: the loop collects and appends all results before attempting synchronous compression. For scale, analytical length accounting with 128 fields of 170 KiB each and the default 800,000-byte budget gives about 22.3 MB of initial input, 124 truncation passes, and 1.44 GB of cumulative rendered text. These are calculated text volumes, not measured heap allocations or a runtime benchmark; intermediate copies are not included. Please avoid rebuilding the whole request on every cut. One approach is to precompute fixed XML/template overhead and the number of The existing XML design is not a constraintPlease also feel free to rethink or replace the XML-based compression design entirely, rather than only patching around it. It is worth reassessing whether this whole-history XML approach is still the right fit compared with commonly used agent-memory patterns, such as:
XML itself is not inherently obsolete, and changing XML to JSON or Markdown alone would not fix the repeated-work problem. The more important choices are bounded processing, explicit handling of omitted evidence, and a budget policy that distinguishes a byte heuristic from the provider's actual token limit and output headroom. A broader redesign is welcome, but is not required to land a focused fix for the performance issue. Please reconcile the chosen policy with #1170 rather than stacking two independent truncation strategies. Validation for this feedback was code inspection and analytical length accounting; repository tests and runtime benchmarks were not executed. AI assistance disclosure: This feedback was prepared with OpenAI Codex and the |
fitCompressionInput re-rendered the full XML + template on each field
truncation, so a round with many oversized tool results spent O(n^2 * L)
building text it already knew. Track the number of {{context}} expansions
and update the excess from each cut's actual byte reduction instead, then
render once. Adds a many-large-results regression test and a benchmark.
|
@lizhengfeng101 thanks for the detailed P2 analysis. Addressed in d1c058a:
On the broader redesign point, I kept this PR scoped to the performance fix as you suggested, and it still reconciles with #1170 (that PR drops older messages at the token-limit boundary, this one bounds the single compression request's own payload). I did not use AI/LLM assistance to generate this change; I reviewed it myself and will be responsible for addressing any further maintainer feedback. |
|
@lizhengfeng101 gentle ping — the P2 "repeatedly rendering the compression request" concern is now addressed in |
|
Thanks for the thorough iteration on this — the rendered-byte accounting and the linear-time fitting loop are solid improvements over the earlier approach. Before merging, I found two P2 defects and one test-fixture gap, all reproduced locally against the merged tree (main @ 734a104 + this PR): P2-1: The byte budget does not guarantee the token limit fitCompressionInput uses MaxContextTokens * 4 bytes as the budget, but 4 bytes/token is only an average for English prose. Measured with the repo's own tokenizer: digits: 3.00 bytes/token With MaxContextTokens=1000 the budget is 4000 bytes, but 3914 bytes of pure-digit tool output still tokenizes to 1305 tokens — over the 1000-token model limit, so the compression request is rejected anyway. This is exactly the failure #1876 asks to prevent. Suggest either validating the final request's token count after fitting, or budgeting with a conservative lower bound (e.g. MaxContextTokens * 2) instead of the average. P2-2: Duplicate {{context}} placeholders cause over-truncation At compression.go:332, target := max(0, largest-excess) subtracts the rendered excess directly from a field-level length, but each field byte removed shrinks the rendered request by ctxCount bytes. The correct target is largest - ceil(excess/ctxCount). Reproduced: one 2000-byte tool result, a template with three {{context}} references, budget 4096. Current code truncates the field to 15 bytes (just the suffix); the correct cut keeps ~1292 bytes. Most of the preservable history is silently discarded. Test fixture gap The equivalence fixtures use MaxTokens=100, so the new budget is 400 bytes while the real compression template text alone is 1772 bytes. fitCompressionInput returns errCompressionInputTooLarge before sending, and TestReviewExecutionEquivalence/{review,scan}/compression fail against the pre-existing fixtures. I confirmed that bumping the fixture to MaxTokens=500 and regenerating the snapshots makes the full reviewtask + llmloop suites pass with -race, so this is fixture adaptation rather than a logic bug — but the PR should include it. Happy to re-review once these are addressed. AI assistance disclosure: This review was conducted by Hermes Agent (model: Kimi-K3.1-Pro) |
Address review feedback on the compression input bound (alibaba#1893): - P2-1: the byte budget (MaxContextTokens x 4) did not guarantee the token limit for dense content. Validate the final compression request's token count against MaxContextTokens and reject it if it still overflows. - P2-2: fitCompressionInput sized the field-level cut against the raw excess instead of excess/ctxCount, over-truncating when the template references {{context}} more than once. Size the cut against ceil(excess/ctxCount). - Fix the compression equivalence fixtures and the uncompressible-context test to use a MaxTokens window the compression request can actually fit.
|
Thanks for the thorough review — all three points are addressed in P2-1 (byte budget doesn't guarantee the token limit): added a post-fit token validation. After P2-2 (duplicate Test fixture gap: the equivalence fixtures ( Happy to re-review — let me know if the token-validation threshold or the budget constant needs further adjustment. |
1ae9b63 to
cefdf10
Compare
|
Thanks for adding the token check after the byte fit. I checked the current head ( 1. A compression request that fits can be rejected. The budget update scales the entire rendered size, including template text and XML that cannot shrink. Here is a small regression case for
Please treat the scaled target as a heuristic, not proof that compression is impossible. Before failing on that target, check the smallest marked request against the original ceilings. If it fits, use it as a lower bound and retain as much history as possible. A regression test should expect success here and keep the existing zero-call assertion for genuinely oversized templates. While touching the ratio, using a 64-bit intermediate would also avoid 2. The per-cut full render is back on the current head. The earlier follow-up describes incremental accounting in Validation: inspected the pinned source and independently checked the byte/token arithmetic for the example above; I did not execute PR code or benchmark it. AI assistance: OpenAI Codex and the |
cefdf10 to
1ae9b63
Compare
…ows tokens Address review feedback on alibaba#1893: the byte budget (MaxContextTokens x 4) is only a heuristic. CJK and other dense content tokenize at ~3 bytes/token, so a request under the byte ceiling can still exceed MaxContextTokens. Instead of rejecting it outright, scale the byte budget down by the observed token density and refit, so a compressible history is kept rather than dropped. The scale factor is < 1 whenever the token count is over budget, so the budget strictly shrinks each pass and the fit eventually either succeeds or reports the markup/template alone is too large.
|
Thanks for the careful review, and apologies again for the I took your point about the byte budget being only a heuristic (not proof a request fits) and fixed it properly. The current head (
To your specific points:
I added Full package tests ( |
…equest Template text and XML markup cannot shrink, so scaling the whole rendered size by the token density can push the byte budget below the smallest request truncation can produce, and a request that fits the token window was rejected. Clamp the scaled budget to the size of that smallest request and skip compression only when it is still over the window. Compute the scaling in 64 bits so it cannot overflow on 32-bit builds, and mark the CJK test fixtures for the English-only check.
|
Correction to my previous reply: point 1 was not actually fixed in 84e257a. 91a6d66 adds a lower bound: the scaled byte budget never drops below the size of the smallest truncated request, so compression is only skipped when even that request is over the token limit. Your example is now a regression test (TestRunCompression_ScaledBudgetKeepsReachableRequest). |
Summary
Fixes #1876: memory compression serializes an unbounded input even after the context threshold is exceeded.
runCompressionserializes every compress-zone message withbuildMessageXMLand sends the result as the compression request, without bounding its size.MaxTokensonly limits completion output. When one tool result carries an unbounded line (for example a 170 KB one-line file read), the request meant to reduce context can exceed the provider's context limit itself.Change
Before sending,
fitCompressionInputbounds the rendered compression request toMaxContextTokens × 4bytes:ReasoningContent, the per-message XML markup, and the compression template's own text, not justExtractText().... (truncated), so the summarizer can see that content was elided.ToolCalls,Native,ToolCallIDand the untouched field are kept.runCompressionreturnserrCompressionInputTooLargewithout sending a request. The loop already logs compression failures and keeps the original messages.The bound is in bytes rather than tokens: tokenizing a multi-hundred-KB single-line result is slow, and the bound only needs a cheap, deterministic ceiling.
Tests
TestFitCompressionInput_*cover:ReasoningContent;TestTruncateToByteBudgetadds a multi-byte rune case.TestRunCompression_RequestStaysWithinBudgetdrivesrunCompressionwith a recording client and measures the request it actually sends.TestRunCompression_OversizedTemplateSkipsRequestasserts that no request is sent when the budget cannot be met.runCompressionfixtures usedMaxContextTokens: 50(a 200-byte budget), which the markup of their 20 messages alone exceeds. Raised to 1000 so those tests still exercise the success and identity paths.make checkandmake testpass, andinternal/llmloopcoverage is 94.7%.AI disclosure
This PR was prepared with AI assistance (Claude Code, Claude Opus 5.5). I reviewed and tested the changes.