Prevent ValidationsGenerator from emitting open generic type references
Addresses the open-generic emission failure described in #65418. The delegate-variable/parameter resolution gap from the same issue remains tracked by #67122.
One invariant
A symbol whose type tree still contains a type parameter never reaches the generated resolver. TryExtractValidatableType rejects it up front via ContainsTypeParameter, which recurses through type arguments (List<T>, Dictionary<string, T>), array elements (T[]), and containing types (Outer<T>.Inner — no type arguments of its own, but its emitted name carries the outer's parameter).
Fails on main
Both tests fail on main because the generated resolver does not compile (CS0246); VerifyEndpoint re-emits source + generated code, so the tests are exactly that repro:
| Shape | On main | With this change |
|---|---|---|
[ValidatableType] class Wrapper<T> |
emits typeof(global::Wrapper<T>) |
open declaration skipped; Wrapper<string> from the endpoint registers and validates |
[ValidatableType] on Outer<T>.Inner |
emits typeof(global::Outer<T>.Inner) |
skipped via ContainingType recursion; Outer<string>.Inner registers and validates |
Locally: GeneratorTests 55/55, Validation.Tests 134/134.
What this deliberately does not do
An earlier revision also walked ITypeParameterSymbol.ConstraintTypes to discover validatable types reachable through constraints. That is discovery with its own semantics — a declared class constraint (where T : UserRequest) is reachable, but the closed call-site type argument behind a marker-interface constraint (where TRequest : IValidatable) is not, and the latter is what #65418 describes. It has been removed together with its tests and snapshots; if wanted, it should get its own issue with explicit semantics.
🤖 Generated with Claude Code
Thanks for your PR, @@ANcpLua. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.
@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
CI failures are pre-existing infrastructure flakes, unrelated to this change:
RestartAppShouldNotAffectOtherApps— 36.62% historical failure rate (IIS Express test)Cannot create a file when that file already exists— tracked in #61178
Happy to re-run if needed.
Commenter does not have sufficient privileges for PR 65419 in repo dotnet/aspnetcore
Commenter does not have sufficient privileges for PR 65419 in repo dotnet/aspnetcore
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.
@copilot apply changes based on the comments in this thread
@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.
@Youssef1313 rebased onto latest main in 8508a901cb. Upstream commit c472800278 (#66646 — localization support) landed yesterday and rewrote the same TypesParser.cs call sites this PR modifies plus changed the emitter format, so the conflict needed manual resolution:
ITypeParameterSymbolbranch and the newdisplayAttributeSymbol/displayNameAttributeSymbollookups auto-merged (separated by theDeclaredAccessibilityguard).- At both record and regular property paths I placed the
ContainsTypeParameterearly-continueguard before the newGetDisplayInfocalls — a property whose type is an unresolved type parameter is now skipped before computing display info that would only be discarded. - The two snapshots owned by this PR (
CanValidateOpenTypeParameterReachableThroughConstraint,CanValidateTypesWithGenericBaseClass) were regenerated against the new emitter rather than hand-merged. The bug witness is intact: the resolver forCanValidateOpenTypeParameterReachableThroughConstraintstill emitstypeof(global::UserRequest)and itsName/Agemember entries, which is the silent-skip half of #65418 — without theITypeParameterSymbolbranch the resolver body for that type is empty.
Local verification on the merged tree: dotnet test src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests reports 45 / 45 passed (Debug, net11.0) — the 28 pre-existing generator tests + the 15 new DisplayName* tests from #66646 + the 2 type-parameter tests added by this PR. Final PR scope vs current origin/main is 4 files, +1046 / -0.
The scenarios tested here also look different from what the issue original reports.
The scenarios tested here also look different from what the issue original reports.
You're right, and I dug into why: the issue's literal repro passes the handler as a Func<TRequest, ...> parameter (endpoints.MapPost(pattern, handler)), and that shape never reaches the code this PR touches — ResolveMethodFromOperation has no case for parameter/local delegate references, so such handlers are silently skipped today even for non-generic handlers. That's a separate pre-existing bug in shared RDG source; I've filed #67122 for it rather than growing this PR's scope.
This PR fixes the ITypeParameterSymbol layer that the resolver can reach: discovery through constraints for generic mappers with inline lambdas (CanValidateOpenTypeParameterReachableThroughConstraint), and the typeof(T) leak that breaks the build for any discovered CRTP model (CanValidateTypesWithGenericBaseClass, DoesNotEmitTypeofForTypeParameterMembersReachedThroughConstraint). I've added a comment to #65418 clarifying the two distinct root causes.
@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.
Pushed 2e56d8c4e3 hardening the type-level guard from 10b4e3e2cb against two adjacent shapes:
ContainsTypeParameternow recurses intoContainingType. A non-generic type nested inside an open generic —[ValidatableType]onOuter<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 closedOuter<string>.Innerendpoint parameter keeps registering and validating end-to-end (DoesNotEmitTypeofForValidatableTypeNestedInOpenGeneric).DoesNotEmitTypeofForOpenGenericConstraintWithConcreteMemberspins that the guard also covers the constraint-walk entry point:where T : Node<T>whereNode<TSelf>has a concrete[Required]member — the variant that stays non-empty after the member-level guards and previously registeredglobal::Node<T>. (The existingDoesNotEmitTypeofForTypeParameterMembersReachedThroughConstraintonly 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.
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).
@Youssef1313 checking back in on this one. Both items from your review are done:
- Rebased on latest main (branch tip merges current
mainas of today). - Test that fails on main:
CanValidateOpenTypeParameterReachableThroughConstraintputs theMapPostinside a genericMapValidated<T>() where T : UserRequest, so the generator sees an open type parameter. Onmain,UserRequestis never discovered and the snapshot is missing the 21-linetypeof(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.
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.
@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.