Skip to content

Add MEV analyzers - #67993

Merged
Youssef1313 merged 44 commits into
mainfrom
dev/ygerges/mev-analyzers
Aug 12, 2026
Merged

Youssef1313 merged 44 commits into
mainfrom
dev/ygerges/mev-analyzers

Conversation

@Youssef1313

@Youssef1313 Youssef1313 commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Related to #64435

This PR adds an analyzer with 3 descriptors.

ASP0033: [ValidatableType] is applied to an inaccessible type

Whenever [ValidatableType] attribute is applied to a file-local type or a nested private type, this diagnostic produces a warning. The source-generated code won't be able to generate a resolver for such type.


ASP0034: Endpoint parameter type is inaccessible from generated code

Similar to ASP0033, but for endpoint parameters.


ASP0035: Validatable property or its type is not accessible

If a property is internal, we don't handle it today in the generation. In addition, if the property is public but its type isn't accessible by the same rule governing ASP0033 and ASP0034, a warning is also produced for the property.


ASP0036: [ValidatableType] cannot be used in generated code

If [ValidatableType] is used in generated code. Our source generator won't be able to see them.


ASP0037: [ValidatableType] should not be used without a call to 'AddValidation'

If [ValidatableType] is used without a call to AddValidation. Our source generator will do nothing and the attribute has no effect.

@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch 3 times, most recently from 4f60a59 to afcb90e Compare July 25, 2026 09:24
@Youssef1313
Youssef1313 marked this pull request as ready for review July 25, 2026 10:12
Copilot AI review requested due to automatic review settings July 25, 2026 10:12
@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch from 606d200 to c277059 Compare July 25, 2026 10:12
@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch from c277059 to defb55b Compare July 25, 2026 10:13

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

Adds a new ValidationsDiagnosticAnalyzer (ASP0031–ASP0034) intended to warn when the validation source generator would otherwise silently skip validation due to accessibility/graph issues, plus new generator test coverage and diagnostic documentation updates.

Changes:

  • Introduces ValidationsDiagnosticAnalyzer with four new diagnostics (ASP0031–ASP0034) and release-tracking files.
  • Adds analyzer-focused test infrastructure and new tests validating diagnostic behavior.
  • Updates the public diagnostics list to include the new ASP0031–ASP0034 warnings.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGeneratorTestBase.cs Refactors metadata reference setup and adds helper to run the analyzer and collect diagnostics.
src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGenerator.Analyzer.cs Adds analyzer unit tests validating ASP0031/33/34 scenarios.
src/Validation/gen/Microsoft.Extensions.Validation.ValidationsGenerator.csproj Adds analyzer release tracking files as AdditionalFiles.
src/Validation/gen/Analyzers/ValidationsDiagnosticAnalyzer.cs Implements the new MEV/validation diagnostics analyzer (ASP0031–ASP0034).
src/Validation/gen/AnalyzerReleases.Unshipped.md Declares the new unshipped analyzer rules for release tracking.
src/Validation/gen/AnalyzerReleases.Shipped.md Initializes shipped analyzer releases tracking file.
docs/list-of-diagnostics.md Documents the new ASP0031–ASP0034 diagnostics.

Comment thread docs/list-of-diagnostics.md Resolved
@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch 3 times, most recently from 639b91e to 05f3d9e Compare July 25, 2026 10:20
@Youssef1313
Youssef1313 requested review from a team and wtgodbe as code owners July 25, 2026 10:20
@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch 2 times, most recently from f03bbe9 to 5c3e45c Compare July 25, 2026 15:06
@Youssef1313 Youssef1313 self-assigned this Jul 27, 2026
@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch from 5c3e45c to 24f994e Compare August 3, 2026 09:58
@Youssef1313
Youssef1313 force-pushed the dev/ygerges/mev-analyzers branch from 2aae6f7 to 4155328 Compare August 4, 2026 13:33
|| property.IsStatic
|| property.IsWriteOnly
|| property.GetMethod is null
|| property.GetMethod.DeclaredAccessibility is not Accessibility.Public

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.

ASP0035 currently cannot fire for a non-public property, so the rule is effectively dead code.

Accessors without an explicit modifier inherit the property's declared accessibility, so for internal TheChild Child { get; } Roslyn reports GetMethod.DeclaredAccessibility == Internal. This line therefore makes ShouldSkipProperty return true for every non-public property, and AnalyzeType calls it and continues before it ever reaches IsPropertyIgnoredDueToAccessibility.

The other branch of that check (public property whose type is inaccessible) is largely unreachable too, because C# rejects it with CS0053 (inconsistent accessibility).

Evidence from the last completed CI run on this branch: ASP0035 does not appear once in the test log (no AD0001 either), while ASP0033/ASP0034/ASP0036 do. ReportsNonPublicProperty_WhoseTypeIsValidatable, ReportsInaccessibleProperty_ViaEndpointParameter and ReportsNonPublicProperty_OnRecordType are all asserting a diagnostic that is never produced.

Suggested fix: split the helper, so the analyzer does not inherit the accessibility gate it is trying to diagnose.

// Shape-based skips only; shared by generator and analyzer.
internal static bool ShouldSkipPropertyShape(...)
    => property.IsImplicitlyDeclared
        || property.IsIndexer
        || property.IsStatic
        || property.IsWriteOnly
        || property.GetMethod is null
        || property.IsEqualityContract(wellKnownTypes)
        || property.IsSkippedValidationProperty(skipValidationAttributeSymbol)
        || property.IsJsonIgnoredProperty(jsonIgnoreAttributeSymbol);

// Generator keeps the accessibility gate on top.
internal static bool ShouldSkipProperty(...)
    => ShouldSkipPropertyShape(...)
        || property.GetMethod!.DeclaredAccessibility is not Accessibility.Public;

Once fixed, a test for public string X { private get; set; } would be worth adding, since that is the one shape where property and getter accessibility genuinely differ.

Minor, same method: the comment above is truncated mid-sentence ("properties without a public getter, and .").


Generated by Copilot, reviewed by @oroztocil.

DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: null,
helpLinkUri: GetHelpLinkUri("ASP0035"));

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.

ASP0035 is reported from the compilation-end action but is missing WellKnownDiagnosticTags.CompilationEnd.

ASP0034 and ASP0037 carry the tag; ASP0035 does not, yet it is reported from RegisterCompilationEndAction via the endpoint-parameter loop (AnalyzeType call further down). Roslyn may drop or stale it in live analysis.

On the question you raised in the other thread about using two descriptors with the same ID where only one is tagged: I would avoid that shape. Roslyn partly determines "is this a compilation-end analyzer" at analyzer granularity by scanning SupportedDiagnostics for the tag, and duplicate IDs in SupportedDiagnostics make effective-severity resolution and release tracking (RS2000/RS2001) ambiguous. Two cleaner options:

  • (a) Two distinct IDs - keep ASP0035 for the [ValidatableType] path (untagged, live in the IDE) and allocate a new ID for the endpoint-parameter path (tagged CompilationEnd). Sidesteps the tooling ambiguity and is self-documenting in list-of-diagnostics.md.
  • (b) One tagged descriptor with all ASP0035 reporting moved into the compilation-end action. Simplest, at the cost of the live-editing experience you are trying to preserve.

(a) seems preferable. Worth settling this after the dead-code issue flagged on ShouldSkipProperty, since that changes what the attribute-path descriptor can actually report.


Generated by Copilot, reviewed by @oroztocil.

{
if (!addValidationFound && validatableTypeAttributeFound)
{
context.ReportDiagnostic(Diagnostic.Create(ValidatableTypeIsUsedWithoutAddValidation, Location.None));

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.

ASP0037 is reported at Location.None, and the message misdirects library authors.

Location.None means the diagnostic cannot be navigated to, does not surface in the editor, and cannot be suppressed with #pragma warning disable. Consider collecting the [ValidatableType] attribute syntax locations in the operation action and reporting at one of them (and including the type name in the message, since today there is no indication of which type triggered it).

Separately, the message says the attribute has no effect "if there is no 'AddValidation' call in your application entry-point". For the common class-library case that is misleading: because the generator emits a file-scoped interceptor bound to call sites in its own compilation, a library needs AddValidation() in that project (typically inside its own public registration method), not in the app's entry point. A library author reading the current text is likely to conclude the warning does not apply to them.

Something like: "'[ValidatableType]' on type '{0}' has no effect because this project does not call 'AddValidation'. The generated resolver only covers types in the project containing the 'AddValidation' call, so add it here (for example, in a public service-registration method)."

To be clear, the rule itself is correct - I had initially misread this as a false positive for libraries and was wrong.


Generated by Copilot, reviewed by @oroztocil.

=> property.DeclaredAccessibility != Accessibility.Public ||
IsInaccessibleFromGeneratedCode(property.Type.UnwrapType());

private static bool IsInaccessibleFromGeneratedCode(ITypeSymbol type)

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.

Accessibility check does not walk the containing type chain.

DeclaredAccessibility and IsFileLocal are both properties of the type itself, so a public type nested inside a file or private container reads as accessible. Verified against Roslyn:

FileOuter                            declAcc=Internal  isFileLocal=True
FileOuter+NestedPublic               declAcc=Public    isFileLocal=False
PrivateHost+PrivOuter                declAcc=Private   isFileLocal=False
PrivateHost+PrivOuter+NestedPublic   declAcc=Public    isFileLocal=False

So file class Outer { public class Inner { } } is missed by the analyzer. Worth noting the generator has the identical gap in TryExtractValidatableType, so in that case it will emit typeof(global::Outer.Inner) into a separate file and produce CS0122 in the generated code. Computing effective accessibility by walking ContainingType would fix analyzer and generator together.


Generated by Copilot, reviewed by @oroztocil.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed


if (IsPropertyIgnoredDueToAccessibility(property) &&
(ValidationsGenerator.HasValidationAttributes(property, wellKnownTypes) ||
TypeHasValidation(property.Type, wellKnownTypes)))

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.

TypeHasValidation receives the raw property type while the accessibility check above unwraps it.

IsPropertyIgnoredDueToAccessibility uses property.Type.UnwrapType(), but this call passes property.Type directly. As a result internal List<Child> Items where Child has [Required] is missed: List<Child> itself has no validation attributes, does not implement IValidatableObject, and none of its own members are annotated, so TypeHasValidation returns false.

property.Type.UnwrapType() here would make the two checks consistent.


Generated by Copilot, reviewed by @oroztocil.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed

var skipValidationAttribute = wellKnownTypes.Get(WellKnownTypeData.WellKnownType.Microsoft_Extensions_Validation_SkipValidationAttribute);
var jsonIgnoreAttributeSymbol = wellKnownTypes.Get(WellKnownTypeData.WellKnownType.System_Text_Json_Serialization_JsonIgnoreAttribute);

var topLevelValidatableTypes = new ConcurrentDictionary<ITypeSymbol, byte>(SymbolEqualityComparer.Default);

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.

Compilation-start mutable state gates whether a per-operation diagnostic is reported.

topLevelValidatableTypes is scoped to the CompilationStart closure, but AnalyzeType's TryAdd guard decides whether ASP0035 is reported at all, and ASP0035/ASP0033 are reported from a per-operation action. In IDE live analysis the scope is reused across document analyses, so whether a type's properties get analyzed depends on which document was analyzed first: a type added during one document's analysis is skipped on the next. The usual symptom is squiggles that appear, vanish on edit, and do not come back.

The robust shape is to accumulate in the operation actions and report everything from the compilation-end action. This largely folds into whichever option you pick for the ASP0035 descriptor split.


Generated by Copilot, reviewed by @oroztocil.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'm not sure I'm following or seeing what the bug here is.

new CSharpCompilationOptions(OutputKind.ConsoleApplication));

var compilationWithAnalyzers = compilation.WithAnalyzers([new ValidationsDiagnosticAnalyzer(), new ValidatableTypeInGeneratedCodeDiagnosticAnalyzer()]);
var diagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync();

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 test helper suppresses compiler diagnostics rather than separating them, so assertions stay coupled to unrelated compiler output.

GetAllDiagnosticsAsync() returns compiler diagnostics as well as analyzer ones, and filtering only Hidden still leaves every Info/Warning/Error in the collection. That is why #nullable enable had to be added across ~12 test sources and a synthetic Main added to ReportsForUseInGeneratedCode - and any future test source with an unrelated compiler warning will break the assertions again.

Separating the two concerns keeps the analyzer assertions stable and still gives the compiler-clean guarantee:

Assert.DoesNotContain(compilation.GetDiagnostics(), d => d.Severity == DiagnosticSeverity.Error);

var analyzerDiagnostics = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync();
Assert.DoesNotContain(analyzerDiagnostics, d => d.Id == "AD0001");
return [.. analyzerDiagnostics.OrderBy(d => d.Id).ThenBy(d => d.Location.SourceSpan.Start)];

The explicit AD0001 assertion is worth keeping - it is the one real benefit GetAllDiagnosticsAsync was providing, and without it an analyzer crash would silently look like "no diagnostics" and make the negative tests pass vacuously.

Also worth making OutputKind a parameter (hardcoded to ConsoleApplication above), which is the cleaner fix for the generated-code test than adding an entry point to it.


Generated by Copilot, reviewed by @oroztocil.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's fine. Catching the additional errors helped making the test better actually.

Comment thread docs/list-of-diagnostics.md Outdated
## Analyzer Warnings

### ASP (`ASP0000-ASP0032`)
### ASP (`ASP0000-ASP0036`)

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.

Heading range is out of date and bracket escaping is inconsistent.

The heading says ASP0000-ASP0036, but the table below now goes up to ASP0037.

Also, in the rows added below: ASP0033 uses \[ValidatableType\] (both brackets escaped) while ASP0036 and ASP0037 use \[ValidatableType] (closing bracket unescaped). Worth making these consistent.


Generated by Copilot, reviewed by @oroztocil.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both are valid escaping for markdown AFAIK.

Fixed the range.

var diagnostics = await GetAnalyzerDiagnosticsAsync(source, additionalReferences: [externalReference]);
Assert.Empty(diagnostics);
}
}

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.

A few test gaps worth closing before this ships.

  • ASP0035's genuinely reachable shape - public string X { private get; set; }. Relevant once the ShouldSkipProperty issue is resolved; today all ASP0035 tests cover a shape the analyzer cannot report.
  • Public type nested in a file/private container - e.g. file class Outer { public class Inner { } }, which is currently missed by the accessibility check.
  • Restore the deleted dedup test (ReportsSingleDiagnostic_WhenTypeReachedByValidatableTypeAndEndpointParameter). It was the only coverage for topLevelValidatableTypes, which is now untested.
  • Record primary constructor parameters - ReportsNonPublicProperty_OnRecordType only covers a plain property. The generator has a separate code path for primary-constructor parameters that the analyzer does not model at all.
  • ASP0037 in a class library - two cases: it does fire with [ValidatableType] and no AddValidation, and it does not fire when the library's own public registration method calls AddValidation(). The second pins the intended library authoring pattern, which is currently not documented or tested anywhere.

Generated by Copilot, reviewed by @oroztocil.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hopefully addressed

Comment on lines +153 to +154
// Skip compiler generated properties, indexers, static properties, properties without
// a public getter, and .

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.

Update the comment

Comment on lines +165 to +167
// TODO: This logic sounds wrong.
// If a property has some validation attributes and its type has SkipValidationAttribute, we
// should only skip the "type validation" part of the property, but still validate the property itself.

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.

Regarding the SkipValidation logic:

if type has SkipValidationAttribute, we should only skip the "type validation" part of the property

That would not be very useful. If you want to skip type-level validation, you just don't add type-level attributes on the type 🙂

The idea behind the logic as it is now is that you can put SkipValidation on a type to disable validation of all properties and parameters of that type, while not disabling validation of any nested types when those are reached elsewhere in the type graph.

Example:

class A
{
    B NestedB { get; set; }
    C NestedC { get; set; }
}

[SkipValidation]
class B
{
    C NestedC { get; set; }
}

class C
{
    [Required]
    string? Name { get; set; }
}

A valueA = new();

Here valueA.NestedB.NestedC.Name is not validated, while valueA.NestedC.Name is validated.

Scenario "validate the attributes on the property but on its type" can be, again, expressed by not adding type-level attributes on the property's type.

What we do not have direct way of expressing is the scenario "validate the property's attributes and its type's attributes, but do not recurse into the type's members" - at least not as per-property opt out. In the example above, you can put SkipValidation on B.NestedC but that means that you don't recurse into NestedC for all uses of B.

However, I would argue that having too subtle type graphs where sometimes you do nested validation and sometimes not is an anti-pattern: it creates footguns for code that uses such models. You can go further and say that only the "parse, don't validate" kind of approaches are safe. That said, there are smaller and bigger footguns, and we are trying to keep ours small. Hence the simple SkipValidation rules: on property/parameter it skips validation for that member, on type it skips validation for all members of that type. (MVC's ValidateNever has the same semantics.)

var topLevelValidatableTypes = new ConcurrentDictionary<ITypeSymbol, byte>(SymbolEqualityComparer.Default);
var endpointParameters = new ConcurrentDictionary<IParameterSymbol, byte>(SymbolEqualityComparer.Default);

var validatableTypeAttributeLocations = new ConcurrentDictionary<Location?, byte>();

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.

Why is the key nullable?

Comment on lines 83 to 94
// Skip file-local types, which are only accessible within their declaring file
// and cannot be referenced from generated code in a different file
if (typeSymbol is INamedTypeSymbol { IsFileLocal: true })
{
return false;
}

// Skip types that are not accessible from generated code
if (typeSymbol.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Internal))
{
return false;
}

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 analyzer should now be correct but the generator itself has different logic.

For types private or file-local types with nested public types, e.g.

class Host { private class Priv { public class Inner { } } }`

the generator does not skip and creates identifier global::Host.Priv.Inner which will break the build on the generated code (while the analyzer only emits warning saying that the type will be skipped from validation).

Comment thread docs/list-of-diagnostics.md Outdated
Comment on lines +43 to +44
| __`ASP0035`__ | Validatable property or its type is not accessible |
| __`ASP0036`__ | Validatable property or its type is not accessible |

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.

We should probably differentiate the two diagnostics in wording, at least slightly.

Comment on lines +96 to +98
private static bool IsPropertyIgnoredDueToAccessibility(IPropertySymbol property)
=> property.DeclaredAccessibility != Accessibility.Public ||
IsInaccessibleFromGeneratedCode(property.Type.UnwrapType());

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.

ValidationsGenerator.TypesParser.cs:286 checks DeclaredAccessibility of the getter method rather than the property itself. What about properties public int X { private get; set; } - these two checks will return different results, no?

}

[Fact]
public async Task ReportsNonPublicProperty_OnRecordType()

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.

Can we add test with primary constructor parameters? They have separate code paths in multiple places.

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

Great work, thanks!

@Youssef1313
Youssef1313 merged commit 8372d2a into main Aug 12, 2026
28 checks passed
@Youssef1313
Youssef1313 deleted the dev/ygerges/mev-analyzers branch August 12, 2026 14:26
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-rc1 milestone Aug 13, 2026
ANcpLua added a commit to ANcpLua/aspnetcore that referenced this pull request Aug 20, 2026
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]>
@Youssef1313 Youssef1313 added the feature-validation Issues related to model validation in minimal and controller-based APIs label Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature-validation Issues related to model validation in minimal and controller-based APIs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants