@@ -33,7 +33,17 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif
3333 private readonly bool _traceLevelEnabled ;
3434 private readonly ConcurrentDictionary < TestNodeUid , ( string Name , Type Type , DateTimeOffset StartTime ) > _testsCurrentExecutionState = new ( ) ;
3535
36- private bool _exitSignalActivityIndicatorAsync ;
36+ private readonly TimeSpan _activitySignalInterval ;
37+ private readonly TimeSpan _activitySignalShutdownTimeout = TimeSpan . FromSeconds ( 30 ) ;
38+
39+ private volatile bool _exitSignalActivityIndicatorAsync ;
40+ private int _activitySignalPending ;
41+
42+ // The first disposer retains ownership even when it must defer cleanup past the shutdown timeout.
43+ private int _disposeStarted ;
44+
45+ private CancellationTokenSource ? _activitySignalCancellation ;
46+ private Task ? _activitySignalTask ;
3747 private NamedPipeServer ? _singleConnectionNamedPipeServer ;
3848 private PipeNameDescription ? _pipeNameDescription ;
3949
@@ -58,6 +68,7 @@ public HangDumpActivityIndicator(
5868 _namedPipeClient . RegisterSerializer ( new VoidResponseSerializer ( ) , typeof ( VoidResponse ) ) ;
5969 _namedPipeClient . RegisterSerializer ( new ConsumerPipeNameRequestSerializer ( ) , typeof ( ConsumerPipeNameRequest ) ) ;
6070 _namedPipeClient . RegisterSerializer ( new ActivitySignalRequestSerializer ( ) , typeof ( ActivitySignalRequest ) ) ;
71+ _activitySignalInterval = HangDumpOptions . GetActivitySignalInterval ( HangDumpOptions . GetTimeout ( _commandLineOptions ) ) ;
6172 }
6273 }
6374
@@ -100,13 +111,87 @@ await _namedPipeClient.RequestReplyAsync<ConsumerPipeNameRequest, VoidResponse>(
100111 // Wait the connection from the testhost controller
101112 await _singleConnectionNamedPipeServer . WaitConnectionAsync ( cancellationToken ) . TimeoutAfterAsync ( TimeoutHelper . DefaultHangTimeSpanTimeout , cancellationToken ) . ConfigureAwait ( false ) ;
102113 await _logger . LogTraceAsync ( "Test host controller connected" ) . ConfigureAwait ( false ) ;
114+
115+ _activitySignalCancellation = CancellationTokenSource . CreateLinkedTokenSource ( cancellationToken ) ;
116+ CancellationToken stopToken = _activitySignalCancellation . Token ;
117+ _activitySignalTask = _task . Run ( ( ) => SignalActivityLoopAsync ( stopToken , cancellationToken ) , CancellationToken . None ) ;
103118 }
104119 catch ( OperationCanceledException ex ) when ( ex . CancellationToken == cancellationToken )
105120 {
106121 // Do nothing, we're stopping
107122 }
108123 }
109124
125+ private async Task SignalActivityLoopAsync ( CancellationToken stopToken , CancellationToken sessionCancellationToken )
126+ {
127+ try
128+ {
129+ while ( true )
130+ {
131+ await _task . Delay ( _activitySignalInterval , stopToken ) . ConfigureAwait ( false ) ;
132+
133+ // The stop token only interrupts the wait. A request in flight completes, so the pipe is never
134+ // left with a half-read reply when the session ends.
135+ await SendPendingActivitySignalAsync ( sessionCancellationToken ) . ConfigureAwait ( false ) ;
136+ }
137+ }
138+ catch ( OperationCanceledException ) when ( stopToken . IsCancellationRequested )
139+ {
140+ // Stopped by the end of the session or by cancellation.
141+ }
142+ catch ( Exception ex )
143+ {
144+ // Log now: without activity signals the controller can take a hang dump before the session ends
145+ // and rethrows this failure.
146+ await _logger . LogErrorAsync ( "Failed to send a hang dump activity signal to the test host controller; activity signals stopped." , ex ) . ConfigureAwait ( false ) ;
147+ throw ;
148+ }
149+ }
150+
151+ private async Task StopActivitySignalLoopAsync ( )
152+ {
153+ // Idempotent: whoever takes the fields stops the loop, so session end and disposal never race on them.
154+ CancellationTokenSource ? cancellation = Interlocked . Exchange ( ref _activitySignalCancellation , null ) ;
155+ Task ? loop = Interlocked . Exchange ( ref _activitySignalTask , null ) ;
156+ if ( cancellation is null )
157+ {
158+ return ;
159+ }
160+
161+ try
162+ {
163+ #if NET
164+ await cancellation . CancelAsync ( ) . ConfigureAwait ( false ) ;
165+ #else
166+ cancellation . Cancel ( ) ;
167+ #endif
168+ if ( loop is not null )
169+ {
170+ await loop . ConfigureAwait ( false ) ;
171+ }
172+ }
173+ finally
174+ {
175+ cancellation . Dispose ( ) ;
176+ }
177+ }
178+
179+ private async Task SendPendingActivitySignalAsync ( CancellationToken cancellationToken )
180+ {
181+ if ( Interlocked . Exchange ( ref _activitySignalPending , 0 ) == 0 || _exitSignalActivityIndicatorAsync )
182+ {
183+ return ;
184+ }
185+
186+ ApplicationStateGuard . Ensure ( _namedPipeClient is not null ) ;
187+ await _namedPipeClient . RequestReplyAsync < ActivitySignalRequest , VoidResponse > ( ActivitySignalRequest . Instance , cancellationToken ) . ConfigureAwait ( false ) ;
188+
189+ if ( _traceLevelEnabled )
190+ {
191+ await _logger . LogTraceAsync ( "Activity signal sent." ) . ConfigureAwait ( false ) ;
192+ }
193+ }
194+
110195 private async Task < IResponse > CallbackAsync ( IRequest request )
111196 {
112197 if ( request is GetInProgressTestsRequest )
@@ -167,31 +252,107 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella
167252 await _logger . LogTraceAsync ( $ "Signal for action node { nodeChangedMessage . TestNode . DisplayName } - '{ state } '. _exitSignalActivityIndicatorAsync: { _exitSignalActivityIndicatorAsync } ") . ConfigureAwait ( false ) ;
168253 }
169254
170- // Signal the activity.
171- if ( ! _exitSignalActivityIndicatorAsync )
172- {
173- ApplicationStateGuard . Ensure ( _namedPipeClient is not null ) ;
174- await _namedPipeClient . RequestReplyAsync < ActivitySignalRequest , VoidResponse > ( ActivitySignalRequest . Instance , cancellationToken ) . ConfigureAwait ( false ) ;
175-
176- if ( _traceLevelEnabled )
177- {
178- await _logger . LogTraceAsync ( $ "Activity signal sent.") . ConfigureAwait ( false ) ;
179- }
180- }
255+ // Record the activity; the signal loop forwards it to the controller.
256+ Volatile . Write ( ref _activitySignalPending , 1 ) ;
181257 }
182258 }
183259
184- public Task OnTestSessionFinishingAsync ( ITestSessionContext testSessionContext )
185- => Task . CompletedTask ;
260+ public async Task OnTestSessionFinishingAsync ( ITestSessionContext testSessionContext )
261+ {
262+ if ( Volatile . Read ( ref _activitySignalTask ) is null )
263+ {
264+ return ;
265+ }
266+
267+ // Stop the loop before sending the last pending signal, so two requests never share the pipe.
268+ await StopActivitySignalLoopAsync ( ) . ConfigureAwait ( false ) ;
269+
270+ CancellationToken cancellationToken = testSessionContext . CancellationToken ;
271+ try
272+ {
273+ await SendPendingActivitySignalAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
274+ }
275+ catch ( OperationCanceledException ) when ( cancellationToken . IsCancellationRequested )
276+ {
277+ // The final flush is best effort. A canceled session must not skip the session-finishing handlers
278+ // that run after this one.
279+ }
280+ }
186281
187282#if NETCOREAPP
188- public ValueTask DisposeAsync ( )
283+ public async ValueTask DisposeAsync ( )
189284 {
285+ if ( Interlocked . Exchange ( ref _disposeStarted , 1 ) != 0 )
286+ {
287+ return ;
288+ }
289+
290+ // Wait (bounded) for the loop before disposing the pipe client it may be using. This also covers runs
291+ // where session finishing was skipped because execution or a lifecycle handler threw. If the wait times
292+ // out, the pipe client is disposed only when the loop stops.
293+ Task stop = StopActivitySignalLoopAsync ( ) ;
294+ try
295+ {
296+ Task completed = await Task . WhenAny ( stop , Task . Delay ( _activitySignalShutdownTimeout ) ) . ConfigureAwait ( false ) ;
297+ if ( completed != stop )
298+ {
299+ DisposePipeClientAfterLateStop ( stop ) ;
300+ return ;
301+ }
302+
303+ await stop . ConfigureAwait ( false ) ;
304+ }
305+ catch ( Exception ex )
306+ {
307+ await _logger . LogDebugAsync ( $ "Hang dump activity signal loop failed during disposal: { ex . Message } ") . ConfigureAwait ( false ) ;
308+ }
309+
190310 _namedPipeClient ? . Dispose ( ) ;
191- return ValueTask . CompletedTask ;
192311 }
193312#endif
194313
195314 public void Dispose ( )
196- => _namedPipeClient ? . Dispose ( ) ;
315+ {
316+ if ( Interlocked . Exchange ( ref _disposeStarted , 1 ) != 0 )
317+ {
318+ return ;
319+ }
320+
321+ // Wait (bounded) for the loop before disposing the pipe client it may be using. If the wait times out, the
322+ // pipe client is disposed only when the loop stops.
323+ Task stop = StopActivitySignalLoopAsync ( ) ;
324+ try
325+ {
326+ if ( ! stop . Wait ( _activitySignalShutdownTimeout ) )
327+ {
328+ DisposePipeClientAfterLateStop ( stop ) ;
329+ return ;
330+ }
331+ }
332+ catch ( Exception ex )
333+ {
334+ _logger . LogDebug ( $ "Hang dump activity signal loop failed during disposal: { ex . Message } ") ;
335+ }
336+
337+ _namedPipeClient ? . Dispose ( ) ;
338+ }
339+
340+ private void DisposePipeClientAfterLateStop ( Task stop )
341+ {
342+ // A request that is still in flight uses the pipe client's stream and buffers. On Windows a write waits for
343+ // the controller to drain the pipe, and the stop request cannot interrupt that wait. Disposing the client
344+ // under it would make the request fail, and the client then exits the process. Dispose the client only
345+ // after the loop has finished, and observe the loop's failure so it is never unobserved.
346+ _logger . LogDebug ( "Hang dump activity signal loop did not stop within the shutdown timeout during disposal; the pipe client is disposed when it stops." ) ;
347+ _ = stop . ContinueWith (
348+ static ( task , state ) =>
349+ {
350+ _ = task . Exception ;
351+ ( ( NamedPipeClient ? ) state ) ? . Dispose ( ) ;
352+ } ,
353+ _namedPipeClient ,
354+ CancellationToken . None ,
355+ TaskContinuationOptions . None ,
356+ TaskScheduler . Default ) ;
357+ }
197358}
0 commit comments