Repository navigation
Fix NegotiationMatcherPolicy invalidating higher-priority endpoints - #65973
Merged
Merged
Conversation
javiercn
force-pushed
the
javiercn/routing-fix
branch
2 times, most recently
from
March 25, 2026 13:00
0e05397 to
f7ebd33
Compare
javiercn
marked this pull request as ready for review
March 26, 2026 07:02
Contributor
There was a problem hiding this comment.
Pull request overview
This PR addresses a routing correctness issue where NegotiationMatcherPolicy<T>.ApplyAsync (used for Accept-Encoding negotiation) can incorrectly invalidate higher-priority endpoints when a lower-priority endpoint matches an encoding, causing catch-all endpoints to override more-specific routes.
Changes:
- Update
NegotiationMatcherPolicy<T>.ApplyAsync/EvaluateCandidateto avoid invalidating candidates across “priority tiers”. - Add extensive unit tests for
ContentEncodingNegotiationMatcherPolicy.ApplyAsynccovering priority preservation scenarios. - Add end-to-end integration tests for both the
INodeBuilderPolicyandIEndpointSelectorPolicypaths.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Http/Routing/test/UnitTests/Matching/ContentEncodingNegotiationMatcherPolicyTest.cs | Adds many ApplyAsync unit tests plus a CandidateSet helper overload to model scores. |
| src/Http/Routing/test/UnitTests/Matching/ContentEncodingNegotiationMatcherPolicyIntegrationTestBase.cs | New shared end-to-end test suite for content-encoding negotiation behavior. |
| src/Http/Routing/test/UnitTests/Matching/ContentEncodingNegotiationMatcherPolicyINodeBuilderPolicyIntegrationTest.cs | Runs the integration suite via the INodeBuilderPolicy path (no dynamic metadata). |
| src/Http/Routing/test/UnitTests/Matching/ContentEncodingNegotiationMatcherPolicyIEndpointSelectorPolicyIntegrationTest.cs | Runs the integration suite via the selector-policy path (dynamic metadata present). |
| src/Http/Routing/src/Matching/NegotiationMatcherPolicy.cs | Core behavior change: introduces tier tracking and bounds candidate invalidation. |
javiercn
force-pushed
the
javiercn/routing-fix
branch
from
March 28, 2026 15:11
9eb9c30 to
ca5edea
Compare
ilonatommy
reviewed
Apr 1, 2026
maraf
approved these changes
Apr 3, 2026
maraf
self-requested a review
April 3, 2026 08:20
javiercn
force-pushed
the
javiercn/routing-fix
branch
from
April 6, 2026 06:35
4e1f2f3 to
ee7bdb3
Compare
javiercn
enabled auto-merge (squash)
April 6, 2026 06:35
ilonatommy
approved these changes
Apr 7, 2026
javiercn
force-pushed
the
javiercn/routing-fix
branch
from
April 7, 2026 15:06
ee7bdb3 to
da4b143
Compare
This was referenced Apr 7, 2026
Open
javiercn
force-pushed
the
javiercn/routing-fix
branch
2 times, most recently
from
April 8, 2026 14:32
25b91ba to
d1ed8fe
Compare
javiercn
force-pushed
the
javiercn/routing-fix
branch
from
April 8, 2026 14:47
d1ed8fe to
dd6764f
Compare
NegotiationMatcherPolicy.ApplyAsync has two invalidation points that do
not account for routing priority (CandidateState.Score). When a
lower-priority endpoint (e.g. a catch-all with ContentEncodingMetadata)
matches the Accept-Encoding header, it blindly invalidates all preceding
candidates — including higher-priority endpoints representing different
resources.
This manifests when MapStaticAssets registers catch-all endpoints (e.g.
{**path:nonfile} for SPA fallback) with gzip/br/identity variants. A
request to a specific API or configuration endpoint (e.g.
_blazor/_configuration) that shares a DFA path node with these catch-alls
gets incorrectly overridden by the catch-all's gzip variant.
The fix leverages the fact that candidates are already sorted by
ascending Score. A scoreTierStart variable tracks where the current
score tier begins. Backward sweeps in EvaluateCandidate use
Math.Max(bestMatchIndex, scoreTierStart) as the start bound, and
post-match invalidation skips candidates with strictly lower score
than the best match. This preserves higher-priority endpoints without
adding per-element Score comparisons.
End-to-end tests that exercise the full DFA routing pipeline with real RouteEndpoint instances and route patterns. Tests run through both the INodeBuilderPolicy path (DFA branch construction) and the IEndpointSelectorPolicy path (runtime candidate filtering). Key scenarios: - Basic encoding negotiation (gzip/br/identity selection) - Literal endpoint preserved when catch-all has encoding metadata - Multiple catch-all encoding variants don't defeat literal endpoints - Parameterized endpoints preserved over catch-alls with metadata - Mixed priority tiers (literal > parameterized > catch-all) - Static file encoding variants with catch-all present - 406 when no encoding matches and no identity fallback
- Use separate currentTierScore variable instead of candidates[scoreTierStart].Score to avoid reading bitwise-negated scores after SetValidity invalidates candidates - Add Match_ContentEncoding_AcceptQualityWins_WhenBothAcceptAndEndpointQualityDiffer test Agent-Logs-Url: https://github.com/dotnet/aspnetcore/sessions/133133cd-c173-4ceb-97d3-1524b005fc2e Co-authored-by: javiercn <[email protected]>
javiercn
force-pushed
the
javiercn/routing-fix
branch
from
April 9, 2026 08:09
dd6764f to
e9f530d
Compare
6 tasks
javiercn
added a commit
that referenced
this pull request
Jun 8, 2026
Port the production-readiness pieces from Aspire's Gateway.cs.in into Microsoft.AspNetCore.Components.Gateway so the framework-shipped gateway behaves like the Aspire copy at runtime: - ConfigureOpenTelemetry: OTel logging with formatted message + scopes, metrics for AspNetCore/HttpClient/Runtime, tracing with the app source + AspNetCore/HttpClient instrumentation, anti-feedback-loop filters for /_otlp/ requests and outbound /v1/* calls, and UseOtlpExporter() gated on OTEL_EXPORTER_OTLP_ENDPOINT. - Suppress per-request log noise from StaticAssets, Routing, and the OtlpExporter HttpClient. - HSTS in non-development. - Conditional HTTPS redirect only for document navigations (Sec-Fetch-Dest: document), so OTLP/API fetches are never redirected. - /health and /alive health endpoints in development. - ServiceDiscovery + StandardResilience on HttpClient defaults. Skipped from Aspire's port because 11.0 makes them unnecessary: - Per-app .Add(ep => reb.Order = int.MaxValue) hack — StaticAsset manifests now carry Order (#65975) and NegotiationMatcherPolicy respects routing priority (#65973), and the gateway already uses MapFallbackToFile for the SPA fallback. - File-based-app properties (#:property ...) are net10.0-only. Add OpenTelemetryInstrumentationAspNetCoreVersion to eng/Versions.props and reference the OpenTelemetry + Http.Resilience packages directly from the gateway csproj (it already opts into DisablePackageReferenceRestrictions). Co-authored-by: Copilot <[email protected]>
javiercn
added a commit
that referenced
this pull request
Jun 8, 2026
Port the production-readiness pieces from Aspire's Gateway.cs.in into Microsoft.AspNetCore.Components.Gateway so the framework-shipped gateway behaves like the Aspire copy at runtime: - ConfigureOpenTelemetry: OTel logging with formatted message + scopes, metrics for AspNetCore/HttpClient/Runtime, tracing with the app source + AspNetCore/HttpClient instrumentation, anti-feedback-loop filters for /_otlp/ requests and outbound /v1/* calls, and UseOtlpExporter() gated on OTEL_EXPORTER_OTLP_ENDPOINT. - Suppress per-request log noise from StaticAssets, Routing, and the OtlpExporter HttpClient. - HSTS in non-development. - Conditional HTTPS redirect only for document navigations (Sec-Fetch-Dest: document), so OTLP/API fetches are never redirected. - /health and /alive health endpoints in development. - ServiceDiscovery + StandardResilience on HttpClient defaults. Skipped from Aspire's port because 11.0 makes them unnecessary: - Per-app .Add(ep => reb.Order = int.MaxValue) hack — StaticAsset manifests now carry Order (#65975) and NegotiationMatcherPolicy respects routing priority (#65973), and the gateway already uses MapFallbackToFile for the SPA fallback. - File-based-app properties (#:property ...) are net10.0-only. Add OpenTelemetryInstrumentationAspNetCoreVersion to eng/Versions.props and reference the OpenTelemetry + Http.Resilience packages directly from the gateway csproj (it already opts into DisablePackageReferenceRestrictions). Co-authored-by: Copilot <[email protected]>
javiercn
added a commit
that referenced
this pull request
Jun 8, 2026
Port the production-readiness pieces from Aspire's Gateway.cs.in into Microsoft.AspNetCore.Components.Gateway so the framework-shipped gateway behaves like the Aspire copy at runtime: - ConfigureOpenTelemetry: OTel logging with formatted message + scopes, metrics for AspNetCore/HttpClient/Runtime, tracing with the app source + AspNetCore/HttpClient instrumentation, anti-feedback-loop filters for /_otlp/ requests and outbound /v1/* calls, and UseOtlpExporter() gated on OTEL_EXPORTER_OTLP_ENDPOINT. - Suppress per-request log noise from StaticAssets, Routing, and the OtlpExporter HttpClient. - HSTS in non-development. - Conditional HTTPS redirect only for document navigations (Sec-Fetch-Dest: document), so OTLP/API fetches are never redirected. - /health and /alive health endpoints in development. - ServiceDiscovery + StandardResilience on HttpClient defaults. Skipped from Aspire's port because 11.0 makes them unnecessary: - Per-app .Add(ep => reb.Order = int.MaxValue) hack — StaticAsset manifests now carry Order (#65975) and NegotiationMatcherPolicy respects routing priority (#65973), and the gateway already uses MapFallbackToFile for the SPA fallback. - File-based-app properties (#:property ...) are net10.0-only. Add OpenTelemetryInstrumentationAspNetCoreVersion to eng/Versions.props and reference the OpenTelemetry + Http.Resilience packages directly from the gateway csproj (it already opts into DisablePackageReferenceRestrictions). Co-authored-by: Copilot <[email protected]>
javiercn
added a commit
that referenced
this pull request
Jun 9, 2026
Port the production-readiness pieces from Aspire's Gateway.cs.in into Microsoft.AspNetCore.Components.Gateway so the framework-shipped gateway behaves like the Aspire copy at runtime: - ConfigureOpenTelemetry: OTel logging with formatted message + scopes, metrics for AspNetCore/HttpClient/Runtime, tracing with the app source + AspNetCore/HttpClient instrumentation, anti-feedback-loop filters for /_otlp/ requests and outbound /v1/* calls, and UseOtlpExporter() gated on OTEL_EXPORTER_OTLP_ENDPOINT. - Suppress per-request log noise from StaticAssets, Routing, and the OtlpExporter HttpClient. - HSTS in non-development. - Conditional HTTPS redirect only for document navigations (Sec-Fetch-Dest: document), so OTLP/API fetches are never redirected. - /health and /alive health endpoints in development. - ServiceDiscovery + StandardResilience on HttpClient defaults. Skipped from Aspire's port because 11.0 makes them unnecessary: - Per-app .Add(ep => reb.Order = int.MaxValue) hack — StaticAsset manifests now carry Order (#65975) and NegotiationMatcherPolicy respects routing priority (#65973), and the gateway already uses MapFallbackToFile for the SPA fallback. - File-based-app properties (#:property ...) are net10.0-only. Add OpenTelemetryInstrumentationAspNetCoreVersion to eng/Versions.props and reference the OpenTelemetry + Http.Resilience packages directly from the gateway csproj (it already opts into DisablePackageReferenceRestrictions). Co-authored-by: Copilot <[email protected]>
javiercn
added a commit
that referenced
this pull request
Jun 9, 2026
Port the production-readiness pieces from Aspire's Gateway.cs.in into Microsoft.AspNetCore.Components.Gateway so the framework-shipped gateway behaves like the Aspire copy at runtime: - ConfigureOpenTelemetry: OTel logging with formatted message + scopes, metrics for AspNetCore/HttpClient/Runtime, tracing with the app source + AspNetCore/HttpClient instrumentation, anti-feedback-loop filters for /_otlp/ requests and outbound /v1/* calls, and UseOtlpExporter() gated on OTEL_EXPORTER_OTLP_ENDPOINT. - Suppress per-request log noise from StaticAssets, Routing, and the OtlpExporter HttpClient. - HSTS in non-development. - Conditional HTTPS redirect only for document navigations (Sec-Fetch-Dest: document), so OTLP/API fetches are never redirected. - /health and /alive health endpoints in development. - ServiceDiscovery + StandardResilience on HttpClient defaults. Skipped from Aspire's port because 11.0 makes them unnecessary: - Per-app .Add(ep => reb.Order = int.MaxValue) hack — StaticAsset manifests now carry Order (#65975) and NegotiationMatcherPolicy respects routing priority (#65973), and the gateway already uses MapFallbackToFile for the SPA fallback. - File-based-app properties (#:property ...) are net10.0-only. Add OpenTelemetryInstrumentationAspNetCoreVersion to eng/Versions.props and reference the OpenTelemetry + Http.Resilience packages directly from the gateway csproj (it already opts into DisablePackageReferenceRestrictions). Co-authored-by: Copilot <[email protected]>
javiercn
added a commit
that referenced
this pull request
Jun 16, 2026
* Align blazor-wasm-servicedefaults template with Aspire client defaults Fixes #67032: the WASM app threw CircularDependencyException (ILoggerFactory) on startup when OTEL_EXPORTER_OTLP_ENDPOINT was not configured, because the OTel logger provider activates OtlpExporterOptions while the LoggerFactory is being constructed and our IPostConfigureOptions resolved ILoggerFactory from the same container. - Skip OpenTelemetry wiring entirely when OTEL_EXPORTER_OTLP_ENDPOINT is empty. This is the contract Aspire's BlazorHosted / BlazorStandalone ClientServiceDefaults already follow. - Resolve the OTLP path against HostEnvironment.BaseAddress and set per-signal endpoints (v1/logs, v1/metrics, v1/traces) so telemetry flows through the same origin as the WASM page. - Use a fixed serviceInstanceId so all browser tabs report as a single instance in the dashboard. - Drop the redundant AddComponentsMetrics / AddComponentsTracing calls; WebAssemblyHostBuilder registers them automatically on net11+ when Meter.IsSupported is true (now the default). - console.warn on /_blazor/_configuration fetch failures in the standalone JS initializer so the no-gateway case is diagnosable. - Add Run-BlazorWasmServiceDefaults-Locally.ps1 to iterate on the template content the same way every other web template does. Co-authored-by: Copilot <[email protected]> * Bring Components.Gateway up to parity with Aspire BlazorGateway Port the production-readiness pieces from Aspire's Gateway.cs.in into Microsoft.AspNetCore.Components.Gateway so the framework-shipped gateway behaves like the Aspire copy at runtime: - ConfigureOpenTelemetry: OTel logging with formatted message + scopes, metrics for AspNetCore/HttpClient/Runtime, tracing with the app source + AspNetCore/HttpClient instrumentation, anti-feedback-loop filters for /_otlp/ requests and outbound /v1/* calls, and UseOtlpExporter() gated on OTEL_EXPORTER_OTLP_ENDPOINT. - Suppress per-request log noise from StaticAssets, Routing, and the OtlpExporter HttpClient. - HSTS in non-development. - Conditional HTTPS redirect only for document navigations (Sec-Fetch-Dest: document), so OTLP/API fetches are never redirected. - /health and /alive health endpoints in development. - ServiceDiscovery + StandardResilience on HttpClient defaults. Skipped from Aspire's port because 11.0 makes them unnecessary: - Per-app .Add(ep => reb.Order = int.MaxValue) hack — StaticAsset manifests now carry Order (#65975) and NegotiationMatcherPolicy respects routing priority (#65973), and the gateway already uses MapFallbackToFile for the SPA fallback. - File-based-app properties (#:property ...) are net10.0-only. Add OpenTelemetryInstrumentationAspNetCoreVersion to eng/Versions.props and reference the OpenTelemetry + Http.Resilience packages directly from the gateway csproj (it already opts into DisablePackageReferenceRestrictions). Co-authored-by: Copilot <[email protected]> * Move gateway dev-only log filters from code to RunArguments The unconditional Microsoft.AspNetCore.StaticAssets / Routing and System.Net.Http.HttpClient.OtlpExporter filters ported from Aspire's Gateway.cs.in suppressed useful per-request logging in production. Drop them from BlazorGateway.ConfigureOpenTelemetry and instead pass the log-level overrides as --Logging:LogLevel:* command-line arguments from Microsoft.AspNetCore.Components.Gateway.targets, alongside the existing --environment Development argument. The args only take effect when the gateway is launched via 'dotnet run' / IDE F5 through the package's RunCommand, so production hosts (Aspire AppHost, direct 'dotnet blazor-gateway.dll' execution, integration tests) get the full ASP.NET Core defaults. Co-authored-by: Copilot <[email protected]> * Add BlazorGatewayOptions for configurable gateway behavior Replace the hardcoded paths and feature toggles in BlazorGateway with a typed options object bound from the BlazorGateway configuration section. Source-generated configuration binding is implicit once PublishAot is enabled on the gateway, so the call sites stay AOT-clean. - Switch to WebApplication.CreateSlimBuilder for AOT readiness. - Bind BlazorGatewayOptions from the 'BlazorGateway' section. Defaults live as property initializers on the options POCO. - Gate every feature on the bound options: - Hsts.Enabled (only outside Development) - HttpsRedirection.Enabled (Sec-Fetch-Dest: document scope is fixed) - HealthChecks.Enabled + Path/LivenessPath/LivenessTag (only mapped in Development) - Telemetry.Enabled with configurable ExcludePaths / ExcludeOutboundPaths driving the AspNetCore + HttpClient instrumentation filters - HttpClient.ServiceDiscovery / StandardResilience - PathBase - Drop the legacy lowercase 'pathbase' flat config key (replaced by BlazorGateway:PathBase). No backward-compatibility shim. Co-authored-by: Copilot <[email protected]> * Add integration tests for Microsoft.AspNetCore.Components.Gateway Replace the configuration-binding and telemetry-filter unit tests with end-to-end coverage that boots BlazorGateway inside an in-process TestServer and exercises each option through real HTTP traffic. - Refactor BlazorGateway.BuildWebHost to expose an internal overload that accepts a pre-configured WebApplicationBuilder so tests can install UseTestServer before the gateway is built. - Add explicit usings to BlazorGateway.cs so the file compiles outside Microsoft.NET.Sdk.Web's GlobalUsings (the test project consumes the source via Compile Include and uses Microsoft.NET.Sdk). - Drop BlazorGatewayOptionsTests and TelemetryFiltersTests in favor of the new BlazorGatewayTests scenarios. Scenarios covered (14 tests, all passing): HealthChecks_ReturnsOk_InDevelopment_WithDefaultOptions HealthChecks_NotMapped_InProduction HealthChecks_Disabled_ReturnsNotFound_EvenInDevelopment HealthChecks_HonorsCustomPaths Hsts_HeaderEmitted_InProduction_WithDefaultOptions Hsts_HeaderAbsent_InDevelopment Hsts_Disabled_DoesNotEmitHeader_InProduction HttpsRedirection_RedirectsTopLevelNavigations_WithDefaultOptions HttpsRedirection_LeavesProgrammaticRequestsAlone HttpsRedirection_Disabled_DoesNotRedirectDocumentNavigations PathBase_MountsEndpointsUnderConfiguredPrefix ClientApps_ConfigEndpoint_ReturnsConfiguredJson Co-authored-by: Copilot <[email protected]> * Remove inspectUri from Blazor template launchSettings.json The inspectUri property steered F5 debugging through the legacy DOTNET_MODIFIABLE_ASSEMBLIES Mono runtime debug proxy at /_framework/debug/ws-proxy. The .NET 11 WASM debugger no longer needs this hint, so drop it from the WASM and Blazor Web templates. Co-authored-by: Copilot <[email protected]> * Fix Components.TestServer build break from BlazorGateway.cs changes BlazorGateway.cs is compiled into Components.TestServer via a Compile Include, but the new using directives (HealthChecks, OpenTelemetry) introduced by this PR were not available to TestServer: - Add <Reference> entries for Microsoft.AspNetCore.Diagnostics.HealthChecks and Microsoft.Extensions.Diagnostics.HealthChecks to TestServer.csproj. - Add <Reference> entries for all OpenTelemetry and Http.Resilience packages used by BlazorGateway.cs. - Also add Compile Include for BlazorGatewayOptions.cs and TelemetryFilters.cs which are now part of the gateway source. - Register the new packages in eng/Dependencies.props as LatestPackageReference so they can be used via <Reference> in repo projects. Co-authored-by: Copilot <[email protected]> * Add Microsoft.AspNetCore.HttpsPolicy to Components.TestServer BlazorGateway.cs uses UseHsts() and UseHttpsRedirection() which are defined in Microsoft.AspNetCore.HttpsPolicy. Components.TestServer compiles BlazorGateway.cs directly via Compile Include but was missing this reference, causing: CS1061: 'WebApplication' does not contain a definition for 'UseHsts' CS1061: 'IApplicationBuilder' does not contain a definition for 'UseHttpsRedirection' Co-authored-by: Copilot <[email protected]> * Make BlazorGateway liveness check shutdown-aware Mirrors the AspNetCore.HealthChecks.ApplicationStatus behavior used by the YARP container application (inline, no third-party dependency): the 'self' check flips to Unhealthy as soon as IHostApplicationLifetime signals ApplicationStopping, so Kubernetes/ACA stop routing new requests to the pod during the drain window while in-flight requests complete. Co-authored-by: Copilot <[email protected]> * Add BlazorGateway proxy and service-discovery test coverage - Extract shared GatewayTestHelpers (StartGatewayAsync, StartUpstreamAsync) so tests can spin up a real Kestrel-hosted upstream alongside the TestServer-hosted gateway. - Add BlazorGatewayProxyTests covering: no-config 404 fallback, request forwarding, path/query preservation, service-discovery resolution from configuration, and service-discovery disabled behavior. - Only register the YARP service-discovery destination resolver when Gateway:HttpClient:ServiceDiscovery is enabled; otherwise YARP fails unrelated unresolved-service addresses at startup. Co-authored-by: Copilot <[email protected]> * Remove BlazorGateway StandardResilience toggle ConfigureHttpClientDefaults + AddStandardResilienceHandler only applies to IHttpClientFactory clients. YARP's IForwarderHttpClientFactory builds an HttpMessageInvoker directly around a SocketsHttpHandler and bypasses IHttpClientFactory, so the toggle had no observable effect on proxied traffic. The gateway has no other IHttpClientFactory consumers by default, making the option dead code. Remove the toggle, the registration, and the Microsoft.Extensions.Http.Resilience package references from both src and test csproj files. Users who add their own HttpClient consumers to the gateway can call AddStandardResilienceHandler explicitly. Co-authored-by: Copilot <[email protected]> * Make BlazorGateway service discovery unconditional; always map /alive YARP container application treats service discovery as part of the contract (always registers AddServiceDiscovery + AddServiceDiscoveryDestinationResolver on the proxy). Match that: - Remove the Gateway:HttpClient:ServiceDiscovery toggle and the now-empty HttpClientDefaultsOptions class. - Always call AddServiceDiscovery() and AddServiceDiscoveryDestinationResolver(). - Drop the ConfigureHttpClientDefaults block (it only existed to add SD to all IHttpClientFactory clients, but the gateway has no such consumers OOB). Also decouple the /alive liveness probe from /health: /alive is now mapped in all environments (so external orchestrators can probe a running deployment) while /health (the broader aggregate that can leak dependency status) remains dev-only. Tests updated: - ServiceDiscovery_Disabled_LeavesUnresolvedAddress → ServiceDiscovery_UnresolvedAddress_FailsAtRequestTime. - HealthChecks_NotMapped_InProduction → HealthChecks_Liveness_AlwaysMapped_Health_OnlyInDevelopment. Co-authored-by: Copilot <[email protected]> * Incorporate PR #66887: rename shortName to blazorwasm-servicedefaults, add IDE icon Co-authored-by: javiercn <[email protected]> * Update src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWasmServiceDefaults-CSharp/wwwroot/BlazorWasm.ServiceDefaults1.lib.module.js * Add GatewayDisableDefaultLoggingFilters MSBuild toggle for dev logging verbosity Co-authored-by: javiercn <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fix
NegotiationMatcherPolicy<T>.ApplyAsyncinvalidating higher-priority endpoints when a lower-priority endpoint has matching negotiation metadata (e.g.ContentEncodingMetadata).Description
NegotiationMatcherPolicy<T>.ApplyAsyncinvalidates higher-priority endpoints when a lower-priority endpoint has matching negotiation metadata (e.g.ContentEncodingMetadata). Content-encoding negotiation should only disambiguate between representations of the same resource, not override the routing system's priority-based selection across different resources.The Problem
When a catch-all endpoint (e.g.
{**path}) carriesContentEncodingMetadataand shares a DFA path node with a higher-priority literal endpoint that has no encoding metadata,ApplyAsyncincorrectly invalidates the literal endpoint.This happens because
GetEdgescorrectly adds endpoints without encoding metadata to all DFA branches as "parent" endpoints. So the literal endpoint appears in the gzip branch alongside the catch-all's gzip variant. WhenApplyAsyncfinds the catch-all as an encoding match, it blindly invalidates all preceding candidates — including the higher-priority literal endpoint that represents a completely different resource.Root Cause
ApplyAsynchas two invalidation points that don't account for routing priority (CandidateState.Score):Point 1 —
EvaluateCandidatebackward sweep (when a higher-quality encoding match is found):Point 2 — Post-match invalidation (when a candidate doesn't match and a best match already exists):
Neither point checks whether the candidate being invalidated has better routing priority (lower Score) than the one being promoted. A catch-all with
Score=1defeats a literal endpoint withScore=0.The Fix
Candidates are already sorted by ascending
Score(fromDfaMatcherBuilder.ApplyPoliciesusingEndpointComparer). The fix leverages this sorted order:scoreTierStartandcurrentTierScoretracking — The outer loop tracks where the current score tier begins and stores the tier's score value in a separatecurrentTierScorevariable. This is necessary becauseSetValiditybitwise-negatesCandidateState.Scorewhen marking candidates invalid; readingcandidates[scoreTierStart].Scoreafter invalidation would corrupt the tier boundary. Using a dedicatedcurrentTierScorevariable avoids this.Bounded backward sweeps —
EvaluateCandidate's backward sweeps useMath.Max(bestMatchIndex, scoreTierStart)as the start bound, skipping all higher-priority score tiers entirely without per-element Score comparisons.Post-match guard — The post-match invalidation checks
candidates[i].Score < bestMatchScorebefore invalidating, preserving higher-priority endpoints that represent different resources.This ensures content-encoding negotiation only disambiguates within the same score tier (same routing priority), preserving the routing system's priority ordering across different resources.
Tests
ContentEncodingNegotiationMatcherPolicy.ApplyAsynccovering priority preservation scenarios.INodeBuilderPolicyandIEndpointSelectorPolicypaths.Match_ContentEncoding_AcceptQualityWins_WhenBothAcceptAndEndpointQualityDiffer: verifies that when two encoding variants of the same route have the same endpoint quality (tie-breaker), the client'sAccept-Encodingpreference correctly determines the winner. Covers both theINodeBuilderPolicyandIEndpointSelectorPolicy(HasDynamicMetadata == true) paths.✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.