Python: .NET: [Bug]: background agent wait ignores caller cancellation
Description
BackgroundAgentsProvider's background_agents_wait_for_first_completion tool does not honor the CancellationToken passed to AIFunction.InvokeAsync. A parent agent can start a long-running child, enter this tool, and then have its own run cancelled while the tool remains pending. The default wait timeout is five minutes.
The factory delegate accepts only taskIds (BackgroundAgentsProvider.cs:657). It awaits Task.WhenAny of child completion and Task.Delay backed by a new, unrelated token source (lines 695–705). Cancelling the caller completes neither side of that race. BackgroundAgentsProviderOptions.DefaultWaitTimeout is five minutes (options).
To reproduce:
- Start a background task whose agent run remains pending.
- Invoke
background_agents_wait_for_first_completionfor its task ID with a cancellable invocation token. - Cancel that token while the wait is pending.
Actual: The wait stays pending. A caller cannot promptly stop its own run; with the default configuration it may wait up to five minutes.
I reproduced this on an upstream main checkout at c804f32c9 with only a cancellation regression test added. The single test failed 1/1: it expected OperationCanceledException, but its five-second observation bound threw TimeoutException: The operation has timed out. That exception came from the test's bound; the tool invocation itself was still pending.
Expected: The wait promptly throws OperationCanceledException for the caller's token. The background task remains running and can be observed or awaited by a later invocation. A normal timeout still returns the existing retry-oriented message without cancelling the task.
Code Sample
After starting task 1 with a background agent whose run is still pending:
using var cancellation = new CancellationTokenSource();
Task<object?> wait = waitForFirst.InvokeAsync(
new AIFunctionArguments { ["taskIds"] = new List<int> { 1 } },
cancellation.Token).AsTask();
cancellation.Cancel();
await wait.WaitAsync(TimeSpan.FromSeconds(5)); // Before a fix, this observation times out.Error Messages / Stack Traces
The tool itself emits no cancellation error. The bounded observation throws TimeoutException after five seconds; the tool invocation remains pending.
Package Versions
Microsoft.Agents.AI source checkout c804f32c9 (VersionPrefix 1.22.0); this reproduction does not use a published package build.
.NET Version
.NET 10.0 (net10.0 test target; SDK 10.0.401).
Additional Context
#7454 reported an unbounded wait in the Python implementation. #7911 added a configurable timeout and retry message to the .NET tool. The open #8760 concerns Python background tasks moving between host processes. None addresses cancellation of this .NET tool invocation before its timeout expires.
I am implementing this fix in #8805.
Source: microsoft/agent-framework