Repository navigation
fix(SubAgentTool): interrupt orphan sub-agent on tool call cancellation - #1784
Conversation
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes an orphan sub-agent resource leak in SubAgentTool when ToolExecutor times out and retries. The core fix adds a doFinally(CANCEL) handler in executeConversation() that interrupts the orphan agent via ReActAgent.interrupt(RuntimeContext). Signal type selection is precise — only cancellation triggers interrupt, not error or completion. Thread safety is ensured via AtomicBoolean in InterruptControl. State saving is unaffected since doOnSuccess doesn't fire on cancel. Test coverage includes both unit tests and integration tests. Well-designed fix.
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes an orphan sub-agent resource leak in SubAgentTool when ToolExecutor times out and retries. The core fix adds a doFinally(CANCEL) handler in executeConversation() that interrupts the orphan agent via ReActAgent.interrupt(RuntimeContext). Signal type selection is precise — only cancellation triggers interrupt, not error or completion. Thread safety is ensured via AtomicBoolean in InterruptControl. State saving is unaffected since doOnSuccess doesn't fire on cancel. Test coverage includes both unit tests and integration tests. Well-designed fix.
…on (agentscope-ai#1784) # fix(SubAgentTool): interrupt orphan sub-agent on tool call cancellation Closes agentscope-ai#1783 ## Before → After ``` Before (buggy): After (fixed): ToolExecutor times out sub-agent ToolExecutor times out sub-agent → retryWhen() re-subscribes → retryWhen() re-subscribes → agentProvider.provide() AGAIN → doFinally(CANCEL) interrupts old agent → NEW ReActAgent runs → agentProvider.provide() AGAIN → OLD ReActAgent LEAKS ❌ → NEW ReActAgent runs ✅ → OLD ReActAgent STOPPED ✅ ``` ## Summary When `ToolExecutor` times out a `call_subtask_agent` call and `maxAttempts > 1`, `retryWhen()` creates a new subscription → a new `ReActAgent`. The old one is never disposed and leaks LLM tokens, SSH connections and threads. This PR adds a `doFinally(CANCEL)` handler in `SubAgentTool.executeConversation()` that interrupts the orphan agent. ## Problem ### Root cause chain ``` 1. Mono.timeout() cancels upstream subscription 2. retryWhen() creates new subscription 3. Mono.deferContextual → agentProvider.provide() → NEW ReActAgent 4. Old ReActAgent is unreachable — nothing holds a reference to it 5. It runs to completion, wasting every resource it consumes ``` ### Production impact A single inspection run (9 sub-agents, `maxAttempts=3, timeout=10min`): | Metric | Value | |---|---| | Actual invocations | **19** (not 9) — 8 timed out + retry, 2 timed out + 2 retries | | Wasted tokens | **~1 million** (redundant agents doing identical LLM work) | | Execution time | **30+ min** (redundant agents contending for same resources) | ## Solution ### `SubAgentTool.java` — core fix (+37 lines) **Cancel handler in `executeConversation()`:** ```java result = result.doFinally(signal -> { if (signal == SignalType.CANCEL) { interruptAgent(agent, runtimeContext); } }); ``` **Helper method:** ```java private void interruptAgent(Agent agent, RuntimeContext ctx) { if (agent instanceof ReActAgent ra) { ra.interrupt(ctx); logger.warn("Sub-agent '{}' was interrupted — subscription cancelled.", ra.getName()); } } ``` ### Design decisions | Decision | Choice | Why | |---|---|---| | Signal type | `doFinally(CANCEL)` not `doOnCancel` | `doOnCancel` also fires on normal error cleanup | | Interrupt API | `interrupt(RuntimeContext)` not deprecated `interrupt(InterruptSource)` | Deprecated method only looks up `defaultSessionId` | | Fix location | `SubAgentTool`, not `ToolExecutor` | The component creating the resource should clean it up | ### `ToolExecutor.java` — log enhancement (+4/-1 lines) Retry warning now includes tool name: ``` Retrying tool call 'call_subtask_agent' (attempt 2/2) due to: Tool execution timeout after PT10M. The previous attempt is cancelled and may still be consuming resources. ``` ## Tests Two new test files covering the contract and end-to-end behavior. ### 1. End-to-end integration test (`SubAgentToolTimeoutRetryIntegrationTest`) ⭐ Uses a **real `ReActAgent`** as the sub-agent (no mocked `call()`) powered by the project's existing `MockModel` infrastructure. The sub-agent is given a custom `write_to_file` tool that writes one line every 100ms to a temp file while a `running` flag is true. **Test flow:** ``` 1. Build slow sub-agent: ReActAgent + MockModel("call write_to_file") + write_to_file tool 2. Build fast sub-agent: ReActAgent + MockModel("OK") 3. Wrap in SubAgentTool → .timeout(3s).retryWhen(1) 4. doFinally(CANCEL) → interrupt(ctx) → flips running=false → tool loop exits 5. Assert: file stopped growing; interrupt was called exactly on the timed-out agent ``` **Limitation acknowledged:** `ReActAgent` internally detaches tool execution via a separate `.subscribe()` in `runToolBatch`. Cancelling the outer Mono does **not** automatically interrupt the tool thread. The spy on `interrupt()` bridges this gap by flipping `running = false`, which is exactly the pattern production tools (SSH commands, DB queries) should follow to respond to interrupt signals. **Assertions:** | # | Assertion | Meaning | |---|---|---| | 1 | `lines1 > 10` | Tool was actively writing during the 3s timeout window | | 2 | `lines2 == lines1` (frozen) | File stopped growing 1.2s after retry → tool loop exited | | 3 | `verify(slowSpy, atLeastOnce()).interrupt(any(RuntimeContext.class))` | Interrupt delivered via correct API | | 4 | `verify(fastSpy, never()).interrupt(any(RuntimeContext.class))` | Only the timed-out agent was interrupted | ``` Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 Time elapsed: 4.778 s ``` ### 2. Unit test (`SubAgentToolCancellationTest`) - Spy agent with `call()` → `Mono.never()` with `doOnCancel` instrumentation - Subscribe → `dispose()` (simulates timeout cancel) - **Verifies**: `interrupt(RuntimeContext)` called **and** agent Mono cancelled ``` Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 ``` ### 3. Existing tests (`SubAgentConfigTest`) 18 tests, all pass — no regression. ### Run all ```bash cd agentscope-java mvn test -pl agentscope-core \ -Dtest="SubAgentConfigTest,SubAgentToolCancellationTest,SubAgentToolTimeoutRetryIntegrationTest" # Tests run: 20, Failures: 0, Errors: 0, Skipped: 0 ✅ ``` ## Files changed | File | Δ | Description | |---|---|---| | `agentscope-core/src/main/java/.../tool/subagent/SubAgentTool.java` | +37 | `doFinally(CANCEL)` + `interruptAgent` helper | | `agentscope-core/src/main/java/.../tool/ToolExecutor.java` | +4/-1 | Enhanced retry log | | `.../test/.../SubAgentToolCancellationTest.java` | +125 | Unit: `dispose()` → interrupt + cancel | | `.../test/.../SubAgentToolTimeoutRetryIntegrationTest.java` | +215 | E2E: real ReActAgent → file stops growing | Co-authored-by: xiaguanglei <[email protected]>
fix(SubAgentTool): interrupt orphan sub-agent on tool call cancellation
Closes #1783
Before → After
Summary
When
ToolExecutortimes out acall_subtask_agentcall andmaxAttempts > 1,retryWhen()creates a new subscription → a newReActAgent. The old one isnever disposed and leaks LLM tokens, SSH connections and threads. This PR
adds a
doFinally(CANCEL)handler inSubAgentTool.executeConversation()that interrupts the orphan agent.
Problem
Root cause chain
Production impact
A single inspection run (9 sub-agents,
maxAttempts=3, timeout=10min):Solution
SubAgentTool.java— core fix (+37 lines)Cancel handler in
executeConversation():Helper method:
Design decisions
doFinally(CANCEL)notdoOnCanceldoOnCancelalso fires on normal error cleanupinterrupt(RuntimeContext)not deprecatedinterrupt(InterruptSource)defaultSessionIdSubAgentTool, notToolExecutorToolExecutor.java— log enhancement (+4/-1 lines)Retry warning now includes tool name:
Tests
Two new test files covering the contract and end-to-end behavior.
1. End-to-end integration test (
SubAgentToolTimeoutRetryIntegrationTest) ⭐Uses a real
ReActAgentas the sub-agent (no mockedcall()) powered by theproject's existing
MockModelinfrastructure. The sub-agent is given a customwrite_to_filetool that writes one line every 100ms to a temp file while arunningflag is true.Test flow:
Limitation acknowledged:
ReActAgentinternally detaches tool execution via aseparate
.subscribe()inrunToolBatch. Cancelling the outer Mono does notautomatically interrupt the tool thread. The spy on
interrupt()bridges this gapby flipping
running = false, which is exactly the pattern production tools(SSH commands, DB queries) should follow to respond to interrupt signals.
Assertions:
lines1 > 10lines2 == lines1(frozen)verify(slowSpy, atLeastOnce()).interrupt(any(RuntimeContext.class))verify(fastSpy, never()).interrupt(any(RuntimeContext.class))2. Unit test (
SubAgentToolCancellationTest)call()→Mono.never()withdoOnCancelinstrumentationdispose()(simulates timeout cancel)interrupt(RuntimeContext)called and agent Mono cancelled3. Existing tests (
SubAgentConfigTest)18 tests, all pass — no regression.
Run all
Files changed
agentscope-core/src/main/java/.../tool/subagent/SubAgentTool.javadoFinally(CANCEL)+interruptAgenthelperagentscope-core/src/main/java/.../tool/ToolExecutor.java.../test/.../SubAgentToolCancellationTest.javadispose()→ interrupt + cancel.../test/.../SubAgentToolTimeoutRetryIntegrationTest.java