Skip to content

fix(harness): 保留跳过摘要时的轻量上下文裁剪结果 - #2971

Closed
yyyzl wants to merge 1 commit into
agentscope-ai:mainfrom
yyyzl:codex/preserve-pruned-compaction-input
Closed

yyyzl wants to merge 1 commit into
agentscope-ai:mainfrom
yyyzl:codex/preserve-pruned-compaction-input

Conversation

@yyyzl

@yyyzl yyyzl commented Sep 3, 2026

Copy link
Copy Markdown

关联问题

Fixes #2970

AgentScope-Java Version

2.0.3-SNAPSHOT,基于 main 的 ea511ec2f68ca929a6bbc4e92cd0c0952a38c592。

背景与必要性

ConversationCompactor.compactIfNeeded() 在判断是否需要 LLM 摘要前,先执行工具参数截断和工具结果裁剪。但下面两个提前返回分支会丢弃已经生成的裁剪结果:

  1. 裁剪后的 token 数低于摘要触发阈值;
  2. 触发了摘要,但安全切分点为 0,没有可摘要的前缀。

这两个分支都返回 Optional.empty()。CompactionMiddleware 因此继续传递原始 ReasoningInput,也不更新工作 AgentState。结果是:轻量裁剪确实执行了,下一次模型请求却仍携带原始大段内容,可能继续触发上下文超限。

这与 #2267 / #2319 修复的 ToolResultEvictionMiddleware 状态和输入不同步问题不同;本次问题位于 ConversationCompactor 的提前返回路径。

变更内容

  1. 保存轻量裁剪产生的替换列表,在上述两个分支中返回;只有消息未变化时才返回 Optional.empty()。
  2. 复用现有调用方处理非空结果的逻辑,使模型输入和工作状态都得到裁剪后的消息,无需修改 Middleware 或新增返回类型。
  3. 更新公开方法的 Javadoc:非空结果既可能是轻量裁剪后的消息,也可能是摘要加保留尾部。
  4. 增加真实 Middleware 调用边界的回归测试,不 mock compactor。

两个轻量处理方法在无改动时都会返回原列表,因此这里只比较列表引用,不对大段消息做深度比较。

复现与验证

最小输入为一条用户消息、一条工具调用及其匹配结果。工具结果含 "x".repeat(10_000);配置 triggerTokens(1_000)、keepTokens(0)、keepMessages(20),以及 protectTokens(0)、minimumTokens(1)、maxOutputChars(100) 的裁剪策略。裁剪后低于阈值,但原实现仍把原始请求传给 next。

设置 triggerMessages(3) 可覆盖安全切分点为 0 的分支;将大段内容放到 write_file 参数并启用参数截断,可复现参数截断对应的两个分支。

新增 6 个参数化场景:

  • 工具结果裁剪 / 工具参数截断 × 低于摘要阈值 / 安全切分点为 0,共 4 个场景;
  • 两个提前返回分支下消息确实未变化的 2 个对照场景。

修复前:4 个裁剪场景全部失败,2 个无变化场景通过。修复后:ConversationCompactorTest 和 CompactionMiddlewareTest 共 23 项全部通过。

此外,mvn -pl agentscope-harness -am test 构建成功:Core 共 2,318 项(跳过 9 项),Harness 共 925 项(跳过 5 项),均为 0 failures / 0 errors。验证环境为 Java 17 / Maven 3.8.7,运行时状态目录隔离到临时测试目录。

断言同时检查下游输入、工作状态、原输入不被修改、系统消息和工具调用配对保留、tools/options 透传,并确认轻量裁剪不触发模型调用。测试使用 mock model,不需要模型凭证或网络调用。

mvn -pl agentscope-harness spotless:apply
mvn -pl agentscope-harness -am \
  -Dtest=ConversationCompactorTest,CompactionMiddlewareTest \
  -Dsurefire.failIfNoSpecifiedTests=false test
mvn -pl agentscope-harness -am test

当前范围与兼容性

  • 保留现有方法签名,不新增依赖、配置或 LLM 调用。
  • 不改摘要逻辑、异常降级和中断传播。
  • 不改变默认参数截断开关、裁剪阈值、排除工具和最近消息保护窗口。
  • 本 PR 只保证“已经做出的裁剪能被使用”,不保证所有超大上下文都能降到模型窗口内;处于保护窗口的内容、未启用参数截断的工具输入,仍需按原有策略处理。

想请维护者确认的取舍

这里保留 Optional<List<Msg>>,将非空结果解释为“存在应应用的替换消息”,不再隐含“一定生成了摘要”。目前仓内两个生产调用点都按替换列表使用结果。希望确认这一返回语义是否符合项目预期;若外部调用方需要区分轻量裁剪和摘要,可另行讨论显式结果类型,本 PR 暂不扩大 API 改动范围。

Checklist

  • 已执行 Harness 模块的 mvn spotless:apply。
  • 已运行并通过本次改动对应的聚焦测试。
  • Core/Harness 全量测试构建成功;跳过项数量见验证结果。
  • 已更新 Javadoc,说明轻量裁剪结果的返回语义。
  • 无需修改公开配置文档或使用示例。
  • 代码可供审查。

验证范围为 Core/Harness,未宣称其他所有模块的全仓 mvn test 已通过。

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Sep 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@oss-maintainer

Copy link
Copy Markdown
Collaborator

CLA Not Signed

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.

@yyyzl please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.


Automated check by github-manager-bot

@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

Targeted fix for #2970: the lightweight truncation/pruning results were computed and then dropped when the early-return paths (below summary threshold, or safe cutoff 0) returned Optional.empty(), so both the model input and the working AgentState kept carrying the raw oversized payload. Returning the lightweight result on those paths is the right shape, and the new middleware-level regression tests exercise the real call boundary rather than a mocked compactor — good.

Findings are refinements, not blockers: the reference-identity change detection deserves a contract test of its own, and the fact that lightweight reductions now become durable state (and bypass the memory-flush path) deserves an explicit decision plus a Javadoc note.

Notes

  • CLA check for this PR reports license/cla still pending, so this review is left as a comment rather than an approval.
  • CI for the current head is green (build ubuntu/windows, Check License, Check Module Sync, codecov patch all passing).

Automated review by github-manager-bot

config.getPruneConfig());
// Both lightweight passes return the original list when they make no changes.
Optional<List<Msg>> lightweightResult =
messages == conversationMessages ? Optional.empty() : Optional.of(messages);

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 messages == conversationMessages reference check is correct today, but it silently depends on the undocumented contract that both truncateArgs() and pruneToolResults() return the caller's list instance when they change nothing. If either pass is ever changed to return a defensive copy, this starts reporting "changed" on every turn, which then rewrites AgentState on each reasoning step. CompactionMiddlewareTest.unchangedConversationKeepsOriginalInput covers this only at the middleware level. Could you pin the contract in the class that owns it (a small ConversationCompactorTest case asserting assertSame on both passes' no-op return), or make it explicit by having the passes return a "changed" flag/optional instead of relying on identity?

int totalTokens = TokenCounterUtil.calculateToken(messages);
if (!shouldCompact(messages, totalTokens, config)) {
return Mono.just(Optional.empty());
return Mono.just(lightweightResult);

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.

This is the interesting semantic change: the lightweight result is now not just sent to the model, it is written back into the working AgentState by CompactionMiddleware.applyToContext(), i.e. the pruning becomes durable. The full tool-result / tool-arg text that buildPrunePreview() drops is therefore no longer recoverable later in the session, and it never goes through MemoryFlushManager the way the summarization path does. That is probably the right trade-off for #2970, but it deserves an explicit decision: (a) is losing the raw payload from state acceptable for long-term memory, and (b) should the pruned payload be offloaded first (similar to what ToolResultEvictionMiddleware does in #2267/#2319) instead of being replaced inline? A sentence in the class Javadoc stating that lightweight reductions are persisted would keep the behaviour discoverable.


/** Lightweight reductions must reach both reasoning and state even without a summary. */
@ParameterizedTest
@CsvSource({"false, 0", "false, 3", "true, 0", "true, 3"})

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 @CsvSource matrix always enables exactly one lightweight pass (truncateArgs ? large-args+no-prune : small-args+prune). The identity check at ConversationCompactor line 114 is evaluated over the composition of both passes, so the "both passes modify the conversation" case is untested. A fifth scenario with truncateArgs(...) and prune(...) both active (and still below triggerTokens) would lock down that interaction.

Buktal pushed a commit that referenced this pull request Oct 13, 2026
…3326)

## AgentScope-Java Version

2.0.4-SNAPSHOT (based on `main` @ `9c8b10d4e`)

## Description

`ConversationCompactor.pruneToolResults` trims old oversized tool
results to a head+tail preview. When rebuilding the trimmed block it
copies only `id` and `name`, which silently discards the rest of the
block's identity:

- **metadata** — wiped. Markers that downstream code branches on are
lost: the eviction marker `agentscope.tool_result_evicted` (written by
`ToolResultEvictionMiddleware`, #2319) and the suspension marker
`agentscope_suspended` (consumed by `ToolResultBlock.isSuspended()` and
ReActAgent's suspend/resume matching), plus any integrator-supplied
metadata.
- **state** — reset to `RUNNING` (the `ToolResultBlock` constructor
default for null), so a pruned `ERROR` result is rewritten as `RUNNING`.
`MessageUtils` result-state maps and event-side state reporting observe
the corrupted value.
- **`Msg.usage`** — dropped by the message rebuild.

The eviction middleware already follows a lossless rebuild discipline
(`withPlaceholder` preserves metadata and adds its own marker). This PR
applies the same discipline to prune: the rebuilt block now copies
`metadata` and `state` from the original block, and the rebuilt `Msg`
keeps `usage`. Only the output text is replaced with the preview.

Context size is strictly reduced, never grown — the preserved fields
were already in the conversation before pruning, and formatters do not
render block metadata into the model prompt. This matters once
lightweight pruning results reach the working `AgentState` (e.g. once
#2970/#2971 is addressed): a persisted-and-replayed pruned block
currently loses every field downstream consumers branch on.

### Compatibility

- No serialization/format change: `metadata`, `state`, `usage` are
existing `@JsonProperty` fields of `ToolResultBlock`/`Msg`.
- No context growth: only the output text shrinks relative to the
pre-prune message.
- Sessions persisted by older builds read back unchanged (those blocks
already carry the default values).

### Tests

New `ConversationCompactorPruneTest` (5 cases). The preservation case
was red-verified against pre-fix code — verbatim failure output:

```
org.opentest4j.AssertionFailedError: expected: <{agentscope.tool_result_evicted=true, agentscope_suspended=true, custom_key=custom_value}> but was: <{}>
```

| Test | Asserts |
|---|---|
| `pruneToolResults_preservesMetadataStateAndUsageWhenTrimming` |
metadata map, `isSuspended()`, `state=ERROR`, block id/name and `Msg`
id/metadata/timestamp/usage all survive; preview actually trimmed |
| `pruneToolResults_multiBlockMessagePrunesOnlyOversizedBlock` | a
message carrying several results is rebuilt with only the oversized
block replaced; untouched blocks keep their original reference (pinned
via `assertSame`, so the rebuild is surgical rather than destructive) |
| `pruneToolResults_skipsExcludedTools` | excluded tool is never pruned
(original list reference returned) |
| `pruneToolResults_returnsOriginalWhenBelowMinimum` | below-threshold
conversation returned unchanged |
| `pruneToolResults_handlesBlockWithoutMetadataOrState` | metadata-less
block prunes without failure, defaults intact |

Regression: `ConversationCompactorTest` 7/7,
`ToolResultEvictionMiddlewareTest` green, full `agentscope-harness`
suite green, `spotless:check` clean.

### Out of scope

The `truncateArgs` rebuilds in the same class keep even less
(`truncateToolUseArgs` drops the message id/metadata/usage;
`truncateToolUseBlock` drops `ToolUseBlock` metadata). They are masked
by the same #2970 discard path and left for a follow-up to keep this
change single-purpose.

One pre-existing interaction edge is worth recording: an eviction
placeholder larger than prune's `maxOutputChars` is itself prunable, and
the head+tail preview may cut the embedded `read_file` pointer text.
This PR preserves the eviction *marker* through that rewrite, but cannot
recover the pointer text itself; in practice the default placeholder
(~4K chars) only hits this under a custom `maxOutputChars` at or above
that size.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [x] All tests are passing (`mvn test`)
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated (PruneConfig has no
user-facing docs today; the method Javadoc documents the preservation
contract)
- [x] Code is ready for review
@jujn jujn closed this Oct 18, 2026
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]: Lightweight compaction results are discarded when summarization is skipped

4 participants