Skip to content

[API Proposal]: JsonSourceGenerationOptionsAttribute.EmitAttributeProviders to opt out of generated attribute provider reflection #137566

Description

@Sergio0694

Background and motivation

For every serialized property or field, the System.Text.Json source generator emits an AttributeProviderFactory lambda such as static () => typeof(T).GetProperty("Name", ...). For every object type with a constructor it also emits a ConstructorAttributeProviderFactory with typeof(T).GetConstructor(...). These back JsonPropertyInfo.AttributeProvider, JsonTypeInfo.ConstructorAttributeProvider and JsonParameterInfo.AttributeProvider, and are evaluated lazily.

In NativeAOT, ILC treats each constant-string GetProperty/GetField/GetConstructor call as a reflection root, so every serialized member stays reflectable even if nothing ever reads the provider. This costs binary size (reflection metadata, invoke map entries, accessors). The runtime itself only reads providers in JsonSchemaExporter (to report [Obsolete] members as deprecated), and the Store only reads them in one contract modifier.

Measured on the Windows Store app (NativeAOT, OptimizationPreference=Size, about 2,700 generated factory sites across its contexts), by opting 14 contexts out and leaving the one context whose contract modifier reads AttributeProvider unchanged:

WinStore.App.dll deflate (level 6)
Baseline 84,881,408 B 27,617,909 B
14 contexts opted out 83,336,704 B 27,091,326 B
Delta -1,544,704 B (-1.82%) -526,583 B

Ignoring the dataflow only in ILC saved just 270,848 B, so the lambdas need to not exist at all, which only the generator can do. A runtime feature switch would not help either, since it applies per app and the lambdas would still be emitted. The switch has to be per JsonSerializerContext because some contexts in the same app legitimately need the providers.

API Proposal

namespace System.Text.Json.Serialization;

public sealed partial class JsonSourceGenerationOptionsAttribute : JsonAttribute
{
    /// <summary>
    /// Specifies whether the generated contracts expose attribute providers. Defaults to true.
    /// </summary>
    public bool EmitAttributeProviders { get; set; } // default: true
}

When set to false, the generator emits null instead of the factories, and for contracts of that context JsonPropertyInfo.AttributeProvider, JsonTypeInfo.ConstructorAttributeProvider and JsonParameterInfo.AttributeProvider return null. These members are already annotated nullable, and null is already possible today (for example ignored properties of types not otherwise in the graph, or hand-built contracts). Serialization behavior is unchanged; only consumers that inspect attributes at run time are affected:

  • JsonSchemaExporter no longer marks [Obsolete] members as deprecated.
  • Contract modifiers and schema transformers that read attributes get null. A modifier can still assign JsonPropertyInfo.AttributeProvider, but the constructor and parameter providers have no public setter and cannot be restored.

Default behavior and generated output are unchanged. There is no runtime change, no new runtime API, and no per-[JsonSerializable] setting.

API Usage

[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(Customer))]
[JsonSourceGenerationOptions(EmitAttributeProviders = false)]
internal partial class AppJsonContext : JsonSerializerContext;

Alternative Designs

  • Naming: EmitAttributeProviders (default true) is positive and follows DataMemberAttribute.EmitDefaultValue = true. It is the first default-true bool on this attribute, whereas the existing ones all default to false. A negative OmitAttributeProviders / SkipAttributeProviders (default false, similar to LoggerMessageAttribute.SkipEnabledCheck) is the alternative if reviewers prefer that convention.
  • MSBuild/analyzer config property: applies per compilation, not per context, and the generator has no precedent for reading analyzer config.
  • Runtime feature switch: per app, the lambdas are still emitted, and ILC-only suppression saved far less (see above).
  • Per-type setting on [JsonSerializable]: would need a tri-state enum, since a bool can't express "unspecified". Contexts are the natural unit, and types that need providers can be moved to their own context. It could be added later following the GenerationMode pattern.
  • Make null the default under trimming/AOT: would silently break schema/attribute-reading consumers.

Risks

  • Consumers reading AttributeProvider from a context that opted out silently get null, and code that dereferences it without a null check throws. The doc comment should call this out.
  • A project using the new property with an older generator hits the existing default: throw for unknown named arguments in the generator's parser, as for previous options added to this attribute.

Note

This issue was drafted with AI assistance (GitHub Copilot) and reviewed by the author. A working prototype exists locally; the size numbers above come from a full Store NativeAOT build with it.

Activity

  1. added
    api-suggestion
    on Nov 15, 2026
  2. added
    untriaged
    on Nov 15, 2026
  3. dotnet-policy-service commented on Nov 15, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-text-json
    See info in area-owners.md if you want to be subscribed.

  4. teo-tsirpanis commented on Nov 15, 2026

    @teo-tsirpanis
    Contributor

    ILC treats each constant-string GetProperty/GetField/GetConstructor call as a reflection root, so every serialized member stays reflectable even if nothing ever reads the provider

    Can't this be improved instead?

  5. Sergio0694 commented on Nov 17, 2026

    @Sergio0694
    ContributorAuthor

    It can't, that's working as intended and would break code otherwise, and even without it, you'd not get all size back. The lambda returns a PropertyInfo/FieldInfo/ConstructorInfo to arbitrary code, so marking those as roots is correct. ILC can only see that someone in the app uses that property (we do have some places in the Store where we do need it, in a specific context), but it can't know exactly which instance that maps to, so it's forced to root it for everything, which causes the binary size bloat.

    I did try just for curiosity to check the size difference if I changed ILC to not root those reflection calls (never mind the fact that doing that is not correct and breaks code). Even with that, it only saved ~270KB, which is about 16% of the total saving. The only way to get all that 1.5MB back is by actually not emitting those lambdas entirely, as doing so just roots a whole lot of code for a combinations of reasons.

    @eiriktsarpalis could you help me get this to API review? System.Text.Json is a major source of binary size bloat across several 1st party components (including the Store, but also several Windows components, and other inbox apps), and reducing binary size is a critical metric for us. This is the only change I found so far that would actually require a public API change. Thank you! 🙂

  6. eiriktsarpalis commented on Nov 18, 2026

    @eiriktsarpalis
    Member

    I don't think this is the right solution, long term. The issue fundamentally is that any code inside lambda literals gets automatically rooted by the linker (see #137809). Improving the linker or updating the implementation to use a single-method interface instead might let us have our cake and eat it.

  7. Sergio0694 commented on Nov 18, 2026

    @Sergio0694
    ContributorAuthor

    But even with that you'd still unnecessarily be marking a lot of methods as reflection visible. I mean conceptually isn't this equivalent to when the Metadata mode for generation was added, which was meant to avoid emitting the serialization fast path to reduce binary size? This is just another case of the generator emitting too much stuff by default and causing binary size increase.

  8. eiriktsarpalis commented on Nov 18, 2026

    @eiriktsarpalis
    Member

    But even with that you'd still unnecessarily be marking a lot of methods as reflection visible.

    How so? If the code enabling that reflection gets trimmed then the corresponding members stop being reflection visible.

  9. Sergio0694 commented on Nov 18, 2026

    @Sergio0694
    ContributorAuthor

    I think there might be a misunderstanding here. There's two separate points:

    1. Yes, the cost comes from delegate targets being compiled unconditionally by ILC. Your suggested approach of using an interface would let ILC trim the provider code in apps where nothing reads AttributeProvider, which would be an improvement over today. Similarly I'd imagine somehow making ILC smarter for delegates could get some of that gain (even though it might not be possible here since Func<T> is contravariant and there's always going to be callers of Func<object> somewhere, meaning things might still get rooted anyway. But yes with the interface you could get some savings.
    2. The above though does not help at all for apps where you are using AttributeProvider, which is the case of the Store. We have several JSON contexts, but we only care about AttributeProvider for one of them. Because we do use AttributeProvider, ILC has to mark the property as rooted, including all overrides, since it can't track individual instances. So even if you were to use an interface and make ILC smarter, you'd still be leaving a lot of size on the table without an opt-out switch.

    I ran a test for (1) (2,000 properties) with one reader, the interface shape recovered about a third of what a per-context opt-out does (132 KB vs 422 KB). In the Store, the opt-out saves 1.54 MB. Which is a lot of size.

    Basically what I'm saying is the three items are not mutually exclusive: you can add an interface to make AttributeProvider less expensive, you can make ILC smarter to potentially also get the same savings when using lambdas, but you'd still need the opt-out switch to get back the rest 2/3rds of the binary size savings regardless.

  10. eiriktsarpalis commented on Nov 19, 2026

    @eiriktsarpalis
    Member

    Ok, so you're basically looking for a mechanism to schope attribute providers to individual contexts?

  11. Sergio0694 commented on Nov 19, 2026

    @Sergio0694
    ContributorAuthor

    Yup, that's correct, so you can only generate them for contexts you actually need, or just always keep them disabled if you never use that functionality 🙂

  12. jkotas commented on Nov 20, 2026

    @jkotas
    Member

    Specifies whether the generated contracts expose attribute providers. Defaults to true.

    This is not a good doc comment. Doc comment needs to explain when to set it to true / false - how do I tell from my S.T.Json usage pattern whether it is fine to set it to false? Is that automatable - can you build an analyzer that checks the setting is right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Text.Jsonuntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions