Skip to content

SafeArea pins discarded elements (and collectible AssemblyLoadContexts) via strong subscriptions to process-global ApplicationView/InputPane events #1602

Closed

Description

@nickrandolph

Problem

SafeArea (attached via SafeArea.SetInsets / utu:SafeArea.Insets) creates an internal SafeAreaDetails per owner element. When the owner loads, SafeAreaDetails.RegisterEvents() subscribes instance-method delegates to events on process-global singletons:

// src/Uno.Toolkit.UI/Controls/SafeArea/SafeArea.cs (SafeAreaDetails.RegisterEvents, before fix)
ApplicationView.GetForCurrentView().VisibleBoundsChanged += OnInsetUpdateRequired;
...
inputPane.Showing += OnInputPaneChanged;
inputPane.Hiding += OnInputPaneChanged;

These subscriptions are only removed by Unregister(), which runs exclusively from the owner's Unloaded event. If an element is discarded without Unloaded ever firing — most notably when a host tears down a collectible AssemblyLoadContext containing a plugin/preview app, or drops a whole tree/window abruptly — the global singleton keeps the delegate forever.

Impact

The retention chain is:

ApplicationView/InputPane singleton (process lifetime) → instance delegate → SafeAreaDetails → _subscriptions closures (which capture owner strongly, e.g. () => owner.Loaded -= OnOwnerLoaded) → owner FrameworkElement → its entire subtree, DataContext, and — when the owner's type lives in a collectible AssemblyLoadContext — the ALC itself.

Consequences:

  • A host that loads plugin/preview apps into collectible ALCs can never actually unload them if the loaded content uses SafeArea: AssemblyLoadContext.Unload() never completes, and every load/unload cycle leaks a full visual tree plus its assemblies. Growth is unbounded (one leak per SafeArea owner per cycle).
  • Regular apps leak any SafeArea-annotated subtree that is discarded without receiving Unloaded.

Found while auditing a designer-style host that loads preview apps into collectible AssemblyLoadContexts: a ClrMD heap-dump GC-root attribution campaign traced the remaining ALC pins to the ApplicationView.VisibleBoundsChanged and InputPane.Showing/Hiding invocation lists holding SafeAreaDetails delegates.

Root cause

  • ApplicationView.GetForCurrentView() and InputPane.GetForCurrentView() return process-global, process-lifetime singletons on Uno targets. An instance-method delegate subscription makes the singleton a GC root for the subscriber.
  • SafeAreaDetails deliberately holds its owner via WeakReference _owner, but its CompositeDisposable _subscriptions contains closures that capture owner strongly — so rooting the SafeAreaDetails transitively roots the owner element and everything below it.
  • Cleanup is coupled to FrameworkElement.Unloaded, which is not guaranteed to fire: it does not run when a collectible ALC is torn down abruptly, nor when a tree is discarded wholesale. Lifetime of a subscription on a process-global source must not depend on a tree event.

Reproduction (self-contained, this repo)

  1. In the runtime-tests app (src/Uno.Toolkit.RuntimeTests), create a Grid, call SafeArea.SetInsets(grid, SafeArea.InsetMask.VisibleBounds), set it as window content, and wait for Loaded (this runs RegisterEvents()).
  2. Capture new WeakReference(grid) and new WeakReference(SafeArea.SafeAreaDetails.FindInstance(grid)).
  3. Simulate abrupt teardown (the ALC-unload case where Unloaded never fires): detach the details' OnOwnerUnloaded handler from grid.Unloaded (via a reflection-bound delegate), then clear the window content and drop all strong references.
  4. Run GC.Collect() / GC.WaitForPendingFinalizers() in a loop with dispatcher idles.
  5. Observed (before fix): both WeakReferences stay alive indefinitely. A heap dump shows the ApplicationView singleton's VisibleBoundsChanged invocation list holding SafeAreaDetails.OnInsetUpdateRequired.
  6. Expected: both are collected; nothing global roots the discarded tree.

Red/green test definition

Test: SafeAreaTests.When_Owner_Discarded_Without_Unloaded_Details_And_Owner_Are_Collected
Location: src/Uno.Toolkit.RuntimeTests/Tests/SafeAreaTests.cs (the test class already has internal access to SafeArea.SafeAreaDetails.FindInstance). Not yet written — to be added with the fix.

  • Arrange (in a [MethodImpl(NoInlining)] helper so no locals root the graph): create a Grid, SafeArea.SetInsets(grid, SafeArea.InsetMask.VisibleBounds), await UnitTestUIContentHelperEx.SetContentAndWait(grid) so Loaded fires and the global subscriptions are made; resolve details = SafeArea.SafeAreaDetails.FindInstance(grid); unhook the Unloaded → Unregister path by removing a reflection-bound RoutedEventHandler for the private OnOwnerUnloaded from grid.Unloaded (this models the collectible-ALC teardown where Unloaded never fires); clear the content; return WeakReferences to grid and details.
  • Act: loop up to ~10 iterations of GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); with WaitForIdle() between passes, exiting early once both references die.
  • Assert: Assert.IsFalse(weakDetails.IsAlive) and Assert.IsFalse(weakGrid.IsAlive).
  • Red: on current main the ApplicationView/InputPane singletons root details (and, through the _subscriptions closures, grid), so both stay alive and the test fails. Green: with the weak-handler fix nothing global roots them and both are collected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions