Skip to content

Commit 72475f8

Browse files
EvangelinkCopilot
andauthored
[rel/4.5] Complete cleanup cancellation corrections (#12292)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 2e9f40b commit 72475f8

6 files changed

Lines changed: 881 additions & 170 deletions

File tree

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.cs‎

Lines changed: 176 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -381,139 +381,231 @@ async SynchronizationContextPreservingTask<TestResult> ExecuteWithTimeoutTokenAs
381381
TestResult? result = null;
382382
Exception? failure = null;
383383
var invocationState = new TestInvocationState();
384+
var executionCompletion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
384385
CancellationTokenSource cancellationTokenSource = TestContext.Context.CancellationTokenSource;
386+
CancellationToken? runCancellationToken = PlatformServiceProvider.Instance.TestRunCancellationToken?.CancellationToken;
387+
CancellationTokenSource timeoutTokenSource = new();
388+
int timeoutSourceOwners = 2;
389+
int executionState = 0;
390+
using CancellationTokenSource monitorCancellationTokenSource = new();
391+
using CancellationTokenRegistration testCancellationRegistration = cancellationTokenSource.Token.Register(() =>
392+
{
393+
// Fixture cancellation must not end the whole-test wait while cleanup is still running.
394+
if (!invocationState.IsCleanupStarted)
395+
{
396+
monitorCancellationTokenSource.Cancel();
397+
}
398+
});
399+
using CancellationTokenRegistration? runCancellationRegistration =
400+
runCancellationToken?.Register(monitorCancellationTokenSource.Cancel);
401+
using CancellationTokenRegistration timeoutRegistration =
402+
timeoutTokenSource.Token.Register(() => TestContext.Context.CancellationTokenSource.Cancel());
385403
TaskScheduler? synchronizationContextScheduler = SynchronizationContext.Current is null
386404
? null
387405
: TaskScheduler.FromCurrentSynchronizationContext();
388406
bool executionCompleted;
407+
var executionTimer = Stopwatch.StartNew();
389408

390-
if (synchronizationContextScheduler is null)
391-
{
392-
executionCompleted = PlatformServiceProvider.Instance.ThreadOperations.Execute(
393-
ExecuteAsyncAction, TimeoutInfo.Timeout, cancellationTokenSource.Token);
394-
}
395-
else
409+
try
396410
{
397-
// Queue the invocation on its original dispatcher without blocking the message pump.
398-
// A new STA thread cannot access controls owned by this UI thread.
399-
Task executionTask = Task.Factory.StartNew(
400-
ExecuteOnSynchronizationContextAsync,
401-
cancellationTokenSource.Token,
402-
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler,
403-
synchronizationContextScheduler).Unwrap();
404-
using var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token);
405-
var timeoutTask = Task.Delay(TimeoutInfo.Timeout, timeoutCancellation.Token);
406-
Task completedTask = await Task.WhenAny(executionTask, timeoutTask).ConfigureAwait(false);
407-
executionCompleted = completedTask == executionTask && !executionTask.IsCanceled;
411+
if (synchronizationContextScheduler is null)
412+
{
413+
executionCompleted = PlatformServiceProvider.Instance.ThreadOperations.Execute(
414+
ExecuteAsyncAction, TimeoutInfo.Timeout, monitorCancellationTokenSource.Token);
415+
}
416+
else
417+
{
418+
// Queue the invocation on its original dispatcher without blocking the message pump.
419+
// A new STA thread cannot access controls owned by this UI thread.
420+
Task executionTask = Task.Factory.StartNew(
421+
ExecuteOnSynchronizationContextAsync,
422+
monitorCancellationTokenSource.Token,
423+
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler,
424+
synchronizationContextScheduler).Unwrap();
425+
using var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(monitorCancellationTokenSource.Token);
426+
var timeoutTask = Task.Delay(TimeoutInfo.Timeout, timeoutCancellation.Token);
427+
Task completedTask = await Task.WhenAny(executionTask, timeoutTask).ConfigureAwait(false);
428+
executionCompleted = completedTask == executionTask && !executionTask.IsCanceled;
408429
#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks.
409-
timeoutCancellation.Cancel();
430+
timeoutCancellation.Cancel();
410431
#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks.
411-
}
432+
}
412433

413-
if (executionCompleted)
414-
{
415-
if (failure != null)
434+
if (executionCompleted)
416435
{
417-
throw failure;
418-
}
436+
if (failure is not null)
437+
{
438+
throw failure;
439+
}
419440

420-
DebugEx.Assert(result is not null, "result is not null");
421-
return result;
422-
}
441+
DebugEx.Assert(result is not null, "result is not null");
442+
if (result.Outcome == UnitTestOutcome.Passed
443+
&& (cancellationTokenSource.IsCancellationRequested || TestContext.Context.CancellationTokenSource.IsCancellationRequested))
444+
{
445+
result.Outcome = UnitTestOutcome.Timeout;
446+
result.TestFailureException = new TestFailedException(
447+
UnitTestOutcome.Timeout,
448+
string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, TestMethodName));
449+
}
423450

424-
// Timed out or canceled
425-
string errorMessage = string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Timeout, TestMethodName, TimeoutInfo.Timeout);
426-
if (cancellationTokenSource.IsCancellationRequested)
427-
{
428-
errorMessage = string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, TestMethodName);
429-
}
430-
else
431-
{
432-
// Cancel the token source as test has timed out
451+
return result;
452+
}
453+
454+
int remainingTimeout = (int)Math.Max(0, TimeoutInfo.Timeout - executionTimer.ElapsedMilliseconds);
455+
bool isTimeout = !monitorCancellationTokenSource.IsCancellationRequested || remainingTimeout == 0;
456+
string errorMessage = isTimeout
457+
? string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Timeout, TestMethodName, TimeoutInfo.Timeout)
458+
: string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, TestMethodName);
433459
#pragma warning disable VSTHRD103 // Call async methods when in an async method - likely fine in this context. CancelAsync is .NET Core only. We prefer having the same behavior between .NET Core and .NET Framework.
434-
cancellationTokenSource.Cancel();
460+
if (isTimeout)
461+
{
462+
timeoutTokenSource.Cancel();
463+
}
464+
else
465+
{
466+
if (runCancellationToken?.IsCancellationRequested == true)
467+
{
468+
TestContext.Context.CancellationTokenSource.Cancel();
469+
}
470+
471+
// A body cancellation may already have been consumed by fresh cleanup; only the original deadline may cancel it again.
472+
timeoutTokenSource.CancelAfter(remainingTimeout);
473+
}
435474
#pragma warning restore VSTHRD103 // Call async methods when in an async method
436-
}
437475

438-
TestResult timeoutResult = new() { Outcome = UnitTestOutcome.Timeout, TestFailureException = new TestFailedException(UnitTestOutcome.Timeout, errorMessage) };
476+
TestResult timeoutResult = new() { Outcome = UnitTestOutcome.Timeout, TestFailureException = new TestFailedException(UnitTestOutcome.Timeout, errorMessage) };
477+
CancellationTokenSource? cleanupTimeoutSource = isTimeout ? null : timeoutTokenSource;
478+
bool cleanupCompleted = false;
439479

440-
// Execution context propagation here may still not be accurate.
441-
// if test init was successfully executed by ExecuteAsyncAction, but then the test itself timed out or cancelled,
442-
// then at this point we will run the cleanup on an execution context that doesn't have any state set by the test initialize.
443-
if (synchronizationContextScheduler is null)
444-
{
445-
await RunTestCleanupMethodAsync(timeoutResult, null, invocationState).ConfigureAwait(false);
446-
}
447-
else if (!invocationState.IsCleanupStarted
448-
&& invocationState.TryGetCleanupSnapshot(out TestInvocationCleanupSnapshot snapshot))
449-
{
450-
if (!HasCleanupsToInvoke(snapshot.ClassInstanceLease))
480+
// Execution context propagation here may still not be accurate.
481+
// if test init was successfully executed by ExecuteAsyncAction, but then the test itself timed out or cancelled,
482+
// then at this point we will run the cleanup on an execution context that doesn't have any state set by the test initialize.
483+
if (synchronizationContextScheduler is null)
451484
{
452-
// Cancellation bookkeeping does not need a dispatcher blocked by synchronous user code.
453-
await RunTestCleanupMethodAsync(timeoutResult, null, invocationState).ConfigureAwait(false);
485+
cleanupCompleted = await RunTestCleanupMethodAsync(timeoutResult, cleanupTimeoutSource, invocationState).ConfigureAwait(false);
454486
}
455-
else
487+
else if (!invocationState.IsCleanupStarted
488+
&& invocationState.TryGetCleanupSnapshot(out TestInvocationCleanupSnapshot snapshot))
456489
{
457-
const int CleanupDispatchTimeoutMilliseconds = 1_000;
458-
int cleanupDispatchClaimed = 0;
459-
Task cleanupTask = Task.Factory.StartNew(
460-
async () =>
461-
{
462-
// Either the dispatcher starts cleanup, or the monitor leaves it to the original invocation.
463-
if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) == 0)
464-
{
465-
await RunTestCleanupMethodAsync(timeoutResult, null, invocationState).ConfigureAwait(false);
466-
}
467-
},
468-
CancellationToken.None,
469-
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler,
470-
synchronizationContextScheduler).Unwrap();
471-
using var dispatchTimeoutCancellation = new CancellationTokenSource();
472-
await Task.WhenAny(
473-
cleanupTask,
474-
Task.Delay(CleanupDispatchTimeoutMilliseconds, dispatchTimeoutCancellation.Token)).ConfigureAwait(false);
475-
#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks.
476-
dispatchTimeoutCancellation.Cancel();
477-
#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks.
478-
if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) != 0)
490+
if (!HasCleanupsToInvoke(snapshot.ClassInstanceLease))
479491
{
480-
await cleanupTask.ConfigureAwait(false);
492+
// Cancellation bookkeeping does not need a dispatcher blocked by synchronous user code.
493+
cleanupCompleted = await RunTestCleanupMethodAsync(timeoutResult, cleanupTimeoutSource, invocationState).ConfigureAwait(false);
481494
}
482-
else if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsVerboseEnabled)
495+
else
483496
{
484-
PlatformServiceProvider.Instance.AdapterTraceLogger.Verbose(
485-
"MSTest.TestMethodInfo: Cleanup for timed out test '{0}' is deferred because its synchronization context did not become available within {1}ms.",
486-
TestMethodName,
487-
CleanupDispatchTimeoutMilliseconds);
497+
const int CleanupDispatchTimeoutMilliseconds = 1_000;
498+
int cleanupDispatchClaimed = 0;
499+
Task cleanupTask = Task.Factory.StartNew(
500+
async () =>
501+
{
502+
// Either the dispatcher starts cleanup, or the monitor leaves it to the original invocation.
503+
if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) == 0)
504+
{
505+
cleanupCompleted = await RunTestCleanupMethodAsync(timeoutResult, cleanupTimeoutSource, invocationState).ConfigureAwait(false);
506+
}
507+
},
508+
CancellationToken.None,
509+
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler,
510+
synchronizationContextScheduler).Unwrap();
511+
using var dispatchTimeoutCancellation = new CancellationTokenSource();
512+
await Task.WhenAny(
513+
cleanupTask,
514+
Task.Delay(CleanupDispatchTimeoutMilliseconds, dispatchTimeoutCancellation.Token)).ConfigureAwait(false);
515+
#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks.
516+
dispatchTimeoutCancellation.Cancel();
517+
#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks.
518+
if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) != 0)
519+
{
520+
await cleanupTask.ConfigureAwait(false);
521+
}
522+
else if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsVerboseEnabled)
523+
{
524+
PlatformServiceProvider.Instance.AdapterTraceLogger.Verbose(
525+
"MSTest.TestMethodInfo: Cleanup for timed out test '{0}' is deferred because its synchronization context did not become available within {1}ms.",
526+
TestMethodName,
527+
CleanupDispatchTimeoutMilliseconds);
528+
}
488529
}
489530
}
531+
532+
if (!cleanupCompleted && invocationState.IsCleanupStarted && !timeoutTokenSource.IsCancellationRequested)
533+
{
534+
using var cleanupWaitCancellation = CancellationTokenSource.CreateLinkedTokenSource(
535+
timeoutTokenSource.Token,
536+
runCancellationToken ?? CancellationToken.None);
537+
await Task.WhenAny(
538+
executionCompletion.Task,
539+
Task.Delay(Timeout.Infinite, cleanupWaitCancellation.Token)).ConfigureAwait(false);
540+
#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks.
541+
cleanupWaitCancellation.Cancel();
542+
#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks.
543+
}
544+
545+
return timeoutResult;
490546
}
547+
finally
548+
{
549+
if (Interlocked.CompareExchange(ref executionState, 2, 0) == 0)
550+
{
551+
ReleaseTimeoutSource();
552+
}
491553

492-
return timeoutResult;
554+
ReleaseTimeoutSource();
555+
}
493556

494557
// Local functions
495558
async Task ExecuteOnSynchronizationContextAsync()
496559
{
560+
if (Interlocked.CompareExchange(ref executionState, 1, 0) != 0)
561+
{
562+
return;
563+
}
564+
497565
try
498566
{
499-
result = await ExecuteInternalAsync(arguments, null, invocationState).ConfigureAwait(false);
567+
result = await ExecuteInternalAsync(arguments, timeoutTokenSource, invocationState).ConfigureAwait(false);
500568
}
501569
catch (Exception ex)
502570
{
503571
failure = ex;
504572
}
573+
finally
574+
{
575+
ReleaseTimeoutSource();
576+
executionCompletion.TrySetResult(true);
577+
}
505578
}
506579

507580
void ExecuteAsyncAction()
508581
{
582+
if (Interlocked.CompareExchange(ref executionState, 1, 0) != 0)
583+
{
584+
return;
585+
}
586+
509587
try
510588
{
511-
result = ExecuteInternalAsync(arguments, null, invocationState).GetAwaiter().GetResult();
589+
result = ExecuteInternalAsync(arguments, timeoutTokenSource, invocationState).GetAwaiter().GetResult();
512590
}
513591
catch (Exception ex)
514592
{
515593
failure = ex;
516594
}
595+
finally
596+
{
597+
ReleaseTimeoutSource();
598+
executionCompletion.TrySetResult(true);
599+
}
600+
}
601+
602+
void ReleaseTimeoutSource()
603+
{
604+
// A timed-out worker may still be unwinding after the monitor returns.
605+
if (Interlocked.Decrement(ref timeoutSourceOwners) == 0)
606+
{
607+
timeoutTokenSource.Dispose();
608+
}
517609
}
518610
}
519611

0 commit comments

Comments
 (0)