From 51c244e3e9fd4b55bbc250c43cdc157a4aade2a1 Mon Sep 17 00:00:00 2001 From: grzonu Date: Wed, 2 Dec 2026 18:35:51 +0000 Subject: [PATCH] Evict System.Text.Json metadata for collectible types when their AssemblyLoadContext unloads Reflection-based metadata for a type defined in a collectible AssemblyLoadContext was held by caches that can live as long as the process, so the context could never be unloaded once one of its types had been serialized. - The per-options caching context, which is shared by equivalent options instances and backs JsonSerializerOptions.Default and Web, now removes the entries of collectible types when a collectible AssemblyLoadContext starts unloading. The cache itself is unchanged for every other type. - The last-used JsonTypeInfo that an options instance remembers for the root-level entry points no longer remembers collectible types. - The process-wide cache of emitted member accessors keeps the delegates of collectible types in a ConditionalWeakTable keyed by the owning type. Nothing in those delegates refers back to an options instance, so they go away together with the type. - The runtime-type fallbacks that a polymorphic type resolver and a union case index compute for types they were not configured with are not cached for collectible runtime types. Co-Authored-By: Claude Mythos 5.2 --- .../JsonSerializerOptions.Caching.cs | 105 ++++++- .../DefaultJsonTypeInfoResolver.Union.cs | 10 +- .../Metadata/PolymorphicTypeResolver.cs | 17 +- .../ReflectionEmitCachingMemberAccessor.cs | 62 +++- .../Serialization/CacheTests.cs | 282 ++++++++++++++++++ 5 files changed, 458 insertions(+), 18 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs index e0911c28ad113f..99b9959fa434cc 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs @@ -7,6 +7,9 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; +#if NET +using System.Runtime.Loader; +#endif using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Threading; @@ -180,7 +183,16 @@ internal JsonTypeInfo GetTypeInfoForRootType(Type type, bool fallBackToNearestAn if (jsonTypeInfo?.Type != type) { - _lastTypeInfo = jsonTypeInfo = GetTypeInfoInternal(type, fallBackToNearestAncestorType: fallBackToNearestAncestorType); + jsonTypeInfo = GetTypeInfoInternal(type, fallBackToNearestAncestorType: fallBackToNearestAncestorType); + +#if NET + // Metadata for types defined in a collectible AssemblyLoadContext is evicted from the caching context + // when the AssemblyLoadContext unloads; this field would keep such metadata alive beyond that point. + if (!jsonTypeInfo.Type.IsCollectible) +#endif + { + _lastTypeInfo = jsonTypeInfo; + } } return jsonTypeInfo; @@ -237,7 +249,10 @@ internal void ClearCaches() internal sealed class CachingContext { private readonly ConcurrentDictionary _cache = new(); -#if !NET +#if NET + // Set once the cache has stored metadata for a type defined in a collectible AssemblyLoadContext. + private volatile bool _containsCollectibleTypes; +#else private readonly Func _cacheEntryFactory; #endif @@ -276,9 +291,45 @@ public void Clear() _cache.Clear(); } +#if NET + /// + /// Removes the metadata of every type defined in a collectible . + /// A caching context can live for as long as the process does, and would otherwise keep such a context from unloading. + /// + public void RemoveCollectibleTypes() + { + if (!_containsCollectibleTypes) + { + return; + } + + _containsCollectibleTypes = false; + + foreach (KeyValuePair entry in _cache) + { + if (entry.Key.IsCollectible) + { + _cache.TryRemove(entry.Key, out _); + } + } + } +#endif + private CacheEntry GetOrAddCacheEntry(Type type) { #if NET + if (_cache.TryGetValue(type, out CacheEntry? entry)) + { + return entry; + } + + if (type.IsCollectible) + { + // Make sure the entry gets evicted when the AssemblyLoadContext of the type unloads. + CollectibleTypeEviction.EnsureRegistered(type); + _containsCollectibleTypes = true; + } + return _cache.GetOrAdd(type, CreateCacheEntry, this); #else return _cache.GetOrAdd(type, _cacheEntryFactory); @@ -415,6 +466,56 @@ public CacheEntry(ExceptionDispatchInfo exception) } } +#if NET + /// + /// Evicts the cached metadata of types defined in collectible instances + /// when one of these contexts starts unloading. The metadata caches hold on to the types they describe, + /// and they can live for as long as the process does, so without eviction the context could never unload. + /// + internal static class CollectibleTypeEviction + { + private static readonly ConditionalWeakTable s_registeredContexts = new(); + + public static void EnsureRegistered(Type type) + { + Debug.Assert(type.IsCollectible); + + if (type.HasElementType) + { + EnsureRegistered(type.GetElementType()!); + return; + } + + if (type.IsConstructedGenericType) + { + // A constructed generic type is collectible as soon as one of its type arguments is. + foreach (Type typeArgument in type.GetGenericArguments()) + { + if (typeArgument.IsCollectible) + { + EnsureRegistered(typeArgument); + } + } + } + + if (AssemblyLoadContext.GetLoadContext(type.Assembly) is { IsCollectible: true } loadContext && + s_registeredContexts.TryAdd(loadContext, null)) + { + loadContext.Unloading += static _ => RemoveCollectibleTypesFromAllCaches(); + } + } + + private static void RemoveCollectibleTypesFromAllCaches() + { + // Types of other collectible contexts are evicted as well; their metadata is rebuilt on next use. + foreach (KeyValuePair options in TrackedOptionsInstances.All) + { + options.Key._cachingContext?.RemoveCollectibleTypes(); + } + } + } +#endif + /// /// Defines a cache of CachingContexts; instead of using a ConditionalWeakTable which can be slow to traverse /// this approach uses a fixed-size array of weak references of that can be looked up lock-free. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Union.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Union.cs index 06f48df6877969..8d21a7b1d1c557 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Union.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/DefaultJsonTypeInfoResolver.Union.cs @@ -395,7 +395,15 @@ private static void PopulateUnionConstructor( } } - caseIndex[runtimeType] = found; +#if NET + // The index belongs to the metadata of the union type, which can outlive a collectible AssemblyLoadContext, + // so it must not hold on to a runtime type defined in one. The result is recomputed instead. + if (!runtimeType.IsCollectible) +#endif + { + caseIndex[runtimeType] = found; + } + return found; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs index 64b72f87bf45b4..b1fac5ccf19096 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/PolymorphicTypeResolver.cs @@ -150,12 +150,12 @@ public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out // Calculate (and cache the result) of the nearest ancestor for given runtime type. // A `null` result denotes no matching ancestor type, we also cache that. result = CalculateNearestAncestor(runtimeType); - _typeToDiscriminatorId[runtimeType] = result; + CacheRuntimeType(runtimeType, result); break; case JsonUnknownDerivedTypeHandling.FallBackToBaseType: // Recover the polymorphic contract (i.e. any type discriminators) for the base type, if it exists. _typeToDiscriminatorId.TryGetValue(BaseType, out result); - _typeToDiscriminatorId[runtimeType] = result; + CacheRuntimeType(runtimeType, result); break; case JsonUnknownDerivedTypeHandling.FailSerialization: @@ -182,6 +182,19 @@ public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out } } + private void CacheRuntimeType(Type runtimeType, DerivedJsonTypeInfo? result) + { +#if NET + // The resolver can belong to a base type that outlives a collectible AssemblyLoadContext, + // so it must not hold on to a runtime type defined in one. The result is recomputed instead. + if (runtimeType.IsCollectible) + { + return; + } +#endif + _typeToDiscriminatorId[runtimeType] = result; + } + public bool TryGetDerivedJsonTypeInfo(object typeDiscriminator, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeInfo) { Debug.Assert(typeDiscriminator is int or string); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/ReflectionEmitCachingMemberAccessor.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/ReflectionEmitCachingMemberAccessor.cs index 0d80689e660a69..b84ad0e0fa704a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/ReflectionEmitCachingMemberAccessor.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/ReflectionEmitCachingMemberAccessor.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. #if NETFRAMEWORK || NET +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; +using System.Runtime.CompilerServices; namespace System.Text.Json.Serialization.Metadata { @@ -12,6 +14,12 @@ internal sealed partial class ReflectionEmitCachingMemberAccessor : MemberAccess { private readonly ReflectionEmitMemberAccessor _sourceAccessor; private readonly Cache<(string id, Type declaringType, MemberInfo? member)> _cache; +#if NET + // This accessor is a process-wide singleton, so a strong cache entry for a type or member defined in a collectible + // AssemblyLoadContext would keep that context from unloading. The delegates emitted for such types are cached + // per owning type in a ConditionalWeakTable instead, and go away together with the type. + private readonly ConditionalWeakTable> _collectibleTypeCache = new(); +#endif [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] [RequiresUnreferencedCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] @@ -21,65 +29,93 @@ public ReflectionEmitCachingMemberAccessor() _cache = new(slidingExpiration: TimeSpan.FromMilliseconds(1000), evictionInterval: TimeSpan.FromMilliseconds(200)); } - public override void Clear() => _cache.Clear(); + public override void Clear() + { + _cache.Clear(); +#if NET + _collectibleTypeCache.Clear(); +#endif + } + + private TValue GetOrAdd((string id, Type declaringType, MemberInfo? member) key, Func<(string id, Type declaringType, MemberInfo? member), TValue> valueFactory) + where TValue : class? + { +#if NET + // The member is the more specific of the two: its declaring type can depend on the type in the key, but not the reverse. + Type? collectibleOwner = + key.member is { IsCollectible: true } member ? member.DeclaringType ?? key.declaringType : + key.declaringType.IsCollectible ? key.declaringType : + null; + + if (collectibleOwner is not null) + { + return (TValue)_collectibleTypeCache.GetOrCreateValue(collectibleOwner).GetOrAdd( + key, + static (key, valueFactory) => valueFactory(key), + valueFactory)!; + } +#endif + + return _cache.GetOrAdd(key, valueFactory); + } public override Action CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>() => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateAddMethodDelegate), typeof(TCollection), null), _ => _sourceAccessor.CreateAddMethodDelegate()); public override Func? CreateParameterlessConstructor(Type type, ConstructorInfo? ctorInfo) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateParameterlessConstructor), type, ctorInfo), valueFactory: key => _sourceAccessor.CreateParameterlessConstructor(key.declaringType, (ConstructorInfo?)key.member)); public override Func CreateFieldGetter(FieldInfo fieldInfo) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateFieldGetter), typeof(TProperty), fieldInfo), valueFactory: key => _sourceAccessor.CreateFieldGetter((FieldInfo)key.member!)); public override Action CreateFieldSetter(FieldInfo fieldInfo) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateFieldSetter), typeof(TProperty), fieldInfo), valueFactory: key => _sourceAccessor.CreateFieldSetter((FieldInfo)key.member!)); public override Func>, TCollection> CreateImmutableDictionaryCreateRangeDelegate() => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateImmutableDictionaryCreateRangeDelegate), typeof((TCollection, TKey, TValue)), null), valueFactory: _ => _sourceAccessor.CreateImmutableDictionaryCreateRangeDelegate()); public override Func, TCollection> CreateImmutableEnumerableCreateRangeDelegate() => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateImmutableEnumerableCreateRangeDelegate), typeof((TCollection, TElement)), null), valueFactory: _ => _sourceAccessor.CreateImmutableEnumerableCreateRangeDelegate()); public override Func CreateParameterizedConstructor(ConstructorInfo constructor) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateParameterizedConstructor), typeof(T), constructor), valueFactory: key => _sourceAccessor.CreateParameterizedConstructor((ConstructorInfo)key.member!)); public override JsonTypeInfo.ParameterizedConstructorDelegate? CreateParameterizedConstructor(ConstructorInfo constructor) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateParameterizedConstructor), typeof(T), constructor), valueFactory: key => _sourceAccessor.CreateParameterizedConstructor((ConstructorInfo)key.member!)); public override Func CreateSingleParameterConstructor(ConstructorInfo constructor) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreateSingleParameterConstructor), typeof(T), constructor), valueFactory: key => _sourceAccessor.CreateSingleParameterConstructor((ConstructorInfo)key.member!)); public override Func CreatePropertyGetter(PropertyInfo propertyInfo) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreatePropertyGetter), typeof(TProperty), propertyInfo), valueFactory: key => _sourceAccessor.CreatePropertyGetter((PropertyInfo)key.member!)); public override Func CreatePropertyGetter(PropertyInfo propertyInfo) => - _cache.GetOrAdd( + GetOrAdd( key: ("CreatePropertyGetter`2", typeof((TDeclaringType, TProperty)), propertyInfo), valueFactory: key => _sourceAccessor.CreatePropertyGetter((PropertyInfo)key.member!)); public override Action CreatePropertySetter(PropertyInfo propertyInfo) => - _cache.GetOrAdd( + GetOrAdd( key: (nameof(CreatePropertySetter), typeof(TProperty), propertyInfo), valueFactory: key => _sourceAccessor.CreatePropertySetter((PropertyInfo)key.member!)); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs index f7a535390f9904..1a3361a90685f6 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CacheTests.cs @@ -2,9 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; +#if NET +using System.Runtime.Loader; +#endif using System.Text.Encodings.Web; using System.Text.Json.Serialization.Metadata; using System.Threading.Tasks; @@ -307,6 +312,283 @@ static Func CreateCacheCountAccessor() } } +#if NET + [ActiveIssue("https://github.com/dotnet/runtime/issues/34072", TestRuntimes.Mono)] + [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + [InlineData(CollectibleTypeScenario.DefaultOptions)] + [InlineData(CollectibleTypeScenario.WebOptions)] + [InlineData(CollectibleTypeScenario.TransientOptionsEquivalentToLongLivedOptions)] + [InlineData(CollectibleTypeScenario.LongLivedOptionsWithCustomResolver)] + [InlineData(CollectibleTypeScenario.ObjectRootValue)] + [InlineData(CollectibleTypeScenario.CollectionsOfCollectibleType)] + [InlineData(CollectibleTypeScenario.PolymorphicFallBackToNearestAncestor)] + [InlineData(CollectibleTypeScenario.PolymorphicFallBackToBaseType)] + public static void TypesFromCollectibleAssemblyLoadContext_DoNotPreventUnloading(CollectibleTypeScenario scenario) + { + // The metadata caches are shared by equivalent options instances and can live for as long as the process, + // so every scenario runs in a process of its own. + RemoteExecutor.Invoke(static scenarioName => + { + CollectibleTypeScenario scenario = Enum.Parse(scenarioName); + JsonSerializerOptions longLivedOptions = CreateLongLivedOptions(scenario); + + WeakReference loadContext = RoundtripTypeFromCollectibleLoadContext(scenario, longLivedOptions); + + for (int i = 0; i < 10 && loadContext.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + Assert.False(loadContext.IsAlive); + GC.KeepAlive(longLivedOptions); + }, scenario.ToString(), new RemoteInvokeOptions() { + TimeOut = RemoteExecutor.FailWaitTimeoutMilliseconds * PlatformDetection.SlowRuntimeTimeoutModifier + }).Dispose(); + } + + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + public static void TypesFromCollectibleAssemblyLoadContext_AreCachedWhileTheContextIsAlive() + { + RemoteExecutor.Invoke(static () => + { + var loadContext = new AssemblyLoadContext(nameof(TypesFromCollectibleAssemblyLoadContext_AreCachedWhileTheContextIsAlive), isCollectible: true); + Type collectibleType = LoadCollectibleCopy(loadContext, typeof(ClassLoadedIntoCollectibleContext)); + Assert.True(collectibleType.IsCollectible); + var options = new JsonSerializerOptions(); + options.MakeReadOnly(populateMissingResolver: true); + + JsonTypeInfo typeInfo = options.GetTypeInfo(collectibleType); + object value = JsonSerializer.Deserialize("""{"Name":"name","Number":42,"Child":{"Numbers":[1,2]}}""", collectibleType, options)!; + + Assert.Same(typeInfo, options.GetTypeInfo(collectibleType)); + Assert.True(options.TryGetTypeInfo(collectibleType, out JsonTypeInfo? cachedTypeInfo)); + Assert.Same(typeInfo, cachedTypeInfo); + Assert.Equal("""{"Name":"name","Number":42,"Child":{"Numbers":[1,2]}}""", JsonSerializer.Serialize(value, collectibleType, options)); + Assert.Equal("""{"Name":"name","Number":42,"Child":{"Numbers":[1,2]}}""", JsonSerializer.Serialize(value, options)); + GC.KeepAlive(loadContext); + }, new RemoteInvokeOptions() { + TimeOut = RemoteExecutor.FailWaitTimeoutMilliseconds * PlatformDetection.SlowRuntimeTimeoutModifier + }).Dispose(); + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/34072", TestRuntimes.Mono)] + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + public static void TypesFromCollectibleAssemblyLoadContext_DoNotPreventUnloading_WhenTheContextIsOnlyDropped() + { + RemoteExecutor.Invoke(static () => + { + WeakReference collectibleType = SerializeTypeFromCollectibleLoadContextWithoutUnloading(); + + // The context is unloaded by its finalizer, so more than one collection is needed. + for (int i = 0; i < 20 && collectibleType.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + Assert.False(collectibleType.IsAlive); + }, new RemoteInvokeOptions() { + TimeOut = RemoteExecutor.FailWaitTimeoutMilliseconds * PlatformDetection.SlowRuntimeTimeoutModifier + }).Dispose(); + + [MethodImpl(MethodImplOptions.NoInlining)] + static WeakReference SerializeTypeFromCollectibleLoadContextWithoutUnloading() + { + var loadContext = new AssemblyLoadContext(nameof(TypesFromCollectibleAssemblyLoadContext_DoNotPreventUnloading_WhenTheContextIsOnlyDropped), isCollectible: true); + Type collectibleType = LoadCollectibleCopy(loadContext, typeof(ClassLoadedIntoCollectibleContext)); + Assert.Equal("""{"Name":null,"Number":0,"Child":null}""", JsonSerializer.Serialize(Activator.CreateInstance(collectibleType), collectibleType)); + return new WeakReference(collectibleType); + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/34072", TestRuntimes.Mono)] + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + public static void TypesFromCollectibleAssemblyLoadContext_KeepWorkingAfterAnotherContextUnloads() + { + RemoteExecutor.Invoke(static () => + { + const string Json = """{"Name":"name","Number":42,"Child":{"Numbers":[1,2]}}"""; + var options = new JsonSerializerOptions(); + var survivingContext = new AssemblyLoadContext("surviving", isCollectible: true); + Type survivingType = LoadCollectibleCopy(survivingContext, typeof(ClassLoadedIntoCollectibleContext)); + object value = JsonSerializer.Deserialize(Json, survivingType, options)!; + Assert.Equal(Json, JsonSerializer.Serialize(value, survivingType, options)); + + WeakReference unloadedContext = RoundtripTypeFromCollectibleLoadContext(CollectibleTypeScenario.LongLivedOptionsWithCustomResolver, options); + for (int i = 0; i < 10 && unloadedContext.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + Assert.False(unloadedContext.IsAlive); + Assert.Equal(Json, JsonSerializer.Serialize(value, survivingType, options)); + Assert.Equal(Json, JsonSerializer.Serialize(JsonSerializer.Deserialize(Json, survivingType, options), survivingType, options)); + Assert.Same(options.GetTypeInfo(survivingType), options.GetTypeInfo(survivingType)); + GC.KeepAlive(survivingContext); + }, new RemoteInvokeOptions() { + TimeOut = RemoteExecutor.FailWaitTimeoutMilliseconds * PlatformDetection.SlowRuntimeTimeoutModifier + }).Dispose(); + } + + public enum CollectibleTypeScenario + { + DefaultOptions, + WebOptions, + TransientOptionsEquivalentToLongLivedOptions, + LongLivedOptionsWithCustomResolver, + ObjectRootValue, + CollectionsOfCollectibleType, + PolymorphicFallBackToNearestAncestor, + PolymorphicFallBackToBaseType, + } + + private static JsonSerializerOptions CreateLongLivedOptions(CollectibleTypeScenario scenario) + { + switch (scenario) + { + case CollectibleTypeScenario.DefaultOptions: + case CollectibleTypeScenario.ObjectRootValue: + case CollectibleTypeScenario.CollectionsOfCollectibleType: + return JsonSerializerOptions.Default; + + case CollectibleTypeScenario.WebOptions: + return JsonSerializerOptions.Web; + + case CollectibleTypeScenario.TransientOptionsEquivalentToLongLivedOptions: + var options = new JsonSerializerOptions { IncludeFields = true }; + JsonSerializer.Serialize(42, options); + return options; + + case CollectibleTypeScenario.LongLivedOptionsWithCustomResolver: + return new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + + case CollectibleTypeScenario.PolymorphicFallBackToNearestAncestor: + return CreatePolymorphicOptions(JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor); + + case CollectibleTypeScenario.PolymorphicFallBackToBaseType: + return CreatePolymorphicOptions(JsonUnknownDerivedTypeHandling.FallBackToBaseType); + + default: + throw new ArgumentOutOfRangeException(nameof(scenario)); + } + + static JsonSerializerOptions CreatePolymorphicOptions(JsonUnknownDerivedTypeHandling unknownDerivedTypeHandling) => + new JsonSerializerOptions + { + TypeInfoResolver = new DefaultJsonTypeInfoResolver + { + Modifiers = + { + typeInfo => + { + if (typeInfo.Type == typeof(EventArgs)) + { + typeInfo.PolymorphismOptions = new JsonPolymorphismOptions + { + UnknownDerivedTypeHandling = unknownDerivedTypeHandling, + DerivedTypes = { new JsonDerivedType(typeof(CancelEventArgs), "cancel") }, + }; + } + } + } + } + }; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference RoundtripTypeFromCollectibleLoadContext(CollectibleTypeScenario scenario, JsonSerializerOptions longLivedOptions) + { + const string ExpectedJson = """{"Name":"name","Number":42,"Child":{"Numbers":[1,2]}}"""; + + var loadContext = new AssemblyLoadContext(scenario.ToString(), isCollectible: true); + Type collectibleType = LoadCollectibleCopy(loadContext, typeof(ClassLoadedIntoCollectibleContext)); + Assert.True(collectibleType.IsCollectible); + + switch (scenario) + { + case CollectibleTypeScenario.DefaultOptions: + case CollectibleTypeScenario.WebOptions: + case CollectibleTypeScenario.LongLivedOptionsWithCustomResolver: + object value = JsonSerializer.Deserialize(ExpectedJson, collectibleType, longLivedOptions)!; + Assert.Equal(ExpectedJson, JsonSerializer.Serialize(value, collectibleType, JsonSerializerOptions.Default)); + Assert.NotNull(JsonSerializer.Serialize(value, collectibleType, longLivedOptions)); + break; + + case CollectibleTypeScenario.TransientOptionsEquivalentToLongLivedOptions: + var transientOptions = new JsonSerializerOptions { IncludeFields = true }; + value = JsonSerializer.Deserialize(ExpectedJson, collectibleType, transientOptions)!; + Assert.Equal(ExpectedJson, JsonSerializer.Serialize(value, collectibleType, transientOptions)); + break; + + case CollectibleTypeScenario.ObjectRootValue: + value = JsonSerializer.Deserialize(ExpectedJson, collectibleType, longLivedOptions)!; + Assert.Equal(ExpectedJson, JsonSerializer.Serialize(value, longLivedOptions)); + Assert.Equal($$"""{"Value":{{ExpectedJson}}}""", JsonSerializer.Serialize(new ClassWithObjectProperty { Value = value }, longLivedOptions)); + break; + + case CollectibleTypeScenario.CollectionsOfCollectibleType: + Type listType = typeof(List<>).MakeGenericType(collectibleType); + Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), collectibleType); + Type arrayType = collectibleType.MakeArrayType(); + Assert.True(listType.IsCollectible); + Assert.Equal($"[{ExpectedJson}]", JsonSerializer.Serialize(JsonSerializer.Deserialize($"[{ExpectedJson}]", listType, longLivedOptions), listType, longLivedOptions)); + Assert.Equal($"[{ExpectedJson}]", JsonSerializer.Serialize(JsonSerializer.Deserialize($"[{ExpectedJson}]", arrayType, longLivedOptions), arrayType, longLivedOptions)); + Assert.Equal($$"""{"key":{{ExpectedJson}}}""", JsonSerializer.Serialize(JsonSerializer.Deserialize($$"""{"key":{{ExpectedJson}}}""", dictionaryType, longLivedOptions), dictionaryType, longLivedOptions)); + break; + + case CollectibleTypeScenario.PolymorphicFallBackToNearestAncestor: + Type derivedType = LoadCollectibleCopy(loadContext, typeof(CancelEventArgsLoadedIntoCollectibleContext)); + Assert.Equal("""{"$type":"cancel","Cancel":false}""", JsonSerializer.Serialize((EventArgs)Activator.CreateInstance(derivedType)!, longLivedOptions)); + break; + + case CollectibleTypeScenario.PolymorphicFallBackToBaseType: + derivedType = LoadCollectibleCopy(loadContext, typeof(CancelEventArgsLoadedIntoCollectibleContext)); + Assert.Equal("{}", JsonSerializer.Serialize((EventArgs)Activator.CreateInstance(derivedType)!, longLivedOptions)); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(scenario)); + } + + // Once unloading has been requested, the runtime keeps the context alive + // for as long as anything still references one of its assemblies or types. + loadContext.Unload(); + return new WeakReference(loadContext); + } + + private static Type LoadCollectibleCopy(AssemblyLoadContext loadContext, Type type) + { + Assembly assembly = loadContext.Assemblies.FirstOrDefault() ?? loadContext.LoadFromAssemblyPath(type.Assembly.Location); + Type collectibleType = assembly.GetType(type.FullName!, throwOnError: true)!; + Assert.NotSame(type, collectibleType); + return collectibleType; + } + + public class ClassLoadedIntoCollectibleContext + { + public string? Name { get; set; } + public int Number { get; set; } + public ChildOfClassLoadedIntoCollectibleContext? Child { get; set; } + } + + public class ChildOfClassLoadedIntoCollectibleContext + { + public int[]? Numbers { get; set; } + } + + public class CancelEventArgsLoadedIntoCollectibleContext : CancelEventArgs + { + public int Number { get; set; } + } + + public class ClassWithObjectProperty + { + public object? Value { get; set; } + } +#endif + [ActiveIssue("https://github.com/dotnet/runtime/issues/66232", TargetFrameworkMonikers.NetFramework)] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void JsonSerializerOptions_ReuseConverterCaches()