Skip to content

Commit 3ed1272

Browse files
committed
fix(harness): stop a running background subagent on task cancel
cancelTask only recorded CANCELLED for a local background task that was already running. The task ran through CompletableFuture.supplyAsync, and CompletableFuture.cancel(true) never interrupts the thread computing it, so the subagent kept calling the model and tools until it finished. A task promoted after a sync timeout had the same gap: the registered future was derived from the bridge, and cancelling it did not reach the child's subscription. WorkspaceTaskRepository now runs the local execution as a FutureTask and cancels it together with the task. The interrupt reaches the thread only while the execution runs, so block() disposes the child's subscription and the record updates around the execution are never interrupted. The interrupt is consumed once the execution stops, and the task is recorded as CANCELLED without failing it or waking its parent, matching a cancellation observed after the run. AgentSpawnTool disposes the inner subscription when a promoted task is cancelled, reusing doFinally(CANCEL) to interrupt the child and release its lease. Fixes #2790
1 parent aeeb3fd commit 3ed1272

4 files changed

Lines changed: 209 additions & 9 deletions

File tree

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java‎

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,13 @@
3333
import java.util.concurrent.CompletableFuture;
3434
import java.util.concurrent.CompletionException;
3535
import java.util.concurrent.ConcurrentHashMap;
36+
import java.util.concurrent.ExecutionException;
3637
import java.util.concurrent.ExecutorService;
3738
import java.util.concurrent.Executors;
39+
import java.util.concurrent.FutureTask;
3840
import java.util.concurrent.ScheduledExecutorService;
3941
import java.util.concurrent.ThreadLocalRandom;
4042
import java.util.concurrent.TimeUnit;
41-
import java.util.function.Supplier;
4243
import org.slf4j.Logger;
4344
import org.slf4j.LoggerFactory;
4445

@@ -67,6 +68,7 @@
6768
* persisted terminal state without hanging.
6869
* <li>Cancellation sets a {@link TaskRecord#isCancelRequested()} flag in workspace storage;
6970
* the originating node checks this flag before invoking the subagent for best-effort cancel.
71+
* Cancelling on the originating node also interrupts a running local execution.
7072
* <li>Remote {@link TaskRunSpec.RemoteTaskRunSpec} tasks use a {@link RemoteSubagentTransport}
7173
* (Agent Protocol by default) and persist {@link TaskRecord#getRemoteBaseUrl()} for
7274
* cross-node resume.
@@ -321,16 +323,22 @@ public BackgroundTask putTask(
321323
}
322324
});
323325
} else if (spec instanceof TaskRunSpec.LocalTaskRunSpec local) {
324-
future =
326+
FutureTask<String> execution = new FutureTask<>(() -> local.execution().get());
327+
CompletableFuture<String> localFuture =
325328
CompletableFuture.supplyAsync(
326329
() ->
327330
runLocalSupplier(
328-
capturedRc,
329-
sessionId,
330-
taskId,
331-
subAgentId,
332-
local.execution()),
331+
capturedRc, sessionId, taskId, subAgentId, execution),
333332
executor);
333+
// CompletableFuture.cancel never interrupts the thread computing it, so cancel the
334+
// execution too: cancelTask() must stop a running subagent, not only record CANCELLED.
335+
localFuture.whenComplete(
336+
(ignored, error) -> {
337+
if (localFuture.isCancelled()) {
338+
execution.cancel(true);
339+
}
340+
});
341+
future = localFuture;
334342
} else if (spec instanceof TaskRunSpec.RemoteTaskRunSpec remote) {
335343
future =
336344
CompletableFuture.supplyAsync(
@@ -370,7 +378,7 @@ private String runLocalSupplier(
370378
String sessionId,
371379
String taskId,
372380
String subAgentId,
373-
Supplier<String> taskExecution) {
381+
FutureTask<String> execution) {
374382
Optional<TaskRecord> latest =
375383
workspaceManager.readTaskRecord(rc, parentAgentId, sessionId, taskId);
376384
if (latest.isPresent() && latest.get().isCancelRequested()) {
@@ -380,7 +388,18 @@ private String runLocalSupplier(
380388

381389
updateStatus(rc, sessionId, taskId, TaskStatus.RUNNING, null, null);
382390
try {
383-
String result = taskExecution.get();
391+
// Cancelling the task interrupts this thread only while the execution itself runs,
392+
// never during the record updates around it.
393+
execution.run();
394+
if (execution.isCancelled()) {
395+
// Consume the interrupt that stopped the execution so it does not leak into the
396+
// record update below. As with a cancellation seen after the run, the task
397+
// neither fails nor wakes its parent.
398+
Thread.interrupted();
399+
markCancelled(rc, sessionId, taskId);
400+
return null;
401+
}
402+
String result = resultOf(execution);
384403
Optional<TaskRecord> afterRun =
385404
workspaceManager.readTaskRecord(rc, parentAgentId, sessionId, taskId);
386405
if (afterRun.isPresent() && afterRun.get().isCancelRequested()) {
@@ -400,6 +419,17 @@ private String runLocalSupplier(
400419
}
401420
}
402421

422+
/** Returns the result of a finished execution, rethrowing what its supplier threw. */
423+
private static String resultOf(FutureTask<String> execution) throws Exception {
424+
try {
425+
return execution.get();
426+
} catch (ExecutionException e) {
427+
if (e.getCause() instanceof Exception failure) throw failure;
428+
if (e.getCause() instanceof Error error) throw error;
429+
throw e;
430+
}
431+
}
432+
403433
private String runRemoteTask(
404434
RuntimeContext rc,
405435
String sessionId,

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/AgentSpawnTool.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1647,6 +1647,14 @@ private void handleExecError(
16471647
String taskId = "task_" + UUID.randomUUID();
16481648
String parentSessionId = runtimeContext != null ? runtimeContext.getSessionId() : null;
16491649
CompletableFuture<String> textFuture = bridge.thenApply(AgentSpawnTool::textOf);
1650+
// Cancelling the promoted task must stop the child: disposing its subscription runs
1651+
// doFinally(CANCEL), which interrupts the agent and releases the lease.
1652+
textFuture.whenComplete(
1653+
(ignored, error) -> {
1654+
if (textFuture.isCancelled()) {
1655+
innerSub.dispose();
1656+
}
1657+
});
16501658
taskRepository.putTask(
16511659
runtimeContext,
16521660
taskId,

‎agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,17 @@
3838
import java.util.Map;
3939
import java.util.Optional;
4040
import java.util.concurrent.CountDownLatch;
41+
import java.util.concurrent.ExecutorService;
42+
import java.util.concurrent.Executors;
43+
import java.util.concurrent.TimeUnit;
4144
import java.util.concurrent.atomic.AtomicBoolean;
4245
import java.util.concurrent.atomic.AtomicInteger;
4346
import org.junit.jupiter.api.AfterEach;
4447
import org.junit.jupiter.api.BeforeEach;
4548
import org.junit.jupiter.api.DisplayName;
4649
import org.junit.jupiter.api.Test;
4750
import org.junit.jupiter.api.io.TempDir;
51+
import reactor.core.publisher.Mono;
4852

4953
/**
5054
* Tests for {@link WorkspaceTaskRepository}:
@@ -311,6 +315,93 @@ void cancelTask_writesCancelRequestedToWorkspace() throws Exception {
311315
release.countDown();
312316
}
313317

318+
@Test
319+
@DisplayName("cancelTask stops a running local execution instead of only recording CANCELLED")
320+
void cancelTask_stopsRunningLocalExecution() throws Exception {
321+
String session = "sess-cancel-running";
322+
String taskId = "task-cancel-running";
323+
ExecutorService executor = Executors.newSingleThreadExecutor();
324+
WorkspaceTaskRepository repository =
325+
WorkspaceTaskRepository.forTests(workspaceManager, "test-agent", executor);
326+
AtomicInteger completionCallbacks = new AtomicInteger();
327+
repository.setCompletionCallback(
328+
(rc, id, agentId, sessionId, result) -> completionCallbacks.incrementAndGet());
329+
CountDownLatch subscribed = new CountDownLatch(1);
330+
CountDownLatch executionCancelled = new CountDownLatch(1);
331+
try {
332+
// Same shape as a background subagent: the supplier blocks on the child's Mono.
333+
repository.putTask(
334+
RuntimeContext.empty(),
335+
taskId,
336+
"agent-blocked",
337+
session,
338+
new TaskRunSpec.LocalTaskRunSpec(
339+
() ->
340+
Mono.<String>never()
341+
.doOnSubscribe(s -> subscribed.countDown())
342+
.doOnCancel(executionCancelled::countDown)
343+
.block()));
344+
assertTrue(subscribed.await(5, TimeUnit.SECONDS));
345+
346+
assertTrue(repository.cancelTask(RuntimeContext.empty(), session, taskId));
347+
348+
assertTrue(
349+
executionCancelled.await(5, TimeUnit.SECONDS),
350+
"cancelTask must stop the running execution");
351+
executor.shutdown();
352+
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
353+
TaskRecord record =
354+
workspaceManager
355+
.readTaskRecord(RuntimeContext.empty(), "test-agent", session, taskId)
356+
.orElseThrow();
357+
assertEquals(TaskStatus.CANCELLED, record.getStatus());
358+
assertNull(record.getErrorMessage());
359+
assertEquals(0, completionCallbacks.get(), "a cancelled task must not wake its parent");
360+
} finally {
361+
executor.shutdownNow();
362+
}
363+
}
364+
365+
@Test
366+
@DisplayName("an interrupted local execution still records its own cancellation")
367+
void cancellingLocalTaskHandle_recordsCancellationAfterInterrupt() throws Exception {
368+
String session = "sess-cancel-handle";
369+
String taskId = "task-cancel-handle";
370+
ExecutorService executor = Executors.newSingleThreadExecutor();
371+
WorkspaceTaskRepository repository =
372+
WorkspaceTaskRepository.forTests(workspaceManager, "test-agent", executor);
373+
CountDownLatch subscribed = new CountDownLatch(1);
374+
try {
375+
BackgroundTask task =
376+
repository.putTask(
377+
RuntimeContext.empty(),
378+
taskId,
379+
"agent-blocked",
380+
session,
381+
new TaskRunSpec.LocalTaskRunSpec(
382+
() ->
383+
Mono.<String>never()
384+
.doOnSubscribe(s -> subscribed.countDown())
385+
.block()));
386+
assertTrue(subscribed.await(5, TimeUnit.SECONDS));
387+
388+
// Cancelling the handle persists nothing, so the stopped worker must record
389+
// CANCELLED itself instead of letting the record stay RUNNING.
390+
task.cancel(true);
391+
392+
executor.shutdown();
393+
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
394+
assertEquals(
395+
TaskStatus.CANCELLED,
396+
workspaceManager
397+
.readTaskRecord(RuntimeContext.empty(), "test-agent", session, taskId)
398+
.orElseThrow()
399+
.getStatus());
400+
} finally {
401+
executor.shutdownNow();
402+
}
403+
}
404+
314405
// ------------------------------------------------------------------
315406
// Compaction simulation: task_list from workspace after clear
316407
// ------------------------------------------------------------------

‎agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnToolLifecycleTest.java‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@
4343
import io.agentscope.harness.agent.subagent.task.TaskRepository;
4444
import io.agentscope.harness.agent.subagent.task.TaskRunSpec;
4545
import io.agentscope.harness.agent.subagent.task.TaskStatus;
46+
import io.agentscope.harness.agent.subagent.task.WorkspaceTaskRepository;
47+
import io.agentscope.harness.agent.workspace.WorkspaceManager;
48+
import java.nio.file.Path;
4649
import java.time.Duration;
4750
import java.util.ArrayList;
4851
import java.util.Collection;
@@ -60,6 +63,7 @@
6063
import java.util.concurrent.atomic.AtomicInteger;
6164
import org.junit.jupiter.api.Test;
6265
import org.junit.jupiter.api.Timeout;
66+
import org.junit.jupiter.api.io.TempDir;
6367
import reactor.core.publisher.Mono;
6468

6569
class AgentSpawnToolLifecycleTest {
@@ -610,6 +614,73 @@ void timeoutPromotedSpawnRemainsBusyUntilOriginalBridgeIsTerminal() throws Excep
610614
}
611615
}
612616

617+
@Test
618+
@Timeout(20)
619+
void cancellingRunningBackgroundSpawnStopsTheChild(@TempDir Path workspace) throws Exception {
620+
assertTaskCancellationStopsChild(workspace, "background-cancel-parent", 0, "accepted");
621+
}
622+
623+
@Test
624+
@Timeout(20)
625+
void cancellingTimeoutPromotedSpawnStopsTheChild(@TempDir Path workspace) throws Exception {
626+
assertTaskCancellationStopsChild(
627+
workspace, "promoted-cancel-parent", 1, "timeout_promoted");
628+
}
629+
630+
/**
631+
* Spawns a child that never finishes on its own, cancels its background task through the real
632+
* {@link WorkspaceTaskRepository}, and requires the child's execution to be cancelled.
633+
*/
634+
private static void assertTaskCancellationStopsChild(
635+
Path workspace, String parentSessionId, int timeoutSeconds, String expectedStatus)
636+
throws Exception {
637+
CountDownLatch entered = new CountDownLatch(1);
638+
CountDownLatch childCancelled = new CountDownLatch(1);
639+
DefaultAgentManager manager =
640+
manager(
641+
rc ->
642+
closeableAgent(
643+
"worker",
644+
new AtomicInteger(),
645+
Mono.<Msg>never()
646+
.doOnSubscribe(s -> entered.countDown())
647+
.doOnCancel(childCancelled::countDown)),
648+
false);
649+
ExecutorService executor = Executors.newCachedThreadPool();
650+
WorkspaceTaskRepository repository =
651+
WorkspaceTaskRepository.forTests(
652+
new WorkspaceManager(workspace), "parent", executor);
653+
try {
654+
AgentSpawnTool tool = new AgentSpawnTool(manager, repository, 0);
655+
RuntimeContext context = context("owner", parentSessionId);
656+
657+
String spawn =
658+
textOf(
659+
tool.agentSpawn(
660+
context,
661+
context.getAgentState(),
662+
"worker",
663+
"never-ending task",
664+
false,
665+
null,
666+
timeoutSeconds,
667+
null)
668+
.block(BLOCK_TIMEOUT));
669+
assertTrue(spawn.contains("status: " + expectedStatus), spawn);
670+
assertTrue(entered.await(10, TimeUnit.SECONDS));
671+
672+
assertTrue(
673+
repository.cancelTask(
674+
context, parentSessionId, valueAfter(spawn, "task_id: ")));
675+
676+
assertTrue(
677+
childCancelled.await(10, TimeUnit.SECONDS),
678+
"cancelling the background task must stop the running child");
679+
} finally {
680+
executor.shutdownNow();
681+
}
682+
}
683+
613684
@Test
614685
@Timeout(20)
615686
void runningAsynchronousSpawnIsBusyUntilTerminal() throws Exception {

0 commit comments

Comments
 (0)