diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java index fe40344ae7..b1eb16cb5a 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java @@ -33,8 +33,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; @@ -66,6 +68,7 @@ * persisted terminal state without hanging. *
  • Cancellation sets a {@link TaskRecord#isCancelRequested()} flag in workspace storage; * the originating node checks this flag before invoking the subagent for best-effort cancel. + * Cancelling on the originating node also interrupts a running local execution. *
  • Remote {@link TaskRunSpec.RemoteTaskRunSpec} tasks use a {@link RemoteSubagentTransport} * (Agent Protocol by default) and persist {@link TaskRecord#getRemoteBaseUrl()} for * cross-node resume. @@ -342,12 +345,27 @@ public BackgroundTask putTask( } }); } else if (spec instanceof TaskRunSpec.LocalTaskRunSpec local) { - future = + FutureTask execution = new FutureTask<>(() -> local.execution().get()); + CompletableFuture localFuture = CompletableFuture.supplyAsync( () -> runLocalSupplier( - capturedRc, sessionId, taskId, subAgentId, local), + capturedRc, + sessionId, + taskId, + subAgentId, + local, + execution), executor); + // CompletableFuture.cancel never interrupts the thread computing it, so cancel the + // execution too: cancelTask() must stop a running subagent, not only record CANCELLED. + localFuture.whenComplete( + (ignored, error) -> { + if (localFuture.isCancelled()) { + execution.cancel(true); + } + }); + future = localFuture; } else if (spec instanceof TaskRunSpec.RemoteTaskRunSpec remote) { future = CompletableFuture.supplyAsync( @@ -387,7 +405,8 @@ private String runLocalSupplier( String sessionId, String taskId, String subAgentId, - TaskRunSpec.LocalTaskRunSpec local) { + TaskRunSpec.LocalTaskRunSpec local, + FutureTask execution) { Optional latest = workspaceManager.readTaskRecord(rc, parentAgentId, sessionId, taskId); if (latest.isPresent() && latest.get().isCancelRequested()) { @@ -397,7 +416,18 @@ private String runLocalSupplier( updateStatus(rc, sessionId, taskId, TaskStatus.RUNNING, null, null); try { - String result = local.execution().get(); + // Cancelling the task interrupts this thread only while the execution itself runs, + // never during the record updates around it. + execution.run(); + if (execution.isCancelled()) { + // Consume the interrupt that stopped the execution so it does not leak into the + // record update below. As with a cancellation seen after the run, the task + // neither fails nor wakes its parent. + Thread.interrupted(); + markCancelled(rc, sessionId, taskId); + return null; + } + String result = resultOf(execution); Optional afterRun = workspaceManager.readTaskRecord(rc, parentAgentId, sessionId, taskId); if (afterRun.isPresent() && afterRun.get().isCancelRequested()) { @@ -419,6 +449,17 @@ private String runLocalSupplier( } } + /** Returns the result of a finished execution, rethrowing what its supplier threw. */ + private static String resultOf(FutureTask execution) throws Exception { + try { + return execution.get(); + } catch (ExecutionException e) { + if (e.getCause() instanceof Exception failure) throw failure; + if (e.getCause() instanceof Error error) throw error; + throw e; + } + } + private String runRemoteTask( RuntimeContext rc, String sessionId, diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/AgentSpawnTool.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/AgentSpawnTool.java index 39578b5900..159f321617 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/AgentSpawnTool.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/AgentSpawnTool.java @@ -1712,6 +1712,14 @@ private void handleExecError( String taskId = "task_" + UUID.randomUUID(); String parentSessionId = runtimeContext != null ? runtimeContext.getSessionId() : null; CompletableFuture textFuture = bridge.thenApply(AgentSpawnTool::textOf); + // Cancelling the promoted task must stop the child: disposing its subscription runs + // doFinally(CANCEL), which interrupts the agent and releases the lease. + textFuture.whenComplete( + (ignored, error) -> { + if (textFuture.isCancelled()) { + innerSub.dispose(); + } + }); submitTask( runtimeContext, taskId, diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 9014f1f5be..bb5c679fd3 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -45,6 +45,9 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -53,6 +56,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import reactor.core.publisher.Mono; /** * Tests for {@link WorkspaceTaskRepository}: @@ -319,6 +323,93 @@ void cancelTask_writesCancelRequestedToWorkspace() throws Exception { release.countDown(); } + @Test + @DisplayName("cancelTask stops a running local execution instead of only recording CANCELLED") + void cancelTask_stopsRunningLocalExecution() throws Exception { + String session = "sess-cancel-running"; + String taskId = "task-cancel-running"; + ExecutorService executor = Executors.newSingleThreadExecutor(); + WorkspaceTaskRepository repository = + WorkspaceTaskRepository.forTests(workspaceManager, "test-agent", executor); + AtomicInteger completionCallbacks = new AtomicInteger(); + repository.setCompletionCallback( + (rc, id, agentId, sessionId, result) -> completionCallbacks.incrementAndGet()); + CountDownLatch subscribed = new CountDownLatch(1); + CountDownLatch executionCancelled = new CountDownLatch(1); + try { + // Same shape as a background subagent: the supplier blocks on the child's Mono. + repository.putTask( + RuntimeContext.empty(), + taskId, + "agent-blocked", + session, + new TaskRunSpec.LocalTaskRunSpec( + () -> + Mono.never() + .doOnSubscribe(s -> subscribed.countDown()) + .doOnCancel(executionCancelled::countDown) + .block())); + assertTrue(subscribed.await(5, TimeUnit.SECONDS)); + + assertTrue(repository.cancelTask(RuntimeContext.empty(), session, taskId)); + + assertTrue( + executionCancelled.await(5, TimeUnit.SECONDS), + "cancelTask must stop the running execution"); + executor.shutdown(); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + TaskRecord record = + workspaceManager + .readTaskRecord(RuntimeContext.empty(), "test-agent", session, taskId) + .orElseThrow(); + assertEquals(TaskStatus.CANCELLED, record.getStatus()); + assertNull(record.getErrorMessage()); + assertEquals(0, completionCallbacks.get(), "a cancelled task must not wake its parent"); + } finally { + executor.shutdownNow(); + } + } + + @Test + @DisplayName("an interrupted local execution still records its own cancellation") + void cancellingLocalTaskHandle_recordsCancellationAfterInterrupt() throws Exception { + String session = "sess-cancel-handle"; + String taskId = "task-cancel-handle"; + ExecutorService executor = Executors.newSingleThreadExecutor(); + WorkspaceTaskRepository repository = + WorkspaceTaskRepository.forTests(workspaceManager, "test-agent", executor); + CountDownLatch subscribed = new CountDownLatch(1); + try { + BackgroundTask task = + repository.putTask( + RuntimeContext.empty(), + taskId, + "agent-blocked", + session, + new TaskRunSpec.LocalTaskRunSpec( + () -> + Mono.never() + .doOnSubscribe(s -> subscribed.countDown()) + .block())); + assertTrue(subscribed.await(5, TimeUnit.SECONDS)); + + // Cancelling the handle persists nothing, so the stopped worker must record + // CANCELLED itself instead of letting the record stay RUNNING. + task.cancel(true); + + executor.shutdown(); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + assertEquals( + TaskStatus.CANCELLED, + workspaceManager + .readTaskRecord(RuntimeContext.empty(), "test-agent", session, taskId) + .orElseThrow() + .getStatus()); + } finally { + executor.shutdownNow(); + } + } + // ------------------------------------------------------------------ // Compaction simulation: task_list from workspace after clear // ------------------------------------------------------------------ diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnToolLifecycleTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnToolLifecycleTest.java index 126d378866..ebdee289ab 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnToolLifecycleTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnToolLifecycleTest.java @@ -43,6 +43,9 @@ import io.agentscope.harness.agent.subagent.task.TaskRepository; import io.agentscope.harness.agent.subagent.task.TaskRunSpec; import io.agentscope.harness.agent.subagent.task.TaskStatus; +import io.agentscope.harness.agent.subagent.task.WorkspaceTaskRepository; +import io.agentscope.harness.agent.workspace.WorkspaceManager; +import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; @@ -60,6 +63,7 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; import reactor.core.publisher.Mono; class AgentSpawnToolLifecycleTest { @@ -610,6 +614,77 @@ void timeoutPromotedSpawnRemainsBusyUntilOriginalBridgeIsTerminal() throws Excep } } + @Test + @Timeout(20) + void cancellingRunningBackgroundSpawnStopsTheChild(@TempDir Path workspace) throws Exception { + assertTaskCancellationStopsChild(workspace, "background-cancel-parent", 0, "accepted"); + } + + @Test + @Timeout(20) + void cancellingTimeoutPromotedSpawnStopsTheChild(@TempDir Path workspace) throws Exception { + assertTaskCancellationStopsChild( + workspace, "promoted-cancel-parent", 1, "timeout_promoted"); + } + + /** + * Spawns a child that never finishes on its own, cancels its background task through the real + * {@link WorkspaceTaskRepository}, and requires the child's execution to be cancelled. + */ + private static void assertTaskCancellationStopsChild( + Path workspace, String parentSessionId, int timeoutSeconds, String expectedStatus) + throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch childCancelled = new CountDownLatch(1); + DefaultAgentManager manager = + manager( + rc -> + closeableAgent( + "worker", + new AtomicInteger(), + Mono.never() + .doOnSubscribe(s -> entered.countDown()) + .doOnCancel(childCancelled::countDown)), + false); + ExecutorService executor = Executors.newCachedThreadPool(); + WorkspaceTaskRepository repository = + WorkspaceTaskRepository.forTests( + new WorkspaceManager(workspace), "parent", executor); + try { + AgentSpawnTool tool = new AgentSpawnTool(manager, repository, 0); + RuntimeContext context = context("owner", parentSessionId); + + String spawn = + textOf( + tool.agentSpawn( + context, + context.getAgentState(), + "worker", + "never-ending task", + false, + null, + timeoutSeconds, + null) + .block(BLOCK_TIMEOUT)); + assertTrue(spawn.contains("status: " + expectedStatus), spawn); + assertTrue(entered.await(10, TimeUnit.SECONDS)); + + assertTrue( + repository.cancelTask( + context, parentSessionId, valueAfter(spawn, "task_id: "))); + + assertTrue( + childCancelled.await(10, TimeUnit.SECONDS), + "cancelling the background task must stop the running child"); + // The worker records the cancellation after the child stops. Wait for it, so the + // temporary workspace is not deleted while the record is still being written. + executor.shutdown(); + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + } + @Test @Timeout(20) void runningAsynchronousSpawnIsBusyUntilTerminal() throws Exception {