Repository navigation
fix(core): preserve business tool-use/result pairs in structured-output cleanup - #4078
Conversation
…ut cleanup In the fallback structured-output path, compressStructuredOutputContext drops a whole Msg whenever isStructuredOutputRelated(msg) is true. That classifier matches an assistant message as soon as ANY ToolUseBlock in it is the synthetic generate_response tool. When a model returns a business tool call and generate_response in the same assistant response, the whole message is removed, including the business ToolUseBlock. The business ToolResultBlock lives in its own message and is not classified as structured, so it stays behind. The next model request then receives a tool_result without its tool_use, which providers reject; explicit AgentStateStore reads show the same corruption. Returning the two calls in separate rounds works, so the bug is specific to a mixed batch. Rebuild mixed messages with only the generate_response ToolUseBlock / ToolResultBlock removed, preserving text, thinking, business tool blocks and the message identity (id/name/role/timestamp/metadata/usage). Pure structured-output messages and synthetic reminders keep the existing whole-message removal. isStructuredOutputRelated is deliberately left unchanged: collectAggregatedUsage and collectLastThinking reuse it and run before compression, so usage/thinking extraction is unaffected. Tool dispatch, permissions and the native response_format path are untouched. Adds StructuredMixedBatchAuditTest: the 6 scenarios from the issue (both mixed-batch orders and a separate-rounds control, with default and explicit state stores) plus a check that the rebuilt message keeps its role/id/name and non-tool content. The fake model rejects orphan tool_results on the next turn, so the fixture fails on the corrupted pairing itself. Fixes agentscope-ai#4073.
juruoO-o
left a comment
There was a problem hiding this comment.
[P2] 混合消息保留 usage 后,会与最终结构化结果重复记账。
修复业务 tool-use/result 配对有必要,但 stripStructuredOutputBlocks() 在重建混合消息时保留了 msg.getChatUsage()。调用方此前已通过 collectAggregatedUsage() 收集同一笔 usage,随后又把它写入最终结构化结果;因此同一笔消耗同时留在业务消息和最终结果中。
已在本次 main(dee7a210b)与该 head 的干净合并快照上交叉执行 #4086 的 ReActAgentStructuredOutputCleanupTest:8 个用例中 4 个混合批次用例失败,历史 inputTokens 合计 expected=100、actual=200;本 PR 自带 StructuredMixedBatchAuditTest 的 7 个用例均通过。
请在保留业务调用及消息属性的同时,移除已归入最终结果的 usage 字段及 CHAT_USAGE 元数据,且不要修改原消息。补充内存/持久化两条路径的 usage 不重复计数断言。#4086 已处理这一点,同组 8 个用例本地通过;两份实现解决同一问题,建议保留一份。
## AgentScope-Java Version 2.1.0-SNAPSHOT,验证基线为 `main` 的 `5baff2613401bf87b3a967b185f2f14945ec594e`。 ## Description Fixes #4073. ### 问题与修复 降级结构化输出路径允许模型在同一响应中返回业务工具调用与内部 `generate_response` 调用。原来的 `compressStructuredOutputContext` 会删除整个混合消息,业务工具结果却仍保留,导致持久化历史以及下一轮请求出现没有对应 `tool_use` 的 `tool_result`。 本 PR 仅调整该清理方法: - 混合消息只移除内部输出工具内容块,保留业务调用及其配对结果,以及原消息的 ID、名称、角色、时间戳、非 usage metadata、text 和 thinking。 - 纯输出工具消息和内部提醒继续按原规则删除;无关消息(包括空消息)原样保留。 - 清理前已归集到最终结构化结果的 usage,不再保留到混合消息副本中,避免同一份使用量在历史里重复计数;最终返回值的 usage 不变,也不修改原消息对象。 不修改共用分类函数、usage/thinking 收集器、工具调度、权限、重试、native structured-output 路径或公共 API;不迁移此前已损坏的历史。 ### 回归测试 新增 `ReActAgentStructuredOutputCleanupTest`,使用假模型和真实本地 Java 工具,不需要网络或模型凭证: - 输出工具在业务工具之前/之后、业务与输出分轮、纯输出四种情况,分别使用默认状态和显式 `InMemoryAgentStateStore`,共 8 个参数化场景。 - 验证工具调用与结果的 ID 配对、内部输出工具内容被清理、业务工具不重复执行。 - 读回持久化状态并重建 Agent,验证下一轮模型收到的历史仍完整。 - 验证消息身份、非 usage 元数据、text/thinking、最终返回 usage,以及历史 usage 总量不重复;原消息对象保持不变。 - 未修复实现上,4 个混合批次场景失败,4 个对照场景通过;修复后 8 个全部通过。 同步补充中英文 Agent 文档中的历史清理行为说明。 ### 验证结果与边界 以下 Maven 检查在上述基线加本提交上完成,本地使用离线缓存和 central-only settings: ```sh mvn -B -T1C -pl agentscope-core -am test mvn -B -T1C -pl agentscope-core -am spotless:check ``` - Core 全量:3031 项,0 failures、0 errors、9 skipped,BUILD SUCCESS。跳过项为现有的 7 个流契约占位测试、1 个需显式开启的压力测试、1 个仅 Windows 的测试。 - 结构化输出相关针对性测试:37 项,0 failures、0 errors、1 skipped。 - Spotless 与 `git diff --check` 通过。 - Docs:`npm test` 13 项通过,`npm run validate` 通过,`npm run broken-links` 未发现坏链接。 尚未执行全仓库 `clean verify`、Windows 或真实模型厂商集成测试;不将这些列为已验证。 ### 与相关 PR 的协调 提交前注意到 #4078 也针对 #4073 提供了实现,两个 PR 存在重叠。本实现同时包含非零 usage 的历史总量断言、原消息不变性和持久化后重建 Agent 的回归检查,保留混合消息时不再重复携带已归集到最终结果的 usage。这里说明本实现的设计与验证范围,并非对 #4078 未验证行为的缺陷判断。 欢迎维护者比较、选择或整合合适的实现与测试;不需要合并两个重复修复。 ## Checklist - [x] Code has been formatted; Spotless checks pass. - [ ] All repository tests are passing (`mvn test`) — 已验证上述 core 范围,未执行全仓库测试。 - [x] Javadoc comments follow project conventions — 未新增公共 API。 - [x] Related documentation has been updated in English and Chinese. - [x] Code is ready for review.
Upstream PR agentscope-ai#4086 already fixed agentscope-ai#4073 in ReActAgent#compressStructuredOutputContext: mixed messages are rebuilt with the synthetic generate_response blocks removed and CHAT_USAGE is dropped from the retained copy. Keep that implementation and remove the now-unused stripStructuredOutputBlocks / isStructuredOutputBlock helpers from this branch, so the two fixes do not coexist in the same method. This branch keeps its javadoc clarification on the cleanup method and the StructuredMixedBatchAuditTest regression suite, which still passes against the upstream implementation.
juruoO-o
left a comment
There was a problem hiding this comment.
复审 head b8ff78f,与本次 fetch 的 main@c627cc7c9 可干净合并。
原 usage 重复记账问题已解决:该分支保留已合入 #4086 的生产实现,删除重叠清理逻辑;当前相对 main 只增加 cleanup Javadoc 和 StructuredMixedBatchAuditTest,没有第二份生产实现。
本轮在最新 main + 本 head 的干净合并快照上运行 ReActAgentStructuredOutputCleanupTest 与 StructuredMixedBatchAuditTest:15 项通过,覆盖 usage 去重、混合批次业务 tool-use/result 保留,以及内存/状态存储路径。未发现新的阻塞问题。未重跑全仓 verify。
AgentScope-Java Version
2.1.0-SNAPSHOT (upstream
main@a63c625)Description
Fixes #4073.
The bug
In the fallback structured-output path,
compressStructuredOutputContextremoves a wholeMsgwheneverisStructuredOutputRelated(msg)is true. That classifier returns true if anyToolUseBlockin the message isgenerate_response.So when a model returns a business tool call and the synthetic
generate_responsecall in the same assistant response:ToolUseBlock;ToolResultBlocklives in its own message and is not classified as structured, so it stays;generate_responseresult message is dropped as before.The next model request then sees a
tool_resultwithout itstool_use. Providers reject that, and the session state is corrupted. ExplicitInMemoryAgentStateStorereads show the same corruption. Returning the two calls in separate rounds works; swapping their order in one batch does not.The fix
agentscope-core/.../ReActAgent.java— for messages that mix internal structured-output blocks with business tool blocks, rebuild the message with only thegenerate_responseToolUseBlock/ToolResultBlockremoved, instead of deleting the whole message. Everything else (text, thinking, business tool blocks) and the message identity (id/name/role/timestamp/metadata/usage) are preserved, so the businesstool_use/tool_resultpair stays intact.Pure structured-output messages (and synthetic reminder messages) keep the existing whole-message removal, exactly as before.
isStructuredOutputRelatedis deliberately left unchanged:collectAggregatedUsageandcollectLastThinkingreuse it and run before compression, so usage/thinking extraction is unaffected. Tool dispatch, permissions and the nativeresponse_formatfallback are untouched — this only changes post-hoc context cleanup.Two small helpers back this up:
stripStructuredOutputBlocks(Msg)— returnsnullfor pure/reminder messages (caller drops them), otherwise the rebuilt message.isStructuredOutputBlock(ContentBlock)— matchesToolUseBlock/ToolResultBlocknamedgenerate_response.Tests
agentscope-core/src/test/java/io/agentscope/core/agent/StructuredMixedBatchAuditTest.java(new, no network / API key / real model):InMemoryAgentStateStore). A fakeModelrejects any orphantool_resulton the next turn, so the fixture fails on exactly the corrupted pairing rather than on an assertion about a private field. It also asserts the structured result is returned and the business tool ran once.AssistantMessagewith the original id/name, its non-tool text survives, and nogenerate_responsetool_usesurvives cleanup.Verified that the tests are genuine regressions: reverting only the
ReActAgent.javachange makes 5 of the 7 fail (the 4 mixed-batch cases and the identity test) while the 2 separate-rounds controls pass; with the fix all 7 pass.Checks
mvn -B -T1C -pl agentscope-core -am test -Dtest=StructuredMixedBatchAuditTest→ 7 tests, 0 failures, 0 errors.mvn -B -T1C clean verify→ full 99-module reactor:AgentScope Java - CoreSUCCESS,HarnessSUCCESS, spotless clean, all modules that ran green except one pre-existing unrelated flake (AnthropicModelProviderTest.createWithAuthTokenOptionSendsBearerHeader, a 10s timeout against a local MockWebServer under parallel load). That test passes 7/7 when run in isolation; the same test also fails on unmodifiedmainunder the same parallel load, so it is not caused by this change.mvn -B -T1 clean verify(sequential, no parallel-load contention) → 92 modules including Core, Harness and Anthropic all SUCCESS (anthropic now passes, confirming the-T1Cfailure was a load-induced timeout, not a real failure). The only failure isagentscope-paw'snpm install(EPERM: root-owned files in ~/.npm), a local frontend-tooling environment issue unrelated to Java or this change. Upstream CIbuild (ubuntu-latest)andbuild (windows-latest)are both green.mvn -pl agentscope-core spotless:applyapplied;spotless:checkclean.Scope
agentscope-coreonly; no public API, builder, serialized state, event payload, or docs change (docs describe the cleanup contract, not the internal message shape).Checklist
mvn spotless:applymvn test)