Repository navigation
Description
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 perSafeAreaowner per cycle). - Regular apps leak any
SafeArea-annotated subtree that is discarded without receivingUnloaded.
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()andInputPane.GetForCurrentView()return process-global, process-lifetime singletons on Uno targets. An instance-method delegate subscription makes the singleton a GC root for the subscriber.SafeAreaDetailsdeliberately holds its owner viaWeakReference _owner, but itsCompositeDisposable _subscriptionscontains closures that captureownerstrongly — so rooting theSafeAreaDetailstransitively 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)
- In the runtime-tests app (
src/Uno.Toolkit.RuntimeTests), create aGrid, callSafeArea.SetInsets(grid, SafeArea.InsetMask.VisibleBounds), set it as window content, and wait forLoaded(this runsRegisterEvents()). - Capture
new WeakReference(grid)andnew WeakReference(SafeArea.SafeAreaDetails.FindInstance(grid)). - Simulate abrupt teardown (the ALC-unload case where
Unloadednever fires): detach the details'OnOwnerUnloadedhandler fromgrid.Unloaded(via a reflection-bound delegate), then clear the window content and drop all strong references. - Run
GC.Collect()/GC.WaitForPendingFinalizers()in a loop with dispatcher idles. - Observed (before fix): both
WeakReferences stay alive indefinitely. A heap dump shows theApplicationViewsingleton'sVisibleBoundsChangedinvocation list holdingSafeAreaDetails.OnInsetUpdateRequired. - 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 aGrid,SafeArea.SetInsets(grid, SafeArea.InsetMask.VisibleBounds),await UnitTestUIContentHelperEx.SetContentAndWait(grid)soLoadedfires and the global subscriptions are made; resolvedetails = SafeArea.SafeAreaDetails.FindInstance(grid); unhook theUnloaded→Unregisterpath by removing a reflection-boundRoutedEventHandlerfor the privateOnOwnerUnloadedfromgrid.Unloaded(this models the collectible-ALC teardown whereUnloadednever fires); clear the content; returnWeakReferences togridanddetails. - Act: loop up to ~10 iterations of
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();withWaitForIdle()between passes, exiting early once both references die. - Assert:
Assert.IsFalse(weakDetails.IsAlive)andAssert.IsFalse(weakGrid.IsAlive). - Red: on current main the
ApplicationView/InputPanesingletons rootdetails(and, through the_subscriptionsclosures,grid), so both stay alive and the test fails. Green: with the weak-handler fix nothing global roots them and both are collected.
Activity
fix(SafeArea): assert non-capturing delegates in CreateWeakHandler