Skip to content

Fix flaky WebApplicationFactory Kestrel port race - #67714

Merged
DeagleGross merged 3 commits into
mainfrom
brennanconroy-investigate-test-failure
Nov 11, 2026
Merged

DeagleGross merged 3 commits into
mainfrom
brennanconroy-investigate-test-failure

Conversation

@BrennanConroy

Copy link
Copy Markdown
Member

Fix a flaky WebApplicationFactory Kestrel port race

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making.

Description

RealServerUsingMinimalBackedIntegrationTests intermittently fails with:

System.InvalidOperationException : IServerAddressesFeature.Addresses cannot be modified after the server has started.

Root cause

When WebApplicationFactory is configured with UseKestrel(port), it called TryConfigureServerPort, which cleared and re-added entries in IServerAddressesFeature.Addresses after builder.Build(). For minimal / WebApplication apps the app owns its own lifecycle: DeferredHostBuilder.Build() runs the entry point via HostFactoryResolver, and the app starts Kestrel on its own thread. Kestrel's BindAsync calls PreventPublicMutation(), making the addresses collection read-only. That bind races with the factory's Addresses.Clear() on the test thread; when Kestrel wins the race, Clear() throws.

Fix

Instead of mutating the addresses after the host is built, configure the Kestrel endpoint directly via KestrelServerOptions.Listen(IPAddress.Loopback, port) in ConfigureBuilderToUseKestrel. This runs during the app's own startup, before binding, so there is no post-start mutation and no race. With PreferHostingUrls == false (the default), AddressBinder uses OverrideWithEndpointsStrategy, so the configured endpoint overrides any addresses the app set via app.Urls, and the resolved (possibly dynamic) port is written back into the addresses feature so TryExtractHostAddress still reads the real bound port. TryConfigureServerPort is removed.

This also un-quarantines RealServerUsingMinimalBackedIntegrationTests.CanResolveServices, which was quarantined for the same exception.

Verification

  • Microsoft.AspNetCore.Mvc.Testing builds clean.
  • Confirmed at runtime that a Listen(Loopback, 0) endpoint overrides a non-empty app.Urls and reports the real dynamically assigned port (the semantics the factory relies on). The full Mvc.FunctionalTests project requires the native IIS/ANCM build, so the real-server tests will be validated in CI.

Fixes #67340

Configure the Kestrel endpoint via KestrelServerOptions.Listen instead of
mutating IServerAddressesFeature.Addresses after the host is built. For
minimal/WebApplication apps run via DeferredHostBuilder, the app starts
Kestrel on its own thread, which can make the addresses collection read-only
before the factory could update it, causing an intermittent
InvalidOperationException ("IServerAddressesFeature.Addresses cannot be
modified after the server has started").

Also un-quarantines
RealServerUsingMinimalBackedIntegrationTests.CanResolveServices, whose root
cause is this same race.

Co-authored-by: Copilot App <[email protected]>
@BrennanConroy
BrennanConroy marked this pull request as ready for review November 10, 2026 23:46
@BrennanConroy
BrennanConroy requested review from DeagleGross and halter73 and a balanced review from Copilot November 10, 2026 23:46

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.

🟡 Changes recommended

The Kestrel configuration can ignore the factory’s requested port and retain existing endpoints, breaking dynamic-port isolation and causing port collisions or startup failures.

3 open issues
What changed in this PR

This PR addresses the WebApplicationFactory startup race behind #67340 by configuring the Kestrel port before binding rather than modifying server addresses after the host is built.

Changes:

  • Configures a loopback listener through Kestrel options for the requested port.
  • Removes TryConfigureServerPort and its post-build calls from both host creation paths.
File Description
src/​Mvc/​Mvc.Testing/​src/​WebApplicationFactory.cs Moves port selection into Kestrel configuration to avoid racing with server startup.

Review effort: Balanced

{
builder.UseKestrel(_configureKestrelOptions);
}
else if (_kestrelPort is int port)
// (e.g. minimal apps run via DeferredHostBuilder) bind Kestrel on their own thread
// and can make the addresses collection read-only before the factory could update it,
// causing an intermittent InvalidOperationException.
builder.UseKestrel(options => options.Listen(IPAddress.Loopback, port));
// (e.g. minimal apps run via DeferredHostBuilder) bind Kestrel on their own thread
// and can make the addresses collection read-only before the factory could update it,
// causing an intermittent InvalidOperationException.
builder.UseKestrel(options => options.Listen(IPAddress.Loopback, port));
@DeagleGross
DeagleGross merged commit 0df9b73 into main Nov 11, 2026
30 checks passed
@DeagleGross
DeagleGross deleted the brennanconroy-investigate-test-failure branch November 11, 2026 10:23
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 8%

No docs needed: internal bug fix for a flaky port race in WebApplicationFactory with Kestrel; no public API or documented behavior change.

Documentation surfaces considered

  • Conceptual article: Not required — Bug fix restoring intended UseKestrel(port) behavior; no new public API or documented behavior change. Signals: no_signal.
  • Migration guidance: Not required — No upgrade action needed.
  • Breaking change: Not required — No compatibility impact; fixes an intermittent exception.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 2aaaf426 Deployed Nov 11, 2026 by DeagleGross via conclusion #292
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Quarantine Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.CanResolveServices

4 participants