Skip to content

Fix prefetcher shutdown-cancellation test race on the outer token - #21438

Closed
David Fowler (davidfowl) wants to merge 1 commit into
mainfrom
agent/fix-prefetcher-cancellation-race
Closed

David Fowler (davidfowl) wants to merge 1 commit into
mainfrom
agent/fix-prefetcher-cancellation-race

Conversation

@davidfowl

Copy link
Copy Markdown
Collaborator

Description

Fixes the intermittent 30s timeout in NuGetPackagePrefetcherTests.PrefetchingCancellationDueToShutdownLogsCleanMessage with a test-only change. The product code is unchanged.

Fixes #20507

Root cause

  • BackgroundService.StartAsync(stoppingCts.Token) links the service's stopping token to stoppingCts by registering on stoppingCts.Token.
  • The test's two callbacks then registered on the outer stoppingCts.Token through AsyncTestHelpers.WaitForCancellationAsync.
  • Cancellation callbacks run in reverse registration order (LIFO). So stoppingCts.Cancel() completes the callbacks' cancelled TaskCompletionSource (with RunContinuationsAsynchronously) before it cancels the prefetcher's linked token.
  • If the thread pool runs the continuation in that window, the OperationCanceledException reaches catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) while the filter is still false.
  • The generic catch then logs Debug: Non-fatal error while prefetching …. The expected Trace: … prefetching was cancelled … message never arrives, and Task.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 already true. The race exists only because the test fake waited on a different token.

Fix

The callbacks now wait on the CancellationToken the prefetcher passes to GetChannelsAsync / 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 and DefaultTimeout() 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:

    Run Job Failure
    39374723384 118470779619 30s timeout at line 175
    40007279567 120599232490 30s timeout at line 175
    40023434009 120654469417 30s timeout at line 175

    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.Token and holds Cancel() (bounded at 5s) until that branch's catch has logged. This deterministically reproduces the adverse ordering. Each run used the unchanged run-tests.yml with --filter-class '*.NuGetPackagePrefetcherTests'.

Run Branch Callbacks wait on Result
41027949574 before, e572a10e stoppingCts.Token (original) Failed (1 failed, 30 passed). Expected: "Trace: Template package prefetching was cancelled …", Actual: "Debug: Non-fatal error while prefetching template …"
41027952535 after, 3be71361 prefetcher's token (this PR) Passed (31 of 31)

A standalone console reproduction against Microsoft.Extensions.Hosting.Abstractions 10.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

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
    • No

🤖 Posted by AspireAgent (AI Agent)

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>
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21438

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21438"

@github-actions

Copy link
Copy Markdown
Contributor

Tests selector

1 / 100 PR test projects · 0 PR jobs, from 1 changed file.

Selected PR test projects (1 / 100)

Aspire.Cli.Tests

Selected PR jobs (0)

none


How these were chosen — grouped by what changed

🧪 tests/Aspire.Cli.Tests/NuGet/NuGetPackagePrefetcherTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

Job reasons

none


Selection computed for commit 6ba78bc.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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

Copy link
Copy Markdown
Collaborator Author

This conflict comes from #21599, which has merged into main with the same fix: both callbacks now wait on the token the prefetcher passes in instead of stoppingCts.Token. Resolving the conflict faithfully leaves this PR with no remaining diff, so I haven't pushed a merge. I suggest closing it as superseded by #21599.

🤖 Posted by AspireAgent (AI Agent)

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #21599 (same fix).

🤖 Posted by AspireAgent (AI Agent)

David Fowler (davidfowl) added a commit that referenced this pull request Nov 4, 2026
…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>
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.

[CI Failure] Flaky: NuGetPackagePrefetcherTests.PrefetchingCancellationDueToShutdownLogsCleanMessage times out after 30s

3 participants