Repository navigation
fix(alc): stop shared framework caches/resources from pinning collectible AssemblyLoadContexts - #23413
Conversation
|
Nick Randolph seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
There was a problem hiding this comment.
Pull request overview
This PR addresses collectible AssemblyLoadContext (ALC) retention by removing several default-context references that could keep collectible ALC graphs alive across unload/reload cycles, particularly via XAML parsing state and shared ResourceDictionary behaviors. It also adds targeted unit tests and a new spec documenting the leak mechanisms and fixes.
Changes:
- Update
XamlParseContextto hold non-default ALCs viaWeakReference<AssemblyLoadContext>(with a strong fast-path forAssemblyLoadContext.Default). - Prevent
ResourceDictionary“key not found” caching from storing collectibleTypekeys, and flagDependencyObjectresources so they don’t inherit/cacheDataContext. - Add unit tests covering ALC collection, not-found cache behavior, and
DataContextinheritance parity; add spec044documenting the fixes.
Note: The PR description should include a linked GitHub issue using a full URL (Fixes/Closes/Related). Please provide the issue link/number so it can be added.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Uno.UI/UI/Xaml/XamlParseContext.cs | Switch non-default ALC storage to weak reference; keep default ALC strong; support re-resolution after unload/collect. |
| src/Uno.UI/UI/Xaml/ResourceDictionary.cs | Add collectible-type guard for not-found caching and mark stored/materialized DO resources as non-DataContext inheritors. |
| src/Uno.UI/UI/Xaml/DependencyObjectStore.cs | Add IsResourceDictionaryItem flag and block inherited DataContext propagation for flagged stores. |
| src/Uno.UI.Tests/Windows_UI_Xaml/Given_XamlParseContext.cs | New unit tests validating weak ALC handling and default ALC behavior. |
| src/Uno.UI.Tests/Windows_UI_Xaml/Given_ResourceDictionary_NotFoundCache.cs | New unit tests ensuring collectible Type misses are not cached/pinned. |
| src/Uno.UI.Tests/Windows_UI_Xaml/Given_ResourceDictionary_DataContext.cs | New unit tests validating resources don’t inherit DataContext while normal children/bindings still work. |
| specs/044-alc-memory-leak-fixes/spec.md | New spec describing leak root causes/fixes and validation claims (needs alignment with actual PR contents/tests). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23413/wasm-skia-net9/index.html |
Addresses review on #23413: the spec documented an AlcContentHost fix and a runtime test that are not part of this PR. - Remove AlcContentHost as an implemented fix; move it to a follow-up note as a related, separately-tracked collectible-ALC pin - Drop the Given_AlcContentHost runtime-test bullet from Validation - Document the resource-DataContext fix (DependencyObjectStore IsResourceDictionaryItem + ResourceDictionary) that this PR actually contains, with its Given_ResourceDictionary_DataContext coverage - Note the end-to-end measurement reflects the full fix workstream Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23413/wasm-skia-net9/index.html |
A strong ALC reference in XamlParseContext pinned collectible secondary-app ALCs forever: parse contexts are retained long-term by ResourceBinding and ThemeResourceReference on elements reachable from non-collectible statics, and the lazy by-AssemblyName resolution could cache a collectible ALC inside a never-dying generated __ParseContext_ singleton. gcroot showed this field as the pinning edge in every chain to a leaked secondary Application (~+48 MB / +420K objects leaked per reload). - Store non-default ALCs via WeakReference<AssemblyLoadContext> - Keep a strong fast-path field for the process-immortal default ALC - Re-run lazy by-name resolution when a previously resolved target was collected, so a reloaded same-name assembly resolves to the NEW ALC (consistent with ResourceResolver's bump-to-live-registration behavior) - Post-unload lookups return null and fall back to host resolution per ResourceResolver's documented priority order Red/green: Given_XamlParseContext.When_Collectible_Alc_Unloaded_Then_Context_Does_Not_Pin_It Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-found cache Typed resource lookups that miss (e.g. implicit-style probes for secondary-app element types hosted in the host visual tree) were cached in _keyNotFoundCache as ResourceKeys strongly holding the RuntimeType. Element-level dictionaries live for the host's lifetime and are never touched by CleanupNonDefaultAlcCaches, so a single cached collectible RuntimeType pinned LoaderAllocator -> ALC -> the entire previous secondary-app graph. gcroot reported 10,378 root paths through one such cache entry on a host page's Resources. Skip the not-found cache for keys whose Type.IsCollectible is true (CanCacheKeyNotFound); re-probing such keys is cheap compared to leaking a whole secondary app. Non-collectible keys keep the existing caching behavior. Red/green: Given_ResourceDictionary_NotFoundCache (collectible type emitted via AssemblyBuilderAccess.RunAndCollect must be collectable after a miss; non-collectible keys still miss consistently) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Documents the problem (one full secondary-app graph leaked per reload, ALC never collected after Unload), the three gcroot-confirmed root causes in Uno.UI (XamlParseContext strong ALC capture, AlcContentHost projected-resource retention, ResourceDictionary not-found cache pinning collectible Types), the fixes, and the red/green + end-to-end validation (secondary Application count flat at 1 across 4 reload cycles vs +1 per reload before). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A DependencyObject stored as a value in a ResourceDictionary is now flagged
(IsResourceDictionaryItem) so it does not inherit or cache the DataContext of
the subtree it is applied into. This matches WinUI, where resources have no
DataContext.
Why it matters for collectible ALCs: a shared resource (e.g. a brush in a
GlobalStaticResources singleton) is rooted by a long-lived dictionary, yet it
is pulled into many short-lived subtrees via {StaticResource}/{ThemeResource}.
If it cached the inherited DataContext of one such subtree, it would keep that
DataContext — and everything it transitively references — alive forever. When
the subtree lives in a collectible AssemblyLoadContext, that retention pins the
whole context and prevents it from unloading. Only DataContext is blocked;
other inherited properties (FlowDirection, theme, …) still propagate.
Adds Given_ResourceDictionary_DataContext regression tests (flagging on store,
DataContext block, and a non-resource child still inheriting).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- ResourceDictionary: extract TryCacheKeyNotFound() so the collectible-key guard is applied
once instead of repeated at each key-not-found site (jeromelaban). Folding CanCacheKeyNotFound
directly into useKeysNotFoundCache was avoided because that variable also gates the
`modifiedKey { ShouldFilter = false }` transform used by the value lookup, so a helper keeps
lookup behaviour identical.
- DependencyObjectStore: back IsResourceDictionaryItem with a single-byte [Flags] StoreFlags
bitfield instead of a standalone bool field, so future per-store flags don't grow the
per-instance footprint (jeromelaban).
- Add When_Element_Binding_Uses_Inherited_DataContext_Then_It_Still_Resolves to guard that the
DataContext block (scoped to ResourceDictionary items) does not break binding propagation in
styles/resources (jeromelaban).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses review on #23413: the spec documented an AlcContentHost fix and a runtime test that are not part of this PR. - Remove AlcContentHost as an implemented fix; move it to a follow-up note as a related, separately-tracked collectible-ALC pin - Drop the Given_AlcContentHost runtime-test bullet from Validation - Document the resource-DataContext fix (DependencyObjectStore IsResourceDictionaryItem + ResourceDictionary) that this PR actually contains, with its Given_ResourceDictionary_DataContext coverage - Note the end-to-end measurement reflects the full fix workstream Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
506f600 to
afafe45
Compare
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23413/wasm-skia-net9/index.html |
|
|
The reuse-on-reload warning claimed all state is immutable across hot-reload, but the AssemblyLoadContext is now held weakly and can lapse. Note it as the explicit exception — the reference only dies on ALC unload (teardown), not hot-reload — so contributors aren't misled about what may change across reloads. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23413/wasm-skia-net9/index.html |
Per review request: add runtime tests (real visual tree, XAML-parsed) confirming
the ResourceDictionary DataContext block does not regress style-based binding
DataContext propagation. A resource Style carries no DataContext, but the element
it is applied to still inherits DataContext and its {Binding} resolves; an ordinary
child still inherits while a sibling resource does not.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23413/wasm-skia-net9/index.html |
|
|
The collectible-ALC and collectible-type reclamation loops did only Collect + WaitForPendingFinalizers. Reclaiming a collectible AssemblyLoadContext / LoaderAllocator reliably needs a second Collect after finalizers run, since finalization can release the last references keeping it alive — without it the assertions can intermittently fail on CI. Add the trailing Collect to both loops. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23413/wasm-skia-net9/index.html |
|
|
Problem
When a host loads an app into a collectible
AssemblyLoadContext(ALC) and later unloads it, shared default-context framework state can retain references that reach into the collectible ALC and prevent it from being collected. Over repeated load/unload cycles these pins accumulate; on WASM (MonoVM), whereWebAssembly.Memory.grow()is irreversible, this is eventually fatal.This PR removes three such default-context → collectible-ALC references in the framework.
Changes
AssemblyLoadContextof the assembly it was created for.Typekeys — a cachedRuntimeTypepins itsLoaderAllocatorand the whole collectible ALC after unload; collectible type keys are no longer cached on a miss.DependencyObjectstored as a value in aResourceDictionaryis flagged (IsResourceDictionaryItem) so it never inherits/caches theDataContextof the subtree it is applied into. A shared resource (e.g. a brush in a generated statics singleton) is rooted by a long-lived dictionary yet pulled into many short-lived subtrees via{StaticResource}/{ThemeResource}; caching one subtree's DataContext would keep it — and any collectible ALC it reaches — alive forever. Only DataContext is blocked; other inherited properties still propagate.Tests (red/green)
Given_XamlParseContext— ALC is collectible after the parse context is released.Given_ResourceDictionary_NotFoundCache— a collectibleTypekey miss is not pinned.Given_ResourceDictionary_DataContext(new) — element flagged on store; resource does not inherit DataContext; a normal logical child still does.Part of the collectible-ALC memory-leak fixes documented in
specs/044-alc-memory-leak-fixes(see alsospecs/000-alc-secondary-app-support). Includes commits by @derekraven1994 (XamlParseContext, ResourceDictionary not-found cache, spec) grouped here by theme.