Skip to content

Fix RetryOrchestrator leaking CancellationTokenSource and Process.Exited handler per attempt - #8382

Merged
Amaury Levé (Evangelink) merged 2 commits into
mainfrom
dev/amauryleve/fix-retry-cts-leak
May 20, 2026
Merged

Amaury Levé (Evangelink) merged 2 commits into
mainfrom
dev/amauryleve/fix-retry-cts-leak

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Fixes #8380

See the linked issue for full context and rationale.

Changes

  • processExitedCancellationToken is now a using var so it is disposed when the iteration's scope ends.
  • The Process.Exited handler is stored in a local and detached in a finally block so it does not anchor the closure for the life of the process.
  • The handler's Cancel() call is wrapped in a try { ... } catch (ObjectDisposedException) { } to make cleanup race-safe against a late Exited firing.

…ted handler per attempt

`RetryOrchestrator` previously created a `CancellationTokenSource` and subscribed a `Process.Exited` handler on every retry iteration, but neither the CTS nor the handler were ever released. This anchored a closure that retained the `CancellationTokenSource`, the `Process` and the logger graph for as long as the test host process was alive, and accumulated linearly with `--retry-failed-tests N`. It also left a late `Exited` firing calling `Cancel()` on a CTS whose linked source had already been disposed, so the cancellation signal was effectively dead.

Make the CTS a `using var`, store the handler in a local, and detach it in a `finally`. Guard the `Cancel()` call with `ObjectDisposedException` to keep the cleanup race-safe against late `Exited` firings.

Fixes #8380

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings May 20, 2026 12:06

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 addresses a per-retry-attempt resource leak in the Retry extension’s RetryOrchestrator by ensuring that attempt-scoped cancellation resources and Process.Exited subscriptions are cleaned up promptly, avoiding retained closures and CTS instances across retries.

Changes:

  • Disposes the per-attempt CancellationTokenSource used to signal process exit (using var).
  • Stores the Exited event handler in a local and unsubscribes it in a finally block.
  • Makes the Cancel() call race-safe by swallowing ObjectDisposedException if the CTS was already disposed.
Show a summary per file
File Description
src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs Dispose per-attempt CTS and detach Exited handler to prevent resource/closure retention across retry attempts.

Copilot's findings

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

@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.

Review Summary

Overall: Good, targeted fix. The PR correctly addresses a CancellationTokenSource resource leak and a dangling event handler.

Dimension Result
1. Algorithmic Correctness ✅ Logic is correct. Event unsubscription in finally covers all exit paths including early returns.
2. Threading & Concurrency ✅ No new races introduced. Handler unsubscription via -= is correct; the ObjectDisposedException catch guards the one theoretical (but practically unreachable) race window.
3. Security / IPC N/A
4. Public API N/A — no public API changes.
5. Performance ✅ Minor: extracting exitedHandler to a local variable avoids a new lambda allocation on each retry attempt, which is a small improvement.
6. Cross-TFM ✅ No TFM-specific APIs used. using var syntax is valid across all targets.
7. Resource & IDisposable ✅ This is the core fix. Adding using var to processExitedCancellationToken closes the resource leak present in the original code.
8. Defensive Coding ⚠️ See inline comment — the catch (ObjectDisposedException) silently swallows without logging, which could hide future bugs.
9. Localization N/A
10–21. Other dimensions N/A for this change scope

One minor finding: The catch (ObjectDisposedException) block is effectively unreachable given the current ownership model (handler is unsubscribed in finally before the CTS using scope ends), and it silently swallows the exception. Consider logging it at debug level for diagnostic visibility.

Generated by Expert Code Review (on open) for issue #8382 · ● 3.4M

…edException

Two findings from PR review (copilot-pull-request-reviewer + @Evangelink):

1. IProcess is IDisposable but testHostProcess was not disposed across

   retry attempts, leaking OS process handles until finalization. Change

   the variable to a using declaration so it's disposed deterministically

   at the end of each iteration (after WaitForExitAsync, after we've read

   ExitCode, and on every early-return / break / continue path).

2. The catch (ObjectDisposedException) block previously swallowed the

   exception silently. Add a debug log line with a comment explaining the

   race it's guarding against (Exited handler queued before -=, executes

   after CTS Dispose) so unexpected occurrences stay observable.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@Evangelink

Copy link
Copy Markdown
Member Author

Thanks both — addressed in 9691ff8:

  1. IProcess disposal (copilot-pull-request-reviewer): Good catch — IProcess does extend IDisposable (it wraps System.Diagnostics.Process). Changed IProcess testHostProcess = ... to using IProcess testHostProcess = ... so the process handle is released deterministically at the end of each iteration. using declarations run their dispose on every exit path (normal continuation, break, continue, and the early return (int)ExitCode.GenericFailure;), and they unwind in reverse declaration order so processExitedCancellationToken is disposed first — safe because the handler has already been detached in the inner finally.

  2. Empty catch (ObjectDisposedException) (Amaury Levé (@Evangelink) + copilot-pull-request-reviewer): Agreed it's a narrow race and was effectively invisible if it ever fired. I kept the catch as a safety net (the Exited event invocation can race with -= on the threadpool — once dispatched, an in-flight handler still completes even after the source has unsubscribed it) and added a debug log per your suggestion, plus a comment explaining the race.

@Evangelink
Amaury Levé (Evangelink) merged commit 938c1a7 into main May 20, 2026
45 of 51 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/fix-retry-cts-leak branch May 20, 2026 13:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Retry] RetryOrchestrator leaks CancellationTokenSource and Process.Exited handler each attempt

2 participants