Skip to content

fix(core): retain reasoning details from all streaming chunks - #3128

Merged
jujn merged 3 commits into
agentscope-ai:mainfrom
pengmoubuaixuexi:fix/streaming-reasoning-details
Sep 13, 2026
Merged

jujn merged 3 commits into
agentscope-ai:mainfrom
pengmoubuaixuexi:fix/streaming-reasoning-details

Conversation

@pengmoubuaixuexi

@pengmoubuaixuexi pengmoubuaixuexi commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.3-SNAPSHOT, based on main 7399ed61b2ea22b25e2ead4dec9d59df6a77785c.

Description

Fixes #3127.

When OpenAI-compatible streaming responses carry reasoning_details in multiple chunks, ThinkingAccumulator replaces each earlier list via metadata.putAll. The final stored/replayed assistant message therefore contains only the last chunk's records. A local parser -> accumulator -> converter regression receives two distinct encrypted records and reproduces [rs_1] instead of [rs_0, rs_1] on unmodified main.

List-valued metadata is now accumulated in stream order, with copies both when accepting input lists and when building aggregated output. Empty lists receive the same isolation. Scalar values use last-write-wins, including when replacing an earlier list; a list following a scalar starts a new accumulated list. Reset clears the accumulated metadata. The change preserves opaque list elements without introducing provider-specific DTO dependencies in core.

Tests cover multi-chunk order, empty lists, thinking text, scalar/list transitions, caller-list mutation, independence of older and current aggregated snapshots, and reset. The integration regression uses the actual JSON parser and message converter with synthetic local response chunks and no model API calls.

Validation

  • Original main: the streaming pipeline regression fails with expected: <[rs_0, rs_1]> but was: <[rs_1]> (1 failure, 0 errors).
  • Snapshot regression on intermediate commit 4004cfe: mutating the latest returned list also clears accumulator state (expected: <[a, b]> but was: <[]>). It passes after copying list values in buildAggregated().
  • Final local run on ac48a30: selected core tests 31 passed; selected OpenAI extension tests 103 passed, 1 pre-existing disabled test. Total: 134 passed, 1 skipped, 0 failures/errors.
  • The skipped converter test concerns a SYSTEM + ToolResultBlock message rejected at construction; it is already disabled upstream.
mvn -B -pl agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai -am -Dtest=ThinkingAccumulatorReasoningDetailsTest,ReasoningContextTest,ToolCallsAccumulatorTest,StreamingReasoningDetailsReplayTest,OpenAIResponseParserTest,OpenAIMessageConverterTest,OpenAIMultiAgentFormatterTest,OpenAIThoughtSignatureTest,MinimaxDoubledSummaryReplayTest -Dsurefire.failIfNoSpecifiedTests=false -Dspotless.skip=true test

Spotless apply/check passed for the changed files; the final follow-up was checked with:

mvn -B -pl agentscope-core -DspotlessFiles=.*ThinkingAccumulator.java,.*ThinkingAccumulatorReasoningDetailsTest.java spotless:apply spotless:check

git diff --cached --check passed. Environment: Windows 11, Temurin 17.0.15, Maven 3.9.12. The full multi-module suite and live provider APIs were not run locally.

Checklist

  • Changed files formatted with Spotless.
  • Relevant tests pass, with the existing upstream skip documented above.
  • Full repository mvn test (not run locally).
  • No public API changes; metadata merging behavior is documented in Javadoc.
  • Diff reviewed and ready for review.

AI assistance was used for source review, implementation and tests. The reported reproduction and validation commands were executed locally.

Copilot AI lite review requested due to automatic review settings September 13, 2026 00:11

Copilot AI 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.

🟡 Changes recommended

One or more issues must be addressed before approval.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Fixes streaming loss of OpenAI reasoning_details by accumulating records across chunks and adding regression coverage.

Changes:

  • Accumulates reasoning details in order and clears them on reset.
  • Adds core accumulator tests and an end-to-end OpenAI replay test.
  • Preserves existing metadata behavior.
File summaries
File Description
agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/formatter/StreamingReasoningDetailsReplayTest.java Updated as part of this pull request.
agentscope-core/src/test/java/io/agentscope/core/agent/accumulator/ThinkingAccumulatorReasoningDetailsTest.java Updated as part of this pull request.
agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ThinkingAccumulator.java Updated as part of this pull request.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

if (!metadata.isEmpty()) {
builder.metadata(metadata);
Map<String, Object> aggregatedMetadata = new HashMap<>(metadata);
if (!reasoningDetails.isEmpty()) {

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.

Fixed in 958190b. The accumulator now tracks whether any list was received, independently of its size, and copies even an empty accumulated list on every build. The new regression reproduces the bug on the previous head: expected [] but got [late mutation] after the caller mutated its originally empty list. It now passes. Reset also clears the list-seen flag. Re-ran the selected core/OpenAI suites: 134 passed, 1 existing upstream skip; scoped Spotless and diff checks pass.

@codecov

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@oss-maintainer 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 #3127: ThinkingAccumulator previously let metadata.putAll overwrite reasoningDetails on every chunk, so only the last chunk's encrypted records survived the stream. Accumulating the list in received order plus copying it into a fresh metadata map per buildAggregated() is the right shape, and the two-layer test (unit + parse→accumulate→convert regression) demonstrates the original [rs_1] failure convincingly. LGTM — approving with two non-blocking notes.

Findings

  • [Info] ThinkingAccumulator.java:51 — unconditional concatenation assumes per-chunk incremental payloads; a cumulative-snapshot gateway (or a re-sent detail id) would now produce duplicates that are replayed and persisted.
  • [Info] ThinkingAccumulator.java:76 — asymmetric handling between the accumulated list and the last-value putAll when a chunk carries a non-List value under the same key.

What I verified locally

  • ThinkingBlock.METADATA_REASONING_DETAILS is the only metadata key with list semantics; all read sites (OpenAIMessageConverter:342, OpenAIMultiAgentFormatter:166) already guard with instanceof List, so making the value always a List is backward compatible for consumers.
  • ThinkingBlock copies the metadata map but not its values, so the per-build new ArrayList<>(reasoningDetails) is what keeps already-emitted blocks stable — the added independence test covers this properly.
  • No public API change; reset() clears all three fields consistently.

Suggestions

If you want to harden the incremental assumption without dragging provider DTOs into core, LinkedHashMap-style keying on (id, index) for Map entries would be enough, with a fallback to plain append for unknown shapes.


Automated review by github-manager-bot

Object details = block.getMetadata().get(ThinkingBlock.METADATA_REASONING_DETAILS);
if (details instanceof List<?> list) {
// Each streaming chunk carries only its own reasoning details, not a snapshot.
reasoningDetails.addAll(list);

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 accumulation is an unconditional concatenation, so it assumes each chunk carries only its own (incremental) reasoning_details. That holds for the current OpenAIResponseParser, which emits the per-chunk list. If an OpenAI-compatible gateway instead sends a cumulative snapshot per chunk, or re-sends the same detail id, this now produces duplicate entries that get replayed to the model and persisted in agent state. A cheap guard would be to skip items whose identity was already accumulated (for map-shaped entries, id + index are available without depending on provider DTOs), or to state the incremental-chunk assumption explicitly in the class javadoc so future providers cannot break it silently.

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.

Addressed via the documentation option in 958190b. The class Javadoc explicitly requires incremental records and tells snapshot-emitting providers to normalize before accumulation. I kept the received order without identity-based deduplication: repeated identifiers can represent distinct streaming fragments, and deduplicating them in provider-neutral core could discard valid data.

builder.metadata(metadata);
Map<String, Object> aggregatedMetadata = new HashMap<>(metadata);
if (!reasoningDetails.isEmpty()) {
aggregatedMetadata.put(

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.

Two one-sided cases here: (1) metadata.putAll() still keeps last-value semantics for the same key, so if a chunk carries a non-List value under METADATA_REASONING_DETAILS (single object / JSON string), the accumulated list silently wins in the aggregated block and the scalar is lost. (2) Conversely, a chunk that carries an empty list last still leaves the previous records in place, which is the desired outcome but is only documented in the inline comment. Consider normalising: if the incoming value is not a List, either log at debug or wrap it into the accumulated list, so the aggregated block never drops provider payload.

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.

Clarified and tested in 958190b. Once any list (including an empty one) has been received, later non-list metadata cannot replace its accumulated records. Before the first list, non-list values retain the existing last-value behavior; reset restores that initial state. The added regression covers those transitions. I avoided wrapping malformed scalar payloads into a reasoning record because readers expect actual detail objects/maps and wrapping would not establish valid semantics. The class Javadoc now states both the empty-list and non-list rules.

oss-maintainer

This comment was marked as abuse.

@pengmoubuaixuexi

Copy link
Copy Markdown
Contributor Author

@jujn Thanks for generalizing the metadata merge in 4004cfe. I kept that design and added a small snapshot follow-up in ac48a30.

buildAggregated() copied the outer map, but its list values still referenced the accumulator's current lists. The existing independence test cleared an older snapshot after another add(), which already allocated a replacement list, so it did not catch mutation of the latest snapshot. Extending that test with:

details(accumulator.buildAggregated()).clear();
assertEquals(List.of("a", "b"), details(accumulator.buildAggregated()));

fails on 4004cfe: expected: <[a, b]> but was: <[]> (4 tests, 1 failure, 0 errors).

The follow-up copies each list value when building the returned metadata snapshot. Generic list accumulation and scalar last-write-wins remain as in your update. The extended test and selected core/OpenAI suites now pass: 134 passed, 1 existing upstream skip; scoped Spotless and diff checks pass. I also updated the PR description to describe the generalized implementation.

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]: ThinkingAccumulator drops earlier streamed reasoning_details during replay

4 participants