Skip to content

fix(alc): stop shared framework caches/resources from pinning collectible AssemblyLoadContexts - #23413

Merged
MartinZikmund merged 9 commits into
masterfrom
dev/nr/alc-shared-cache-pinning
Jun 18, 2026
Merged

MartinZikmund merged 9 commits into
masterfrom
dev/nr/alc-shared-cache-pinning

Conversation

@nickrandolph

Copy link
Copy Markdown
Contributor

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), where WebAssembly.Memory.grow() is irreversible, this is eventually fatal.

This PR removes three such default-context → collectible-ALC references in the framework.

Changes

  • XamlParseContext holds the ALC weakly — the parse context no longer keeps a strong reference to the AssemblyLoadContext of the assembly it was created for.
  • ResourceDictionary not-found cache never caches collectible Type keys — a cached RuntimeType pins its LoaderAllocator and the whole collectible ALC after unload; collectible type keys are no longer cached on a miss.
  • Resources do not inherit DataContext (WinUI parity) — a DependencyObject stored as a value in a ResourceDictionary is flagged (IsResourceDictionaryItem) so it never inherits/caches the DataContext of 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 collectible Type key 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 also specs/000-alc-secondary-app-support). Includes commits by @derekraven1994 (XamlParseContext, ResourceDictionary not-found cache, spec) grouped here by theme.

Copilot AI review requested due to automatic review settings June 10, 2026 14:04
@github-actions github-actions Bot added area/automation Categorizes an issue or PR as relevant to project automation kind/documentation labels Jun 10, 2026
@CLAassistant

CLAassistant commented Jun 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 3 committers have signed the CLA.

❌ Nick Randolph
❌ nickrandolph
❌ DerekRaven


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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 XamlParseContext to hold non-default ALCs via WeakReference<AssemblyLoadContext> (with a strong fast-path for AssemblyLoadContext.Default).
  • Prevent ResourceDictionary “key not found” caching from storing collectible Type keys, and flag DependencyObject resources so they don’t inherit/cache DataContext.
  • Add unit tests covering ALC collection, not-found cache behavior, and DataContext inheritance parity; add spec 044 documenting 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.

Comment thread specs/044-alc-memory-leak-fixes/spec.md Resolved
Comment thread specs/044-alc-memory-leak-fixes/spec.md Resolved
@unodevops

Copy link
Copy Markdown
Contributor

nickrandolph pushed a commit that referenced this pull request Jun 10, 2026
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]>
@unodevops

Copy link
Copy Markdown
Contributor

@nickrandolph nickrandolph removed area/automation Categorizes an issue or PR as relevant to project automation kind/documentation labels Jun 15, 2026
DerekRaven and others added 6 commits June 15, 2026 18:15
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]>
Copilot AI review requested due to automatic review settings June 15, 2026 08:23
@nickrandolph
nickrandolph force-pushed the dev/nr/alc-shared-cache-pinning branch from 506f600 to afafe45 Compare June 15, 2026 08:23

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread src/Uno.UI/UI/Xaml/XamlParseContext.cs Resolved
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 218258 has failed on Uno.UI - CI.

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]>
@unodevops

Copy link
Copy Markdown
Contributor

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]>
Copilot AI review requested due to automatic review settings June 17, 2026 18:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 218716 has failed on Uno.UI - CI.

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]>
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 218794 has failed on Uno.UI - CI.

@MartinZikmund
MartinZikmund enabled auto-merge June 18, 2026 12:15
@MartinZikmund
MartinZikmund merged commit f1b7ab6 into master Jun 18, 2026
48 of 49 checks passed
@MartinZikmund
MartinZikmund deleted the dev/nr/alc-shared-cache-pinning branch June 18, 2026 12:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants