Skip to content

fix(SubAgentTool): interrupt orphan sub-agent on tool call cancellation - #1784

Merged
chickenlj merged 1 commit into
agentscope-ai:mainfrom
xiaguanglei:fix_agent-tool_retry
Jun 17, 2026
Merged

chickenlj merged 1 commit into
agentscope-ai:mainfrom
xiaguanglei:fix_agent-tool_retry

Conversation

@xiaguanglei

Copy link
Copy Markdown
Contributor

fix(SubAgentTool): interrupt orphan sub-agent on tool call cancellation

Closes #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():

result = result.doFinally(signal -> {
    if (signal == SignalType.CANCEL) {
        interruptAgent(agent, runtimeContext);
    }
});

Helper method:

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

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

@xiaguanglei
xiaguanglei requested a review from a team June 17, 2026 02:16
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Jun 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...ain/java/io/agentscope/core/tool/ToolExecutor.java 0.00% 1 Missing ⚠️
...io/agentscope/core/tool/subagent/SubAgentTool.java 90.90% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@AgentScopeJavaBot AgentScopeJavaBot added bug Something isn't working area/core/tool Tool, skill, RAG abstractions labels Jun 17, 2026

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

🤖 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 AgentScopeJavaBot 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.

🤖 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.

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

LGTM.

@chickenlj
chickenlj merged commit 029cc55 into agentscope-ai:main Jun 17, 2026
5 checks passed
wzl521 pushed a commit to wzl521/agentscope-java that referenced this pull request Aug 12, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/tool Tool, skill, RAG abstractions bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:SubAgentTool leaks orphan ReActAgent on timeout with retry

5 participants