Skip to content

feat: add run cancellation and abort support - #1983

Open
nvsaigokul-sudo wants to merge 1 commit into
google:mainfrom
nvsaigokul-sudo:feat/run-cancellation-abort-support
Open

nvsaigokul-sudo wants to merge 1 commit into
google:mainfrom
nvsaigokul-sudo:feat/run-cancellation-abort-support

Conversation

@nvsaigokul-sudo

Copy link
Copy Markdown

Closes #1341

Link to Issue or Description of Change

Problem:
ADK Java lacked a public, thread-safe, cooperative cancellation API (RunConfig / Runner) to abort an active agent invocation across lifecycle stages (pending session loads, onUserMessage / beforeRun / beforeAgent / afterAgent / model / tool callbacks, RequestProcessor / ResponseProcessor execution, LLM streaming, async tool execution, sub-agent transfers, composite agent loops/fan-out, workflow nodes, session serialization queues, and bidirectional live connections) without losing previously persisted events or misreporting cancellation as an execution error.

Solution:
Introduces cooperative, idempotent, thread-safe run cancellation via CancellationToken and CancellationTokenSource while preserving existing RxJava stream disposal and transport cleanup semantics:

  • Public Cancellation API (com.google.adk.agents):
    • Added @FunctionalInterface CancellationToken (isCancellationRequested(), default Completable onCancellation(), and CancellationToken.none() singleton) and AutoCloseable CancellationTokenSource (token(), idempotent thread-safe cancel(), close(), isCancellationRequested()).
  • RunConfig & InvocationContext Integration:
    • Added non-null RunConfig.cancellationToken() defaulting to CancellationToken.none(), preserved across RunConfig.builder(RunConfig) and toBuilder(), and exposed cancellationToken() / isCancellationRequested() helpers on InvocationContext.
  • Runner Lifecycle, Resumability & Session Queue Ordering:
    • Propagated cancellation through Runner.runAsync (including invocationId resume), runAsyncImpl, runUserTurn, runAgentForUserEvent, resumeCore, runResumedAgent, runLive, and runLiveImpl using .toMaybe().takeUntil(token.onCancellation().toFlowable()).flatMapPublisher(...) so in-flight setup disposes cleanly without throwing CancellationException.
    • Updated Runner.serializePerSession so a queued run cancelled while waiting behind an active run exits immediately without disturbing the active run while still keeping subsequent queued runs ordered behind the active run's completion.
    • Preserved ADK callback semantics in executeAgentPipeline and runLiveWithPluginCallbacks: cancellation before beforeRun finishes skips afterRunCallback and compactEvents; cancellation after run start invokes afterRunCallback once for cleanup.
    • Prevented post-cancellation errors from triggering onRunErrorCallback, onModelErrorCallback, or onToolErrorCallback while leaving genuine non-cancelled execution errors unchanged.
  • Composite Agents & Workflow Nodes:
    • Guarded sub-agent scheduling, iteration (LoopAgent via repeatUntil), parallel fan-out (ParallelAgent), resumable paths (LlmAgent, SequentialAgent, LoopAgent, ParallelAgent) so cancelled resumable runs do not emit endOfAgent, and NodeRunner.runRoot (disposing runRootNode cleanly on cancel and draining the event queue).
  • LLM Streaming, Async Tools, Processors & Callbacks:
    • Wrapped active llm.generateContent(...), async RequestProcessor / ResponseProcessor, BaseLlmFlow model callbacks, BaseAgent callbacks (guarding switchIfEmpty against post-cancel state-delta events), BaseLlmFlow.followTransfer (before PersistBarrier.awaitPersisted and target invocation), and async Functions tool Singles / callbacks (propagating cancellation to nested AgentTool invocations while preserving FunctionResponse events for tools that already completed).
  • Live Connection & Resource Cleanup:
    • Added .takeUntil(...) on BaseLlmFlow.runLive receive stream and shared an idempotent closeConnection / closeConnectionWithError guard (AtomicBoolean) across runLive and startLiveSendLoop so live LlmConnection instances and send loops close cleanly at most once.

Cooperative Cancellation Limitations

  • Arbitrary synchronous blocking Java code inside a custom tool or callback cannot be forcibly terminated by RxJava disposal alone; blocking tool/callback code is expected to poll toolContext.invocationContext().isCancellationRequested() (or execute asynchronously via RxJava Single/Maybe so subscription disposal cancels it).
  • If an async beforeAgentCallback mutates callbackContext.state() in memory before cancellation fires, that in-memory session.state() mutation precedes event generation, though emission and persistence of the callback state-delta Event are suppressed on cancellation.

Testing Plan

Unit Tests:

  • Added CancellationTokenSourceTest.java (5 tests) covering none(), idempotency, close(), post-cancel subscriptions, and multi-threaded cancellation.
  • Updated RunConfigTest.java (12 tests total) for default token and copy/toBuilder() propagation.
  • Updated BaseLlmFlowCancelTest.java (23 tests total) for mid-stream SSE cancellation, step-boundary cancellation, async RequestProcessor/ResponseProcessor and model callback disposal, post-cancel onModelErrorCallback suppression, and single-close runLive cancellation.
  • Updated FunctionsTest.java (39 tests total) for async tool disposal, sequential skip, and parallel / PARALLEL_SUBSCRIBE partial completion + cancellation.
  • Added RunnerCancellationTest.java (20 tests) covering pre-start, beforeRun/onUserMessage/beforeAgent async disposal, afterRun once on repeated cancel, multi-step persistence preservation, SequentialAgent/LoopAgent/ParallelAgent/AgentTool/transfer/workflow NodeRunner cancellation, resumable & invocationId resume without endOfAgent, live streaming tool disposal (STREAMING_TOOL_DISPOSED), concurrent cancel/completion race, and queued session serialization cancellation ordering.

Executed Commands & Results:

  • Full core release build and tests (run immediately prior to the final 3 line-wrapping formatting edits):
    • mvn -pl core -Prelease clean package → BUILD SUCCESS (default-test: 5010 run, 0 failed, 0 errors, 35 pre-existing skipped; basic: 5010 run, 0 failed, 0 errors, 35 pre-existing skipped; vertex-ai-rag-retrieval: 3 run, 0 failed, 0 errors; apigee-llm: 33 run, 0 failed, 0 errors, 1 pre-existing skipped; apigee-llm-vertex-ai: 2 run; apigee-llm-enterprise: 2 run; apigee-llm-proxy-url: 1 run; gemini-tracking-headers: 2 run — 0 failures/errors across all executions).
  • Downstream modules (run prior to the final 3 line-wrapping edits):
    • mvn -pl dev,a2a -am test-compile → BUILD SUCCESS.
    • mvn -pl a2a -am test "-Dtest=com.google.adk.a2a.**" "-Dsurefire.failIfNoSpecifiedTests=false" → BUILD SUCCESS (519 run, 0 failures, 0 errors, 0 skipped).
    • mvn -pl dev,a2a -am test → core succeeded; dev ran 277 tests with 0 failures and 1 Windows environment error in unrelated CompiledAgentLoaderTest.isDirWithinSourceRoot_confinementOn_blocksSymlinkEscape:65 (A required privilege is not held by the client creating a symlink); a2a was skipped in that reactor run due to dev stopping first.
  • Post-edit targeted test verification (run after the final 3 line-wrapping edits):
    • mvn -pl core "-Dtest=CancellationTokenSourceTest,RunConfigTest,BaseLlmFlowCancelTest,FunctionsTest,RunnerCancellationTest,RootAgentNodeTest" test -DfailIfNoTests=false → BUILD SUCCESS (default-test & basic: 154 run, 0 failed, 0 errors, 0 skipped; profile surefire executions: 3 + 33 [1 pre-existing skipped] + 2 + 2 + 1 + 2, 0 failures/errors).
  • git diff --check & git diff --cached --check: exited with code 0 and no output.

Checklist

  • I have read the CONTRIBUTING.md document.
  • My pull request contains a single commit.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • Any dependent changes have been merged and published in downstream modules.

@hemasekhar-p hemasekhar-p self-assigned this Dec 3, 2026
@hemasekhar-p

Copy link
Copy Markdown
Contributor

Hi @nvsaigokul-sudo, We greatly appreciate your contribution and the effort you put into this pull request. It is currently under review by our team. We will notify you if any additional details are needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Run Cancellation / Abort Support for Java ADK

2 participants