Repository navigation
Conversation
…mblyLoadContext 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 <noreply@anthropic.com>
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-text-json |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #138673 Contributes to #65323
Problem
Once
System.Text.Jsonhas built reflection-based metadata for a type defined in a collectibleAssemblyLoadContext, the context is never collected afterUnload(). The metadata caches hold the type strongly and they can live as long as the process:JsonSerializerOptions.DefaultandJsonSerializerOptions.Web;JsonTypeInfothat an options instance remembers for the root-level entry points;The result is a memory leak: every context that is loaded, used and unloaded stays in memory. On .NET 11.0.0, 2000 load-serialize-unload cycles of a 26 KB assembly leave 2000 contexts alive and cost about 21 MB of managed heap and about 52 MB of private memory. The issue has the reproduction and the history: the basic problem exists since .NET Core 3.0, and .NET 7 extended it to short-lived options instances.
The change
Caching context. The cache stays the
ConcurrentDictionary<Type, CacheEntry>it is today. What is new is eviction:Type.IsCollectible),CollectibleTypeEviction.EnsureRegisteredsubscribes once to theUnloadingevent of theAssemblyLoadContextthat defines the type. For arrays and constructed generic types it walks to the element type and the collectible type arguments, becauseList<T>over a collectibleTis collectible whileList<>itself lives in the default context.Unloading,RemoveCollectibleTypesruns on the caching context of every live options instance. It usesTrackedOptionsInstances.All, the same set the hot reload handler walks, and removes only the entries whose key is collectible. Entries of other types are not touched.volatile bool.Last-used type.
GetTypeInfoForRootTypedoes not store aJsonTypeInfoof a collectible type in_lastTypeInfo. Such types take the dictionary lookup on every root-level call.Emitted member accessors.
ReflectionEmitCachingMemberAccessoris a process-wide singleton. Delegates for collectible types and members now go into aConditionalWeakTablekeyed by the owning type and no longer into the strong cache with its sliding expiration. A weak table is safe here, unlike in the caching context (see below), because an emitted delegate refers to the type and its members and to nothing that belongs to an options instance.Polymorphism and unions.
PolymorphicTypeResolverand the union case index cache the result they compute for a runtime type they were not configured with. They no longer cache it when the runtime type is collectible, and recompute it.Everything is under
#if NET. Thenetstandard2.0and .NET Framework builds are unchanged.The approach I tried first, and why this is not it
My first version kept the entries of collectible types in a
ConditionalWeakTable<Type, CacheEntry>inside each caching context, so that an entry would go away together with its type. It does unload the context, and it passed the library's tests, but measuring it showed three problems. The first two could be fixed. The third could not, and is the reason for the eviction design.Emitted accessors were not cached at all for collectible types. With a new options instance and resolver on every call, the first serialization of a collectible type went from about 35 us to about 4 ms, because the accessors were emitted again each time. Fixed by the per-type weak table described above, which is part of this change.
Every caching context allocated a
ConditionalWeakTableup front. That is a finalizable object, 369 B more per options instance that gets its own caching context, whether or not the process ever sees a collectible type. Fixed by allocating the table on first use.Options instances leaked for as long as the collectible type stayed loaded. A
JsonTypeInforefers to itsJsonSerializerOptions, the options refer to their caching context, and the caching context owns the weak table. An entry of aConditionalWeakTablekeeps its value alive for as long as its key is alive, so as long as the type was loaded, the table kept theJsonTypeInfoalive, and with it the options instance and the table itself. An options instance that had serialized a collectible type could therefore never be collected while that type's context stayed loaded.For equivalent options instances this is harmless, since they share one caching context. For non-equivalent instances created per call, for example
new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }, it is an unbounded leak in the opposite direction: the options pile up for as long as the plugin runs. Measured with 50,000 calls, each with a new options instance and a new resolver, on a collectible type that stays loaded:mainWhat that design needs is an entry that lives only while the type and the options instance are both alive. A dependent handle ties a value to one key, and the value here refers to both, so whichever of the two is made the key, the other is kept alive through the value. I did not find a way to build the two-key lifetime out of dependent handles and strong references.
Eviction on
Unloadingavoids the question. All references stay strong, so options instances are collected exactly as they are today, and the type is released at a well-defined point.Behaviour to be aware of
ClearCache.Unload()is handled as well: its finalizer raisesUnloading.AssemblyBuilderAccess.RunAndCollect, which are collectible but have noUnloadingevent;Unloading, for example by code of that context that is still running;Testing
System.Text.Json.Testson aclr+libsbuild ofmainfor linux-x64: 54,387 tests, 0 failed.New tests in
CacheTests, each in its own process throughRemoteExecutor, because the caches under test are process-wide. They load a second copy of the test assembly into a collectible context:TypesFromCollectibleAssemblyLoadContext_DoNotPreventUnloading, eight cases:Defaultoptions,Weboptions, a transient options instance equivalent to a long-lived one, long-lived options with their own resolver, anobjectroot value and anobject-typed property,List<T>,T[]andDictionary<string, T>over a collectibleT, and the two polymorphic fallbacks with a non-collectible base type...._DoNotPreventUnloading_WhenTheContextIsOnlyDropped: no call toUnload()...._KeepWorkingAfterAnotherContextUnloads: a second collectible context still round-trips correctly after the first one unloaded and its metadata was evicted along with it...._AreCachedWhileTheContextIsAlive:GetTypeInfokeeps returning the same instance for a loaded collectible type.The first ten cases fail on unmodified
main. The last one passes on both and guards the caching itself.Outside the test suite, the reproduction from the issue prints
Truein every row and column with this change, and its load-serialize-unload loop stays at 0 contexts alive after 2000 cycles (67.7 MB of private memory, against 108.5 MB on .NET 11.0.0).Performance
BenchmarkDotNet. The library was built from
mainfornet11.0, with and without this change, and run on the .NET 11.0.0 runtime. Three alternating runs of each build; the table shows the median of the three means. The machine is a noisy 4-core VM: two runs of the same build differ by up to about 8%. Allocations are identical in every row.mainoptions.GetTypeInfo(type), cachedobject-typed propertySerialize<object>(poco)mainType, default optionsTypeobject-typed propertyoptions.GetTypeInfo(type), cachedThe steady-state paths for ordinary types are within the noise. The one row where the ranges of the two builds do not overlap is the first serialization with a brand new options instance and resolver for an ordinary type (33.7 - 34.5 us against 34.6 - 37.0 us). That path now asks
IsCollectibleonce per cached type and once per emitted accessor. I have not measured the in-boxnet12.0build, whereRuntimeType.IsCollectibleis a read of aMethodTableflag.Relation to #65323
#65323 tracks the same problem and has the earlier design discussion. This change is the approach suggested there in February 2025: subscribe to the unload event of a collectible context the first time one of its types is cached, and evict when it fires. How it lines up with the points raised in that thread:
Pay for play. Nothing changes for non-collectible types: same dictionary, same lookups, no ConditionalWeakTable on any path they take. The benchmarks below show the steady-state paths within noise and identical allocations.
No new public API. Unloading works without the host knowing about the caches, and nothing internal is promoted.
A ConditionalWeakTable only for collectible types was the other pay-for-play option discussed. I built it first. Besides the lookup cost measured in the thread, it has a lifetime problem that the thread does not mention: a JsonTypeInfo refers to its options, so every options instance that has serialized a collectible type stays alive for as long as the type does. The section "The approach I tried first" has the numbers.
Unloading is a request, not a completion. That objection from the thread holds here too: metadata cached after the event, by code of the context that is still running, is not evicted and stays cached as it is today. It is listed under the limitations below. It does not make anything worse than today, and the common case, a host that stops its plugin and then unloads it, is fixed.
There is no unload event for a dynamic assembly created with RunAndCollect, so those types are not covered, as noted in the thread.
Questions for review
TrackedOptionsInstancescarries a comment about linking it away when hot reload is not in use. This change gives it a second consumer.Unloadingas well?