Skip to content

Include parameter default value in RDG endpoint comparison - #69752

Merged
Youssef1313 merged 1 commit into
dotnet:mainfrom
AnsElgyarDev:fix-rdg-default-value-grouping
Nov 20, 2026
Merged

Youssef1313 merged 1 commit into
dotnet:mainfrom
AnsElgyarDev:fix-rdg-default-value-grouping

Conversation

@AnsElgyarDev

@AnsElgyarDev AnsElgyarDev commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor
  • 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. (not applicable here)
  • There's an open issue for the PR that you are making.

Include parameter default value in RDG endpoint comparison

Endpoints that differ only by a parameter's default value are no longer grouped under one interceptor.

Description

Endpoints such as (int page = 1) and (int page = 2) were treated as equal and grouped under a single interceptor. The interceptor casts the handler to the first lambda's delegate type, so the second endpoint threw InvalidCastException at startup.

EndpointParameter.Equals and GetHashCode did not include HasDefaultValue and DefaultValue, although the emitted code depends on them (the Cast delegate type captures default values). This PR includes both in the comparison.

Tests

Added MapAction_QueryParam_SharedDelegateSignature_PreservesDefaultValue, which maps two endpoints differing only by default value and verifies each returns its own default (page 1 / page 2).

  • Without the fix, the new test fails with the same InvalidCastException described in the issue.
  • With the fix, it passes, and the existing generator tests (Microsoft.AspNetCore.Http.Generators.Tests, 1658 tests) pass locally, including after rebasing on the latest main.
  • I also reproduced the bug manually with a standalone project on .NET SDK 10.0.301.

Note on the backport: on release/10.0 this change would not be enough on its own, since endpoints are grouped there through a separate SignatureEquals rather than Equals/GetHashCode. #69676 is a request to backport #67591, still open. Happy to look at a release/10.0 change if the team wants one.

AI assistance: I used Claude (Anthropic) to help analyze the issue and to review and draft the change and test. I reviewed the code and ran all the tests locally.

Fixes #69675

Endpoints whose handlers differ only by a parameter's default value (for example (int page = 1) and (int page = 2)) were treated as equal and grouped under a single interceptor. The interceptor casts the handler to the first endpoint's delegate type, so the second endpoint threw an InvalidCastException at startup.

Compare HasDefaultValue and DefaultValue in EndpointParameter.Equals and GetHashCode so these endpoints get separate interceptors.

Fixes dotnet#69675
@github-actions github-actions Bot added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions label Oct 9, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 9, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @AnsElgyarDev. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@AnsElgyarDev

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree

@AdCodicem AdCodicem left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I filed #69675 and tried this branch at @AnsElgyarDev's request; the results against the repro are in the issue (#69675 (comment)). I am the reporter, not a maintainer, so these are notes, and none of them is blocking.

On this branch, the new test fails without the change to EndpointParameter.cs with the exception of the issue (its CompileTimeCreationTests variant) and passes with it, and Microsoft.AspNetCore.Http.Generators.Tests is 1658/1658 here too.

On the backport sentence of the description. The change to EndpointParameter.cs applies cleanly to release/11.0. On release/10.0 it would not be enough: #67591 is not in that branch, and endpoints are grouped there through a separate SignatureEquals, not through Equals (EndpointParameter.cs#L604-L611, called from Endpoint.cs#L125-L131):

// release/10.0
public bool SignatureEquals(object obj) =>
    obj is EndpointParameter other &&
    SymbolEqualityComparer.IncludeNullability.Equals(other.Type, Type) &&
    other.SymbolName == SymbolName &&
    other.KeyedServiceKey == KeyedServiceKey;

Equals and GetHashCode could take these four lines there and (int page = 1) and (int page = 2) would still share an interceptor. Also, #69676 is my request to backport #67591, still open, rather than a backport.

Testing assisted by Claude (Anthropic); I reviewed the results.

other.LookupName == LookupName &&
other.Ordinal == Ordinal &&
other.IsOptional == IsOptional &&
other.HasDefaultValue == HasDefaultValue &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A note rather than a request: as far as I can tell, this line never decides anything, because DefaultValue already says whether there is a default. GetDefaultValueString returns the bare null only for a parameter without one, and writes an explicit null as default:

(int? p)              // DefaultValue: null       (no default)
(int? p = null)       // DefaultValue: default
(string? s = null)    // DefaultValue: default
(string s = "null")   // DefaultValue: "null"     (quoted)

I checked it by building the generator without the two HasDefaultValue lines: on 175 Map calls, pairs like the first two above included, the generated file was byte-identical to this branch's. The line is harmless and reads well next to IsOptional, so keeping it is fine; it only means that no test can tell it from its absence.

other.Ordinal == Ordinal &&
other.IsOptional == IsOptional &&
other.HasDefaultValue == HasDefaultValue &&
other.DefaultValue == DefaultValue &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One arrangement that works today stops working with this line. It is contrived, and the real defect is older than this PR, but it is a change of behaviour, so it seems worth knowing:

static string B(int? p = null) => $"b {p ?? -1}";

app.MapGet("/a", (int? p) => $"a {p ?? -1}");
app.MapGet("/b", (Func<int?, string>)B);

Before, /a and /b compare equal and share one interceptor, whose cast to Func<int?, string> happens to fit both handlers. After, /b gets its own interceptor, whose cast type is rebuilt from the method (arg0 = default, an anonymous delegate type), while the handler passed is a Func:

System.InvalidCastException : Unable to cast object of type 'System.Func`2[System.Nullable`1[System.Int32],System.String]' to type '<>f__AnonymousDelegate0`2[System.Nullable`1[System.Int32],System.String]'.

Written as a test next to yours, with these three lines as its source, it passes at the base of this PR and fails at its head (CompileTimeCreationTests). /b alone already throws the same way with the 11.0 RC1 generator: the cause is that the cast is rebuilt from the method rather than from the delegate passed, which this PR only stops hiding. I filed it as #69755.

Comment on lines +89 to +90
// Otherwise, the second endpoint reuses the first endpoint's delegate type and default.
var source = """

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other shape of the same bug is a default against no default. This PR fixes it too, but the test does not cover it:

[Fact]
public async Task MapAction_QueryParam_SharedDelegateSignature_PreservesDefaultValuePresence()
{
    // Same parameter, with and without a default value: the handlers have different delegate types.
    var source = """
app.MapGet("/a", (int? page) => $"a {page ?? -1}");
app.MapGet("/b", (int? page = null) => $"b {page ?? -1}");
""";
    var (_, compilation) = await RunGeneratorAsync(source);
    var endpoints = GetEndpointsFromCompilation(compilation);

    Assert.Equal(2, endpoints.Length);

    var httpContextA = CreateHttpContext();
    await endpoints[0].RequestDelegate(httpContextA);
    await VerifyResponseBodyAsync(httpContextA, "a -1");

    var httpContextB = CreateHttpContext();
    await endpoints[1].RequestDelegate(httpContextB);
    await VerifyResponseBodyAsync(httpContextB, "b -1");
}

I ran it on this branch. Without the change to EndpointParameter.cs, its CompileTimeCreationTests variant fails with InvalidCastException (<>f__AnonymousDelegate02[System.Nullable1[System.Int32],System.String] to System.Func2[System.Nullable1[System.Int32],System.String]); with the change it passes.

}

[Fact]
public async Task MapAction_QueryParam_SharedDelegateSignature_PreservesDefaultValue()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bug is not always an exception, which may be worth a test of its own, since it does not go through the cast. 1.0m and 1.00m are equal constants, so both lambdas get the same delegate type and nothing throws; the second endpoint simply answers with the first one's default:

[Fact]
public async Task MapAction_QueryParam_SharedDelegateSignature_PreservesDecimalDefaultScale()
{
    // 1.0m and 1.00m are equal constants, so both lambdas have the same delegate type and nothing throws:
    // only the fallback value tells the two endpoints apart.
    var source = """
app.MapGet("/a", (decimal rate = 1.0m) => rate.ToString(System.Globalization.CultureInfo.InvariantCulture));
app.MapGet("/b", (decimal rate = 1.00m) => rate.ToString(System.Globalization.CultureInfo.InvariantCulture));
""";
    var (_, compilation) = await RunGeneratorAsync(source);
    var endpoints = GetEndpointsFromCompilation(compilation);

    Assert.Equal(2, endpoints.Length);

    var httpContextA = CreateHttpContext();
    await endpoints[0].RequestDelegate(httpContextA);
    await VerifyResponseBodyAsync(httpContextA, "1.0");

    var httpContextB = CreateHttpContext();
    await endpoints[1].RequestDelegate(httpContextB);
    await VerifyResponseBodyAsync(httpContextB, "1.00");
}

I ran it on this branch as well. Without the change to EndpointParameter.cs, its CompileTimeCreationTests variant fails on the last assertion (Expected: "1.00", Actual: "1.0"); with the change it passes.

@AnsElgyarDev

Copy link
Copy Markdown
Contributor Author

Thanks @AdCodicem for testing this so thoroughly and for the notes. I've corrected the backport sentence in the description. I'm keeping the HasDefaultValue line for symmetry with IsOptional, but happy to drop it if the team prefers. I'll leave the extra tests and #69755 to the maintainers' preference, and can add the tests you suggested if they want them in this PR.

@Youssef1313 Youssef1313 added area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc and removed area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions labels Oct 12, 2026
@Youssef1313
Youssef1313 requested review from AdCodicem and a balanced review from Copilot and removed request for AdCodicem October 12, 2026 08:37

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.

🟢 Approval recommended

The focused equality fix matches generated delegate semantics and has faithful regression coverage.

0 open findings

What changed in this PR

Ensures RDG endpoint grouping distinguishes handlers with different parameter defaults, preventing incompatible delegate reuse.

Changes:

  • Adds default-value presence and value to parameter equality and hashing.
  • Adds regression coverage for endpoints with differing defaults.
File Description
EndpointParameter.cs Includes parameter defaults in endpoint comparison keys.
RequestDelegateCreationTests.QueryParameters.cs Verifies each endpoint preserves its own default.

🧠 Review effort: Balanced


💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@AdCodicem AdCodicem left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resolves the issue I created

@AnsElgyarDev

Copy link
Copy Markdown
Contributor Author

Hi @Youssef1313, thanks for the review and approval! Just checking in: is there anything else needed from my side before this can be merged? Also, it looks like 3 workflows are still awaiting maintainer approval. Happy to make any changes if needed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Oct 23, 2026
@AnsElgyarDev AnsElgyarDev reopened this Oct 23, 2026
@github-actions github-actions Bot added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions label Oct 23, 2026
@AnsElgyarDev

Copy link
Copy Markdown
Contributor Author

After close/reopen, the only failures are the known-flaky Blazor E2E tests (aspnetcore-components-e2e), unrelated to this change. All other checks pass and this has 2 approvals. Could someone re-run the failed jobs or let me know if anything else is needed on my side?

@Youssef1313

Copy link
Copy Markdown
Member

/azp run aspnetcore-components-e2e

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@Youssef1313
Youssef1313 enabled auto-merge (squash) November 19, 2026 14:28
@AnsElgyarDev

Copy link
Copy Markdown
Contributor Author

The only failing test is VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements , which Build Analysis reports at a ~10% failure rate, so it looks unrelated to this change. Could someone take a look when you have a moment? Thanks!

@Youssef1313

Copy link
Copy Markdown
Member

/ba-g unrelated failure.

@Youssef1313
Youssef1313 merged commit 00560e2 into dotnet:main Nov 20, 2026
60 of 61 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 5%

No docs needed: internal bug fix to RDG endpoint grouping so endpoints differing only by parameter default values work correctly.

Documentation surfaces considered

  • Conceptual article: Not required — Internal source generator comparison fix in EndpointParameter.cs; no new public API, option, or documented behavior.
  • Migration guidance: Not required — No user action needed when upgrading; it fixes a startup InvalidCastException.
  • Breaking change: Not required — No previously working code breaks; the fix only makes previously failing scenarios work.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 8bbab3fb Deployed Nov 20, 2026 by Youssef1313 via conclusion #407
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions community-contribution Indicates that the PR has been added by a community member pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Request Delegate Generator: handlers that differ only by a parameter's default value share one interceptor, InvalidCastException at startup

4 participants