Skip to content

Expand "Reflection visible array" constructed promotion to generic interfaces implemented by arrays #127249

Open

Description

@NinoFloris

MetadataEETypeNode always promotes reflection-visible array types to MaximallyConstructableType, the rationale being that Array.CreateInstanceFromArrayType might allocate them. This is what makes that API usable without [RequiresDynamicCode].

This rule however doesn't fire for the generic interfaces that arrays implement (IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T>). A library that wants to produce T[] in response to a typeof(IList<T>) entry point can't, because T[]'s MethodTable isn't guaranteed to be emitted.

We're intending to add AOT-friendly support in Npgsql for reading and writing enums without requiring explicit user registrations. Since Postgres pairs every 'base' type with a corresponding array type, we also want to support enum array reading and writing.

Handling these through their underlying type is the recommended AOT-friendly approach for working with unknown enum types. This support can be extended structurally to arrays via Array.CreateInstanceFromArrayType(typeof(TEnum[]), n), using the array cast compatibility to let the underlying type code handle the rest.

Today this works for reader.GetFieldValue<MyEnum[]>() as internally these generic paths do typeof(T) for mapping resolution, which brings the array type up to constructed level through the metadata tier promotion. If a user calls reader.GetFieldValue<IList<MyEnum>>() however, this fails because MyEnum[] was never rooted. None of the workarounds we can apply on our end are satisfying. MakeArrayType requires dynamic code. Per-enum generic registration defeats what convenience the underlying type handling pattern can already give us. And restricting the mappings for this particular case to T[] only loses natural call shapes we support for all other mappings.

The idea would be to root the array type when a reflection-visible closed generic is one of the interfaces arrays implement. With those roots in place Npgsql can safely pair a suppressed MakeArrayType with CreateInstanceFromArrayType to produce an array instance to back the requested interface.

Rooting T[] for every reachable IList<T> (ICollection<T>, and so on) isn't free, but the cost is smaller than the surface suggests. Such reachability in real apps overwhelmingly coexists with T[] already being rooted indirectly via List<T>, ImmutableArray<T>, {ReadOnly}Memory<T>, etc. The rule could also be limited to enum element types, if the unconditional variant would have too wide of an impact. In which case it would just exist to make the underlying type pattern work more uniformly, as if the user explicitly rooted or registered TEnum[].

Activity

  1. added
    untriaged
    on Apr 21, 2026
  2. dotnet-policy-service commented on Apr 21, 2026

    @dotnet-policy-service
    Contributor

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

  3. dotnet-policy-service commented on Apr 21, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @agocke, @dotnet/ilc-contrib
    See info in area-owners.md if you want to be subscribed.

  4. MichalStrehovsky commented on Apr 22, 2026

    @MichalStrehovsky
    Member

    When we do this kind of overfit, it's because there's a trim unsafe API that we can make trim safe by doing this. Is there a trim unsafe API we can make safe or would taking advantage of this require suppressing trimming warnings. We don't encourage doing that, the suppression is a bug pretty much any time i look at suppressed warnings outside this repo (and often in this repo too).

  5. NinoFloris commented on Apr 22, 2026

    @NinoFloris
    ContributorAuthor

    Well effectively the api that could become trim safe would be some form of Array.CreateInstanceFromCollectionInterfaceType, but obviously the chances that gets added are not very realistic.

    There just exists a tension in the advice to handle enums in an erased fashion, while at the same time doing that means you can't guarantee some, any, concrete enum collection type is available to back common collection interface requests with.

    You can't guarantee a concrete collection type is rooted precisely because you are handling these enum types in an erased fashion, following the advice. And the runtime isn't helping you by making just one concrete collection type available based on the 'heuristic' I laid out.

    Since you have no way to create an instance to back these requests with, handling enums in an erased fashion is effectively half usable advice.

    We'll have to tell people the following is all that works (and hope that there isn't an ORM library in between the user and us):
    IList<TEnum> list = reader.GetFieldValue<TEnum[]>()

    Which is kind of absurd because it just shows how non uniformly this support is implemented in the runtime.
    Users will be asking us "Why do I have to cast to IList myself if you have the array type available", to which we'll say: *reasons*.

  6. MichalStrehovsky commented on Apr 22, 2026

    @MichalStrehovsky
    Member

    We can measure this part and see if discussing this is even realistic:

    Rooting T[] for every reachable IList (ICollection, and so on) isn't free, but the cost is smaller than the surface suggests.

    I made the change in #127278 and kicked off a size measurement run at MichalStrehovsky/rt-sz#218. The results should be available in half an hour or so.

  7. MichalStrehovsky commented on Apr 22, 2026

    @MichalStrehovsky
    Member

    This has two measurements, one is for any of the array interfaces, the other is only for enum element types. The enum element types regression would be acceptable (we would need a new API: Array.CreateInstanceFromCollectionInterfaceTypeButOnlyHowNpgsqlNeedsIt). The other one is close to 1%. It takes a lot of effort to save 1%. It's easy to regress by that much.

    We can keep this open if this becomes a recurring theme, however because there's no API we can make safe with this, it doesn't look attractive. We don't overapproximate for so that AOT-unsafe code can work, only for AOT-safe code.

  8. removed
    untriaged
    on Apr 22, 2026
  9. added this to the Future milestone on Apr 22, 2026
  10. NinoFloris commented on Apr 22, 2026

    @NinoFloris
    ContributorAuthor

    Yeah the size is not too bad for enums indeed.

    I did think a bit more about the api that could work. We could maybe tap into the dataflow analysis to discharge the RDC warning on Array.CreateInstance(elementType, ...) if it was preceded by an elementType.IsEnum check?

    Similar things are already done for MakeGenericType and such so it's not entirely without precedent?

  11. MichalStrehovsky commented on Apr 22, 2026

    @MichalStrehovsky
    Member

    I did think a bit more about the api that could work. We could maybe tap into the dataflow analysis to discharge the RDC warning on Array.CreateInstance(elementType, ...) if it was preceded by an elementType.IsEnum check?

    That would be a different implementation. We didn't measure that: if an enum type is generated, also generate associated array.

  12. NinoFloris commented on Apr 22, 2026

    @NinoFloris
    ContributorAuthor

    No it's not, it's how we could provide an 'api'. On our end we already need to match on the incoming type anyway. For exampnle IList<MyEnum> comes in, we pull the T out and check whether its type is an enum before we even try to build up an enum underlying mapping, because we do not know MyEnum, and consequently neither do we know IList<MyEnum>.

    For us to go from IList<MyEnum> to MyEnum[] currently can be done in two ways anyway:

    • Array.CreateInstance(myEnumElementType)
    • myEnumElementType.MakeArrayType() -> Array.CreateInstanceFromArrayType(...)

    Both of these would be with suppression today, and break. These could be with suppression + this PR and work, but the suppression is bad.

    Now the first obvious alternative is to add a new api like CreateInstanceFromCollectionInterfaceType that can be called unsuppressed (or CreateInstanceFromEnumCollectionInterfaceType if we cannot root T[] in all interface cases). But as you also concluded that's very unsatisfying and would basically exist to service AOT implementation details.

    The final alternative then is to instead use refinement logic to codify the conditions under which an existing trim-unsafe api is now safe. And this is essentially already done throughout the codebase, when a constant type is passed to other reflection apis, for runtimefeatures, OperatingSystem checks and so on.

    My question is, instead of making this weird new api, can we just use the dataflow analysis to discharge the RDC warning on Array.CreateInstance(elementType, ...) iff this call is guarded by an IsEnum check in the same method?

  13. MichalStrehovsky commented on Apr 22, 2026

    @MichalStrehovsky
    Member

    We don't have facilities in the dataflow analysis to do the refinement. #97408 (comment) is similar (MakeGeneric doesn't need to warn if there was a guard that realistically restricts this to reference types only).

  14. MichalStrehovsky commented on Apr 22, 2026

    @MichalStrehovsky
    Member

    The best we could do is if we see MakeGeneric with something constrained to Enum, struct, pretend we just did MakeGeneric with all the enums in the entire program.

  15. NinoFloris commented on Apr 22, 2026

    @NinoFloris
    ContributorAuthor

    OK then I misunderstood the extent to which current dataflow analysis is capable.

    The best we could do is if we see MakeGeneric with something constrained to Enum, struct, pretend we just did MakeGeneric with all the enums in the entire program.

    Unfortunately that would need generic bridging for us to work. Though that would indeed open up all the alternative mappings we cannot support too (and we can back the interface requests with any generic collection type at that point).

    In Npgsql we currently go from GetFieldValue<T> straight to typeof(T), checking caches along the way, and then ending in our resolver chain: PgTypeInfo? GetTypeInfo(Type? type, DataTypeName? dataTypeName, PgSerializerOptions options) (I wrote a bit more about the AOT problems which led us to our current model, but it's basically dealing with many of the STJ problems + a few other ones like massive async bloat #110691 (comment))

  16. vyacheslav-volkov commented on Apr 24, 2026

    @vyacheslav-volkov

    @MichalStrehovsky how difficult would it be for NativeAOT to support patterns like:

    typeof(GenericClass<>).MakeGenericType(typeof(T).GetGenericArguments()[0])

    in cases where T is itself known for the closed generic instantiation?
    Because a simpler form like this, can be analyzable:

    typeof(GenericClass<>).MakeGenericType(typeof(T))

    So I’m wondering whether GetGenericArguments() is mainly a current analysis limitation, or whether there is some deeper reason in NativeAOT why this pattern is much harder to make work reliably.

    If GetGenericArguments were supported by NativeAOT, there would be no problem writing something like this and the problem would be solved.

        internal static bool FalseCondition;
        
        public static T GetFieldValue<T>()
        {
            if (!RuntimeFeature.IsDynamicCodeSupported && typeof(T).IsGenericType && typeof(IEnumerable).IsAssignableFrom(typeof(T)) && FalseCondition)
            {
                //this code will never be executed, we only use it to keep the array type.
                Activator.CreateInstance(typeof(ArrayStub<>).MakeGenericType(typeof(T).GetGenericArguments()[0]));
            }
        }
    
        private sealed class ArrayStub<T>
        {
            private T[]? _array;
            
            public ArrayStub()
            {
                _array = [];
            }
        }
  17. NinoFloris commented on Apr 24, 2026

    @NinoFloris
    ContributorAuthor

    Until #83021 lands we cannot have this kind of code in the dispatch path, it'll destroy AOT size. It's one of the reasons we internally have to box for enums when !RuntimeFeature.IsDynamicCodeSupported as well, as we cannot gate the TUnderlying switch on typeof(T).IsEnum, as scanning has already happened for every T.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status
      No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions