Skip to content

fix(harness): prevent missed compaction for multilingual contexts - #2990

Closed
guslegend0510 wants to merge 22 commits into
agentscope-ai:mainfrom
guslegend0510:codex/fix-2985-compaction-token-budget
Closed

guslegend0510 wants to merge 22 commits into
agentscope-ai:mainfrom
guslegend0510:codex/fix-2985-compaction-token-budget

Conversation

@guslegend0510

Copy link
Copy Markdown
Contributor

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:

  • Counts non-ASCII text more conservatively while preserving the existing ASCII estimate, and includes thinking and hint text.
  • Includes system prompts, tool definitions and response-format schemas in the trigger budget.
  • Uses the primary reasoning model's context window for dynamic thresholds, even when a separate summary model is configured.
  • Applies argument truncation and tool-result pruning even when summarization is skipped.
  • Preserves original history when summarization fails or returns empty text.
  • Retains existing public method signatures and updates English and Chinese documentation.

Token counts remain estimates; exact Qwen tokenizer accuracy and live deployment behavior have not been validated.

Validation

  • 40 focused compaction tests passed.
  • Full Core suite: 2,318 tests, 0 failures/errors, 9 skipped.
  • Full Harness suite: 942 tests, 0 failures/errors, 5 skipped.
  • The 15 new budget regression cases produced 14 failures on unchanged main and all passed with this fix.
  • Spotless and git diff --check passed.

Commands:

  • mvn -pl agentscope-harness -am -Dtest=TokenCounterUtilTest,CompactionBudgetTest,ConversationCompactorTest,CompactionMiddlewareTest -Dsurefire.failIfNoSpecifiedTests=false test
  • mvn -pl agentscope-harness -am test
  • mvn -pl agentscope-harness -am spotless:check -DskipTests

Related links

Checklist

  • Code has been formatted with mvn spotless:apply
  • Full Core/Harness reactor tests pass; other modules were not run
  • Javadoc comments have been updated
  • Related English and Chinese documentation has been updated
  • Code is ready for review

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

codecov Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.11765% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...agent/memory/compaction/ConversationCompactor.java 87.50% 1 Missing and 1 partial ⚠️
...harness/agent/middleware/CompactionMiddleware.java 88.88% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@CryoThrust CryoThrust left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@birdie7761

Copy link
Copy Markdown
Contributor

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 effective = max(lastReportedInputTokens + heuristicDelta, pureHeuristic) — the heuristic then only prices the delta between anchors, so systematic bias (CJK ratios, chat templates, tool schemas, multimodal) is absorbed by the ground truth on every call. DeepSeek's open-source harness (deepseek-harness, packages/llm/token-meter) ships exactly this anchored-measurement design in production, including a conservative guard (usage accepted only when ≥ the heuristic price of the same surface) and route-consistency (anchor reused only under the same provider/model).

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 triggerTokens users (especially Chinese-heavy ones) will see compaction fire noticeably earlier after this lands, a release-notes line would help.

@guslegend0510

Copy link
Copy Markdown
Contributor Author

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 effective = max(lastReportedInputTokens + heuristicDelta, pureHeuristic) — the heuristic then only prices the delta between anchors, so systematic bias (CJK ratios, chat templates, tool schemas, multimodal) is absorbed by the ground truth on every call. DeepSeek's open-source harness (deepseek-harness, packages/llm/token-meter) ships exactly this anchored-measurement design in production, including a conservative guard (usage accepted only when ≥ the heuristic price of the same surface) and route-consistency (anchor reused only under the same provider/model).

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 triggerTokens users (especially Chinese-heavy ones) will see compaction fire noticeably earlier after this lands, a release-notes line would help.

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.

@guslegend0510

Copy link
Copy Markdown
Contributor Author

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 effective = max(lastReportedInputTokens + heuristicDelta, pureHeuristic) — the heuristic then only prices the delta between anchors, so systematic bias (CJK ratios, chat templates, tool schemas, multimodal) is absorbed by the ground truth on every call. DeepSeek's open-source harness (deepseek-harness, packages/llm/token-meter) ships exactly this anchored-measurement design in production, including a conservative guard (usage accepted only when ≥ the heuristic price of the same surface) and route-consistency (anchor reused only under the same provider/model).

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 triggerTokens users (especially Chinese-heavy ones) will see compaction fire noticeably earlier after this lands, a release-notes line would help.

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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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: 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.

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());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 == original identity 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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR has conflicts with the main branch and cannot be merged. Please rebase or merge main into your branch and resolve the conflicts:

git fetch origin
git checkout codex/fix-2985-compaction-token-budget
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a re-review after conflicts are resolved.


Automated notification by github-manager-bot

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.

[Bug]:上下文压缩失效导致agent运行失败

5 participants