Repository navigation
Conversation
|
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
CLA Not Signed The Contributor License Agreement (CLA) check is currently pending on this PR ( @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 Automated check by github-manager-bot |
oss-maintainer
left a comment
There was a problem hiding this comment.
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/clastill 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); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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"}) |
There was a problem hiding this comment.
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.
…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
关联问题
Fixes #2970
AgentScope-Java Version
2.0.3-SNAPSHOT,基于main的ea511ec2f68ca929a6bbc4e92cd0c0952a38c592。背景与必要性
ConversationCompactor.compactIfNeeded()在判断是否需要 LLM 摘要前,先执行工具参数截断和工具结果裁剪。但下面两个提前返回分支会丢弃已经生成的裁剪结果:这两个分支都返回
Optional.empty()。CompactionMiddleware因此继续传递原始ReasoningInput,也不更新工作AgentState。结果是:轻量裁剪确实执行了,下一次模型请求却仍携带原始大段内容,可能继续触发上下文超限。这与 #2267 / #2319 修复的
ToolResultEvictionMiddleware状态和输入不同步问题不同;本次问题位于ConversationCompactor的提前返回路径。变更内容
Optional.empty()。两个轻量处理方法在无改动时都会返回原列表,因此这里只比较列表引用,不对大段消息做深度比较。
复现与验证
最小输入为一条用户消息、一条工具调用及其匹配结果。工具结果含
"x".repeat(10_000);配置triggerTokens(1_000)、keepTokens(0)、keepMessages(20),以及protectTokens(0)、minimumTokens(1)、maxOutputChars(100)的裁剪策略。裁剪后低于阈值,但原实现仍把原始请求传给next。设置
triggerMessages(3)可覆盖安全切分点为 0 的分支;将大段内容放到write_file参数并启用参数截断,可复现参数截断对应的两个分支。新增 6 个参数化场景:
修复前: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,不需要模型凭证或网络调用。
当前范围与兼容性
想请维护者确认的取舍
这里保留
Optional<List<Msg>>,将非空结果解释为“存在应应用的替换消息”,不再隐含“一定生成了摘要”。目前仓内两个生产调用点都按替换列表使用结果。希望确认这一返回语义是否符合项目预期;若外部调用方需要区分轻量裁剪和摘要,可另行讨论显式结果类型,本 PR 暂不扩大 API 改动范围。Checklist
mvn spotless:apply。验证范围为 Core/Harness,未宣称其他所有模块的全仓
mvn test已通过。