Closed
Labels
bugSomething isn't working
Description
AgentSpawnTool.execWithTimeoutPromotion fire-and-forget-subscribes the inner
sub-agent execution Mono via plain .subscribe(...) (line 732). The resulting
Disposable is never captured, so when the parent subscription to
agentSpawn(...) is cancelled (by an outer Mono.timeout(), a user-initiated
stop, or upstream Reactor cancel), the inner execution is not disposed and
the sub-agent keeps running as an orphan — making further LLM calls and tool
calls whose results are silently dropped (the parent's MonoSink is already
cancelled, so the eventual sink.success(...) becomes a no-op).
Same class of bug as #1783, but in the harness-side AgentSpawnTool rather
than the core SubAgentTool. The fix from 029cc55e was not propagated here.
To Reproduce
Test code
// File: agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnToolOrphanCancelTest.java
MockModel slowModel = new MockModel(messages -> {
String callId = "call_" + UUID.randomUUID(); // unique id per call → no dedup
return List.of(ChatResponse.builder()
.id("msg_" + UUID.randomUUID())
.content(List.of(ToolUseBlock.builder()
.name("slow_tool").id(callId)
.input(Map.of()).build()))
.build());
});
ReActAgent slowSpy = Mockito.spy(ReActAgent.builder()
.name("slow_sub").sysPrompt("slow sub")
.model(slowModel).toolkit(slowTk)
.maxIters(50).build());
DefaultAgentManager manager = new DefaultAgentManager(
List.of(new SubagentEntry("slow_agent", "Test", rc -> slowSpy)), null);
AgentSpawnTool tool = new AgentSpawnTool(manager, new NoopTaskRepository(), 0);
RuntimeContext ctx = RuntimeContext.builder().sessionId("s1").userId("u1").build();
// Outer .timeout(2s) cancels the Mono<String> returned by agentSpawn
try {
tool.agentSpawn(ctx, null, "slow_agent", "go", null, 30, null)
.timeout(Duration.ofSeconds(2))
.block();
} catch (Exception expected) { /* outer timeout */ }
long linesAtTimeout = Files.readAllLines(tmpFile).size();
long callsAtTimeout = slowModel.getCallCount();
Thread.sleep(4_000);
long linesAfter = Files.readAllLines(tmpFile).size();
long callsAfter = slowModel.getCallCount();
verify(slowSpy, atLeastOnce()).interrupt(any(RuntimeContext.class)); // FAILS
How to execute
mvn -pl agentscope-harness test \
-Dtest=AgentSpawnToolOrphanCancelTest -DfailIfNoTests=false
What happens
1. agentSpawn(...) returns a Mono<String>. execWithTimeoutPromotion
builds a Mono.create(sink -> ...) whose sink callback fire-and-forget-
subscribes execLocalSync(...):
execLocalSync(agent, sessionId, userId, task, spawned, runtimeContext)
.contextWrite(c -> reactor.util.context.Context.of(parentCtx))
.subscribe(bridge::complete, bridge::completeExceptional, ...);
2. Outer .timeout(2s) cancels the parent subscription at t≈2.2s. Mono.create
honors the cancel by disposing the parent sink — but the inner subscription
from .subscribe(...) is never captured, so it is not disposed.
3. The ReActAgent reasoning loop continues on boundedElastic: model call →
tool_call → slow_tool writes a line → loop.
4. The internal CompletableFuture bridge + race.orTimeout(30s) are still
alive. When the agent eventually finishes, race.whenComplete invokes
sink.success(...) on the already-cancelled sink — a no-op. Result silently
dropped.
5. interrupt(RuntimeContext) is never called on the sub-agent.
Observable proof (measured on commit e070c8a5)
outer timeout fired at t=2202ms
at timeout: lines=8, modelCalls=9, toolCalls=9
after 4s wait: lines=34, modelCalls=34, toolCalls=34
delta = +26 lines, +25 modelCalls, +25 toolCalls
Mockito.verify(slowSpy, atLeastOnce()).interrupt(any): FAILS (0 calls)
- 8 iterations completed during the 2s legitimate window.
- 25 additional iterations executed after parent cancel — each one a wasted
LLM call + tool execution whose result was silently dropped.
Expected behavior
When the parent subscription to agentSpawn(...) is cancelled, the inner
fire-and-forget subscription should be disposed and ReActAgent.interrupt(ctx)
invoked on the sub-agent — mirroring the fix applied to SubAgentTool in
029cc55e.
After the fix, the same test asserts:
- delta lines ≤ 1 (an in-flight tool call may still complete)
- delta modelCalls ≤ 1
- interrupt(RuntimeContext) called at least once on the sub-agent
Production impact
Observed in a Spring Boot + AgentScope-Java multi-agent orchestration backend:
┌──────────────────────────────────────────────────────────────────┬─────────┐
│ Metric │ Value │
├──────────────────────────────────────────────────────────────────┼─────────┤
│ Sub-agents spawned per main-agent run │ 9 │
├──────────────────────────────────────────────────────────────────┼─────────┤
│ Total sub-agent invocations (incl. retries) │ 19 │
├──────────────────────────────────────────────────────────────────┼─────────┤
│ Estimated wasted tokens (orphan continuations after parent exit) │ ~1M │
├──────────────────────────────────────────────────────────────────┼─────────┤
│ Wall-clock inflation per affected run │ 30+ min │
└──────────────────────────────────────────────────────────────────┴─────────┘
In production the trigger is not Mono.timeout() but the parent main-agent
exiting (user abort, exception, or natural completion with pending
sub-agents). Orphan sub-agents continue hitting the LLM until they hit
maxIters, and the application has no way to retrieve or observe their
results — they silently burn tokens.
A local workaround was attempted in application code (intercepting the
parent AgentEndEvent and force-interrupting tracked sub-agents), but it
is brittle and breaks the legitimate async-cooperation path (children
intentionally outliving the parent, woken up later via WakeupDispatcher).
A framework-level fix is needed.
Root cause
AgentSpawnTool.execWithTimeoutPromotion (agentscope-harness, lines 706-766)
decouples sub-agent execution from observation using a CompletableFuture
bridge. This decoupling is intentional for the timeout-promotion path:
when the internal race.orTimeout(timeoutMs) fires, the bridge is wrapped
as AdoptedTaskRunSpec so the user can retrieve the result later via
task_output.
However, the same fire-and-forget pattern also handles external parent
cancellation — and there, the result is genuinely lost (no task_id was
returned before cancel). The inner subscription should be disposed and the
agent interrupted in this case, but the code does neither.
The fix is to capture the inner Disposable and dispose it on parent cancel,
plus add a doFinally(CANCEL) that calls interrupt(ctx) on the sub-agent
(mirroring 029cc55e):
// in execWithTimeoutPromotion, inside Mono.create(sink -> ...)
Mono<Msg> inner = execLocalSync(agent, sessionId, userId, task, spawned, runtimeContext)
.contextWrite(c -> reactor.util.context.Context.of(parentCtx))
.doFinally(signal -> {
if (signal == SignalType.CANCEL) {
interruptAgent(agent, runtimeContext);
}
});
Disposable innerSub = inner.subscribe(
bridge::complete,
bridge::completeExceptional,
() -> { if (!bridge.isDone()) bridge.complete(null); });
// ...
sink.onCancel(innerSub::dispose);
This preserves the timeout-promotion path (the internal orTimeout does not
produce a CANCEL signal — it completes race exceptionally with
TimeoutException, handled separately by handleExecError).
Environment
- AgentScope-Java commit: e070c8a5 (main, 2026-07-08)
- JDK: OpenJDK 21
- Module: agentscope-harness
- OS: Windows 11 (reproducible on any platform)
Additional context
- Same class of bug as #1783 (filed 2026-06-17 by @xiaguanglei), which fixed
SubAgentTool in commit 029cc55e. This issue is the equivalent fix for
the harness-side AgentSpawnTool.
- Difference between the two tools:
- SubAgentTool (core): inner Mono is part of the Reactor chain — cancel
propagates naturally once doFinally(CANCEL) is added.
- AgentSpawnTool (harness): inner Mono is fire-and-forget subscribed —
needs explicit Disposable capture + sink.onCancel(...) to propagate
cancel.
- The async cooperation path (children intentionally outliving the parent,
woken up via WakeupDispatcher → MessageBus.enqueueWakeup) uses
TaskRepository.putTask with timeout_seconds=0 and is not affected
by this fix. Only the sync execution path (execWithTimeoutPromotion)
is changed.
- Full reproduction test: AgentSpawnToolOrphanCancelTest.java (included in
the PR).Metadata
Metadata
Assignees
Labels
bugSomething isn't working
Activity
fix(harness): interrupt orphan sub-agent when AgentSpawnTool parent s…
fix(harness): interrupt orphan sub-agent when AgentSpawnTool parent s…