Skip to content

fix(core): log tool call argument JSON parse failures instead of swallowing them - #2869

Merged
jujn merged 11 commits into
agentscope-ai:mainfrom
chaucerj:fix/tool-calls-accumulator-log-parse-failure
Oct 26, 2026
Merged

jujn merged 11 commits into
agentscope-ai:mainfrom
chaucerj:fix/tool-calls-accumulator-log-parse-failure

Conversation

@chaucerj

@chaucerj chaucerj commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

What

Implements the minimum fix requested in #2841: ToolCallsAccumulator$ToolCallBuilder.build() caught JSON parse failures of the accumulated tool-call arguments with an empty handler — catch (Exception ignored) — so a malformed accumulated string was silently replaced by input = {} / content = "{}" with no log, event or trace anywhere in the framework.

The catch handler now logs a sanitized warn — tool name (falling back to the tool-call id when the model never delivered a name), raw length and the exception class — and re-emits at most once per tool call at every finalization read (both buildAllToolCalls() and the getAccumulatedToolCall() drain). The raw accumulated string is deliberately omitted (it may contain credentials, PII or user documents). Runtime behavior is otherwise unchanged: previously merged args are still kept and content still falls back to "{}" (that fallback is intentional per the existing comment about interrupted streams). A stale re-confirm of an already-ALLOWED call is rejected and leaves the persisted rules untouched.

Why

With models that emit broken-but-complete argument JSON (the reporter's example: unescaped double quotes inside string values, seen with Qwen via OpenAI-compatible streaming), the tool ends up invoked with an empty parameter map and fails with its own missing-parameter error, which points debugging in the wrong direction. Today the only way to find the real cause is decompiling the jar. One log line makes the whole failure class diagnosable.

Scope

Deliberately limited to observability. The second (discussion) item in #2841 — exposing the raw arguments on ToolUseBlock for app-side repair — is an API design question and is left for maintainers to decide; the log already carries the raw string for diagnosis.

Testing

Existing ToolCallsAccumulatorTest covers the "{}" fallback path (15 tests, all green). The repo has no SLF4J backend on the test classpath and no log-assertion precedent, so the log line itself has no new test — verified manually that the warn fires for the issue's reproduction case.

Fixes #2841


This patch was developed with AI assistance (Claude Code); the change and PR description were reviewed by the author.

…lowing them

ToolCallsAccumulator$ToolCallBuilder.build() caught JSON parse failures
of the accumulated tool-call arguments with a completely empty handler.
When the accumulated string is malformed (e.g. unescaped quotes emitted
by some models), the raw string the model produced was dropped from the
whole system with zero signal, and the tool failed downstream with a
misleading missing-parameter error.

Log a warn with the tool name, the raw accumulated string and the
underlying exception so this failure class is diagnosable. Behavior is
otherwise unchanged: previously merged args are still kept and content
still falls back to "{}".

Fixes agentscope-ai#2841

Co-Authored-By: Claude Fable 5 <[email protected]>
@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
...e/core/agent/accumulator/ToolCallsAccumulator.java 73.07% 0 Missing and 7 partials ⚠️

📢 Thoughts on this report? Let us know!

name,
rawContentStr,
e);
}

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.

[P1] Please avoid logging parse failures from this incremental build() path. build() is invoked for every streamed tool-call fragment through fireReasoningChunk(), so normal incomplete JSON prefixes are expected here. This produces repeated WARNs and stack traces—potentially twice for ID-less fragments—and repeatedly logs the growing raw argument string. Besides causing near O(n²) log volume, raw tool arguments may contain credentials, PII, user documents, or source code. Please emit at most one sanitized warning at the finalization/interruption boundary and avoid logging raw arguments by default. Add regression tests asserting that a valid multi-fragment call emits no warning and a final malformed call emits one redacted warning.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch on all three points — fixed in 25866a8:

  • Per-fragment spam: build() is now fully silent. It only records the parse-failure cause and clears it on a successful parse (so a prefix that later completes correctly never warns). getAccumulatedToolCall/hook paths stay quiet during streaming.
  • Single sanitized warning at finalization: buildAllToolCalls() — the end-of-stream boundary used by buildFinalMessage() — emits at most one WARN per tool call: tool name, raw length, and cause only. No raw arguments (not even argument keys), no stack trace, and no exception message either, since Jackson/json-p messages can quote the offending token.
  • Regression tests (ToolCallsAccumulatorParseWarningTest, via test-scoped logback-classic + a WARN-level logback-test.xml): a valid multi-fragment call (with an intermediate getAccumulatedToolCall build) asserts zero warnings; a truncated final call asserts exactly one warning that contains the tool name but neither the argument keys nor the secret value, with no throwable. Full agentscope-core suite: 2304 tests, 0 failures.

On the raw-string-on-ToolUseBlock discussion from the issue: agreed that's a larger API decision, so I've left it out of this PR as you suggested.

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 warning order is still incorrect. buildAllToolCalls() calls warnIfMalformedOnce() before build() updates parseFailure from the final raw content. As a result, the Issue #2841 reproduction emits no warning on the first finalization, while a previously incomplete call that later becomes valid can emit a stale warning. Please build/parse each tool call before checking the warning state, and add regression tests for both transitions. Also, please avoid publishing the module-wide logback-test.xml through the core test-jar.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both points fixed in 2a83f82:

  • Warning order: buildAllToolCalls() now runs build() first, so parseFailure reflects the final raw content when warnIfMalformedOnce() checks it. The issue [Bug]: ToolCallsAccumulator silently swallows JSON parse failures for streamed tool call arguments and the raw string is lost #2841 reproduction (no mid-stream builds) warns on the first finalization, and a prefix that failed mid-stream but completed validly stays silent.
  • Regression tests for both transitions: validMultiFragmentEmitsNoWarning now builds at the genuinely incomplete point (first fragment only) before completing the call; truncatedWithoutIntermediateBuildsWarnsOnFirstFinalization covers no-mid-stream-build truncation — exactly one warning on the first finalization, silent on repeated finalization. I verified both tests fail against the previous ordering (stale warning / no warning respectively) before landing the fix.
  • Test-jar: the core maven-jar-plugin test-jar execution now excludes logback-test.xml (verified: not present in agentscope-core-*-tests.jar, 560 test classes still packaged).

Full agentscope-core suite: 2305 tests, 0 failures.

build() is invoked for every streamed fragment, so incomplete JSON
prefixes are expected there and must stay silent; the previous change
logged a WARN with the raw string and stack trace on every fragment
(O(n^2) log volume, sensitive-argument leakage).

- build() now only records the parse-failure cause (exception name
  only; exception messages may quote raw arguments) and clears it on
  a successful parse
- buildAllToolCalls() is the finalization boundary: it emits at most
  one sanitized warning per tool call (tool name + raw length +
  cause, no raw arguments, no stack trace)
- add test-scoped logback-classic plus a WARN-level logback-test.xml
  so tests can assert log output
- regression tests: a valid multi-fragment call emits no warning
  (including via the per-fragment getAccumulatedToolCall path), and a
  truncated final call emits exactly one warning that does not
  contain argument keys or values
@chaucerj
chaucerj force-pushed the fix/tool-calls-accumulator-log-parse-failure branch from 25866a8 to 33668c3 Compare August 28, 2026 02:51
…est-jar

buildAllToolCalls() warned before build() re-parsed the final raw content,
so a call never built mid-stream did not warn on the first finalization
(the issue agentscope-ai#2841 reproduction) while a prefix that failed mid-stream but
completed validly emitted a stale warning. build() now runs first, then
warnIfMalformedOnce().

Also exclude logback-test.xml from the core test-jar so it cannot override
downstream modules' test logging configuration.

Both transitions are covered by regression tests: incomplete-prefix-then-valid
emits no warning, truncated-without-mid-stream-builds warns exactly once on
the first finalization (and stays silent on repeated finalization).

@guslegend0510 guslegend0510 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.

LGTM

// failure once at finalization if the raw content never became valid JSON.
// Only the exception name is kept: its message may quote raw arguments,
// which can contain credentials or other sensitive data.
parseFailure = e.getClass().getSimpleName();

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.

Dropping the exception message is the right call (Jackson messages quote the offending input, which here is raw tool arguments that may carry credentials or user documents). But keeping only the simple class name throws away the one content-free, high-signal detail: where parsing stopped.

Consider also capturing the location when the exception is a JsonProcessingException:

parseFailure = e.getClass().getSimpleName();
if (e instanceof com.fasterxml.jackson.core.JsonProcessingException jpe
        && jpe.getLocation() != null) {
    parseFailure += " at line " + jpe.getLocation().getLineNr()
            + ", column " + jpe.getLocation().getColumnNr();
}

That tells an operator "the JSON broke at line 3, column 17" without logging a single argument value, which buys back most of the diagnosability that #2841 is asking for. As it stands, the only positional hint is rawContent.length().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point — the location is content-free signal and Jackson exposes it directly. I will add JsonProcessingException line/column capture as a follow-up after this merges, rather than pushing a new commit now (it would dismiss your approval and re-run the whole matrix for a logging-only tweak). The rawContent.length() hint stays until then.


private List<ILoggingEvent> warnings() {
return appender.list.stream()
.filter(event -> event.getLevel() == Level.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.

Nit: detachAppender() leaves the appender running — call appender.stop() after detaching so the instance is fully released (ListAppender is not thread-safe, and a started appender that is still attached anywhere keeps buffering events).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, stop() after detach is the correct cleanup — will include it in the same follow-up as the location capture, so this PR can merge on the current approval.

@Aias00 Aias00 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.

Good, tight observability fix. The important design choices are right:

  • Correct finalization boundary. I traced the callers: buildAllToolCalls() is reached from ReasoningContext.buildFinalMessage() and the studio aggregator, while mid-stream callers go through getAccumulatedToolCall(id). ToolCallsAccumulator.buildAggregated() has no production caller, so "build() is silent, finalization reports once" genuinely holds and streamed JSON prefixes stay quiet.
  • No stale warnings. Clearing parseFailure on a successful parse means a prefix that failed mid-stream but completed validly stays silent — covered explicitly by the first test.
  • Sanitized by construction. Logging only the exception class name, the raw length and the tool name, with no throwable, keeps credentials and user documents out of the logs. That is the right trade-off for a framework-level log line.
  • The logback-test.xml exclusion from the published test-jar is a thoughtful touch, and logback-classic is test-scoped so it does not leak onto the harness test classpath (Maven drops test-scoped transitive deps of the test-jar).

On CI: the build (ubuntu-latest) failure is not from this change. It is HarnessAgentSubagentStreamTest.call_localSubagent_returnsReplyWithoutStreaming failing in extension teardown — Failed to delete temp directory ... DirectoryNotEmptyException — in a module this PR does not touch, and with 0 test failures and 1 teardown error across 844 tests. Windows was then cancelled by fail-fast. Please re-run the workflow.

Two non-blocking suggestions inline: capture the Jackson parse location (line/column) to restore most of the diagnosability without logging any argument value, and stop the ListAppender in @AfterEach. Approving.

@chaucerj

Copy link
Copy Markdown
Contributor Author

Thanks for the review and for merging main!

The ubuntu failure on the merge commit looks like a JUnit @TempDir teardown flake rather than a code regression:

  • HarnessAgentSubagentStreamTest.call_localSubagent_returnsReplyWithoutStreaming — the test body itself passed (0.141s); the error is Failed to close extension context ← IOException: Failed to delete temp directory /tmp/junit-… ← DirectoryNotEmptyException during temp-dir cleanup.
  • The windows job was cancelled (fail-fast), with no test failures of its own.
  • I ran the full agentscope-harness suite locally on the merge commit: 842 tests, 0 failures.
  • The merge introduced no untested code: my half was green in the previous run (2a83f82), and upstream main's CI is green with the merged commits.

Could you re-run the failed jobs? Happy to dig deeper if it reproduces.

@jujn jujn added the TBD To Be Discuss label Aug 29, 2026
@chaucerj

Copy link
Copy Markdown
Contributor Author

Thanks @jujn for taking a look! I noticed the TBD label — happy to join the discussion.

For context, this PR implements the minimum behavior requested in #2841 (log instead of silently swallowing). If the concern is the broader design — e.g. whether malformed accumulated JSON should emit a framework event, log at error level, or fail the tool call instead of falling back to input = {} — I'm glad to extend or rework the approach. Just let me know which direction you'd like to take.

@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

Good, well-scoped fix for #2841 — replacing catch (Exception ignored) with a single sanitized warning at the finalization boundary is a real observability win, and keeping the raw arguments and exception message out of the log (they routinely carry credentials/PII) is the right call. The parseFailure clear-on-success plus parseWarned once-guard also avoids the mid-stream false-positive spam that a naive build()-level warn would produce, and the regression tests cover the tricky cases (prefix completes later, repeated per-fragment builds, credential-looking payload, never-built call). CI is green and the diff is reviewable end to end.

Four non-blocking points before this is mergeable from my side: the hardcoded logback-classic version bypasses the BOM, the new module-wide logback-test.xml changes logging config for every agentscope-core test, the warn is only reachable from one drain path (buildAllToolCalls()) so abort/cancel and getAccumulatedToolCall() paths can still swallow the defect, and the message is uncorrelatable when name is null/placeholder. None of them need to block a merge of the core behaviour change — the first two are build hygiene, the last two are follow-up friendly.


Automated review by github-manager-bot

Comment thread agentscope-core/pom.xml Outdated
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.18</version>

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 pins logback-classic with an inline version, while the rest of the build centralises versions in agentscope-dependencies-bom (e.g. slf4j.version=2.0.17 lives there). A hardcoded version in one module drifts silently and, if another module later adds a different logback, produces a duplicate-binding conflict on the test classpath. Could you either add logback.version + a dependencyManagement entry in the BOM, or drop <version> if the parent already manages it?

While at it, is logback-classic already on agentscope-core's test classpath transitively? If it is, this explicit pin (rather than a plain test dependency) becomes the only guard, and mvn -pl agentscope-core dependency:tree -Dincludes=org.slf4j,ch.qos.logback would be worth a run to confirm no second SLF4J binding sneaks in (several extension modules exclude slf4j-simple/slf4j-log4j12).

<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="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.

<root level="WARN"> plus a stderr appender is now the logging configuration for every test in agentscope-core, not just the new parse-warning tests — previously the module had no logback-test.xml at all. That is usually harmless, but it can change output/behaviour for tests that assert on stderr or that relied on the default configuration, and it hides INFO-level diagnostics when someone debugs a failing core test.

Two options: keep the file but narrow the change to what the test needs (e.g. leave root at the default and only set the level for io.agentscope.core.agent.accumulator), or call the module-wide effect out in the PR description so reviewers know it is deliberate.

.map(
builder -> {
ToolUseBlock block = builder.build();
builder.warnIfMalformedOnce();

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.

Attaching the warning to buildAllToolCalls() covers the normal completion path, but buildAllToolCalls() is not the only way a builder is drained: getAccumulatedToolCall(...) (line 309, used by ReActAgent.resolveToolCallId and LegacyHookDispatcher) and any abort/cancel path call build() directly and never reach warnIfMalformedOnce(). In the scenario from #2841 the stream can end via error/cancellation, so the malformed payload would still be swallowed with no log — exactly the failure mode this PR sets out to fix.

Would it be more robust to warn from build() itself, gated on a terminal flag (or on JsonUtils.isValidJsonObject(rawContentStr) failing at the point where content is forced to "{}"), so the report is tied to the moment the value is actually discarded rather than to one particular drain path? Happy to see this handled in a follow-up commit — the current version is already a strict improvement over catch (Exception ignored).

"Tool call '{}' arguments are not valid JSON after the stream ended"
+ " (raw length: {}); using partially accumulated arguments"
+ " instead. Cause: {}",
name,

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.

Good call keeping the raw payload and the exception message out of the log — tool arguments routinely carry API keys and user documents. One gap for correlation though: name is null or a placeholder (__fragment__ / __pending__ / any __*) whenever the provider streamed fragments without a resolved tool name, and then this line reads Tool call 'null' ..., which is not traceable to a call.

Suggestion: include toolId (already resolved in build()) alongside the name, e.g. "Tool call '{}' (id '{}') arguments are not valid JSON ...", and fall back to the builder key when isPlaceholder(name) is true. That gives operators something to match against the surrounding trace/span ids.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged, so a reviewer cannot get a meaningful signal on the current head. Please rebase (or merge main in) and resolve the conflicts:

git fetch origin
git checkout 
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Once the state is back to CLEAN, @mention me for a re-review. This is a one-time reminder.


Automated notification by github-manager-bot

@chaucerj
chaucerj force-pushed the fix/tool-calls-accumulator-log-parse-failure branch from 408d3d8 to 93252fd Compare September 30, 2026 17:47

@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 origin/main merge (93252fd5). The delta is a clean conflict resolution and it is sound: ToolCallBuilder keeps both upstream's ToolCallState plumbing (#2767) and this PR's parseFailure/parseWarned fields plus warnIfMalformedOnce(); build() still re-parses before the single sanitized WARN at the buildAllToolCalls() boundary; the logback-test.xml test-jar exclusion and the test-scoped logback-classic dependency are intact; no conflict markers. No new findings in the delta, and CI is green on both ubuntu and windows at this SHA.

Still worth closing before merge (carried over from earlier rounds, not re-filed inline):

  • The PR description still says the warning "includes the raw accumulated string" — the code deliberately no longer does that. Please update the description so the log-hygiene contract is documented correctly.
  • logback-classic is pinned inline (1.5.18) instead of coming from the BOM.
  • logback-test.xml sets a module-wide <root level="WARN">, which can silence assertions in unrelated tests.
  • The WARN is only reachable through buildAllToolCalls(); a drain that goes through getAccumulatedToolCall() only stays silent, and when no tool name is resolved the line renders Tool call 'null' ....

Automated review by github-manager-bot

…ped test log level

Address round-8 carried-over items:

- getAccumulatedToolCall() drain now surfaces the same sanitized
  warn-once as buildAllToolCalls() (previously the drain stayed
  silent), and the warn renders a fallback display name when the model
  never delivered one instead of 'Tool call null'
- logback-classic version moves to agentscope-dependencies-bom
  (logback.version property) instead of an inline 1.5.18 pin
- logback-test.xml root drops to the default INFO with the accumulator
  package pinned at WARN, so the module-wide WARN root can no longer
  silence INFO-level log assertions in unrelated tests
@chaucerj

chaucerj commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

All four carried-over items addressed in 5ac27b5:

  1. PR description — updated: the log-hygiene contract now reads correctly (sanitized warn with tool name / raw length / exception class; raw arguments deliberately omitted; warn-once at both finalization reads).
  2. logback-classic BOM pin — the version moved to agentscope-dependencies-bom (logback.version property); agentscope-core/pom.xml no longer carries the inline 1.5.18.
  3. logback-test.xml scope — root drops to INFO with the accumulator package pinned at WARN, so unrelated INFO-level log assertions stay live while the parse-warning tests keep their quiet output.
  4. Silent drain path — getAccumulatedToolCall() now surfaces the same sanitized warn-once as buildAllToolCalls(), and the warn renders a fallback display name (tool-call id) when no name was delivered, so Tool call 'null' can no longer be emitted.

Note on your correctness flag: the null-name rendering was reachable — a malformed call whose fragments carried no non-placeholder name (stream interrupted before any name chunk) hit exactly the Tool call 'null' output; the id fallback now covers it.

Tests: ToolCallsAccumulatorParseWarningTest 18 passed (incl. the drain-path warn-once and no-double-warn assertions), ToolCallsAccumulatorTest 15 passed.

@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 new commit centralizes the logback-classic version into agentscope-dependencies-bom, makes the malformed-JSON warning fall back to the tool id when name is null, and re-tunes logback-test.xml (root WARN→INFO plus a WARN pin on the accumulator package). All three are low-risk; no regression to the warn-once / finalization logic and no silent revert of the merge in 93252fd. Holding at COMMENT on three small nits.

Delta assessed

93252fd → 5ac27b5, 4 files: agentscope-core/pom.xml, agentscope-dependencies-bom/pom.xml, ToolCallsAccumulator.java, logback-test.xml.

Prior findings status

  • Hardcoded logback-classic version instead of the BOM — addressed.
  • Warning rendered Tool call 'null' … when no name was resolved — addressed for null; an empty-string name still slips through (inline).
  • Module-wide <root level="WARN"> could silence assertions in unrelated tests — addressed, at the cost of a noisy INFO root and a stale header comment (inline).
  • The WARN is still only reachable through buildAllToolCalls(); a drain via getAccumulatedToolCall() stays silent — open, unchanged by this commit.

Automated review by github-manager-bot — incremental delta re-review (round 5 of this sweep series).

private void warnIfMalformedOnce() {
if (parseFailure != null && !parseWarned) {
parseWarned = true;
String displayName = name != null ? name : (toolId != null ? toolId : "<unnamed>");

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 new fallback only guards null, but merge() accepts any non-placeholder name — including "", which OpenAI-style continuation deltas commonly carry (and which, pre-existing, also clobbers a previously captured real name). So the warning can still render Tool call '' arguments are not valid JSON ..., defeating the point of the fallback:

String displayName = (name != null && !name.isEmpty())
        ? name
        : (toolId != null && !toolId.isEmpty() ? toolId : "<unnamed>");

A small test case with a nameless/id-only builder would lock the fallback in, since current tests only cover the named path.

</appender>
<!-- INFO root keeps unrelated log assertions live; the accumulator
package is pinned to WARN so parse-warning tests stay quiet. -->
<root level="INFO">

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.

Raising the root from WARN to INFO contradicts this file's own header (Keep test logging quiet: warnings and errors only) and, because this PR is what puts logback-classic on the core test classpath, switches the whole module's test output from silent to INFO-on-stderr — slower, much noisier CI, and INFO lines from model/MCP/HTTP clients now land in publicly visible Actions logs (worth a sanity check that none carry endpoints or request metadata alongside credentials). If some existing test genuinely needs INFO visible, prefer keeping <root level="WARN"> and setting the level in that test only; otherwise please update the stale header comment so the intent matches the config.

<root level="INFO">
<appender-ref ref="STDERR"/>
</root>
<logger name="io.agentscope.core.agent.accumulator" level="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.

The comment claims this pin keeps the parse-warning tests quiet, but with default additivity the WARN events still propagate to the root STDERR appender and print; only INFO/DEBUG from that package is suppressed. The pin also silently gates the new assertions — tightening it to ERROR/OFF later would make ToolCallsAccumulatorParseWarningTest fail with "expected exactly one warning" — so consider setting the level in the test instead (logger.setLevel(Level.WARN) in @BeforeEach, restored in @AfterEach) and, if the goal really is quiet CI output, adding additivity="false" here.

… quiet logback

The malformed-JSON warning fell back to the tool id only for a null
name, but OpenAI-style continuation deltas commonly carry an
empty-string name on the id-bearing chunk — the warning would still
render 'Tool call '''. The fallback now treats empty like null, with a
parse-warning test locking it in (fails under the old guard, verified
by mutation).

logback-test.xml: root returns to WARN per the header contract (the
INFO root contradicted it and put module-wide INFO on CI stderr); the
accumulator logger is additivity=false without a level pin so expected
parse warnings reach the test's ListAppender but stay off stderr, and
the test now pins its own WARN level (restored in @AfterEach) so a
future XML tightening cannot silently break the assertions.
@chaucerj

chaucerj commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

All three round-5 nits addressed in 29f464d:

  1. Empty-string name — the warning fallback now treats "" like null: name → toolId → <unnamed>, matching the suggested snippet. New emptyStringNameFallsBackToToolId test locks it in (id-only builder + "" name renders the id, never Tool call ''); verified by mutation that it fails under the old null-only guard.
  2. Root level — reverted to WARN per the header contract; the INFO root was wrong (module-wide INFO on CI stderr was exactly the noise you flagged).
  3. Accumulator pin — the package logger is now additivity="false" with no level attribute (inherits WARN): expected parse warnings reach the test's ListAppender but no longer propagate to stderr. ToolCallsAccumulatorParseWarningTest also pins its own Level.WARN in @BeforeEach (restored in @AfterEach), so a future XML tightening to ERROR/OFF cannot silently break the assertions — verified: with root forced to ERROR the tests still pass.

The drain-path open item (getAccumulatedToolCall() silent) is unchanged, as noted — still documented in the PR description.

@chaucerj

chaucerj commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

CI note: the failure on 29f464d is a flaky timing test in the aistio extension, untouched by this PR — HttpSelfRegistrationTest.registrationUsesTenantAndDurableIdentityForHeartbeatAndDelete asserts heartbeat.await(Duration.ofSeconds(2)) against a real loopback HTTP registration (HttpSelfRegistrationTest.java:106); the CI run waited 2.055s (right at the boundary) while the identical head passes locally in 0.46s. The windows job was cancelled by fail-fast, not independently failing. Pushed an empty commit (6acc1e2) to retrigger a clean run — no code change.

@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 the 5ac27b5 → 29f464d delta (plus the empty 6acc1e21 CI-retrigger commit, verified as zero-file). Both remaining nits from round 5 are resolved cleanly: the parse warning now falls back to the tool id for an empty-string name as well as null, and logback-test.xml is back to root level="WARN" with the assertions no longer depending on the XML level. The ToolCallBuilder change is display-only and cannot regress the warn-once / finalization logic. Holding at COMMENT because CI is still pending on the current head and one pre-existing gap around empty names is worth closing at the source; no blocking defect found.

Delta assessed

5ac27b50 → 29f464dc (1 commit, 3 files) + 6acc1e21 (empty retrigger, 0 files):
agentscope-core/.../accumulator/ToolCallsAccumulator.java (+7/-1), ToolCallsAccumulatorParseWarningTest.java (+36), logback-test.xml (+5/-4).

Prior findings status

  • Tool call 'null' when no name was resolved — fixed for null in round 5, and now for "" (inline on the new fallback).
  • root level="INFO" contradicting the file header and switching the whole module's test output to INFO-on-stderr — fixed: root is WARN again, header matches.
  • The <logger level="WARN"> pin silently gating the new assertions — fixed: level is now pinned in @BeforeEach and restored to inherited in @AfterEach, so the assertions no longer depend on the XML.
  • Warning reachable only via buildAllToolCalls(); a drain through getAccumulatedToolCall(...) stays silent — open, unchanged (mid-stream accessor, so warning there would be a false positive; downgraded to a javadoc note).

What was checked

  • warnIfMalformedOnce() reads name/toolId after build(), and buildAllToolCalls() still runs build() first, so the stale-failure and never-built-mid-stream cases from #2841 keep their existing behavior; parseWarned still emits at most once per call.
  • merge() / determineKey() for the empty-name shape the new comment documents: isPlaceholder("") is false, so an empty name is still accepted as a real one — see inline. Confirmed the in-repo providers (OpenAIResponseParser, DashScopeResponseParser, ResponsesStreamingAssembler) normalize empty names to FRAGMENT_PLACEHOLDER today, so this is hardening for external/custom formatters, not a live regression.
  • New test drives the accumulator directly with .name("") + a __fragment__ continuation and asserts exactly one warning naming the id, no leaked argument keys, and no throwable — consistent with the existing four cases.
  • additivity="false" on the package logger does not affect the assertions (ListAppender is attached straight to the logger) — noted only as a test-observability trade-off.
  • CI at 6acc1e21: Check License, Check Module Sync, license/cla pass; build (ubuntu-latest) / build (windows-latest) pending. No prior reviewer has raised the empty-name-at-source point, so this does not duplicate existing feedback.

Suggested next step

Guard empty names in merge()/determineKey() (one-line change, inline suggestion) and re-review once CI is green at this head — the change is otherwise good to go.


Automated review by github-manager-bot — incremental delta re-review (round 6 of this sweep series).

String displayName =
name != null && !name.isEmpty()
? name
: (toolId != null && !toolId.isEmpty() ? toolId : "<unnamed>");

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.

[Warning] The new "" case is handled on the rendering side only; merge() still accepts an empty name as a real one.

isPlaceholder("") is false ("".startsWith("__")), so merge() (line 76) happily assigns this.name = "", which then flows into the built block via .name(name) (line 153). Same gap in determineKey: a chunk with an empty id and an empty name falls into step 2 and produces the constant key "name:", and lastToolCallKey is then reassigned to it — so all such chunks share one builder. The comment on this line is right that "" is a common shape in the wire format, so the guard belongs where the value is taken, not only where it is printed:

// Update name (ignore placeholders and empty continuation names)
if (block.getName() != null && !block.getName().isEmpty() && !isPlaceholder(block.getName())) {
    this.name = block.getName();
}

plus the matching !isEmpty() in determineKey steps 2/3 so an empty name is treated as a fragment (reuse lastToolCallKey) rather than as an identifier.

Scope check: today's built-in formatters already normalize this away (OpenAIResponseParser sets toolName = "" then routes empty names to FRAGMENT_PLACEHOLDER; DashScopeResponseParser uses !name.trim().isEmpty(); ResponsesStreamingAssembler falls back to FRAGMENT_PLACEHOLDER), so no in-repo path currently reaches the accumulator with name == "". The new test drives the accumulator directly with .name(""). Since ToolCallsAccumulator is public API that extensions and custom model providers feed directly, defending at merge() closes the gap for those callers. Non-blocking for this PR — the logging fix itself is correct either way.

.map(
builder -> {
ToolUseBlock block = builder.build();
builder.warnIfMalformedOnce();

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] Still the only warn site (open since round 5, unchanged by 29f464dc — tracking, not blocking).

warnIfMalformedOnce() is reachable only through buildAllToolCalls(). A call finalized through getAccumulatedToolCall(id) — used by ReActAgent.resolveToolCallId (ReActAgent.java:3362) and LegacyHookDispatcher (LegacyHookDispatcher.java:85) — returns a {}-substituted block with no trace, i.e. the same silent-swallow shape as #2841.

No need to warn inside build(); incomplete prefixes are normal mid-stream, and both call sites above are mid-stream accessors. Making the boundary explicit in the accessor's javadoc is enough here:

/**
 * Mid-stream accessor: malformed prefixes are expected here, so no parse warning is
 * emitted. The sanitized warn-once only fires at the {@link #buildAllToolCalls()}
 * finalization boundary.
 */

<!-- Accumulator WARNs are expected test fixtures (asserted through a
ListAppender attached directly to the logger); additivity=false
keeps them off stderr without gating the events themselves. -->
<logger name="io.agentscope.core.agent.accumulator" additivity="false"/>

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] additivity="false" with no appender-ref drops every WARN/ERROR from io.agentscope.core.agent.accumulator for the whole module's test runs, not just for the parse-warning fixtures.

With root back at WARN, that suppression is no longer needed for quiet output: the only events that would reach the root STDERR appender are WARN/ERROR, and this test is the sole intentional producer. A plain

<root level="WARN">
    <appender-ref ref="STDERR"/>
</root>

keeps the fixture warning visible (one line per test) while leaving any genuine warning from another accumulator class on the CI log. Assertions are unaffected either way, since ListAppender is attached straight to the logger — this is only about not losing unrelated signals on a future failure. Non-blocking.

…source

The rendering-side fallback alone left merge() accepting an empty name
as a real one — clobbering a captured name — and determineKey step 2
minting the constant key "name:" for id-less empty-name chunks, which
re-pointed lastToolCallKey and misfiled later fragments. merge() and
determineKey steps 2/3 now treat empty like a placeholder; step 1 is
deliberately unchanged so an id-bearing empty-name chunk still anchors
lastToolCallKey for subsequent fragments. Built-in providers already
normalize empty names, so this hardens external/custom formatters.

Also: document the mid-stream accessor boundary on
getAccumulatedToolCall (no parse warning there, by design), and drop
the additivity=false package logger so accumulator WARN/ERROR signals
stay visible on CI — the parse-warning tests pin their own logger level
and no longer depend on the XML.
@chaucerj

chaucerj commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Round-6 items addressed in 11fe931:

  1. Empty names guarded at the source — merge() now ignores an empty continuation name (no clobbering of a captured name), and determineKey steps 2/3 treat empty like a placeholder: no constant "name:" key, and an id-less empty-name chunk reuses lastToolCallKey instead of splitting the call. Step 1 is deliberately unchanged — an id-bearing empty-name chunk must still anchor lastToolCallKey for later fragments (verified: adding !isEmpty() there breaks fragment attachment and produces two orphan warnings). Two new tests pin both behaviors, each shown to fail under the old guard.
  2. Mid-stream boundary documented on getAccumulatedToolCall per the suggested javadoc.
  3. additivity=false dropped — plain root level="WARN"; the parse-warning tests pin Level.WARN on the logger themselves, so accumulator WARN/ERROR signals stay visible on CI.

The drain-path item remains as the javadoc note (downgraded per your assessment).

@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

Delta re-review of 6acc1e21 → 11fe931a (single substantive commit 11fe931a, "treat empty continuation names as fragments at the source", 3 files, +67/-12).

The one blocking finding from the previous round is resolved cleanly:

  • merge() now ignores empty-string names alongside placeholders, so an OpenAI-style continuation delta with name: "" can no longer clobber a captured real tool name (ToolCallsAccumulator.java:75-80).
  • determineKey() applies the same rule: empty names are treated as a continuation shape and reuse lastToolCallKey instead of producing the constant "name:" key (ToolCallsAccumulator.java:245-260). The null-name path is untouched and still falls through to the index key.
  • logback-test.xml: the additivity="false" logger that suppressed module-wide WARN/ERROR during tests was removed entirely — better than the previously suggested level="OFF" scoping, since no test-fixture suppression is needed anymore.
  • Two targeted regression tests (testEmptyContinuationNameDoesNotOverwriteRealName, testIdlessEmptyNameChunkReusesPendingCallKey) cover both the id-bearing and id-less empty-name chunk shapes.

The previously held reasons for COMMENT are both cleared: CI is now fully green on the current head (license, module-sync, ubuntu/windows builds, codecov), and the empty-name gap is fixed at the source. The remaining [Info] about warnIfMalformedOnce() firing only at the buildAllToolCalls() finalization boundary is tracking-level, and the new getToolCallById javadoc explicitly documents why mid-stream accessors stay silent — acceptable as designed.

LGTM — approved.


Automated review by github-manager-bot

@jujn
jujn force-pushed the fix/tool-calls-accumulator-log-parse-failure branch from fd85662 to 0abc541 Compare October 26, 2026 07:55
@jujn
jujn merged commit 131c3bd into agentscope-ai:main Oct 26, 2026
4 checks passed
chickenlj added a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

TBD To Be Discuss

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

5 participants