Skip to content

fix(accumulator): warn on malformed streamed tool arguments - #2844

Closed
mikemikimike wants to merge 22 commits into
agentscope-ai:mainfrom
mikemikimike:codex/2841-tool-call-parse-diagnostics
Closed

mikemikimike wants to merge 22 commits into
agentscope-ai:mainfrom
mikemikimike:codex/2841-tool-call-parse-diagnostics

Conversation

@mikemikimike

@mikemikimike mikemikimike commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes the silent loss of streamed tool-call JSON parse failures described in Issue #2841.

  • Emit a warning after final argument parsing fails, with the tool-call ID and name, UTF-8 byte length, SHA-256 digest, and the underlying Jackson parser message when available. Raw arguments are not written to logs.
  • Clear stale merged arguments, retain the existing {} content fallback, and reject only the malformed call. Valid calls in the same batch still execute.
  • Keep intermediate stream snapshots from being marked as final parse failures, preserve the marker through HITL confirmation, and omit the internal marker from A2A metadata and provider payloads.
  • Catch JsonException for malformed JSON while allowing unrelated codec failures to propagate.
  • Add regression coverage for malformed input, streaming snapshots, mixed tool batches, HITL confirmation, and metadata filtering.

The raw malformed argument string is not retained for recovery. Tool arguments may contain sensitive user data; diagnostics use a digest, byte length, and parser details without copying the payload into default logs or persisted content.

Testing

  • On commit b05599a: mvn -B -T1 -pl agentscope-core -Dtest=ToolCallsAccumulatorTest,ReActAgentHitlTest test — 40 tests passed.
  • Before the diagnostic-only follow-up commit, targeted provider tests ran 82 tests with 0 failures and 2 skipped, and the A2A parser test ran 3 tests with 0 failures. The current-head CI reran these test modules successfully.
  • On the current commit, GitHub Actions full build and test passed on Ubuntu and Windows; Check License, Check Module Sync, Validate Mintlify Docs, and Codecov patch also passed.
  • The HarnessMiddlewareActivePointsTest associated with the earlier temporary-directory cleanup error passed when rerun alone on JDK 17.0.20.1; the current-head CI also passed on both platforms.
  • git diff --check upstream/main HEAD — passed.

Fixes #2841

@gilgold

gilgold commented Aug 26, 2026

Copy link
Copy Markdown

The added observability is useful, but I think this exact form creates two safety problems:

  1. log.warn(... rawContentStr, e) puts the full tool payload into default telemetry. Tool arguments routinely contain credentials, customer text, file contents, and prompt-injection material. I’d log only safe metadata by default: tool-call id/name, provider/model if available, byte length, SHA-256, parser exception class/offset, and stream finish reason. Any raw sample should require an explicit debug policy and be redacted + size-capped.
  2. The new test codifies a more serious ambiguity: after the final JSON parse fails, previously merged input remains executable while content becomes {}. That can combine stale/partial fields with a malformed final payload and makes a parse failure indistinguishable from a genuinely valid empty object downstream.

A minimal fail-closed contract would be:

  • mark the block with a typed PARSE_FAILED outcome (or metadata flag) distinct from valid {} and INTERRUPTED;
  • preserve raw arguments only in an ephemeral caller-controlled diagnostic channel, never checkpoints/default logs;
  • prevent tool execution whenever final parse failed;
  • if repair is enabled: strict parse → conservative deterministic repair → tool-schema validation → execute. Unescaped quotes are ambiguous, so if schema validation cannot prove one reconstruction, return the typed error or make one bounded model retry rather than guessing;
  • change the regression to assert malformed input cannot reach the executor as retained partial args, while valid {} still can.

For AgentScope, this belongs locally in the accumulator/JsonCodec seam. Disclosure: I maintain JSONSuture, a hosted option for teams that need one repair + schema-validation boundary across Java/Python/Node services; it is not a replacement for the framework-level fix here.

@mikemikimike

Copy link
Copy Markdown
Contributor Author

Addressed in 6106aa9: malformed tool-call diagnostics now log only tool id/name, UTF-8 byte length, SHA-256 digest, exception type, and message. The raw argument payload is no longer emitted to default logs. Existing {} fallback and merged-argument behavior remain unchanged. Focused tests (16/16), module tests, Spotless, and git diff --check pass. The earlier full CI failure was unrelated, in agentscope-harness teardown.

@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.76471% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/core/agent/accumulator/ToolCallsAccumulator.java 88.57% 2 Missing and 2 partials ⚠️
...e/src/main/java/io/agentscope/core/ReActAgent.java 93.18% 0 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@gilgold

gilgold commented Aug 26, 2026

Copy link
Copy Markdown

Thanks — 6106aa9e resolves the default-log payload exposure cleanly.

The execution-integrity issue is still present, though, and the new regression currently locks it in: input.path=output.txt remains executable even though the final accumulated payload is malformed and content is emitted as {}. Unless a later layer has an independent parse-failure guard, write_text_file can still run with stale/partial arguments while downstream code cannot distinguish that state from a valid empty object.

A minimal follow-up can stay local and avoid choosing a repair policy here:

  • set a typed PARSE_FAILED outcome/metadata flag in the catch path;
  • clear or quarantine executable input for that block;
  • have the executor reject PARSE_FAILED before tool dispatch;
  • change this regression to assert malformed final JSON is non-executable, while a genuinely valid {} remains executable.

If changing ToolUseBlock is too broad for this PR, a dedicated follow-up issue is reasonable, but I would not merge the retained-input test as the intended safety contract.

@mikemikimike

Copy link
Copy Markdown
Contributor Author

Addressed the remaining execution-integrity concern in f71d92ca:

  • malformed final JSON now clears any previously merged partial input before building the block;
  • the typed PARSE_FAILED state remains set, so ReActAgent rejects the call before tool dispatch;
  • valid {} remains PENDING and keeps the existing executable empty-input behavior;
  • fixed the existing ReActAgent Spotless violation from the prior commit.

Local validation with JDK 21:

  • mvn -pl agentscope-core -Dtest=ToolCallsAccumulatorTest test -Dcheckstyle.skip=true — 17 passed
  • mvn -pl agentscope-core spotless:check -Dcheckstyle.skip=true — passed
  • git diff --check — passed

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently 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/2841-tool-call-parse-diagnostics
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 once the conflicts are resolved.


Automated notification 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

PR #2844 makes malformed streamed tool arguments fail closed: ToolCallsAccumulator marks the final block PARSE_FAILED, clears merged args and logs a redacted diagnostic (id/name/length/sha256), and ReActAgent.executeToolCalls short-circuits the batch into error results. The core idea is right and the earlier log-leak concern is resolved, but the guard fires on every intermediate streaming snapshot (per-chunk WARN + SHA-256 spam), rejects valid sibling calls in mixed batches, and is bypassable on the permission-HITL resume path where ASKING/ALLOWED overwrites PARSE_FAILED — overall: useful fix, needs the three warnings addressed before the fail-closed guarantee actually holds.

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java:131 — build() is also invoked per streamed chunk (LegacyHookDispatcher.fireReasoningChunk → ReasoningContext.getAccumulatedToolCall, and resolveToolCallId for id-less fragments), so the new catch block logs a WARN + full SHA-256 over the partial payload for essentially every argument fragment of every normally-streamed tool call (O(n²) hashing, log noise that drowns real parse failures), and mid-stream ReasoningChunkEvent snapshots now report PARSE_FAILED with empty input while the final args may be valid. Distinguish the final build from intermediate snapshots (e.g. a finalize flag from buildAllToolCalls/buildFinalMessage).
  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:3527 — the anyMatch guard rejects the entire batch when any single call is PARSE_FAILED: valid sibling calls in a parallel batch are also rejected with the same "malformed tool arguments" message (behavior change vs main, misleading per-call feedback). Prefer synthesizing errors only for the malformed calls and dispatching the rest, or a per-call message naming the failing call.
  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:3527 — PARSE_FAILED does not survive the permission HITL flow: updateToolCallStates (ReActAgent.java:3028-3047) overwrites the context block state to ASKING/ALLOWED before the pause, applyConfirmResults (ReActAgent.java:2112) promotes it to ALLOWED, and resumeAgent() → acting(0) re-extracts calls from the context — so a malformed call that was ASK-gated and approved (or auto-allowed next to an ASK-gated sibling) reaches the guard with state=ALLOWED and is dispatched with the cleared empty input map, defeating the "must not execute" guarantee. Enforce at dispatch time or use a flag the permission state machine does not overwrite.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/message/ToolCallState.java:32 — new "parse_failed" constant is part of the serialized message model (sessions, RemoteEventCodec sub-agent events, agent-protocol store); same-version Jackson round-trip verified, but older peers/SDKs pinned to the previous enum will fail to decode it in mixed-version deployments.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java:125 — with the default codec the logged exceptionType/message are always the JsonException wrapper's constants ("Failed to deserialize JSON to java.util.Map"); the actual parse cause is dropped. Jackson 2.21 already redacts source content, so logging e.getCause()'s class/message would be safe and much more useful.
  • [Info] agentscope-core/src/test/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulatorTest.java:109 — new tests cover only the accumulator; the ReActAgent guard is uncovered (matches codecov's missing lines). Add a ReActAgent-level test for a mixed batch and for the ASK → approve → resume path.

Suggestions

  • Track "stream complete" on ToolCallBuilder (set from buildAllToolCalls/finalize) so parse-failure handling only applies to final builds.
  • Move the malformed-arguments rejection to dispatchToolCalls (or Toolkit.callTools) so it holds for every consumer (external-execution resume, structured output) and cannot be erased by state transitions.
  • Include the tool name/id in the synthesized error so the model can correct the right call.

Automated review by github-manager-bot

// fails. The PARSE_FAILED state prevents dispatch through ReActAgent, and
// clearing the map keeps the block fail-closed for other consumers too.
finalArgs.clear();
log.warn(

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.

build() is not only called once at stream end: it is invoked per streamed chunk via LegacyHookDispatcher.fireReasoningChunk (ReActAgent.java:2677-2689 -> ReasoningContext.getAccumulatedToolCall, LegacyHookDispatcher.java:85) and via resolveToolCallId (ReActAgent.java:2850) for id-less fragments. While streaming is in progress the rawContent is an incomplete JSON prefix, so this catch block now fires for essentially every argument fragment of every normally-streamed tool call: one WARN log plus a full SHA-256 and two UTF-8 byte[] copies over the partial payload per fragment (O(n^2) hashing per tool call on the hot streaming path), and the ToolUseBlock snapshots handed to legacy ReasoningChunkEvent hooks come back with state=PARSE_FAILED and empty input even though the final arguments may be perfectly valid. The final message itself stays correct (the clear only affects the returned copy), but the log signal for genuine parse failures is drowned in per-chunk noise. Please distinguish the final build from intermediate snapshots, e.g. a finalize flag passed from buildAllToolCalls()/buildFinalMessage, or suppress the warn/state/clear while the stream is still accumulating.

private Mono<List<Map.Entry<ToolUseBlock, ToolResultBlock>>> executeToolCalls(
List<ToolUseBlock> toolCalls,
BiConsumer<ToolUseBlock, ToolResultBlock> internalChunkCallback) {
if (toolCalls.stream().anyMatch(t -> t.getState() == ToolCallState.PARSE_FAILED)) {

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 guard rejects the entire batch when any single call is PARSE_FAILED. In a parallel batch of [valid, valid, malformed] the two valid calls are also rejected with the same "Tool execution rejected: malformed tool arguments" error even though their arguments parsed fine — a behavior change vs main, where valid siblings executed — and each valid call's error message is misleading, giving the model nothing actionable about which call was actually malformed (it cannot tell its own retry apart). Consider synthesizing the error result only for the PARSE_FAILED calls and dispatching the remaining calls through dispatchToolCalls, or at minimum making the message per-call (name the tool call whose arguments failed to parse).

private Mono<List<Map.Entry<ToolUseBlock, ToolResultBlock>>> executeToolCalls(
List<ToolUseBlock> toolCalls,
BiConsumer<ToolUseBlock, ToolResultBlock> internalChunkCallback) {
if (toolCalls.stream().anyMatch(t -> t.getState() == ToolCallState.PARSE_FAILED)) {

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 PARSE_FAILED marker does not survive the permission HITL flow, so this guard is bypassable. In actingStream, updateToolCallStates (ReActAgent.java:3028-3047) overwrites the context ToolUseBlock's state to ASKING/ALLOWED before RequestStopEvent pauses the turn, and applyConfirmResults (ReActAgent.java:2112) then promotes it to ALLOWED. On resume, resumeAgent() -> acting(0) re-extracts tool calls from the context (ReActAgent.java:2872), so a malformed call that was ASK-gated and then approved — or auto-allowed in a batch where a sibling asked — reaches this check with state=ALLOWED: the anyMatch misses and the tool is dispatched with the cleared, empty input map. That defeats the "must not execute" guarantee of the new state (it only fails later if the tool validates required params). Consider enforcing the check at dispatch time (e.g. in dispatchToolCalls/Toolkit, or a malformed flag that the permission state machine does not overwrite) rather than relying on ToolUseBlock.state alone.

FINISHED("finished"),

/** The streamed tool arguments failed final JSON parsing and must not execute. */
PARSE_FAILED("parse_failed");

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.

state is part of the serialized message model: it is written into persisted sessions (AgentStateStore), remote sub-agent events (RemoteEventCodec) and the agent-protocol task store. Jackson round-trips the new value fine on this version (verified against the repo's Jackson 2.21.1 via @jsonvalue), but peers/SDKs pinned to the previous enum constants will fail to decode a ToolUseBlock carrying "parse_failed" in mixed-version deployments. Worth confirming that cross-version consumers tolerate unknown state values, or noting the constraint for the wire protocol.

}
} catch (Exception ignored) {
// Parsing failed, keep previously merged args
} catch (Exception e) {

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.

With the default codec the caught exception is always JsonUtils' wrapper: exceptionType is io.agentscope.core.util.JsonException and message is the constant "Failed to deserialize JSON to java.util.Map", so the last two log fields tell you nothing about why parsing failed and the underlying cause (e.g. Jackson's "Unexpected character ... column: N") is dropped on the floor. Jackson 2.21 already redacts source content from its exception messages, so including e.getCause()'s class and message — or passing the throwable as the trailing SLF4J argument — would be both safe and far more diagnostic.

@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

PR #2844 makes malformed streamed tool arguments fail closed: ToolCallsAccumulator marks the final block PARSE_FAILED, clears merged args and logs a redacted diagnostic (id/name/length/sha256), and ReActAgent.executeToolCalls short-circuits the batch into error results. The core idea is right and the earlier log-leak concern is resolved, but the guard fires on every intermediate streaming snapshot (per-chunk WARN + SHA-256 spam), rejects valid sibling calls in mixed batches, and is bypassable on the permission-HITL resume path where ASKING/ALLOWED overwrites PARSE_FAILED — overall: useful fix, needs the three warnings addressed before the fail-closed guarantee actually holds.

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java:131 — build() is also invoked per streamed chunk (LegacyHookDispatcher.fireReasoningChunk → ReasoningContext.getAccumulatedToolCall, and resolveToolCallId for id-less fragments), so the new catch block logs a WARN + full SHA-256 over the partial payload for essentially every argument fragment of every normally-streamed tool call (O(n²) hashing, log noise that drowns real parse failures), and mid-stream ReasoningChunkEvent snapshots now report PARSE_FAILED with empty input while the final args may be valid. Distinguish the final build from intermediate snapshots (e.g. a finalize flag from buildAllToolCalls/buildFinalMessage).
  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:3527 — the anyMatch guard rejects the entire batch when any single call is PARSE_FAILED: valid sibling calls in a parallel batch are also rejected with the same "malformed tool arguments" message (behavior change vs main, misleading per-call feedback). Prefer synthesizing errors only for the malformed calls and dispatching the rest, or a per-call message naming the failing call.
  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:3527 — PARSE_FAILED does not survive the permission HITL flow: updateToolCallStates (ReActAgent.java:3028-3047) overwrites the context block state to ASKING/ALLOWED before the pause, applyConfirmResults (ReActAgent.java:2112) promotes it to ALLOWED, and resumeAgent() → acting(0) re-extracts calls from the context — so a malformed call that was ASK-gated and approved (or auto-allowed next to an ASK-gated sibling) reaches the guard with state=ALLOWED and is dispatched with the cleared empty input map, defeating the "must not execute" guarantee. Enforce at dispatch time or use a flag the permission state machine does not overwrite.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/message/ToolCallState.java:32 — new "parse_failed" constant is part of the serialized message model (sessions, RemoteEventCodec sub-agent events, agent-protocol store); same-version Jackson round-trip verified, but older peers/SDKs pinned to the previous enum will fail to decode it in mixed-version deployments.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java:125 — with the default codec the logged exceptionType/message are always the JsonException wrapper's constants ("Failed to deserialize JSON to java.util.Map"); the actual parse cause is dropped. Jackson 2.21 already redacts source content, so logging e.getCause()'s class/message would be safe and much more useful.
  • [Info] agentscope-core/src/test/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulatorTest.java:109 — new tests cover only the accumulator; the ReActAgent guard is uncovered (matches codecov's missing lines). Add a ReActAgent-level test for a mixed batch and for the ASK → approve → resume path.

Suggestions

  • Track "stream complete" on ToolCallBuilder (set from buildAllToolCalls/finalize) so parse-failure handling only applies to final builds.
  • Move the malformed-arguments rejection to dispatchToolCalls (or Toolkit.callTools) so it holds for every consumer (external-execution resume, structured output) and cannot be erased by state transitions.
  • Include the tool name/id in the synthesized error so the model can correct the right call.

Automated review by github-manager-bot

// fails. The PARSE_FAILED state prevents dispatch through ReActAgent, and
// clearing the map keeps the block fail-closed for other consumers too.
finalArgs.clear();
log.warn(

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.

build() is not only called once at stream end: it is invoked per streamed chunk via LegacyHookDispatcher.fireReasoningChunk (ReActAgent.java:2677-2689 -> ReasoningContext.getAccumulatedToolCall, LegacyHookDispatcher.java:85) and via resolveToolCallId (ReActAgent.java:2850) for id-less fragments. While streaming is in progress the rawContent is an incomplete JSON prefix, so this catch block now fires for essentially every argument fragment of every normally-streamed tool call: one WARN log plus a full SHA-256 and two UTF-8 byte[] copies over the partial payload per fragment (O(n^2) hashing per tool call on the hot streaming path), and the ToolUseBlock snapshots handed to legacy ReasoningChunkEvent hooks come back with state=PARSE_FAILED and empty input even though the final arguments may be perfectly valid. The final message itself stays correct (the clear only affects the returned copy), but the log signal for genuine parse failures is drowned in per-chunk noise. Please distinguish the final build from intermediate snapshots, e.g. a finalize flag passed from buildAllToolCalls()/buildFinalMessage, or suppress the warn/state/clear while the stream is still accumulating.

private Mono<List<Map.Entry<ToolUseBlock, ToolResultBlock>>> executeToolCalls(
List<ToolUseBlock> toolCalls,
BiConsumer<ToolUseBlock, ToolResultBlock> internalChunkCallback) {
if (toolCalls.stream().anyMatch(t -> t.getState() == ToolCallState.PARSE_FAILED)) {

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 guard rejects the entire batch when any single call is PARSE_FAILED. In a parallel batch of [valid, valid, malformed] the two valid calls are also rejected with the same "Tool execution rejected: malformed tool arguments" error even though their arguments parsed fine — a behavior change vs main, where valid siblings executed — and each valid call's error message is misleading, giving the model nothing actionable about which call was actually malformed (it cannot tell its own retry apart). Consider synthesizing the error result only for the PARSE_FAILED calls and dispatching the remaining calls through dispatchToolCalls, or at minimum making the message per-call (name the tool call whose arguments failed to parse).

private Mono<List<Map.Entry<ToolUseBlock, ToolResultBlock>>> executeToolCalls(
List<ToolUseBlock> toolCalls,
BiConsumer<ToolUseBlock, ToolResultBlock> internalChunkCallback) {
if (toolCalls.stream().anyMatch(t -> t.getState() == ToolCallState.PARSE_FAILED)) {

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 PARSE_FAILED marker does not survive the permission HITL flow, so this guard is bypassable. In actingStream, updateToolCallStates (ReActAgent.java:3028-3047) overwrites the context ToolUseBlock's state to ASKING/ALLOWED before RequestStopEvent pauses the turn, and applyConfirmResults (ReActAgent.java:2112) then promotes it to ALLOWED. On resume, resumeAgent() -> acting(0) re-extracts tool calls from the context (ReActAgent.java:2872), so a malformed call that was ASK-gated and then approved — or auto-allowed in a batch where a sibling asked — reaches this check with state=ALLOWED: the anyMatch misses and the tool is dispatched with the cleared, empty input map. That defeats the "must not execute" guarantee of the new state (it only fails later if the tool validates required params). Consider enforcing the check at dispatch time (e.g. in dispatchToolCalls/Toolkit, or a malformed flag that the permission state machine does not overwrite) rather than relying on ToolUseBlock.state alone.

FINISHED("finished"),

/** The streamed tool arguments failed final JSON parsing and must not execute. */
PARSE_FAILED("parse_failed");

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.

state is part of the serialized message model: it is written into persisted sessions (AgentStateStore), remote sub-agent events (RemoteEventCodec) and the agent-protocol task store. Jackson round-trips the new value fine on this version (verified against the repo's Jackson 2.21.1 via @jsonvalue), but peers/SDKs pinned to the previous enum constants will fail to decode a ToolUseBlock carrying "parse_failed" in mixed-version deployments. Worth confirming that cross-version consumers tolerate unknown state values, or noting the constraint for the wire protocol.

}
} catch (Exception ignored) {
// Parsing failed, keep previously merged args
} catch (Exception e) {

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.

With the default codec the caught exception is always JsonUtils' wrapper: exceptionType is io.agentscope.core.util.JsonException and message is the constant "Failed to deserialize JSON to java.util.Map", so the last two log fields tell you nothing about why parsing failed and the underlying cause (e.g. Jackson's "Unexpected character ... column: N") is dropped on the floor. Jackson 2.21 already redacts source content from its exception messages, so including e.getCause()'s class and message — or passing the throwable as the trailing SLF4J argument — would be both safe and far more diagnostic.

@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-reviewed head 76ca00d7 (one commit since my 111d884f review). The rework resolves the issue I flagged last round: the parse guard is applied only on the final build, so intermediate stream chunks no longer trip it, and rejection is now scoped per tool call instead of failing the whole batch — a valid sibling executes while the malformed call gets an error result. Dropping ToolCallState.PARSE_FAILED in favour of an internal metadata marker is safe here (the constant never reached main, and no remaining reference exists in the tree), and the new testIntermediateSnapshotDoesNotFailBeforeStreamCompletes plus the two ReActAgentHitlTest cases cover the behaviour change well. One follow-up keeps this a comment rather than an approval: because the marker is only written on the final build, the non-final view returned by getAccumulatedToolCall(...) — which LegacyHookDispatcher hands to hooks — is no longer fail-closed. Details inline; the fix looks otherwise good.

Findings

  • [Warning] ToolCallsAccumulator.java:129 — non-final snapshots keep partial args/PENDING state; LegacyHookDispatcher.java:85 consumes that view, so hook consumers see a well-formed-looking block for a rejected call.
  • [Info] ReActAgent.java:3550 — id-keyed correlation collapses duplicate tool-call ids; a missing id turns into an NPE inside Map.entry.
  • [Info] MessageMetadataKeys.java:158 — internal marker is persisted and replayed; confirm formatters strip it.

Checks

  • CI: Check License, Check Module Sync, build (ubuntu-latest), build (windows-latest), codecov/patch, license/cla — all passing at review time.
  • CLA: signed.

Automated review by github-manager-bot

.toList())
results -> {
for (int i = 0; i < executableCalls.size(); i++) {
resultsById.put(executableCalls.get(i).getId(), results.get(i));

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.

[Info] Correlating by toolCall.getId() is the right shape for partial rejection, but it collapses when a stream emits two tool calls under one id: resultsById.put overwrites the first entry and both Map.entry pairs resolve to the last result, whereas the old positional pairing kept one result per call. A duplicate-id guard, or pairing the rejected entries positionally alongside executableCalls, closes that hole. Map.entry also rejects null values, so if dispatchToolCalls ever yields fewer results than executableCalls the lookup becomes an NPE rather than the previous IndexOutOfBoundsException — same onErrorResume path, just a changed failure mode.

@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

The PR adds final-stream malformed-JSON diagnostics, clears stale arguments, and rejects marked tool calls while allowing valid siblings to run. It resolves the previous snapshot exposure and result-correlation findings, but the parser-failure marker is still not durable across externally reconstructed HITL confirmations and is exported over A2A. Overall verdict: request changes, because approving a malformed call through these adapters can bypass the rejection guard.

Previous round's findings

  • ToolCallsAccumulator.java:129 non-final hook snapshots exposed partial arguments — resolved (the parse-failure path now clears input for both final and non-final builds).
  • ReActAgent.java:3538 ID-keyed result correlation could collapse duplicate or missing IDs — resolved (the new ordered loop pairs each source call with the next executable result).
  • MessageMetadataKeys.java:234 internal-marker persistence/replay needed formatter checks — unresolved (the A2A parser copies all ToolUseBlock.metadata entries into outbound metadata).

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:3527 — Confirmation adapters can drop the parse-failure marker and let a malformed call execute after approval.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/message/MessageMetadataKeys.java:234 — The internal marker is exported in A2A metadata.

Checks

  • CLA: signed (license/cla = success on head a2d5aeec).
  • CI at review time: Check License, Check Module Sync, build (ubuntu-latest), build (windows-latest), codecov/patch, license/cla — all pass.

Verified good

  • Final malformed parsing clears previously merged input, emits the existing {} content fallback, and records the marker only at final build.
  • Intermediate malformed snapshots clear input without receiving a terminal marker, and the added accumulator test covers completion by a later fragment.
  • A valid empty object remains pending, while the ReAct HITL tests cover rejection plus execution of a valid sibling.
  • Diagnostics log tool identity, byte length, SHA-256, and cause type without logging raw tool arguments.
  • The execution loop preserves original tool-call order while omitting marked calls from dispatch and synthesizing their error results.

Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [INFO] agentscope-core/src/main/java/io/agentscope/core/message/MessageMetadataKeys.java:234 — TOOL_CALL_PARSE_FAILED is described as internal but is stored in normal ToolUseBlock.metadata. ToolUseBlockParser copies that map into A2A DataPart.metadata, so malformed calls now expose this internal key on the A2A wire format (and state serialization persists it). Either strip the key at protocol/export boundaries or make this a documented public metadata extension; otherwise downstream A2A consumers observe an unplanned payload change. (line outside diff)

@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 after the new head bfca6786. Both blocking findings from the previous round are resolved: the parse-failure marker is now durable across externally reconstructed HITL confirmations (carried from the retained asking blocks in applyConfirmResults, with a regression test that rebuilds the block without metadata), and the internal _tool_call_parse_failed key is no longer exported over A2A. Ordering between toolCalls and dispatched results is preserved by the new pair loop, and the test coverage (fail-closed final build, non-final snapshot, valid empty object, non-ASCII payload) is thorough. Verdict: approved, with two small non-blocking notes below.

Findings

  • [Warning] ToolCallsAccumulator.java:131 — catch (Exception e) is broader than the JSON failure it detects and converts any throw into a permanent fail-closed rejection.
  • [Info] ToolCallsAccumulator.java:104 — ToolCallState state = ToolCallState.PENDING is a constant local duplicating the builder default.
  • [Info] ReActAgent.java:3614 — hasParseFailure relies on metadata only, so blocks reconstructed from persisted context still read as clean; worth documenting or keeping the raw payload for re-validation.

Suggestions

No further changes required for this PR to be mergeable; the three points above are comment-level and can be addressed in a follow-up if you prefer.


Automated review by github-manager-bot

ToolUseBlock build() {
ToolUseBlock build(boolean finalBuild) {
Map<String, Object> finalArgs = new HashMap<>(args);
ToolCallState state = ToolCallState.PENDING;

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.

[Info] ToolCallState state = ToolCallState.PENDING; is a constant local that is only ever fed to .state(state) on line 167, and ToolCallState / finalMetadata are now built from a copy of metadata instead of the field directly. Two small cleanups:

  • drop the local and use ToolCallState.PENDING at the builder call (or drop .state(...) entirely if ToolUseBlock.builder() already defaults to PENDING — it currently duplicates that default),
  • if .state(PENDING) is meant to be meaningful, add a comment saying the state is deliberately reset for a failed parse; otherwise the reader has to guess.

Not a blocker — just a bit of noise in an otherwise tight change.

@CLAassistant

CLAassistant commented Oct 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@mikemikimike
mikemikimike force-pushed the codex/2841-tool-call-parse-diagnostics branch from 345c956 to 67363bf Compare October 5, 2026 04:33

@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-reviewed the two commits pushed since bfca6786 (head now 2934f4a1). One is an upstream main merge, the other is docs(core): document tool parse failure metadata boundaries. Verdict: approved — and all three of my previous-round notes are now closed.

  • catch (Exception) was broader than the JSON failure it detects — resolved, now catch (JsonException) at ToolCallsAccumulator.java:130. That is the right scope and still fail-closed for the case that matters: JacksonJsonCodec.fromJson wraps every JsonProcessingException into JsonException, so malformed bodies, truncated stream tails and top-level array/scalar payloads (MismatchedInputException) all still set the marker, while a non-JSON codec fault now propagates instead of permanently poisoning the tool call.
  • Constant local ToolCallState state = ToolCallState.PENDING — resolved, gone from build(...).
  • hasParseFailure reads metadata only, so a reconstructed block looks clean — resolved as documentation in MessageMetadataKeys.TOOL_CALL_PARSE_FAILED: raw arguments are discarded, the marker must survive persistence/reconstruction, providers and protocol formatters must omit it outbound. Enforcement is still metadata-only, which is a fair trade for keeping the rejected payload from being re-sent; noted inline rather than asked again.
  • The pair-ordering logic in executeToolCalls survived the upstream merge intact: parse-failed calls are filtered out of dispatch, then re-inserted in original position via resultIndex, so ToolResultBlock ordering still matches toolCalls, and the all-failed case short-circuits on executableCalls.isEmpty() instead of calling the toolkit with an empty list.

The two new provider tests (AnthropicMessageConverterTest, OpenAIMessageConverterTest) are the right shape — they assert the internal key never reaches an outbound payload rather than re-testing the parser. They did not execute on this head though: build (ubuntu-latest) aborts in agentscope-harness on HarnessMiddlewareActivePointsTest (JUnitException: Failed to close extension context, root cause IOException: Failed to delete temp directory /tmp/junit-… DirectoryNotEmptyException), a @TempDir cleanup race in a module this PR does not touch, which leaves every downstream module — Anthropic, OpenAI, A2A client — SKIPPED. build (windows-latest) cancelled behind it. That is an infra flake, not a defect in this change, and CI re-runs are handled by the separate feedback/CI job rather than by this review, so I am not holding the approval for it.

CLA signed (license/cla: success), mergeable, mergeStateStatus=UNSTABLE from that failing check only, no conflict.


Automated review by github-manager-bot

@mintlify

mintlify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit b53e3a2.

Approve preview

@mikemikimike

Copy link
Copy Markdown
Contributor Author

Post-merge validation for a469bb71 completed. The two local full-build failures reproduce against the current upstream/main baseline; the affected test and implementation files are unchanged by this PR: BaseSandboxFilesystemTest.edit_fileNotFound (expected true, got false) and MarketplaceStagerOrphanGcTest.unreadableEntryDoesNotFailStage (NoSuchFileException while changing POSIX permissions in the root container). All other modules completed successfully. On the remote PR, License, Module Sync, documentation validation, and CLA are passing; Ubuntu and Windows builds are still running, and the fork Mintlify preview is skipped because it requires external approval.

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]: ToolCallsAccumulator silently swallows JSON parse failures for streamed tool call arguments and the raw string is lost

4 participants