Repository navigation
feat: add run cancellation and abort support - #1983
Open
nvsaigokul-sudo wants to merge 1 commit into
Open
nvsaigokul-sudo wants to merge 1 commit into
nvsaigokul-sudo wants to merge 1 commit into
Conversation
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/ResponseProcessorexecution, 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
CancellationTokenandCancellationTokenSourcewhile preserving existing RxJava stream disposal and transport cleanup semantics:com.google.adk.agents):@FunctionalInterface CancellationToken(isCancellationRequested(), defaultCompletable onCancellation(), andCancellationToken.none()singleton) andAutoCloseableCancellationTokenSource(token(), idempotent thread-safecancel(),close(),isCancellationRequested()).RunConfig&InvocationContextIntegration:RunConfig.cancellationToken()defaulting toCancellationToken.none(), preserved acrossRunConfig.builder(RunConfig)andtoBuilder(), and exposedcancellationToken()/isCancellationRequested()helpers onInvocationContext.Runner.runAsync(includinginvocationIdresume),runAsyncImpl,runUserTurn,runAgentForUserEvent,resumeCore,runResumedAgent,runLive, andrunLiveImplusing.toMaybe().takeUntil(token.onCancellation().toFlowable()).flatMapPublisher(...)so in-flight setup disposes cleanly without throwingCancellationException.Runner.serializePerSessionso 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.executeAgentPipelineandrunLiveWithPluginCallbacks: cancellation beforebeforeRunfinishes skipsafterRunCallbackandcompactEvents; cancellation after run start invokesafterRunCallbackonce for cleanup.onRunErrorCallback,onModelErrorCallback, oronToolErrorCallbackwhile leaving genuine non-cancelled execution errors unchanged.LoopAgentviarepeatUntil), parallel fan-out (ParallelAgent), resumable paths (LlmAgent,SequentialAgent,LoopAgent,ParallelAgent) so cancelled resumable runs do not emitendOfAgent, andNodeRunner.runRoot(disposingrunRootNodecleanly on cancel and draining the event queue).llm.generateContent(...), asyncRequestProcessor/ResponseProcessor,BaseLlmFlowmodel callbacks,BaseAgentcallbacks (guardingswitchIfEmptyagainst post-cancel state-delta events),BaseLlmFlow.followTransfer(beforePersistBarrier.awaitPersistedand target invocation), and asyncFunctionstoolSingles / callbacks (propagating cancellation to nestedAgentToolinvocations while preservingFunctionResponseevents for tools that already completed)..takeUntil(...)onBaseLlmFlow.runLivereceive stream and shared an idempotentcloseConnection/closeConnectionWithErrorguard (AtomicBoolean) acrossrunLiveandstartLiveSendLoopso liveLlmConnectioninstances and send loops close cleanly at most once.Cooperative Cancellation Limitations
toolContext.invocationContext().isCancellationRequested()(or execute asynchronously via RxJavaSingle/Maybeso subscription disposal cancels it).beforeAgentCallbackmutatescallbackContext.state()in memory before cancellation fires, that in-memorysession.state()mutation precedes event generation, though emission and persistence of the callback state-deltaEventare suppressed on cancellation.Testing Plan
Unit Tests:
none(), idempotency,close(), post-cancel subscriptions, and multi-threaded cancellation.toBuilder()propagation.RequestProcessor/ResponseProcessorand model callback disposal, post-cancelonModelErrorCallbacksuppression, and single-closerunLivecancellation.PARALLEL_SUBSCRIBEpartial completion + cancellation.beforeRun/onUserMessage/beforeAgentasync disposal,afterRunonce on repeated cancel, multi-step persistence preservation,SequentialAgent/LoopAgent/ParallelAgent/AgentTool/transfer/workflowNodeRunnercancellation, resumable &invocationIdresume withoutendOfAgent, live streaming tool disposal (STREAMING_TOOL_DISPOSED), concurrent cancel/completion race, and queued session serialization cancellation ordering.Executed Commands & Results:
corerelease 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).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→coresucceeded;devran 277 tests with 0 failures and 1 Windows environment error in unrelatedCompiledAgentLoaderTest.isDirWithinSourceRoot_confinementOn_blocksSymlinkEscape:65(A required privilege is not held by the clientcreating a symlink);a2awas skipped in that reactor run due todevstopping first.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 code0and no output.Checklist