Repository navigation
Coalesce HangDump activity signals instead of one IPC round trip per test - #12167
Amaury Levé (Evangelink) merged 10 commits into
Conversation
…test The test host awaited an ActivitySignalRequest round trip to the controller for every non-in-progress test node update. The controller only uses the signal to reset its inactivity timer, so a background loop now forwards pending activity at most once per interval (a tenth of the hang timeout, between 10 ms and 1 s). Coalescing only delays the latest signal, so a dump can fire at most one interval later than configured, never earlier. Co-Authored-By: Claude <noreply@anthropic.com>
Dispose and DisposeAsync disposed the cancellation source and named pipe client without waiting for the signal loop, so an in-flight request could hit a disposed pipe and fault unobserved, and session finishing after disposal threw ObjectDisposedException. Loop shutdown is now idempotent and awaited (bounded in synchronous Dispose), and loop failures are logged immediately instead of only surfacing when the session ends. Co-Authored-By: Claude <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved issues can cause false hang dumps and host termination near the inactivity deadline, while disposal may tear down pipe resources before the background worker completes.
2 open issues
What changed in this PR
This PR reduces HangDump overhead in Microsoft.Testing.Platform by batching activity notifications instead of awaiting an IPC round trip for every completed test update.
Changes:
- Adds a background activity flush loop, timeout-based intervals, and a final session flush.
- Shares timeout parsing between the host and controller and records two internal APIs.
- Adds tests for pending-activity coalescing and interval bounds.
Test-value evidence: The PR reports 146 passing tests and a targeted mutation failure. These results were not independently verified; the supplied tests directly check pending-state behavior and interval calculations, not background delivery or shutdown ordering.
| File | Description |
|---|---|
test/UnitTests/Microsoft.Testing.Extensions.UnitTests/HangDumpMutationTests.cs |
Adds coalescing and interval-bound tests. |
src/Platform/Microsoft.Testing.Extensions.HangDump/InternalAPI/InternalAPI.Unshipped.txt |
Records the interval and timeout helpers. |
src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpProcessLifetimeHandler.cs |
Uses shared timeout parsing. |
src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpOptions.cs |
Centralizes timeout parsing and its default. |
src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs |
Adds activity batching and worker lifecycle handling. |
Review effort: Balanced
The controller re-arms its inactivity timer when an activity signal is delivered, but activity right after a delivery can wait up to one signal interval before the next flush. With the timer armed at exactly the hang timeout, a dump could fire before the timeout had elapsed since the last activity. The controller now arms the timer with the timeout plus the signal interval (computed with the same shared formula), so a dump never fires early and fires at most two intervals late. Also bound the wait for the signal loop in DisposeAsync, as in Dispose. Co-Authored-By: Claude <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
The disposal test completes its fake loop during cancellation, so it cannot detect a missing await or disposal returning with work still in flight; both disposal paths need independently gated completion coverage.
3 open issues
Review effort: Balanced
HangDumpActivityBehaviorTests expected ConsumeAsync to fail on the missing pipe client, which relied on per-result IPC. Those cases now await normal completion and keep their bookkeeping, retry, clock and trace assertions, plus a check that no scheduler work is started. HangDumpInProcessProtocolFixture's strict ITask mock now provides a controllable, cancellation-aware Delay. FlushActivityAsync releases one wait of the signal loop and returns once the loop waits again, so the pending signal has been acknowledged. The lifecycle tests flush before asserting acknowledgements, assert coalescing (several results, one signal), assert that activity before the reverse connection is delivered once the loop starts, and cover a canceled final flush on a live pipe.
Close the activity-loop rendezvous semaphore after transport tasks drain and expose the existing cleanup through IAsyncDisposable, resolving CA1001 across all target frameworks. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Amaury Levé (Evangelink)
left a comment
There was a problem hiding this comment.
Note
🤖 Automated review by GitHub Copilot. To request a follow-up action, reply by tagging @copilot directly.
Not ready for approval: make deferred pipe cleanup survive the normal second disposal pass, then extend the shutdown-timeout tests to exercise that sequence. One P2 finding is attached inline.
This review covered the complete nine-file PR, not only the latest fixture fix: pending-activity publication, handshake/startup, cancellation and final flushing, controller timer/grace arithmetic and period splitting, disposal ownership, linked named-pipe transport, supported target frameworks, internal API baselines, and the changed tests and fixtures. The existing coalescing, canceled-flush, timer-limit, and test-integration corrections are present; no unrelated redesign or public API change is needed.
The new finding supplies evidence beyond the previously resolved timeout-disposal concern: the first call now correctly defers disposal, but the unchanged console-host lifecycle subsequently invokes disposal again. That second call bypasses the deferral. It is not a request for hypothetical concurrent-caller hardening.
Revision: merge base 3a95626573dd6932505a860cbd059dae4f79a81d; head bd3306bfa541b1e614c296f498fef69545aac4f7.
Test-value evidence
| Contract / cases | Counterfactual assessment | Evidence / gap |
|---|---|---|
No per-result IPC / ConsumeAsync_CoalescesActivityInsteadOfSendingAnIpcRequestPerResult, revised activity-state cases |
Restoring per-result IPC should fail the missing-client guard. | Static: predicts detection. Matching final-source reports show passing cases; no final-revision mutation was executed in this review. |
Actual coalesced delivery, retry bookkeeping, and canceled final flush / RegisteredLifecycle_HandshakeActivityAndExitUseOwnedRoles, RegisteredLifecycle_SupersededRetrySignalsWithoutLosingTrackedTest |
Missing delivery should violate the real controller-acknowledgment assertions; letting final-flush cancellation escape should fail finishing. | Static: predicts detection. Passing execution records were inspected for the current test sources. |
Ordinary join and one timed-out disposal / DisposeAsync_WaitsForInFlightActivitySignalBeforeReturning, Dispose_WaitsForInFlightActivitySignalBeforeReturning, both ShutdownTimeout_DefersPipeClientDisposalUntilTheLoopStops cases |
Removing the join or disposing immediately on the first timeout should violate the gate/client-state assertions. | Static: predicts detection. Those cases passed, but each timeout test releases its worker after only one disposal invocation. |
| A second disposal while the first timed-out worker remains gated | Repeat disposal before releasing the existing completion gate. | Unverified by execution; regression case absent. The current source disposes the client on that second call, and the normal console host reaches this call sequence. |
Timeout grace and upper timer limit / InactivityTimer_NeverExpiresBeforeTheTimeoutSinceTheLastActivity, GetTimerPeriod_SplitsDueTimesBeyondTheTimerLimit |
Removing the grace or returning an unsplit period should violate their expectations. | Static: predicts detection. Existing passing records cover the arithmetic/boundary checks, not every live scheduling interleaving. |
I reused and re-read the final-source reports from the earlier implementation turn: 1,442 passed, 0 failed, six existing Linux-only skips across net8.0, net9.0, net10.0, net11.0, net462, and net472. All 236 executions of the two affected classes passed without skips. The semaphore-cleanup-only follow-up also has matching 40/40 green-before and green-after records. These results do not cover the newly identified repeated-disposal timeout sequence. The discarded overlapping-patch experiment is not counted as evidence for this final revision.
No PR code was changed, built, or executed during this review. The buffer-disposal consequence was checked against the official .NET MemoryStream implementation, rather than inferred from Stream generally. The inspected current-head CI build 1661680, on merge 2faa8a7459a78b5836ce8acc2d18cd907dd48f9f, has Linux Release, Windows Debug, and app-model jobs passing; Windows Release was still in progress at the inspected snapshot. Its passing jobs are not proof that this untested shutdown sequence is safe.
Confidence at a glance
🟢 Correctness & design
The coalescing change is coherent and appropriately scoped. No additional algorithmic defect was established after baseline comparison.🟠 Concurrency & lifecycle
One high-confidence P2 ownership defect remains: repeated standard-host disposal can close the pipe before its deferred worker finishes.🟢 Security & protocol
No new wire-format, permission, process-launch, or trust-boundary regression identified. The request/reply serialization contract is unchanged.🟢 API & compatibility
Public API is unchanged; the five internal API entries, netstandard2.0 linked sources, and modern/legacy conditional paths are consistent.🟢 Performance
Per-result IPC is removed as intended. The author-reported benchmark measurements were not independently reproduced.🟡 Tests & delivery evidence
The revised real-pipe tests preserve acknowledgment and cleanup checks, and existing reports are green. Repeated disposal after a shutdown timeout is the specific missing regression scenario; mutation and live blocked-pipe proof for it remain unavailable.Give synchronous and asynchronous disposal one atomic cleanup owner so later host disposal passes cannot close the pipe while its timed-out activity worker is still running. Add gated regression cases for repeated and mixed disposal calls, preserving the original bounded wait and eventual cleanup. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>


Summary
Reduce
--hangdumpoverhead by coalescing the test host's activity signals instead of sending one blocking named-pipe round trip to the test host controller per test result.Previously,
HangDumpActivityIndicator.ConsumeAsyncawaited anActivitySignalRequest/VoidResponseround trip for every test node update that was not in progress, including discovery updates. The controller uses the signal only to reset its inactivity timer (default 30 minutes), so per-result delivery was unnecessary. With fast tests, that consumer fell behind, and the message-bus drain at the end of the session waited for thousands of cross-process round trips.Now:
ConsumeAsynconly sets a "pending activity" flag. No IPC happens on the per-result path.OnTestSessionStartingAsyncforwards pending activity at most once per interval. The interval is a tenth of--hangdump-timeout, kept between 10 ms and 1 s.OnTestSessionFinishingAsyncstops the loop, awaits it, and then flushes one final pending signal, so two requests never share the pipe at once.OnTestSessionFinishingAsync,DisposeAsyncandDispose(bounded to 30 s) all stop the loop and wait for it before the pipe client is disposed, so an in-flight request never hits a disposed pipe.HangDumpOptions.GetTimeout, and the controller'sHangDumpProcessLifetimeHandlernow uses it too. Default and parsing behavior are unchanged.Behavioral contract: the controller re-arms its inactivity timer when a signal is delivered, and activity right after a delivery can wait up to one interval for the next flush. So the controller now arms the timer with timeout + interval (
HangDumpOptions.GetInactivityTimerDueTime). Both processes are the same executable and use the same shared formula. A hang dump therefore never fires before the configured timeout has passed since the last activity, and fires at most two intervals late: 2 s at the default 30-minute timeout, 1.6 s at an 8 s timeout. The absolute CI deadline timer is unchanged.No public API changes. Two internal API entries are added.
Design and decision record
This is a localized optimization inside one extension, so no separate design record is needed. Alternatives considered:
The fixed cost of the controller's second process (~250–300 ms per run) is unchanged by this PR. It is ordering work in
TestHostControllersTestHost, out of scope here.Demonstration
Standalone Release/net10.0 MSTest app with 5000 empty tests, referencing local Release builds of MSTest.TestAdapter, Microsoft.Testing.Extensions.TrxReport and Microsoft.Testing.Extensions.HangDump. Baseline and candidate bin folders are identical except
Microsoft.Testing.Extensions.HangDump.dll(baseline built from2a8ebadb1). Each command was run 15 times, alternating baseline/candidate order, with arguments--no-banner --no-progress --results-directory <dir>plus the listed options. Every run exited 0 with 5000 passed. Windows x64 10.0.26300, i7-12700K, 20 logical processors, .NET 10.0.13.--hangdump--hangdump --report-trxTest-host session time from diagnostic logs (
--diagnostic-verbosity information, 6 runs each, candidate build): plain ~450 ms,--hangdump~500 ms. Before the change,--hangdumpadded ~250 ms over plain inside the session. The saving grows with the number of test results.Timing comes from one machine and is not a cross-platform claim. Screenshots add nothing for this internal change.
Validation and regression proof
dotnet build src/Platform/Microsoft.Testing.Extensions.HangDump/Microsoft.Testing.Extensions.HangDump.csproj -c Release: all target frameworks (net8.0, net9.0, net10.0, net11.0, netstandard2.0), 0 warnings, 0 errors.dotnet build test/UnitTests/Microsoft.Testing.Extensions.UnitTests -c Debug -f net10.0: 0 errors.Microsoft.Testing.Extensions.UnitTests.exe --no-banner --progress off --filter "FullyQualifiedName~HangDump"(net10.0, at5da5fc401): total 153, failed 0, succeeded 153, repeated 5 times, exit 0.Manual end-to-end checks with the same harness, baseline vs candidate:
--hangdump --hangdump-timeout 1s: total runtime exceeds the timeout, but no dump is triggered in either build. Both pass 5/5.--hangdump --hangdump-timeout 2s: the dump triggers at ~2.6 s (baseline) and ~2.7 s (candidate). In both builds, dump writing then failed because the ad-hoc harness lacks theMicrosoft.Diagnostics.NETCore.Clientdependency. That path is unchanged by this PR.Not run: integration/acceptance tests (they need packages built), and unit tests on TFMs other than net10.0 (compiled only).
Test-value evidence
New tests in
HangDumpMutationTests.cs:ConsumeAsync_CoalescesActivityInsteadOfSendingAnIpcRequestPerResultchecks that in-progress updates do not mark activity, that terminal updates do, and that no per-result IPC is attempted. The indicator has no pipe client, so any IPC attempt fails the state guard.GetActivitySignalInterval_IsATenthOfTheTimeoutWithinBounds(4 data rows) checks the interval cap, the tenth-of-timeout rule and the floor.DisposeAsync_WaitsForInFlightActivitySignalBeforeReturning(NETCOREAPP only) andDispose_WaitsForInFlightActivitySignalBeforeReturninguse a fake loop that sees cancellation but finishes only when a separate gate is released. Each test checks that disposal stays incomplete until then, and completes after.OnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDisposedLoopchecks that session finishing after disposal does not throw.InactivityTimer_NeverExpiresBeforeTheTimeoutSinceTheLastActivity(4 rows: 10.5 s, 8 s, 30 min, 50 ms) models worst-case delivery of pending activity against controller expiry.BeforeStartAndConsumerHandshake_InitializeEveryFieldAndSerializernow also asserts the controller's_activityTimerDueTimeis 30 min + 1 s.Counterfactual (mutation check on this branch): I restored per-result IPC by re-adding
await SendPendingActivitySignalAsync(cancellationToken)inConsumeAsync, kept the new tests, rebuilt and ran the same filter. Result: total 146, failed 1, succeeded 145. The failure is the intendedConsumeAsync_CoalescesActivityInsteadOfSendingAnIpcRequestPerResult, withSystem.InvalidOperationException: Unexpected state ... HangDumpActivityIndicator.cs at line '159'. With the mutation reverted: 146/146 pass.Counterfactual for the disposal fix: with the two disposal tests kept and
HangDumpActivityIndicator.csrestored to the first commit (96f8b70db), the same filter gives total 148, failed 2, succeeded 146. The failures were the first version of the disposal test andOnTestSessionFinishingAsync_AfterDispose_DoesNotTouchTheDisposedLoop, withSystem.ObjectDisposedException: The CancellationTokenSource has been disposed.With the fix: 148/148 pass.Counterfactual for the gated disposal tests (at
5da5fc401): withawait loopremoved fromStopActivitySignalLoopAsync, total 153, failed 2, succeeded 151. Both..._WaitsForInFlightActivitySignalBeforeReturningtests fail onAssert.IsFalse(dispose.IsCompleted).Counterfactual for the timer grace: with
GetInactivityTimerDueTimemutated to return only the timeout, the same filter gives total 152, failed 5, succeeded 147 (all fourInactivityTimer_...rows plusBeforeStartAndConsumerHandshake_InitializeEveryFieldAndSerializer). With the fix: 152/152 pass.Manual check at
ed0dc4f03: 5 × 700 ms tests with--hangdump-timeout 1stake no dump; a real hang with--hangdump-timeout 2sstill dumps.GetActivitySignalIntervalis new and cannot compile against the baseline, so that test's value is shown only by its assertions on the bounds, not by a red run.Review follow-up
Early dump near the deadline: valid. Fixed in
ed0dc4f03by adding the signal interval to the controller's inactivity timer (see the behavioral contract above).Disposal test could not detect a missing wait: valid. Fixed in
5da5fc401with gated tests covering both disposal paths.Disposal vs. in-flight worker: fixed in
258a69cf2, with the wait inDisposeAsyncbounded ined0dc4f03. Both dispose paths stop the loop and wait for it before disposing the pipe client, including when session finishing is skipped.Real-pipe fixture vs. the signal loop and activity tests vs. the no-IPC consume contract: valid. These are tests from
mainthat the head-only runs missed. Fixed inf4bc3d92f. The fixture now has a controllableITask.Delayand aFlushActivityAsyncstep, and the tests assert coalesced delivery. On the merged branch atf4bc3d92f, the HangDump filter gives 244 total, 0 failed, 8 skipped (net10.0 ×5 and net8.0), and the full Extensions unit suite passes. Without the test changes, 27 tests fail per TFM, matching CI's 108.