Skip to content

fix(SafeArea): subscribe to process-global InputPane/ApplicationView events weakly - #1603

Merged
nickrandolph merged 5 commits into
mainfrom
dev/nr/alc-safearea-weak-global-events
Jul 6, 2026
Merged

nickrandolph merged 5 commits into
mainfrom
dev/nr/alc-safearea-weak-global-events

Conversation

@nickrandolph

Copy link
Copy Markdown
Contributor

ALC pin-fix — standalone (uno.toolkit.ui). Base: main. Independent of the uno framework stack; a downstream host-side sweep mitigates until this ships.

Fixes #1602

Spec

SafeAreaDetails subscribed to the process-global ApplicationView.VisibleBoundsChanged and InputPane.Showing/Hiding events with instance-method delegates, so the process-lifetime singleton strongly rooted the SafeAreaDetails and — through its _subscriptions closures, which capture owner — the owner element and its whole subtree. Unregister() undoes this only on the owner's Unloaded, which does not fire when a tree is discarded abruptly (e.g. a host unloading a plugin/preview app hosted in a collectible AssemblyLoadContext), leaking the owner — and its ALC — for the process lifetime, one leak per unloaded owner.

This PR makes the global-event subscriptions weak so the singleton can never root a discarded SafeAreaDetails, while keeping behaviour identical while the owner is alive. Verified downstream in a designer-style host via ClrMD heap-dump root attribution: after this change (as part of a broader pin audit), zero objects from an unloaded preview-app ALC remain reachable and the ALC completes unloading.

Implementation

src/Uno.Toolkit.UI/Controls/SafeArea/SafeArea.cs (+56/−6, single file):

  • Added SafeAreaDetails.CreateWeakHandler<TSender, TArgs>(target, onEvent, detach, out handler): builds a TypedEventHandler<TSender, TArgs> whose closure captures only a WeakReference<SafeAreaDetails>. While the target is alive it forwards to onEvent; once the target has been collected it self-detaches from the sender via detach. Both callbacks are required to be static (non-capturing) lambdas so the returned delegate never captures the target instance; the handler is also returned via out so the normal Unloaded path can still unsubscribe eagerly.
  • RegisterEvents() — ApplicationView: subscribes VisibleBoundsChanged through CreateWeakHandler forwarding to OnInsetUpdateRequired; the eager-unsubscribe closure added to _subscriptions now captures the same appView instance instead of re-calling GetForCurrentView() at dispose time.
  • RegisterEvents() — InputPane: one weak wrapper serves both Showing and Hiding (forwarding to OnInputPaneChanged); its detach removes it from both events; the eager _subscriptions unsubscribe is preserved.
  • The ScrollViewer-ancestor SizeChanged subscription is intentionally left as a strong instance delegate: the scroll ancestor belongs to the same visual tree as the owner, so it cannot outlive it — there is no cross-lifetime root there.
  • An explanatory comment in RegisterEvents() documents why weak subscription is mandatory for process-global sources.

Test plan

  • Red/green regression test (to be committed with this fix): SafeAreaTests.When_Owner_Discarded_Without_Unloaded_Details_And_Owner_Are_Collected in src/Uno.Toolkit.RuntimeTests/Tests/SafeAreaTests.cs. Arrange: load a SafeArea-annotated Grid, resolve its SafeAreaDetails via the existing internal FindInstance hook, detach the private OnOwnerUnloaded handler (reflection-bound delegate) to model teardown without Unloaded, clear content inside a [NoInlining] helper, keep only WeakReferences. Act: GC collect/finalize loop with dispatcher idles. Assert: both WeakReferences die. Fails on main (singletons root the graph); passes with this change.
  • Existing SafeAreaTests runtime tests cover the alive-path behaviour (insets still applied on VisibleBoundsChanged / input-pane transitions) — unchanged, since the weak wrapper forwards to the same OnInsetUpdateRequired/OnInputPaneChanged methods.
  • Downstream verification: ClrMD dump-based GC-root attribution in a host that load/unload-cycles preview apps in collectible ALCs confirmed the ApplicationView/InputPane-rooted pins are gone and the ALC unloads to zero retained objects.

Risks / rollback

  • Stale wrapper window: after the target is collected, the small wrapper delegate (closure holding one dead WeakReference) stays on the singleton until the next event firing self-detaches it, or until the eager Unloaded-path unsubscribe ran. It cannot root the owner tree; cost is a few dozen bytes per collected instance, bounded and self-cleaning.
  • No timing/reentrancy change: events fire on the same thread and forward to the same handlers; while the owner is alive, behaviour is byte-for-byte equivalent.
  • Rollback: revert the single commit — the change is fully contained in SafeArea.cs.

…events weakly

SafeAreaDetails subscribed to the process-global ApplicationView.VisibleBoundsChanged
and InputPane.Showing/Hiding events with instance-method delegates, so the singleton
strongly rooted the SafeAreaDetails and (through its subscription closures) the owner
element. Unregister() undoes this on the owner's Unloaded event, but that event does
not fire when the owner's AssemblyLoadContext is torn down abruptly (e.g. a host
unloading a collectible plugin/preview ALC), leaking the owner and its ALC for the
process lifetime — and accumulating one leak per unloaded owner.

Subscribe via a weak wrapper (CreateWeakHandler) that holds only a WeakReference to
the SafeAreaDetails and self-detaches once it is collected, so the global singleton
can no longer pin it. Behaviour is unchanged while the owner is alive.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 3, 2026 13:16

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 a memory leak in SafeAreaDetails where subscribing with instance delegates to process-global ApplicationView / InputPane events could strongly root discarded UI trees (and collectible AssemblyLoadContexts) for the lifetime of the process. The fix introduces weak event-handler wrappers so global singletons can no longer keep SafeAreaDetails (and thus its owner subtree) alive once the owner is discarded.

Changes:

  • Added a CreateWeakHandler<TSender, TArgs> helper to create TypedEventHandler delegates that only retain a WeakReference<SafeAreaDetails> and self-detach once the target is collected.
  • Updated RegisterEvents() to subscribe to ApplicationView.VisibleBoundsChanged and InputPane.Showing/Hiding via weak handlers while preserving eager-unsubscribe behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown

Addresses review feedback (#1602): the weak-handler guarantee is defeated
if a caller passes a capturing lambda (its closure would be rooted by the
delegate, reintroducing a strong reference). Add DEBUG assertions that
onEvent/detach have a null Target (static/non-capturing) to catch
accidental captures during development.

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown

@nickrandolph
nickrandolph enabled auto-merge July 3, 2026 15:22
…CS0119)

On net*-android, an unqualified 'Debug' binds to the inherited
Android.Views.ViewGroup.Debug(int) member rather than
System.Diagnostics.Debug, so 'using System.Diagnostics; Debug.Assert(...)'
fails to compile with CS0119. Fully-qualify System.Diagnostics.Debug.Assert
(and drop the now-unused using). Verified: the failing CI job's only
compile error was this CS0119; net9.0 builds clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown

CreateWeakHandler returned the wrapper delegate AND assigned the same value to
an out parameter. Both call sites can capture the return value in a local (the
InputPane site already did, discarding `out _`), so the out parameter was pure
redundancy. Callers now capture the returned handler and use it for both the
event subscription and the unsubscribe closure. No behaviour change: the
delegate's captured state (a WeakReference only) is unaffected by how the caller
stores the returned reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown

@nickrandolph
nickrandolph merged commit 002bb83 into main Jul 6, 2026
21 checks passed
@nickrandolph
nickrandolph deleted the dev/nr/alc-safearea-weak-global-events branch July 6, 2026 18:35
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.

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

5 participants