Skip to content

Add ASP0040 for [ValidatableType] on open generics; guard generator against emitting open generic typeofs - #65419

Open
ANcpLua wants to merge 9 commits into
dotnet:mainfrom
ANcpLua:fix/validations-generator-type-parameter-handling
Open

ANcpLua wants to merge 9 commits into
dotnet:mainfrom
ANcpLua:fix/validations-generator-type-parameter-handling

Conversation

@ANcpLua

@ANcpLua ANcpLua commented Feb 13, 2026 •

Copy link
Copy Markdown

Fixes #65418

The validations source generator emits a non-generic ValidatableInfoResolver, so every typeof(...) it writes must name a fully closed type. Today an open generic can reach emission and produce typeof(Wrapper<T>) / typeof(T): CS0246 in generated code the user can't act on.

Following the discussion with @Youssef1313 on #65418, this PR now has two halves:

1. ASP0040 analyzer diagnostic (author-facing)

[ValidatableType] on a type whose type tree still contains a type parameter (its own, as in Wrapper<T>, or an enclosing type's, as in Outer<T>.Inner) can never be handled statically. Instead of silently skipping, the analyzer introduced in #67993 now reports ASP0040 at the declaration:

The type '{0}' is marked with [ValidatableType] but declares type parameters that cannot be resolved statically. The generated validation code can only reference closed types, so it is skipped by the validation source generator. Validation still applies to closed constructions of this type used as endpoint parameters.

The check reuses the generator's ContainsTypeParameter walk, so the diagnostic and the generator's behaviour cannot drift apart. ID and wording are placeholders (happy to rename in review), and severity is Warning to stay consistent with ASP0033-0038; if you'd rather make this one an error, as your #65418 comment suggests, I'm happy to bump it.

2. Emit-time guard (safety net)

TryExtractValidatableType skips any symbol whose type tree contains a type parameter. This covers shapes no attribute-based analyzer can see: since #67821 resolves delegate-typed handler parameters, a generic registration helper (MapCommand<TRequest> forwarding Func<Command<TRequest>, IResult> to MapPost) hands the parser the open Command<TRequest>, which passes the accessibility check and, without the guard, reaches emission as typeof(global::Command<TRequest>). With the guard, such shapes degrade to "no validation" instead of a build break; a regression test covers the delegate-parameter shape end to end.

Behaviour table

Shape Before After
[ValidatableType] on Wrapper<T> CS0246 in generated code ASP0040 warning, no broken emit
[ValidatableType] on Outer<T>.Inner CS0246 in generated code ASP0040 warning, no broken emit
Wrapper<string> endpoint parameter (closed) works works, generated output byte-identical
Func<Command<TRequest>, ...> via generic helper (post-#67821) CS0246 in generated code fail-closed skip, endpoint runs

Closed constructions at endpoints are covered by existing tests; the two pre-existing snapshots only changed by main's localization emitter update (FindLocalizedTemplate), regenerated in a separate commit.

Copilot AI review requested due to automatic review settings February 13, 2026 09:51
@github-actions github-actions Bot added the needs-area-label Used by the dotnet-issue-labeler to label those issues which couldn't be triaged automatically label Feb 13, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Feb 13, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

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.

Pull request overview

This PR fixes a critical bug in the ValidationsGenerator source generator where generic type parameters (like TRequest from a generic endpoint extension method) were either silently skipped or caused compilation errors when they leaked into generated typeof() expressions. The fix adds type parameter handling to discover validatable types through constraint types, while preventing type parameters from appearing in emitted code.

Changes:

  • Added ITypeParameterSymbol branch in TryExtractValidatableType to walk constraint types and discover validatable types
  • Added ContainsTypeParameter guards in both record and regular property extraction paths to prevent emitting typeof(T) expressions
  • Added ContainsTypeParameter helper method to recursively detect type parameters in type trees

@martincostello martincostello added area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc feature-validation Issues related to model validation in minimal and controller-based APIs and removed needs-area-label Used by the dotnet-issue-labeler to label those issues which couldn't be triaged automatically labels Feb 13, 2026
@ANcpLua

ANcpLua commented Feb 13, 2026

Copy link
Copy Markdown
Author

@ANcpLua please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"

Contributor License Agreement

@dotnet-policy-service agree

@ANcpLua

ANcpLua commented Feb 13, 2026 •

Copy link
Copy Markdown
Author

CI failures are pre-existing infrastructure flakes, unrelated to this change:

Happy to re-run if needed.

@azure-pipelines

Copy link
Copy Markdown
Commenter does not have sufficient privileges for PR 65419 in repo dotnet/aspnetcore

1 similar comment
@azure-pipelines

Copy link
Copy Markdown
Commenter does not have sufficient privileges for PR 65419 in repo dotnet/aspnetcore

@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.

@Youssef1313 Youssef1313 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The added test seems to already be passing without the changes.

@ANcpLua Can you please rebase your branch on latest main, and ensure to create a test case that fails on main to better demonstrate the issue?

@ANcpLua

ANcpLua commented May 7, 2026

Copy link
Copy Markdown
Author

@copilot apply changes based on the comments in this thread

@ANcpLua

ANcpLua commented May 13, 2026 •

Copy link
Copy Markdown
Author

@Youssef1313 thanks for the review — pushed fdf8bf6 and a58595c to address both points.

1. Linux x64 / Source-Build CS1615

The most recent merge from main pulled in b58523d4c9 (#66373, "Cleanup ValidationsGenerator for better incrementality"), which dropped the ref from TryExtractValidatableType's HashSet<ValidatableType> and List<ITypeSymbol> parameters. The new ITypeParameterSymbol branch in this PR was still passing them with ref, so the post-merge build failed with CS1615 at ValidationsGenerator.TypesParser.cs(92,99) and (92,121). Fixed by dropping the two ref keywords in the new branch.

2. Test that fails on main

You were right that CanValidateTypesWithGenericBaseClass did not exercise the bug — the parameter at the MapPost call site there is the concrete CreateOrderCommand, so the generator only ever sees the closed CommandBase<CreateOrderCommand> and TSelf is bound by the time it reaches the emitter. The new test CanValidateOpenTypeParameterReachableThroughConstraint puts the MapPost call inside a generic endpoint extension:

public static RouteHandlerBuilder MapValidated<T>(this IEndpointRouteBuilder endpoints, string pattern)
    where T : UserRequest
    => endpoints.MapPost(pattern, (T req) => Results.Ok());

The inner MapPost is the call site the generator inspects, and the delegate parameter resolves to an open ITypeParameterSymbol. On main T hits the DeclaredAccessibility is not Accessibility.Public guard (NotApplicable for type parameters), TryExtractValidatableType returns false, and the concrete constraint UserRequest is never discovered — even though it carries [Required] and [Range] attributes. Running the new test against main produces a snapshot diff with exactly the 21 lines that should describe UserRequest missing:

+            if (type == typeof(global::UserRequest))
+            {
+                validatableInfo = new GeneratedValidatableTypeInfo(
+                    type: typeof(global::UserRequest),
+                    members: [
+                        new GeneratedValidatablePropertyInfo(
+                            containingType: typeof(global::UserRequest),
+                            propertyType: typeof(string),
+                            name: "Name",
+                            displayName: "Name"
+                        ),
+                        ... (Age member) ...
+                    ]
+                );
+                return true;
+            }

With the fix the ITypeParameterSymbol branch walks typeParam.ConstraintTypes, recurses into UserRequest, and emits the expected resolver entry. I verified this end-to-end locally by reverting just TypesParser.cs to main, rebuilding, and re-running the test — 0 occurrences of typeof(global::UserRequest) in the received snapshot vs. the 6 occurrences in the verified snapshot.

Runtime endpoint behavior is identical fixed-vs-unfixed because the framework falls back to reflection-based validation when the static resolver returns false, so the snapshot is the only deterministic signal. The runtime VerifyEndpoint assertions in the new test are kept as end-to-end regression coverage for the validation pipeline; the bug witness is the snapshot.

Locally dotnet test against Microsoft.Extensions.Validation.GeneratorTests is 30/30 passed with the fix and 1/30 failed (just this test) against main.

@ANcpLua
ANcpLua requested review from Youssef1313 and Copilot May 15, 2026 03:34
@ANcpLua

ANcpLua commented Jun 11, 2026

Copy link
Copy Markdown
Author

@Youssef1313 All review threads now have replies, and the unrelated marketplace.json change is gone — the PR touches only the 5 Validation files. The May 30 scenarios point is addressed above (root-cause split, with the delegate-parameter resolution gap tracked in #67122).

Re-ran validation via close/reopen: zero failing tests on the rerun. The remaining red legs are infrastructure only — macOS arm64 matched to known issues dotnet/dnceng#1883 / dotnet/dnceng#3008, and the two Helix x64 subsets hit 240-minute agent timeouts (queue congestion; no test results, nothing failed). I don't have /azp rights, so if a clean Build Analysis matters for merge I'd appreciate a rerun of the timed-out jobs whenever convenient.

Ready for another look — thanks for the patience on this one.

@ANcpLua

ANcpLua commented Jul 4, 2026

Copy link
Copy Markdown
Author

Pushed 2e56d8c4e3 hardening the type-level guard from 10b4e3e2cb against two adjacent shapes:

  • ContainsTypeParameter now recurses into ContainingType. A non-generic type nested inside an open generic — [ValidatableType] on Outer<T>.Inner — has no type arguments of its own, so the guard missed it while the emitted FQN still carried the outer's parameter: typeof(global::Outer<T>.Inner) → CS0246. Witnessed in the generator test harness before the fix (emit step failed with CS0246 ×3); the closed Outer<string>.Inner endpoint parameter keeps registering and validating end-to-end (DoesNotEmitTypeofForValidatableTypeNestedInOpenGeneric).
  • DoesNotEmitTypeofForOpenGenericConstraintWithConcreteMembers pins that the guard also covers the constraint-walk entry point: where T : Node<T> where Node<TSelf> has a concrete [Required] member — the variant that stays non-empty after the member-level guards and previously registered global::Node<T>. (The existing DoesNotEmitTypeofForTypeParameterMembersReachedThroughConstraint only covers the degenerate all-T-members variant that falls out via the empty-members prune.)

Local: GeneratorTests 49/49, Validation.Tests 81/81.

One deliberate non-goal, flagged for review: skipping registration makes [ValidatableType] on an open generic a silent no-op (closed constructions still validate via endpoint discovery). If a generator diagnostic for that annotation is wanted, I'd propose it as a separate change since it adds a public diagnostic ID.

@ANcpLua

ANcpLua commented Jul 4, 2026

Copy link
Copy Markdown
Author

Merged latest main in 0a2afd582e. The conflict was again in TypesParser.cs: upstream's file-local type skip (IsFileLocal) landed in the same region as this PR's guards. Resolution keeps all checks in order — type-parameter constraint walk, ContainsTypeParameter guard, file-local skip, then the upstream-relaxed accessibility check that now admits internal types.

Also on the branch since the last review: a type-level guard extension covering the [ValidatableType]-on-open-generic shape from the new repro in #65418 (10b4e3e2cb), and containing-type recursion so a non-generic type nested inside an open generic (Outer<T>.Inner) doesn't leak the outer parameter into typeof() (2e56d8c4e3).

All six PR-owned snapshots were regenerated against the new emitter (async validation, IValidatableInfo split, globalized type names); bug witnesses are intact — the constraint-walk resolver still registers global::UserRequest, the guard tests contain no open-generic typeof emissions, and closed constructions (Wrapper<string>, Outer<string>.Inner, CRTP bases) register normally. Local verification on the merged tree: Microsoft.Extensions.Validation.GeneratorTests 58/58 passed (Debug, net11.0).

@ANcpLua ANcpLua left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Sorry, these replies were sitting in a pending review the whole time. All threads answered, two resolved. Let me know what you think on the constraint walking point. Can split that part out if you prefer.

@ANcpLua
ANcpLua requested a review from Youssef1313 July 7, 2026 16:24
@ANcpLua

ANcpLua commented Jul 16, 2026

Copy link
Copy Markdown
Author

@Youssef1313 checking back in on this one. Both items from your review are done:

  • Rebased on latest main (branch tip merges current main as of today).
  • Test that fails on main: CanValidateOpenTypeParameterReachableThroughConstraint puts the MapPost inside a generic MapValidated<T>() where T : UserRequest, so the generator sees an open type parameter. On main, UserRequest is never discovered and the snapshot is missing the 21-line typeof(global::UserRequest) resolver block; the fix emits it.

All four threads are resolved. The one thing I do not have your read on is the constraint-walking half (your :90 question). The core bug is that the generator emits typeof(TSelf), which does not compile, so users get build errors inside generated code they cannot edit. I am happy to split the constraint-discovery enhancement into a follow-up PR if you would prefer to merge just the correctness fix first. Let me know which you would like.

@ANcpLua
ANcpLua force-pushed the fix/validations-generator-type-parameter-handling branch 2 times, most recently from 592768b to 7281d6b Compare July 30, 2026 18:46
@ANcpLua ANcpLua changed the title Fix ValidationsGenerator ITypeParameterSymbol handling Prevent ValidationsGenerator from emitting open generic type references Jul 30, 2026
@ANcpLua

ANcpLua commented Jul 30, 2026

Copy link
Copy Markdown
Author

I've cut this PR down to the one thing that is provably broken, redeeming the split I offered in July.

The previous revision bundled two changes — the emission-safety fix and constraint-walking discovery — and that mix is what stalled review. The criticism was fair: walking ConstraintTypes can surface where T : UserRequest, but it cannot recover the closed call-site type argument behind where TRequest : IValidatable, which is the scenario #65418 actually describes. Discovery is a design decision, not a bug fix, so it's gone.

What remains is one early guard and two tests that fail on main with CS0246 in the generated code. The member-level guards from the earlier revision are gone too: with the type-level guard applied up front they were unreachable — members of a closed construction are fully substituted — and the test suites confirm it (GeneratorTests 55/55, Validation.Tests 134/134).

Net: 4 files instead of 8, +57 lines of generator code, no behavior change for any closed type. Retitled accordingly; this addresses the open-generic emission failure in #65418 rather than closing the whole issue.

ANcpLua and others added 2 commits July 30, 2026 20:56
The generated resolver is non-generic: every typeof(...) it emits must
name a fully closed type. TryExtractValidatableType now rejects any
symbol whose type tree still contains a type parameter — bare T, open
Wrapper<T>, T[] and List<T> through type arguments, and Outer<T>.Inner
through its containing type. On main these shapes emit
typeof(global::Wrapper<T>) / typeof(T) and the generated code fails to
compile (CS0246).

Co-Authored-By: Claude Fable 5 <[email protected]>
Both fail on main with CS0246 in the generated resolver:
[ValidatableType] on an open Wrapper<T>, and [ValidatableType] on
Outer<T>.Inner whose emitted name carries the outer's parameter. The
closed constructions Wrapper<string> and Outer<string>.Inner keep
registering and validating.

Co-Authored-By: Claude Fable 5 <[email protected]>
@ANcpLua
ANcpLua force-pushed the fix/validations-generator-type-parameter-handling branch from 7281d6b to 2608a57 Compare July 30, 2026 18:56
@danroth27 danroth27 modified the milestone: 11.0-rc1 Jul 31, 2026
ANcpLua and others added 4 commits August 2, 2026 05:08
…main

Main replaced the MessageKeyProvider lookup with the convention-based
FindLocalizedTemplate/GetKeySegment emission; no registration changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Per the dotnet#65418 discussion, the silent skip becomes an author-facing
diagnostic: ASP0039 reports at the declaration when a [ValidatableType]
type tree still contains a type parameter (its own, or an enclosing
type's). Lives in the ValidationsDiagnosticAnalyzer introduced in dotnet#67993
and reuses the generator's ContainsTypeParameter walk so the analyzer
and the emit-time guard cannot drift apart. ID and wording are
placeholders for review.

The guard itself stays as the safety net for shapes no attribute-based
analyzer can see: post-dotnet#67821 a generic registration helper forwarding
Func<Command<TRequest>, IResult> to MapPost hands the parser the open
Command<TRequest>, which passes the accessibility check and would reach
emission as typeof(global::Command<TRequest>). A regression test covers
that shape end to end.

Co-Authored-By: Claude Fable 5 <[email protected]>
@ANcpLua
ANcpLua requested a review from SamMonoRT as a code owner August 20, 2026 23:10
@ANcpLua ANcpLua changed the title Prevent ValidationsGenerator from emitting open generic type references Add ASP0039 for [ValidatableType] on open generics; guard generator against emitting open generic typeofs Aug 20, 2026
A diagnostic that exists to end the silent skip should not call the
skip silent once it fires; the message now says "skipped by the
validation source generator", matching ASP0035's phrasing without the
contradiction. Also normalizes punctuation in nearby comments.

Co-Authored-By: Claude Fable 5 <[email protected]>
@ANcpLua

ANcpLua commented Aug 21, 2026

Copy link
Copy Markdown
Author

@Youssef1313 rewrote as discussed on #65418: ASP0039 in the analyzer from #67993 (reuses the generator's ContainsTypeParameter walk so diagnostic and guard cannot drift), guard kept as emit-time safety net, regression test for the delegate-parameter shape included. Severity is Warning for consistency with ASP0033-0038; happy to bump to an error if you prefer. PTAL.

@ANcpLua ANcpLua left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

viewed

ASP0039 is now used on main by the experimental passkey endpoints APIs.
…validations-generator-type-parameter-handling

# Conflicts:
#	docs/list-of-diagnostics.md
@ANcpLua ANcpLua changed the title Add ASP0039 for [ValidatableType] on open generics; guard generator against emitting open generic typeofs Add ASP0040 for [ValidatableType] on open generics; guard generator against emitting open generic typeofs Sep 2, 2026

This branch has not been deployed

No deployments
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 community-contribution Indicates that the PR has been added by a community member feature-validation Issues related to model validation in minimal and controller-based APIs 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.

ValidationsGenerator crashes on generic type parameters (ITypeParameterSymbol)

5 participants