Repository navigation
Fix prefetcher shutdown-cancellation test race on the outer token - #21438
David Fowler (davidfowl) wants to merge 1 commit into
Conversation
The test's callbacks waited on the outer stoppingCts.Token. BackgroundService links its stopping token to that source during StartAsync, so the callbacks' later registrations run first when stoppingCts is cancelled. The asynchronously-continued OperationCanceledException could reach the prefetcher's 'when (stoppingToken.IsCancellationRequested)' filter before the linked token was cancelled, logging the non-fatal Debug message instead of the expected cancellation Trace message, and the test timed out after 30s. Waiting on the token the prefetcher passes in removes the ordering dependency. Assertions and timeouts are unchanged. Fixes #20507 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21438Or
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21438" |
Tests selector1 / 100 PR test projects · 0 PR jobs, from 1 changed file. Selected PR test projects (1 / 100)
Selected PR jobs (0)none How these were chosen — grouped by what changed🧪 Job reasonsnone Selection computed for commit |
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues block the test-only cancellation-token fix.
No open issues 🎉
What changed in this PR
Fixes the shutdown-cancellation test race behind #20507 by making the test callbacks wait on the prefetcher’s cancellation token. Production code is unchanged.
Changes:
- Updates both test callbacks to use the passed cancellation token instead of the outer token.
- Adds a comment explaining the cancellation-ordering race.
- Preserves existing synchronization, assertions, expected logs, and timeout.
| File | Description |
|---|---|
| tests/Aspire.Cli.Tests/NuGet/NuGetPackagePrefetcherTests.cs | Corrects cancellation-token usage in the shutdown test and documents the race. |
Review effort: Balanced
|
This conflict comes from #21599, which has merged into 🤖 Posted by AspireAgent (AI Agent) |
|
Closing as superseded by #21599 (same fix). 🤖 Posted by AspireAgent (AI Agent) |
…ction (#21519) ## Description Fixes the flaky `Cli.EndToEnd` test `TypeScriptCodegenValidationTests.UnAwaitedChainsCompileWithAutoResolvePromises`. The failure is a real product race in the polyglot AppHost server, not a test problem. ### Symptom On attempt 1 of run [41146506214](https://github.com/microsoft/aspire/actions/runs/41146506214) (PR #21504, job 124378846794), the test's AppHost failed with: ``` Flushing 4 pending promise(s). Consider awaiting fluent calls to avoid implicit flushing. ❌ Capability Error: Could not invoke 'run': A health check registration is missing. Check logs for more details. Code: INTERNAL_ERROR Capability: Aspire.Hosting/run ``` The test AppHost deliberately leaves `addPostgres`, `addDatabase` and `addContainer(...).withReference(db)` un-awaited before `addHealthCheck(...).build().run()`. ### Root cause #16110 set `jsonRpc.SynchronizationContext = null` in `JsonRpcServer` so that cross-connection calls don't deadlock. Before that change, StreamJsonRpc's default `NonConcurrentSynchronizationContext` serialized request handlers per connection. Now un-awaited guest calls such as `addPostgres`, `addContainer` and `addHealthCheck` run their exported methods at the same time on thread-pool threads. Those methods mutate non-thread-safe builder state: `IServiceCollection` (a `List<ServiceDescriptor>`) and the resource collection. A concurrent `List.Add` can drop an item: - If the `AddHealthChecks().AddNpgSql(...)` registration from `AddPostgres` is lost, `HealthCheckAnnotation` still references the key. `DistributedApplicationBuilder`'s `HealthCheckServiceOptions` validator then fails with "A health check registration is missing" when `run` starts. - If a resource add is lost, the resource silently disappears. The TS SDK's `flushPendingPromises` is not the problem. It awaits every un-awaited call before `build`. The calls themselves overlap on the server. ### Fix `CapabilityDispatcher` now has a per-connection `CapabilityInvocationGate` (the dispatcher is scoped per connection, like the old synchronization context): - The synchronous invocation of an exported method runs under the gate, so builder mutations from concurrent guest calls no longer overlap. - The gate is released when the invocation returns, including the synchronous prefix of async exports. It is also released when the invocation first calls a guest callback through `AtsCallbackProxyFactory`, because the guest may call back into the server before the callback completes. Re-entrant calls therefore cannot deadlock. The lease flows through `AsyncLocal`, so it is also released when the export offloads the callback to another thread (for example, `Task.Run(callback)`). - Exports that opt into `RunSyncOnBackgroundThread`, such as `run`, keep their existing ungated behavior. This matches how they bypassed the old synchronization context. - Cross-connection dispatch is unchanged. ## Evidence **Regression unit test, deterministic.** `InvokeAsync_ConcurrentCapabilityInvocations_DoNotOverlap` holds one invocation inside an export and then starts a second one. - On `main` it fails with `Assert.False() Failure — Expected: False, Actual: True`: the second invocation ran to completion while the first was still inside the export. - With this fix it passes. **Re-entry guard.** `InvokeAsync_CallbackFromSynchronousInvocation_CanReenterDispatcher` covers a synchronous export that blocks on a guest callback while the callback re-enters the dispatcher. It runs both inline and with the callback offloaded via `Task.Run`, and both pass without deadlocking. With a `[ThreadStatic]` lease, the offloaded case deadlocked (`TimeoutException`) until the lease moved to `AsyncLocal` after review. **Bounded stress on the real `Aspire.Hosting/addContainer` export** (temporary local test, not committed): 50 rounds × 32 concurrent un-awaited `addContainer` calls on one builder, through `CapabilityDispatcher`. | | Lost resources | Errors | |---|---|---| | `main` | 9 / 1600 | 0 | | This PR | 0 / 1600 | 0 | **E2E.** The flaky test itself, `Cli.EndToEnd-TypeScriptCodegenValidationTests`, exercises this path end to end in this PR's CI. On head ab6ec38 (CI run 41165837278, job 124435978766) it **passed** in 13m47s. After the AsyncLocal review fix, on head 17de5ac (CI run 41171583681, job 124453010234) it **passed** again, in 14m2s. **Failure rate:** attempt-1 `Cli.EndToEnd-TypeScriptCodegenValidationTests` jobs across the last 150 `ci.yml` runs (2026-10-30T10:39Z to 2026-10-31T03:47Z): | Outcome | Jobs | |---|---| | Completed | 63 | | Failed because of this test (run 41146506214, health check registration missing) | 1 (about 1.6%) | | Failed because of `RestoreGeneratesSdkFiles_WithConfiguredToolchain(pnpm)` (unrelated) | 1 | | Failed because of runner infrastructure (job died loading the Docker image, no logs) | 1 | The race is timing dependent, so it is rare in CI. It reproduces reliably under the stress run above. ## Validation - `Aspire.Hosting.RemoteHost.Tests` (full suite, local): 673 passed and 5 skipped. 15 failed, all `IntegrationHostProcessTests`, because their fixture build hits `NU1905` (NuGet audit can't reach nuget.org in this sandbox). Those failures are environmental and unrelated to this change. - New tests: fail before, pass after, as shown above. - CI on ab6ec38: all checks green. Attempt 1 lost three Windows VS Code extension E2E shards (coordinated-build, dynamic-debug-configuration, cli-path-rejection) to `The hosted runner lost communication with the server` after about 47 minutes. The same infrastructure failure, with the same shards and the same annotation, hit unrelated PRs (runs 41144696804, 41160826284). These shards exercise C# projects, not the polyglot RemoteHost. The automatic rerun (attempt 2) passed. - CI on 17de5ac (run 41171583681): attempt 1 failed only `Aspire.Cli.Tests` → `NuGetPackagePrefetcherTests.PrefetchingCancellationDueToShutdownLogsCleanMessage`, with a 30s timeout. This is known flake #20507 (fix in #21438). It's CLI NuGet prefetch code, which this PR doesn't touch. The automatic rerun (attempt 2) re-runs it once. ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - Did you add public API? - [x] No - Does the change make any security assumptions or guarantees? - [x] No **🤖 Posted by AspireAgent (AI Agent)** --------- Co-authored-by: davidfowl <95136+davidfowl@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Description
Fixes the intermittent 30s timeout in
NuGetPackagePrefetcherTests.PrefetchingCancellationDueToShutdownLogsCleanMessagewith a test-only change. The product code is unchanged.Fixes #20507
Root cause
BackgroundService.StartAsync(stoppingCts.Token)links the service's stopping token tostoppingCtsby registering onstoppingCts.Token.stoppingCts.TokenthroughAsyncTestHelpers.WaitForCancellationAsync.stoppingCts.Cancel()completes the callbacks' cancelledTaskCompletionSource(withRunContinuationsAsynchronously) before it cancels the prefetcher's linked token.OperationCanceledExceptionreachescatch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)while the filter is stillfalse.Debug: Non-fatal error while prefetching …. The expectedTrace: … prefetching was cancelled …message never arrives, andTask.WhenAll(templateTcs.Task, cliTcs.Task).DefaultTimeout()times out after 30s.In production the exception comes from the prefetcher's own
stoppingToken, so the filter is alreadytrue. The race exists only because the test fake waited on a different token.Fix
The callbacks now wait on the
CancellationTokenthe prefetcher passes toGetChannelsAsync/CheckForCliUpdatesAsync. That token is the linked stopping token, so it is cancelled before the exception is thrown. The barrier, the cancellation trigger, both expected log messages, the assertions andDefaultTimeout()are all unchanged. No sleeps, retries or timeout changes were added.Evidence
Failure rate: I scanned main CI attempt-1 runs from 2026-10-16 to 2026-10-30 (120 runs enumerated, attempt-1 jobs collected for 99 of them).
The
Cli (ubuntu-latest)job ran in 98 runs: 94 succeeded and 4 failed.3 of the 4 failures are this test:
The 4th failure is an unrelated TrayWatch test.
The test and the prefetcher catch blocks had not changed in this region since August, so the same source also passed in the other runs.
Native Ubuntu before/after qualification: Each qualification-only branch adds a forced-ordering test. Inside each callback, the test registers on
stoppingCts.Tokenand holdsCancel()(bounded at 5s) until that branch's catch has logged. This deterministically reproduces the adverse ordering. Each run used the unchangedrun-tests.ymlwith--filter-class '*.NuGetPackagePrefetcherTests'.e572a10estoppingCts.Token(original)Expected: "Trace: Template package prefetching was cancelled …",Actual: "Debug: Non-fatal error while prefetching template …"3be71361A standalone console reproduction against
Microsoft.Extensions.Hosting.Abstractions10.0.0 with the same ordering gave the same split: 20 of 20 non-fatal Debug with the outer token, and 20 of 20 clean cancellation with the passed token.Checklist
🤖 Posted by AspireAgent (AI Agent)