Bug: ToolEmitter progress can be delivered to the wrong concurrent request
[Bug] ToolEmitter progress can be delivered to the wrong concurrent request
Hi! I think I found a concurrency issue around ToolEmitter progress events.
What I am doing
I have one long-lived HarnessAgent / ReActAgent in a Spring service. Different HTTP requests use different RuntimeContext values (userId and sessionId) and call streamEvents(...) concurrently.
One tool sends progress like this:
@Tool(name = "slow_tool", description = "A slow tool with progress")
public String run(
@ToolParam(name = "input") String input,
ToolEmitter emitter) {
emitter.emit(ToolResultBlock.text("progress for " + input));
// Simulate a slow remote call here.
return "done for " + input;
}
This follows the ToolEmitter example in the documentation: emit(...) for intermediate progress and return for the final tool result.
What I see
When many sessions call the shared agent at the same time, progress from one tool call can appear in another request's event stream.
In my local endpoint test, I sent 20 concurrent requests with different conversationIds. All requests reached the knowledge-base tool, which emits streamed progress. The result was:
20 requests total
17 requests received an internal final-result marker
2 requests received no visible result
1 request looked normal
0 HTTP failures
The important part is that the tool did emit its progress, but that progress was sometimes observed by another request. The original request then looked as if it had never emitted anything and received the final return value instead.
Why it looks like a framework-level race
ToolExecutor has one mutable field for the internal callback:
private BiConsumer<ToolUseBlock, ToolResultBlock> internalChunkCallback;
Each ReActAgent call does roughly this:
Set<String> chunkedToolIds = ConcurrentHashMap.newKeySet();
toolkit.setInternalChunkCallback((toolUse, chunk) -> {
chunkedToolIds.add(toolUse.getId());
// emit ToolResultTextDeltaEvent to this call's sink
});
The next concurrent call overwrites that callback on the same Toolkit / ToolExecutor.
Also, getEffectiveChunkCallback() returns a lambda that reads internalChunkCallback when emitter.emit(...) is called. So an emitter created for request A can invoke request B's callback if B replaces the field before A emits a chunk.
Then request A's chunkedToolIds does not contain its own tool ID. When the tool returns, emitToolResultDelta(...) sends the final return value because this check is false:
if (chunkedToolIds.contains(toolId)) {
return;
}
I can also reproduce the callback replacement deterministically with reflection against AgentScope 2.0.0.
Expected behavior
For concurrent calls on one shared agent:
- a tool's progress should always go to the event sink for the same
RuntimeContext/ call; - progress from one session should never appear in another session;
- a streamed tool should not accidentally expose its final internal return value just because another call replaced a callback.
Possible direction
Could the internal chunk callback be passed as call-scoped data to ToolExecutor / ToolCallParam, rather than stored as mutable state on a shared Toolkit? Capturing an immutable callback for the current CallExecution would also avoid this race.
I am happy to provide a small standalone test if that would help. Thanks!
This looks like a real shared-agent correctness issue rather than an event-ordering cosmetic bug. The callback should be call-scoped: an immutable ToolCallExecution/ToolCallParam context (or an emitter-bound callback) should be captured when the tool invocation starts and passed through the executor, instead of resolving Toolkit mutable state at emit() time.\n\nA first patch could preserve the public ToolEmitter API while changing only the internal routing boundary. The regression test should use two concurrent calls and a barrier so request A emits after request B has installed its callback, then assert: (1) each progress block is observed only by its own request sink, (2) each streamed tool call suppresses its own final return exactly once, and (3) a shared Toolkit remains safe when calls use different RuntimeContext values.\n\nIt would also be useful to document the lifecycle rule that an emitter is valid only for its originating tool call, and to keep callback cleanup in a finally path so failed/cancelled calls cannot retain a sink. I would be interested in implementing the focused routing change once maintainers confirm whether ToolCallParam or another internal execution context is the preferred extension point.
I prepared a draft implementation for discussion in #3066. It keeps the public ToolEmitter API, carries the internal callback through the call-scoped ToolCallParam, and adds a barrier-based regression test for two concurrent calls sharing one Toolkit. The draft intentionally leaves the internal overload open to maintainer preference; I can adapt it if another execution-context boundary is preferred.
Issue Evaluation
Category: bug | Status: Confirmed (with one nuance)
Verified against main @ c5db8f7.
Root cause: the internal chunk callback is shared mutable state on a per-agent-instance executor, while registration and resolution are unsynchronized.
ReActAgent.java:247holds oneToolkitper agent →Toolkit.java:78oneToolExecutor→ToolExecutor.java:67-68non-volatileuserChunkCallback/internalChunkCallback.ReActAgent.java:3023(inside each call'sFlux.create) writes it viaToolkit.java:462-464→ToolExecutor.java:107-109. Single production write site, no reset/doFinally— last writer wins.- The value is read back in
ToolExecutor.executeCoreat:242viagetEffectiveChunkCallback()(:122-137) when constructingDefaultToolEmitter. - Nuance vs. the report: resolution happens at emitter construction, not at every
emit()—DefaultToolEmittercaches the callback. The outcome is the same: if call B writes the field between A's write and A's read, A's emitter stays bound to B's callback for the whole tool run, so A'semit(...)lands in B's sink with B'sreplyIdand records A's tool id in B'schunkedToolIds(ReActAgent.java:3028). - Second symptom confirmed:
emitToolResultDelta(ReActAgent.java:3271-3297, called at:3125) only early-returns onchunkedToolIds.contains(toolId), so A emits its full final output as a delta to A's consumer.
Reachability: concurrent sessions on one agent instance are the documented model — HarnessAgent.java:163-166 ("safe to use as a singleton serving multiple users/sessions") and ReActAgent.java:718-729 callSerializationKey serializes only per (userId, sessionId) slot. The write→read window includes synchronous assembly (schema validation at ToolExecutor.java:204). Single-session/sequential use is unaffected. The repo already moved other toolkit state to per-call semantics (Toolkit.java:341-351, per-call soTool at ReActAgent.java:3416-3419) — this field was left behind.
Impact: cross-session tool-progress leakage (one user's tool output can appear in another user's stream, mis-attributed to the wrong replyId) plus missing progress / duplicated final output in the affected streams. Severity: high — a confidentiality and event-contract defect in the multi-tenant streaming path, not a crash.
Suggested fix: carry the callback as call-scoped data instead of executor state — add it to ToolCallParam (or the agent-only Toolkit.callTools overload) at ReActAgent.java:3023 and build the emitter from the param at ToolExecutor.java:242; deprecate Toolkit.setInternalChunkCallback for the agent path (keep user-level setChunkCallback). Regression test: one shared agent, two concurrent stream() calls with different (userId, sessionId) and a slow emitting tool, asserting each stream sees only its own tool ids/replyId.
PR generation: skipped — your draft PR #3066 already targets exactly this scoping fix, so we will not publish a competing implementation. Given the cross-session disclosure aspect, this needs maintainer review before merge.
Automated evaluation by github-manager-bot
This looks fixed on main now. #3283 (3c1c29c0, merged 2026-09-24) moved exactly the state the evaluation flagged off the shared executor:
Toolkit.setInternalChunkCallbackis gone. The internal callback is now threaded per call:Toolkit.callTools(..., internalChunkCallback)→ToolExecutor.execute/executeCore→ theDefaultToolEmitteris built fromgetEffectiveChunkCallback(internalChunkCallback).chunkedToolIdsis no longer agent-level state either — it is a local set created per call inReActAgentand passed down intoemitToolResultDelta.
Together those cover both symptoms in the evaluation: the cross-request callback capture, and the final output still being emitted as a delta. The user-level setChunkCallback was intentionally kept, as the evaluation suggested.
Worth noting the evaluation was verified at c5db8f7 (2026-09-12) and #3283 landed after it, which is why this thread still reads as open. The draft #3066 was closed on 2026-09-29.
If that matches your reading, I think this can be closed.