Skip to content

Fix unobserved task exception in WithCancellationAsync and unignore flaky tests - #9427

Merged
Amaury Levé (Evangelink) merged 3 commits into
mainfrom
evangelink-fix-taskextensions-flaky
Jun 25, 2026
Merged

Amaury Levé (Evangelink) merged 3 commits into
mainfrom
evangelink-fix-taskextensions-flaky

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Summary

Re-enables the two ignored TaskExtensionsTests (issue #6907) by fixing the underlying product bug that made them flaky.

Root cause

In both WithCancellationAsync overloads, the "observe the exception" continuation was scheduled with:

_ = task.ContinueWith(observeAction, cancellationToken);

Passing cancellationToken to ContinueWith cancels the continuation itself once the token fires. So when the token cancels before the awaited task faults, the observe continuation never runs, the task's exception is never observed, and it leaks as an UnobservedTaskException that surfaces during GC — flakily crashing unrelated tests. The sibling TimeoutAfterAsync in the same file already schedules its observe continuation without the token.

Fix

Schedule the observe continuation on TaskScheduler.Default instead of passing the cancellation token, so the exception is always observed. The returned task's cancellation semantics are unchanged.

Verification

A focused repro driving the actual product WithCancellationAsync<T> (cancel at 50ms, inner task faults at 250ms, 200 iterations):

UnobservedTaskException cancellations observed
before fix 200 / 200 200 / 200
after fix 0 / 200 200 / 200

Both unignored tests pass reliably — 15× consecutive on net8.0 and 8× on net462, all green.

No public API or user-facing behavior change (internal helper). No changelog entry added since entries here reference merged PR numbers; happy to add one if maintainers prefer.

Closes #6907.

Co-authored-by: Copilot [email protected]

…ests

The "observe the exception" continuation in both WithCancellationAsync
overloads was scheduled via ContinueWith(observeAction, cancellationToken).
Passing the cancellation token cancels the *continuation itself* once the
token fires, so when the awaited task later faults, its exception is never
observed. This leaks an unobserved TaskException that surfaces during GC and
flakily crashes unrelated tests (issue #6907), which is why
CancellationAsync_ObserveException_Succeeds and
CancellationAsyncWithReturnValue_ObserveException_Succeeds were ignored.

Schedule the observe continuation on TaskScheduler.Default instead (matching
TimeoutAfterAsync in the same file) so the exception is always observed. A
focused repro that drives the actual product method showed 200/200 iterations
leaking before the fix and 0/200 after, while cancellation is still observed
in every iteration. Re-enabled both tests; they pass reliably (verified across
many consecutive runs on net8.0 and net462).

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings June 25, 2026 07:52

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.

Pull request overview

This PR fixes a flakiness source in Microsoft.Testing.Platform’s internal TaskExtensions.WithCancellationAsync helpers by ensuring faulted task exceptions are always observed, and then re-enables the two unit tests that were previously ignored due to the resulting UnobservedTaskException crashes.

Changes:

  • Update both WithCancellationAsync overloads to schedule the “observe exception” continuation without using the cancellation token (using TaskScheduler.Default instead).
  • Re-enable the two previously ignored TaskExtensionsTests covering exception observation under cancellation.
Show a summary per file
File Description
src/Platform/Microsoft.Testing.Platform/Helpers/TaskExtensions.cs Fixes the unobserved-exception bug by preventing the observe-continuation from being canceled.
test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs Removes [Ignore] on the two flaky tests now that the underlying product issue is addressed.

Copilot's findings

  • Files reviewed: 2/2 changed files
  • Comments generated: 0

@Evangelink

This comment has been minimized.

@Evangelink

Copy link
Copy Markdown
Member Author

Note

🤖 Automated review by GitHub Copilot. Posted via a maintainer's GitHub token, so it appears under their account — the account owner did not write or approve this content personally. Generated by the Expert Code Review workflow. To request a follow-up action, reply by tagging @copilot directly.

Code-Review Findings (not tied to diff lines)

🔴 Finding 1 — TimeoutAfterAsync(Task, TimeSpan, CancellationToken) has the same unfixed bug (MAJOR)

File: src/Platform/Microsoft.Testing.Platform/Helpers/TaskExtensions.cs

The PR description states:

"The sibling TimeoutAfterAsync in the same file already schedules its observe continuation without the token."

This is only half-true. The no-token overload is fine, but the with-token overload still passes token to ContinueWith:

// TimeoutAfterAsync(Task, TimeSpan, CancellationToken token, ...)
_ = task.ContinueWith(
    async task => { try { await task.ConfigureAwait(false); } catch (Exception) { } },
    token);   // ← identical bug: continuation silently dropped when token fires

Concrete failing scenario: A caller passes a timeout of 100ms and a token that is independently cancelled at 50ms. The token fires at 50ms; WaitAsync throws OperationCanceledException. The inner task continues running and faults at 200ms. The ContinueWith continuation was already cancelled by token at 50ms, so it never runs, the exception is never observed, and an UnobservedTaskException escapes to the GC finaliser thread — exactly the race this PR is fixing in WithCancellationAsync.

Recommendation: Apply the identical one-line fix:

// was: token
TaskScheduler.Default

🟡 Finding 2 — waitException.WaitOne() without timeout (MODERATE)

File: test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/TaskExtensionsTests.cs

Both re-enabled tests end with an unbounded waitException.WaitOne(). The inner task is:

await Task.Delay(TimeSpan.FromSeconds(5), TestContext.CancellationToken);
waitException.Set();
throw new InvalidOperationException();

Concrete failing scenario: CI runner approaches its test-level timeout and cancels TestContext.CancellationToken. The Task.Delay throws OperationCanceledException, bypassing waitException.Set(). The test is now blocked on waitException.WaitOne() indefinitely — a hang rather than a clean failure, and harder to diagnose.

Recommendation:

Assert.IsTrue(
    waitException.WaitOne(TimeSpan.FromSeconds(30)),
    "Inner task did not reach the exception-throw point within the allotted time.");

A 30-second bound is generous enough that no correctly behaving machine would breach it, while still giving the test runner a clean failure message instead of a process-level hang.

@Evangelink Amaury Levé (Evangelink) left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note

🤖 Automated review by GitHub Copilot. Posted via a maintainer's GitHub token, so it appears under their account — the account owner did not write or approve this content personally. Generated by the Expert Code Review workflow. To request a follow-up action, reply by tagging @copilot directly.

Review Summary — PR #9427

The root-cause diagnosis is correct and the fix for WithCancellationAsync is sound. ContinueWith(action, cancellationToken) treats the token as a scheduling guard — the continuation is silently dropped when the token fires — while ContinueWith(action, TaskScheduler.Default) always runs it. The cancellation semantics visible to callers are unchanged. TaskScheduler.Default is available on every supported TFM (net462, netstandard2.0, net8.0, net9.0) with identical behaviour.

2 findings — see inline comment above.

# Dimension Result Severity
1 Algorithmic Correctness (WithCancellationAsync fix) ✅ LGTM —
2 Threading & Concurrency ✅ LGTM —
3 Cross-TFM Compatibility ✅ LGTM —
4 Resource & IDisposable Management ✅ LGTM —
5 Public API & Binary Compatibility ✅ LGTM —
6 Performance & Allocations ✅ LGTM —
7 Test Isolation ✅ LGTM —
8 Test Assertion Quality ✅ LGTM —
9 Test Completeness & Coverage ✅ LGTM —
10 Scope & PR Discipline ✅ LGTM —
11 Documentation / Code Comments ✅ LGTM —
12 Code Consistency — TimeoutAfterAsync with token ❌ ISSUE MAJOR
13 Flakiness — WaitOne() without timeout ⚠️ ISSUE MODERATE

11/13 dimensions clean.

- Fix the same unobserved-exception bug in the TimeoutAfterAsync(Task,
  TimeSpan, CancellationToken) overload, which still passed the token to
  ContinueWith. Schedule its observe continuation on TaskScheduler.Default
  too (MAJOR review finding).
- Remove the observeException parameter from all four helpers: it was never
  passed as false, so the observe continuation now always runs. Updated the
  single explicit caller in MessageHandlerFactory.
- Add explanatory comments at every observe continuation describing why it
  must be scheduled on TaskScheduler.Default rather than via the token.
- Bound both waitException.WaitOne() calls in the tests with a 30s timeout
  and assert on it, so a cancelled inner task fails cleanly instead of
  hanging (MODERATE review finding).
- Drop the now-stale "#if !NETFRAMEWORK // Polyfill bug" guard around the
  CancellationToken assertion: the WaitAsync polyfill preserves the token,
  and the assertion passes on net462 (verified 6/6 runs).

Co-authored-by: Copilot <[email protected]>
@Evangelink

Copy link
Copy Markdown
Member Author

Addressed both Expert Code Review findings in da3a831:

Finding 1 (MAJOR) — TimeoutAfterAsync(Task, TimeSpan, CancellationToken) had the same bug. Fixed: its observe continuation now schedules on TaskScheduler.Default instead of passing token. For consistency, all four helpers now use explicit TaskScheduler.Default, and the unused observeException parameter (never passed false) was removed.

Finding 2 (MODERATE) — unbounded WaitOne(). Both tests now use Assert.IsTrue(waitException.WaitOne(TimeSpan.FromSeconds(30)), ...) so a cancelled inner task fails cleanly with a message instead of hanging.

Verified: all 9 TaskExtensionsTests pass 6/6 consecutive runs on both net8.0 and net462.

@Evangelink

This comment has been minimized.

@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) June 25, 2026 12:25
@Evangelink Amaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jun 25, 2026
Removing the 'observeException' parameter changed the binary signature of the internal TaskExtensions helpers, which shipped extensions (HangDump, TrxReport) bind to across assemblies. Older extension packages exercised by the forward-compatibility acceptance test (NewerPlatform_WithPreviousExtensions_ShouldExecuteTests) threw MissingMethodException and crashed the test host (exit code 134).

Restore the parameter to keep the signature binary-compatible while preserving the real fix: scheduling the fire-and-forget exception observer on TaskScheduler.Default instead of passing the cancellation token (#6907).

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings June 25, 2026 13:36

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.

Copilot's findings

  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new

@Evangelink

Copy link
Copy Markdown
Member Author

🧪 Test quality grade — PR #9427

ΔTestGradeBandNotes
mod TaskExtensionsTests.
CancellationAsync_
ObserveException_
Succeeds
A 90–100 Exception + token-equality + bounded-synchronization-gate assertions; previous [Ignore] removed and WaitOne properly converted into a timed assertion.
mod TaskExtensionsTests.
CancellationAsyncWithReturnValue_
ObserveException_
Succeeds
A 90–100 Same triple-assertion pattern as its sibling; try/finally with pragma is necessary to demonstrate exception-in-finally, clean AAA structure.

This advisory comment was generated automatically. Grades are heuristic
and informational — they do not block merging. Re-run with
/grade-tests.

🤖 Automated content by GitHub Copilot. Posted via a maintainer's GitHub token, so it appears under their account — the account owner did not write or approve this content personally. Generated by the Grade Tests on PR (on open / sync) workflow. · 146.3 AIC · ⌖ 12.8 AIC · ⊞ 43.7K · [◷]( · ◷)

@Evangelink
Amaury Levé (Evangelink) merged commit 546ac8e into main Jun 25, 2026
33 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the evangelink-fix-taskextensions-flaky branch June 25, 2026 14:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-review Awaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TaskExtensionsTests are flaky

4 participants