Repository navigation
Modernize process management in tests and non-shipping infrastructure - #70668
Conversation
Co-authored-by: Copilot <[email protected]> Copilot-Session: 151a6a4b-fb9b-4efa-bb7c-383fe6bc3a4c
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues block approval of the test and infrastructure process-handling changes.
No open issues 🎉
What changed in this PR
Modernizes process handling across tests and non-shipping infrastructure, independently of the product fixes in #70076 and product modernization in #70669. Shipping implementations remain outside this PR.
Changes:
- Drain redirected output concurrently and distinguish process exit from output completion.
- Improve timeout handling, cancellation, disposal, and IIS Express parent-exit cleanup.
- Configure explicit handle inheritance, simplify process helpers, and remove an unused OpenAPI test wrapper.
| File | Description |
|---|---|
src/Tools/Shared/TestHelpers/NativeAotToolRunner.cs |
Uses combined output capture and exit-status waiting. |
src/Tools/Microsoft.dotnet-openapi/test/ProcessEx.cs |
Removes the unused process wrapper. |
src/SignalR/server/StackExchangeRedis/test/Docker.cs |
Kills timed-out commands and reports their status. |
src/SignalR/perf/benchmarkapps/Crankier/Agent.cs |
Discards unread worker stderr through a null handle. |
src/Shared/Process/ProcessExtensions.cs |
Uses built-in concurrent output capture with a timeout. |
src/Shared/Process/ProcessEx.cs |
Configures explicit handle inheritance. |
src/Shared/E2ETesting/SauceConnectServer.cs |
Configures handle inheritance for tunnel and sentinel processes. |
src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs |
Replaces exit events with cancellation-aware process waiting. |
src/Servers/IIS/IntegrationTesting.IIS/src/IISExpressDeployer.cs |
Adds parent-exit cleanup and modernizes shutdown waits. |
src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/Helpers.cs |
Uses exit-status waiting for worker-stop assertions. |
src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/AppVerifier.cs |
Captures both output streams while commands run. |
src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs |
Removes duplicate process starts and explicitly awaits command exit. |
src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Build.Tests/GenerateAdditionalXmlFilesForOpenApiTests.cs |
Simplifies output capture while preserving process-tree timeout cleanup. |
src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Executable.cs |
Uses streamed output, cancellation-aware waiting, and process disposal. |
src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs |
Simplifies symlink command execution with an argument list. |
src/Hosting/test/FunctionalTests/ShutdownTests.cs |
Replaces the signal subprocess with managed SIGTERM signaling. |
src/Hosting/Server.IntegrationTesting/src/Deployers/SelfHostDeployer.cs |
Configures explicit handle inheritance. |
src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs |
Configures handle inheritance for PowerShell launches. |
src/Hosting/Server.IntegrationTesting/src/Deployers/NginxDeployer.cs |
Uses the environment username and reports command timeouts. |
src/Hosting/Server.IntegrationTesting/src/ApplicationPublisher.cs |
Disposes the process wrapper and waits explicitly for parent exit. |
src/Grpc/Interop/test/InteropTests/Helpers/WebsiteProcess.cs |
Configures handle inheritance for server launches. |
src/Grpc/Interop/test/InteropTests/Helpers/ClientProcess.cs |
Configures handle inheritance for client launches. |
src/Fuzzing/AspNetCoreFuzzing/Program.cs |
Configures handle inheritance for instrumentation commands. |
src/Components/WebView/test/StaticWebAssets/ConsumerBuild.cs |
Bounds output enumeration and process waiting with a shared timeout. |
src/Components/WebView/test/E2ETest/WebViewManagerE2ETests.cs |
Reads output asynchronously and disposes the process wrapper. |
src/Components/Testing/test/PackageIntegrationTests.cs |
Drains NativeAOT consumer output during readiness checks and cleanup. |
src/Components/Gateway/test/GatewayToolInstallation.cs |
Simplifies installation output collection and exit waiting. |
src/Caching/StackExchangeRedis/test/Infrastructure/RedisTestConfig.cs |
Adds conditional handle configuration while retaining older-framework support. |
.github/skills/review-pull-request/tests/PrepareReviewTests.cs |
Captures Git stdout and stderr concurrently as bytes. |
.github/skills/review-pull-request/scripts/prepare-review.cs |
Configures explicit handle inheritance for helper processes. |
Review effort: Balanced
|
/review |
adamsitnik
left a comment
There was a problem hiding this comment.
I've left comments, so other reviewers can understand the reasoning behind the changes and avoid similar issues in the future.
| RedirectStandardOutput = true, | ||
| RedirectStandardError = true, | ||
| UseShellExecute = false, | ||
| InheritedHandles = [], |
There was a problem hiding this comment.
to other code reviewers: this is what we recommend to always set. It makes the process inherit only std handles, without any other inheritable handles that are alive in the parent process. It also allows to spawn processes in parallel on Windows.
There was a problem hiding this comment.
Setting this property on Unix systems that do not have native support for controlling handle inheritance can severely degrade process start performance.
Does that mean we should set it only on Windows?
There was a problem hiding this comment.
Great question! We have fixed that recently in dotnet/runtime#135753 and with dotnet/runtime#137485 we support a performant way to do it for every supported platform.
| start.ArgumentList.Add(arg); | ||
| } | ||
| using var process = Process.Start(start) ?? throw new InvalidOperationException($"Cannot start {command}."); | ||
| using var process = Process.Start(start)!; |
There was a problem hiding this comment.
to other code reviewers: Process.Start can return null only when UseShellExecute is set to true, here it's not.
| using var output = new MemoryStream(); | ||
| process.StandardOutput.BaseStream.CopyTo(output); | ||
| var error = process.StandardError.ReadToEnd(); | ||
| (byte[] output, byte[] error) = process.ReadAllBytes(); |
There was a problem hiding this comment.
to other code reviewers: this was a bug that could lead to deadlock: reading std out and then std err
| ProcessExitStatus status; | ||
| try | ||
| { | ||
| foreach (ProcessOutputLine line in process.ReadAllLines(timeout)) |
There was a problem hiding this comment.
to other code reviewers: this is faster (we don't start two background tasks) and does not require locks.
| Task.Delay(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken)); | ||
| if (completed != readinessTask) | ||
| { | ||
| var output = await process.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken); |
There was a problem hiding this comment.
to other code reviewers: this was a bug: reading std out and then std err (deadlock possible)
| UseShellExecute = false, | ||
| InheritedHandles = [], | ||
| // Prevent orphaned IIS Express processes even if the test process exits during startup. | ||
| KillOnParentExit = true, |
There was a problem hiding this comment.
to other code reviewers: this is 100% atomic on Windows now (includes graceful exit, but also forced termination and crash) and will kill entire process tree when the parent exits. So no need to monitor for process exit on Windows anymore.
| Logger.LogInformation("iisexpress Process {pid} failed to bind to port {port}, trying again", process.Id, port); | ||
|
|
||
| // Wait for the process to exit and try again | ||
| process.WaitForExit(30 * 1000); |
There was a problem hiding this comment.
to other code reviewers: this was calling sync method from an async method
| if (process.WaitForExit((int)timeout.TotalMilliseconds)) | ||
| try | ||
| { | ||
| stdout = process.StandardOutput.ReadToEnd(); |
There was a problem hiding this comment.
to other code reviewers: another bug: reading only std out, while std err was redirected as well
| RedirectStandardInput = true, | ||
| RedirectStandardOutput = true, | ||
| RedirectStandardError = true | ||
| // AgentWorker never reads stderr; discard it to prevent an unread pipe from filling and blocking the worker. |
There was a problem hiding this comment.
to other code reviewers: this is the most performant and safe way to discard output/error now
| ProcessExitStatus status = process.SafeHandle.WaitForExitOrKillOnTimeout(timeout); | ||
| if (status.Canceled) | ||
| { | ||
| process.Close(); |
There was a problem hiding this comment.
to other code reviewers: process.Dispose/Close does not kill the process
There was a problem hiding this comment.
Source-only review of frozen head 6fcb9077a93da82fb53d362ab0afacfe27718168.
Validated new findings
- One inline
P2candidate is retained as unresolved: the changed WebSockets Autobahn cleanup may replace cancellation with aProcess.Kill()exception, but the target-version runtime/BCL ordering and exception contract are not present in the frozen evidence.
Existing-feedback coverage
- No equivalent concrete finding was present in the frozen feedback. The existing bot review reported no open issues; deduplication is not an endorsement of that review.
Unresolved candidates
src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Executable.cs:74: requires the target-version implementation/contract forWaitForExitOrKillOnCancellationAsyncandProcess.Kill(), plus an exact old/new comparison for the same cancellation sequence.
Guide completion
docs/CrossCuttingGuidance.md: complete for all in-scope source checks; runtime/test/CI/browser execution and security assessment were excluded by the frozen policy.docs/BlazorComponentsGuidance.md: complete for all in-scope source checks; the changed Components files are test-process infrastructure and do not alter product rendering or hosting behavior. The same execution and security exclusions apply.- Workers were requested and reported as
review-guide-worker, modelgpt-5.6-sol; reasoning effort was not supplied (runtime default). Runtime telemetry otherwise reported the requested model.
Uncovered areas
- No area-specific guide beyond Cross-Cutting was routed for the non-Components Hosting/IIS, Kestrel/WebSockets, SignalR, gRPC, OpenAPI/tools, Redis/cache, StaticFiles, review-tooling, and fuzzing changes; those areas received cross-cutting process-management review only.
Immutable provenance
- PR
dotnet/aspnetcore#70668; head6fcb9077a93da82fb53d362ab0afacfe27718168; merge base49147673007a4b1d676694e2c5f85b83ad76c36f; base tip and trusted guidance commitfa10021db581bdb7dc44e84953842ac9ccb34009.
Test boundary and limitations
- No target code, tests, CI, browser workflows, or samples were executed. Proof is source-only from tracked frozen Git bytes. Symlink targets, submodule contents, LFS targets, external runtime/BCL behavior, and feedback posted after bundle preparation are not observable.
Generated by ASP.NET Core Pull Request Review for #70668 · copilot · gpt56 · 201.6 AIC · ⌖ 8.49 AIC · ⊞ 20.1K
Comment /review to run again
|
Copilot's local review panel found no issues to raise at this commit. The three sequential arms completed at For each informational item below: Posted for informational purposes so the author can confirm the verifier didn't discard or leave unresolved a real finding; this item does not block
Untested coverage gaps: No full PR test suite, CI image, browser/WebView, IIS/nginx, Unix/macOS, or NativeAOT workflow was run. Existing success-path assertions alone do not prove the changed timeout, cancellation, or high-volume-output paths. Non-Components areas received cross-cutting review, not separate area-specialist review. Existing resolved or already-answered feedback was not reposted. Validation boundary: All arms reviewed frozen source; G and O also ran limited Windows process/BCL probes, and O compiled a copied review producer. S performed source review only. These checks do not verify the unresolved gated-logger scenario. Human-directed and GitHub Copilot-generated. |
Youssef1313
left a comment
There was a problem hiding this comment.
LGTM overall.
Left few questions.
| RedirectStandardOutput = true, | ||
| RedirectStandardError = true, | ||
| UseShellExecute = false, | ||
| InheritedHandles = [], |
There was a problem hiding this comment.
Setting this property on Unix systems that do not have native support for controlling handle inheritance can severely degrade process start performance.
Does that mean we should set it only on Windows?
|
|
||
| try | ||
| { | ||
| await _process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(15)); |
There was a problem hiding this comment.
What's the difference in this case?
There was a problem hiding this comment.
WaitForExitStatusAsync does not wait for EOF, while WaitForExitAsync does.
Long story short, the recommendation is to always prefer WaitForExitStatusAsync over WaitForExitAsync unless you want to wait for an exit of non-child process (because on Unix you can't reap non-child processes so we can't obtain their exit code)
There was a problem hiding this comment.
@adamsitnik I thought WaitForExitAsync only waits for EOF when using the BeginReadX APIs, when not reading directly from the stream?
There was a problem hiding this comment.
@adamsitnik I thought WaitForExitAsync only waits for EOF when using the BeginReadX APIs, when not reading directly from the stream?
You are right. So this particular change has not changed the behavior, but just made it easier to search for potential bugs in the future (find all usages of the old method).
| process.WaitForExit(10_000); | ||
| return process.StandardOutput.ReadToEnd(); | ||
| } | ||
| return Environment.UserName; |
There was a problem hiding this comment.
I'm not sure of all the history, but Environment.UserName is old, what has changed?
If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user. In a published ASP.NET application, this property returns the name of the application pool account (such as Default AppPool).
Not sure if that's relevant here.
| { | ||
| if (line.StandardError) | ||
| { | ||
| LogIfNotNull(logger.LogError, "stderr: {0}", line.Content); |
There was a problem hiding this comment.
I guess it's never null now?
There was a problem hiding this comment.
It can't be null, but it still can be empty. So the helper name is not 100% accurate, but it still performs the right check.
@Youssef1313 if you don't mind I would prefer avoiding renaming the helper method, so I can merge this PR and get back to writing my Connect and use past tense to express that I've contributed to ASP.NET :D
| @@ -100,19 +100,17 @@ private static void RunProcessAndWaitForExit(string fileName, string arguments, | |||
| Arguments = arguments, | |||
| RedirectStandardOutput = true, | |||
| RedirectStandardError = true, | |||
There was a problem hiding this comment.
Should we redirect stderr to File.OpenNullHandle() here instead?
There was a problem hiding this comment.
This is a bit tricky. We could redirect to NUL and avoid the need of draining this pipe, but the problem is that we don't offer a BCL API for draining a single pipe synchronously and respecting timeout.
Since Process.RunAndCaptureText supports timeout, we use it to drain both.
| catch (TimeoutException) | ||
| { | ||
| process.Kill(); | ||
| // Preserve the lack of captured output when the command times out. |
There was a problem hiding this comment.
Previous code used to kill the process on timeout. Is it on purpose that we no longer do that? Why?
There was a problem hiding this comment.
All the new Process.Run* APIs kill the process on timeout/cancellation. So here the process also gets killed and TimeoutException is thrown and we just ignore it.
|
✅ No documentation PR was created. Confidence that documentation is needed: 2% No docs needed: the PR modernizes process handling in tests and non-shipping test/tooling infrastructure only. Documentation surfaces considered
|
Modernize process management in tests and non-shipping infrastructure
Improve process reliability and simplify test/infrastructure helpers.
Description
Test/infrastructure fixes and improvements split from dotnet/aspnetcore#70076, following review feedback. This branch starts directly from main and does not depend on either product branch. The product-improvement split is dotnet/aspnetcore#70669.
whoami, discard unused Crankier stderr directly, simplify output capture/line enumeration, and configure explicit handle inheritance.ProcessEximplementation.This includes non-shipping Hosting/IIS integration-testing libraries, fuzzing/benchmark utilities, and repository review tooling, even when their paths contain
src. The shipping Components.Testing implementation and all other shipping changes are excluded. Regression coverage for product bugs stays with #70076.The nginx shutdown timeout is reported without introducing a new kill policy. Older-framework Redis test compatibility is retained.
This remains a real-world test of the
process-api-net11skill in dotnet/skills#1322.Validation
Commands ran on Windows after
. .\activate.ps1:dotnet test src\Servers\Kestrel\test\Interop.FunctionalTests\Interop.FunctionalTests.csproj --no-restore -v:q -p:UseIisNativeAssets=false --filter 'FullyQualifiedName~H2SpecTests'— 292 passed.dotnet run --project .github\skills\review-pull-request\scripts\PrepareReview.Tests.csproj --no-build -- -noLogo -method '*ProducerGitArgumentsEnableWindowsLongPathsBeforeTheSubcommand' -method '*PreparesBinaryChangesWithoutChangingTheAuthoritativeDiff' -method '*SerializesJavaScriptCompatibleJsonBytes'— 9 passed. An earlier unfiltered review-helper run was stopped without a completed result; it is not counted as passing.dotnet build src\Components\Testing\test\Microsoft.AspNetCore.Components.Testing.Tests.csproj -v:q -p:UseIisNativeAssets=false— passed, including the package-consumer build prerequisites.dotnet run --project src\Components\Testing\test\Microsoft.AspNetCore.Components.Testing.Tests.csproj --no-build -- -class Microsoft.AspNetCore.Components.Testing.Tests.PackageIntegrationTests -noLogo— 5 passed, 2 NativeAOT cases skipped becauseEnableNativeAotPackageIntegrationTestsand a supportedPackageConsumerRuntimeIdentifierwere not configured.dotnet build src\Hosting\Server.IntegrationTesting\src\Microsoft.AspNetCore.Server.IntegrationTesting.csproj -v:q -p:UseIisNativeAssets=false— passed, compiling both shared process helpers.dotnet build src\Servers\IIS\IntegrationTesting.IIS\src\Microsoft.AspNetCore.Server.IntegrationTesting.IIS.csproj -v:q -p:UseIisNativeAssets=false— passed; this is compilation, not IIS runtime validation.dotnet test src\Middleware\StaticFiles\test\UnitTests\Microsoft.AspNetCore.StaticFiles.Tests.csproj --no-build -v:q --filter 'FullyQualifiedName~ReturnsNotFoundForBrokenSymlink'— 1 skipped on Windows; the owning test project compiled in the preceding build/test invocation.git diff --check 49147673007a4b1d676694e2c5f85b83ad76c36f..HEAD— passed.Known baseline build blocker:
dotnet build src\SignalR\perf\benchmarkapps\Crankier\Crankier.csproj -v:q -p:UseIisNativeAssets=falsefails on missingHub,IApplicationBuilder, andIWebHostEnvironmentin the nestedServersources. Temporarily reversing only the transferredAgent.cspatch reproduces the same three errors on unchanged main; this unrelated issue was not changed.The exact pinned SDK and unchanged-main JavaScript bundles were shared as local prerequisites; C# outputs were isolated by worktree. Full browser/WebView, Unix signal/nginx paths, native IIS behavior, NativeAOT package execution, and the remaining cross-platform suites were not exercised. Targeted results do not establish full validation of all 30 files.
Related issue: none linked.