Repository navigation
fix(harness): prevent missed compaction for multilingual contexts - #2990
guslegend0510 wants to merge 22 commits into
Conversation
Include system prompts, tools, response schemas and reasoning text in compaction estimates. Preserve preprocessing results below the summary threshold and retain history on failed or empty summaries. Fixes agentscope-ai#2985
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
CryoThrust
left a comment
There was a problem hiding this comment.
The new request-overhead accounting is used to decide whether compaction starts, but it is not applied when choosing the preserved tail. compactIfNeeded(..., requestOverheadTokens) calls determineCutoffIndex(messages, totalTokens, config) with conversation-only tokens, and findTokenBasedCutoff still keeps up to the full config.getKeepTokens(). The rebuilt request then adds the same system/tool/response-schema overhead back on top of that tail.\n\nFor example, with keepTokens=800, a preserved 800-token conversation suffix and 400 fixed system/tool/schema tokens, compaction can report success but send roughly 1200 input tokens before the summary itself is counted. This is especially likely for large tool schemas, which is one of the cases this PR explicitly adds to the trigger budget.\n\nCould the cutoff budget be max(0, keepTokens - requestOverheadTokens) (with a documented behavior when the fixed overhead alone exceeds the budget), and could there be a regression test asserting that the post-compaction request estimate, including system/tools/response format, stays within the resolved budget? Otherwise the change detects the overflow earlier but cannot reliably make the final request fit.
|
The conservative non-ASCII counting and the expanded budget scope look right, and the red-on-main budget tests are strong evidence. One enhancement worth considering as a follow-up layer: anchor the estimate to the provider-reported usage of the last successful call. Msg usage is now reliably preserved (#2966), so the middleware can hold (lastUsage, surfaceFingerprint) and compute This would complement rather than replace the estimator fix here — the fixed heuristic remains the bootstrap before the first anchored call and the delta layer afterwards. Separately: the "prune even when summarization is skipped" and "preserve history on failed summary" parts overlap with #2971 (fixes #2970) — worth sequencing with the maintainers so the two PRs don't churn the same ConversationCompactor paths. And since explicit |
Thanks @birdie7761, the usage-anchored estimate makes sense as a follow-up, with the heuristic retained for bootstrap and delta estimation. I’d keep that separate from this fix so the usage guard and provider/model consistency can be tested independently. I’ve merged the latest main, resolved the conflicts, and added English and Chinese release notes explaining that explicit triggerTokens may now trigger compaction earlier, especially for Chinese-heavy conversations. Thanks also for flagging the overlap with #2971. I’m happy to coordinate the merge order with the maintainers and adjust the overlapping changes accordingly. |
Thanks @CryoThrust, you’re right—the fixed request overhead also needs to reduce the retained-tail budget. Updated in dbf5704 to use max(0, keepTokens - requestOverheadTokens), with regression tests for overhead consuming the budget and overhead exceeding it. I also clarified the boundary in the English and Chinese docs: the final message and complete assistant/tool groups are preserved even when they exceed the remaining budget, and the generated summary adds tokens separately. This addresses the tail-budget accounting issue, but the current tests do not establish a hard cap on the complete post-compaction request, including the summary. That part of your suggestion remains open. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of PR #2990 at its current head (automated review of the changes in this diff). 1 item(s) raised below; nothing here blocks the approach itself — details inline.
Findings
- [Critical]
agentscope-harness/src/main/java/io/agentscope/harness/agent/memory/compaction/ConversationCompactor.java:137— The system prompt is double-counted in the compaction budget:requestOverheadTokensalready includes the system message computed in CompactionMiddleware, butmessagesalso has it prepended viaprependSystemMessage. This inflatesrequestTokens, causing premature compaction and a smaller retained conversation tail than configured.
Notes
Inline comments are anchored to the diff; if a line anchor was out of range it is listed above instead.
Automated review by github-manager-bot
| @@ -108,14 +136,15 @@ public Mono<Optional<List<Msg>>> compactIfNeeded( | |||
| config.getPruneConfig()); | |||
|
|
|||
There was a problem hiding this comment.
The system prompt is double-counted in the compaction budget: requestOverheadTokens already includes the system message computed in CompactionMiddleware, but messages also has it prepended via prependSystemMessage. This inflates requestTokens, causing premature compaction and a smaller retained conversation tail than configured.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Real bug, well diagnosed: a flat 2.5 chars/token ratio under-counts CJK and other non-Latin scripts, so the compaction trigger can stay below threshold and the context is never compacted. Per-code-point widths (ASCII 0.4, BMP non-ASCII 1.0, supplementary 2.0), long accumulation with saturating casts, HintBlock/ThinkingBlock coverage, and folding system prompt + tool schemas + response format into the decision are all improvements, and the added CompactionBudgetTest/TokenCounterUtilTest coverage is substantial. Using the reasoning model rather than the compaction model for dynamic thresholds is also the correct call.
Findings
- [Warning]
tailBudget = max(0, keepTokens - requestOverhead)can collapse to 0 and then thrash every turn when prompt overhead alone exceeds the keep budget. - [Warning] summarization failures now propagate, which removes the previous (ugly but bounding) fallback and can leave the context unbounded.
- [Info] tool-schema JSON is re-serialized on every reasoning step — cacheable.
- [Info]
processed == originalidentity check encodes "did preprocessing change anything" implicitly.
Suggestions
The msg.withContent(...) substitutions in pruneToolResults/truncateToolUseArgs are a genuine cleanup — the hand-rolled Msg.builder() copies dropped nothing today only because the field list happens to match.
Verdict
Comment only, not approval: the two [Warning]s are behavioural edges in the core memory path (which cascades into harness/distribution), and the PR still has a merge conflict with main.
Automated review by github-manager-bot
| // the conversation tail; the generated summary is additional. If the overhead | ||
| // exhausts the budget, findTokenBasedCutoff still preserves the final message as the | ||
| // minimum viable conversational tail. | ||
| int tailBudget = Math.max(0, config.getKeepTokens() - requestOverheadTokens); |
There was a problem hiding this comment.
When requestOverheadTokens >= keepTokens — realistic for a small-context model with a large tool catalogue, since keepTokens is itself derived from the same context window in dynamic mode (contextWindow - trigger headroom) — tailBudget becomes 0 and findTokenBasedCutoff keeps only the final message. Because the overhead alone already exceeds the trigger, shouldCompact stays true on the next reasoning step too, so the loop rewrites a one-message tail every turn: constant summarization calls, constant context churn, and effectively no conversational memory. Suggest a floor (e.g. keep at least keepMessages/the last N messages regardless of the token budget) or a guard that skips token-based compaction and logs once when requestOverheadTokens >= keepTokens, so the failure is visible instead of silently degenerate. A regression test for that configuration would be valuable.
| log.warn("Summarization LLM call failed: {}", e.getMessage()); | ||
| return Mono.just("(Summarization failed: " + e.getMessage() + ")"); | ||
| }); | ||
| .switchIfEmpty( |
There was a problem hiding this comment.
Removing the placeholder + onErrorResume here means a transient summarization error now aborts compaction for that turn (the middleware logs and continues with an uncompacted context). That is better than writing a (Summarization failed) marker into the history, but it removes the only bound on growth: if the summarizing model keeps failing, context grows until the reasoning call itself is rejected. Consider a last-resort degrade that does not need the LLM — e.g. apply the existing prune/truncate steps and drop the oldest prefix without a summary — or at minimum surface a metric/WARN so operators can tell "compaction permanently disabled" from "compaction not needed yet".
| List<Msg> messages, List<ToolSchema> tools, GenerateOptions options) { | ||
| long tokens = calculateToken(messages); | ||
| if (tools != null && !tools.isEmpty()) { | ||
| tokens += estimateTextTokens(JsonUtils.getJsonCodec().toJson(tools)); |
There was a problem hiding this comment.
CompactionMiddleware recomputes this on every reasoning step, and input.tools() is effectively constant for the life of an agent, so the full tool-catalogue JSON serialization + code-point scan is repeated work on the hot path (same comment applies to estimateTextTokens, which no longer has an O(1) path). Caching the estimate against the tools list identity, or computing it once when the middleware is constructed, keeps the accuracy without the per-step cost.
| } | ||
|
|
||
| private static Optional<List<Msg>> preprocessedResult(List<Msg> original, List<Msg> processed) { | ||
| return processed == original ? Optional.empty() : Optional.of(processed); |
There was a problem hiding this comment.
Identity comparison as the "did preprocessing change anything" signal is a bit fragile: it depends on every preprocessing step returning the same instance when it is a no-op. A future step that returns a fresh but equal list turns "nothing to do" into "replace the whole context" on every turn. An explicit changed flag threaded through preprocessing (or List.equals) would encode the intent directly.
|
This PR has conflicts with the git fetch origin
git checkout codex/fix-2985-compaction-token-budget
git rebase origin/main
# resolve conflicts, then:
git push --force-with-leaseThis is a one-time reminder. Feel free to @mention me for a re-review after conflicts are resolved. Automated notification by github-manager-bot |
AgentScope-Java Version
2.0.3-SNAPSHOT
Description
Fixes #2985
Chinese-heavy conversations could exceed the model's context window before compaction triggered. The estimator used the same character ratio for every language, while the trigger excluded system prompts and tool definitions.
This change:
Token counts remain estimates; exact Qwen tokenizer accuracy and live deployment behavior have not been validated.
Validation
Commands:
Related links
Checklist