Skip to content

fix: weak-subscription / static-pin sweeps for collectible ALCs (batch 3) - #1608

Merged
nickrandolph merged 12 commits into
mainfrom
dev/nr/wasm-alc-sweeps-tk
Jul 24, 2026
Merged

nickrandolph merged 12 commits into
mainfrom
dev/nr/wasm-alc-sweeps-tk

Conversation

@nickrandolph

@nickrandolph nickrandolph commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A batch of low-risk sweeps that stop several Toolkit types from pinning collectible AssemblyLoadContexts. These types subscribe to process-global event sources or hold process-lifetime static references with no teardown (or a teardown path that only runs on an event that may never fire in a fixed-size preview canvas). In an ordinary app this is harmless — process, assembly, window, and app share one lifetime. In a downstream host that loads previewed apps into their own collectible ALCs, these references cross the ALC boundary and keep the ALC's LoaderAllocator alive for the process lifetime.

The weak self-detaching handler reuses the CreateWeakHandler template established for the SafeArea global-event subscriptions: a WeakReference<T> to the target plus static, non-capturing delegates, so the global source holds only a weak reference and the wrapper detaches itself once the target is collected.

Closes #1607

Findings (see specs/alc-weak-subscription-sweeps/recap.md)

  • 1. ResponsiveHelper.InitializeIfNeeded — strong XamlRoot.Changed lambda → weak self-detaching handler + internal Reset() purge hook.
  • 2. DependencyObjectExtensions._dependencyPropertyReflectionCache — Type-keyed static Dictionary → ConditionalWeakTable<Type, Dictionary<string, …>> so the owner Type (and its ALC) is held weakly.
  • 3. NavigationBar → SystemNavigationManager.BackRequested — strong sub → weak self-detaching handler (keeps the Unloaded fast path).
  • 4. ResponsiveExtension — HardSelfReferences / static WindowSizeChanged / TrackedInstances accumulation → weak WindowSizeChanged subscription + Unloaded-hooked removal + dead-instance sweep on Connect.
  • 5. FrameworkElementExtensions.SubscribeToNestedElements — disposable never invoked recorded unsubscribe actions → invoke each Unsubscribe() on dispose.
  • 6. ExtendedSplashScreen — static Instance + retained splash bitmap → release Instance + splash content on Unloaded (Android: recycle the bitmap).

Out of scope (follow-ups): ShadowsCache dispose-on-evict, StatusBar teardown, ResponsiveView slot cache.

Tests

Each fix ships with red/green runtime leak tests (#if DEBUG, under src/Uno.Toolkit.RuntimeTests/Tests/*LeakTests.cs) proving the subscription is now weak/detached or that the cache entry dies with its Type/ALC. Findings 3 and 4 additionally have real-path integration guards that turn red if the production wiring is reverted (not just the DEBUG hook).

Build / test status

  • Uno.Toolkit.UI + Uno.Toolkit.RuntimeTests build clean on net9.0 (0 warnings, 0 errors).
  • Runtime tests are validated by the desktop Skia CI stage (dotnet MaterialSampleApp.dll --runtime-tests=…). A local headless run on the dev machine could not wire the runtime-test output destination ("Application has not been configured with output destination") — an environment nuance, not a test defect — so runtime green is left to CI, which uses the identical invocation. No greens are fabricated.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

6 similar comments
@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@nickrandolph
nickrandolph force-pushed the dev/nr/wasm-alc-sweeps-tk branch from 64f8fce to f5647a4 Compare July 9, 2026 15:29
@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 221549 has failed on Uno Toolkit - CI.

@github-actions

Copy link
Copy Markdown

1 similar comment
@github-actions

Copy link
Copy Markdown

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 221674 has failed on Uno Toolkit - CI.

nickrandolph and others added 9 commits July 23, 2026 16:13
…ge hook

ResponsiveHelper.InitializeIfNeeded subscribed to the process-global
XamlRoot.Changed with a strong lambda capturing the process-lifetime static
_defaultSizeProvider, with no teardown. The host XamlRoot then roots the
Toolkit static chain for the process lifetime, pinning the Toolkit
AssemblyLoadContext in a downstream host that loads previewed apps into their
own collectible ALCs.

- Subscribe via a WeakReference-backed self-detaching handler (static,
  non-capturing onEvent/detach), so the XamlRoot only holds a weak reference.
- Record the subscription in a SerialDisposable.
- Add internal Reset() to tear down the default/override providers and their
  subscriptions between app loads.
- Add DEBUG test hooks and ResponsiveHelperLeakTests (deterministic teardown +
  GC weak-collectibility proof).

Contributes to #1607

Co-Authored-By: Claude Fable 5 <[email protected]>
…nt handlers on dispose

Two ALC-pin sweeps:

- NavigationBar subscribed to the process-global
  SystemNavigationManager.BackRequested with an instance-method delegate. It is
  detached on Unloaded, but Unloaded does not fire when the owner's ALC is torn
  down abruptly. Subscribe via a WeakReference-backed self-detaching handler so
  the global singleton only holds a weak reference; keep the Unloaded fast path.

- FrameworkElementExtensions.SubscribeToNestedElements returned a disposable that
  cleared its subscription list WITHOUT invoking the recorded unsubscribe actions,
  leaving Loaded handlers attached (pinning the closure graph to any host-owned
  element). Invoke each recorded Unsubscribe() on dispose.

Adds red/green runtime leak tests for both (weak-collectibility proofs) and a
DEBUG test hook on NavigationBar.

Contributes to #1607

Co-Authored-By: Claude Fable 5 <[email protected]>
…ectible ALCs unload

DependencyObjectExtensions cached dependency-property reflection results in a
process-lifetime Dictionary<(Type, string), ...>. The strong Type key kept that
Type's LoaderAllocator alive, pinning a collectible AssemblyLoadContext (e.g. a
downstream host that loads previewed apps into their own collectible ALCs) for
the process lifetime.

- Replace with ConditionalWeakTable<Type, Dictionary<string, DependencyPropertyInfo?>>:
  the owner Type is now held weakly, so its per-property cache (and the values it
  holds) becomes unreachable once the Type/ALC is collected.
- Guard inner-dictionary access with a lock.
- Add a DEBUG test hook and a red/green runtime test using a collectible
  (RunAndCollect) dynamic assembly Type, proving the Type key is collectible.

Contributes to #1607

Co-Authored-By: Claude Fable 5 <[email protected]>
…d-instance sweep

ResponsiveExtension rooted every instance in the static HardSelfReferences list
and only removed it from CleanupIfHostDisposed(), which only ran from
OnWindowSizeChanged. In a fixed-size preview canvas the window never resizes, so
that event never fires and dead extensions accumulate forever, each pinning its
target/host graph — and, across a collectible AssemblyLoadContext boundary, the
previewed app's ALC. The static WindowSizeChanged subscription and the static
TrackedInstances weak-reference list had the same accumulation problem.

- Subscribe to the static WindowSizeChanged event via a WeakReference-backed
  self-detaching handler, so a dead extension is collectible without a resize.
- Hook the host's Unloaded to proactively release the hard self-reference and
  tracking (graceful path).
- Sweep dead HardSelfReferences / TrackedInstances entries on each Connect.
- Add DEBUG test hooks and red/green runtime tests (sweep pruning + extension
  collectibility without resize/Uninstall).

Contributes to #1607

Co-Authored-By: Claude Fable 5 <[email protected]>
ExtendedSplashScreen kept a process-lifetime static Instance reference (assigned
in the constructor, never cleared) and held its splash content — which on Android
wraps the retained native splash bitmap. The splash is a one-shot startup control,
so once it unloads those references only serve to pin it (and, when it belongs to
a previewed app loaded into a collectible AssemblyLoadContext, that app's whole
ALC) for the process lifetime.

- Clear the static Instance on Unloaded (only if it still points at this instance).
- Drop SplashScreenContent to an empty placeholder on Unloaded.
- Android: recycle and null the retained splash bitmap via a new partial hook.
- Add a DEBUG test hook and red/green runtime tests (Instance released on Unloaded
  + splash-screen collectibility).

Also finalises specs/alc-weak-subscription-sweeps/recap.md.

Contributes to #1607

Co-Authored-By: Claude Fable 5 <[email protected]>
…n Connect

The handler is a fresh delegate instance per Connect; the previous one is already
detached by '_disposable.Disposable = null' at the top of Connect, so the '-='
was dead code.

Co-Authored-By: Claude Fable 5 <[email protected]>
…siveExtension

Review follow-up: the DEBUG-hook tests verify the weak helpers but cannot fail if
the production wiring is reverted. Add integration tests that drive the real
OnLoaded/Install paths and prove collectibility after tree removal, so a revert of
the subscription/teardown wiring turns the test red. Also correct the
ResponsiveExtension collectibility test's message to describe what it isolates.

Contributes to #1607

Co-Authored-By: Claude Fable 5 <[email protected]>
The Android implementation of the partial ReleaseNativeSplashResources only
clears the process-lifetime static SplashBitmap, so CA1822 (promoted to error
under TreatWarningsAsErrors) required it to be static. Mark both partial
declarations static; the unqualified call site is unaffected. Also fix a
cspell failure (behaviour -> behavior) in the spec recap.
…ensions

FrameworkElementExtensions is internal to the UI assembly, so the XML-doc
<see cref> in the RuntimeTests summary could not be resolved on the
net9.0-android target (code binding honors InternalsVisibleTo, doc-comment
cref resolution does not), failing the Android sample build with CS1574
under warnings-as-errors. Use a <c> code span, which needs no resolution.
Copilot AI review requested due to automatic review settings July 23, 2026 06:14
@nickrandolph
nickrandolph force-pushed the dev/nr/wasm-alc-sweeps-tk branch from 966f52e to 6b718fb Compare July 23, 2026 06:14
@github-actions

Copy link
Copy Markdown

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.

⚠️ Not ready to approve

There are confirmed teardown/leak correctness issues and inaccurate lifecycle comments in the updated event-subscription code that should be fixed before merge.

Pull request overview

This PR addresses collectible AssemblyLoadContext leaks by removing strong roots created via process-global event subscriptions and process-lifetime statics in Uno Toolkit UI types, and adds runtime leak tests to prevent regressions.

Changes:

  • Reworks several process-global event subscriptions to use weak/self-detaching handlers, and adds teardown/reset hooks where needed.
  • Replaces a Type-keyed static reflection cache with a ConditionalWeakTable to avoid pinning collectible types/ALCs.
  • Adds runtime leak tests to validate collectability and teardown behavior across the affected areas.
File summaries
File Description
src/Uno.Toolkit.UI/Markup/ResponsiveExtension.cs Adds weak WindowSizeChanged subscription, Unloaded teardown, and dead-instance sweeping for ResponsiveExtension.
src/Uno.Toolkit.UI/Helpers/ResponsiveHelper.cs Switches XamlRoot.Changed subscription to a weak handler and adds an internal Reset() teardown hook.
src/Uno.Toolkit.UI/Extensions/FrameworkElementExtensions.cs Fixes the returned IDisposable to actually execute recorded unsubscribe actions on dispose.
src/Uno.Toolkit.UI/Extensions/DependencyObjectExtensions.cs Replaces the static DP reflection cache with a ConditionalWeakTable keyed by Type and adds a DEBUG test hook.
src/Uno.Toolkit.UI/Controls/NavigationBar/NavigationBar.cs Uses a weak handler for SystemNavigationManager.BackRequested and adds a DEBUG test hook.
src/Uno.Toolkit.UI/Controls/ExtendedSplashScreen/ExtendedSplashScreen.cs Releases static Instance and drops splash content on Unloaded; adds a DEBUG test hook.
src/Uno.Toolkit.UI/Controls/ExtendedSplashScreen/ExtendedSplashScreen.Android.cs Recycles/releases the retained Android splash bitmap on unload.
src/Uno.Toolkit.RuntimeTests/Tests/ResponsiveHelperLeakTests.cs Adds leak tests for ResponsiveHelper.Reset() and default-provider collectability.
src/Uno.Toolkit.RuntimeTests/Tests/ResponsiveExtensionsLeakTests.cs Adds leak tests validating ResponsiveExtension sweeping and collectability without resize/uninstall.
src/Uno.Toolkit.RuntimeTests/Tests/NavigationBarLeakTests.cs Adds leak tests validating NavigationBar weak BackRequested subscription behavior.
src/Uno.Toolkit.RuntimeTests/Tests/FrameworkElementExtensionsLeakTests.cs Adds leak test ensuring nested-element subscriptions detach on dispose.
src/Uno.Toolkit.RuntimeTests/Tests/ExtendedSplashScreenLeakTests.cs Adds leak tests validating ExtendedSplashScreen.Instance release and collectability after unload.
src/Uno.Toolkit.RuntimeTests/Tests/DependencyObjectExtensionsLeakTests.cs Adds leak test ensuring the DP reflection cache does not root collectible Type keys.
specs/alc-weak-subscription-sweeps/recap.md Adds a recap spec documenting the rationale, fixes, and tests for the sweep batch.

Review details

  • Files reviewed: 14/14 changed files
  • Comments generated: 4
  • Review effort level: Low

Note

Your feedback helps us improve the quality of this feature.
Please use 👍 or 👎 to tell us whether this assessment is correct.


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

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 223768 has failed on Uno Toolkit - CI.

- fix: SubscribeToNestedElements dropped stale-depth subscriptions via
  RemoveRange without detaching their Loaded handlers, so they stayed attached
  yet untracked and leaked their closures; unsubscribe before removing.
- refactor: extract the duplicated per-type CreateWeakHandler into a shared
  internal WeakEventHelper (EventHandler and TypedEventHandler overloads);
  migrate NavigationBar, ResponsiveHelper and ResponsiveExtension to it.
- fix: capture the host XamlRoot weakly in ResponsiveHelper's default-provider
  teardown so the process-lifetime static does not strongly root a closed
  window's XamlRoot.
- style: mark the ResponsiveHelper SerialDisposable statics readonly.
- docs: reword NavigationBar/ResponsiveExtension comments to state the weak
  wrapper self-detaches on the next event raise after collection (Unloaded is
  the proactive teardown), not "once collected".

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

Copy link
Copy Markdown

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.

⚠️ Not ready to approve

ExtendedSplashScreen.LoadNativeSplashScreen can repopulate SplashScreenContent after Unloaded teardown, undermining the intended resource release behavior.

Review details
  • Files reviewed: 15/15 changed files
  • Comments generated: 1
  • Review effort level: Low

Note

Your feedback helps us improve the quality of this feature.
Please use 👍 or 👎 to tell us whether this assessment is correct.

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 223820 has failed on Uno Toolkit - CI.

LoadNativeSplashScreen is fire-and-forget and, on the platforms where
GetNativeSplashScreen awaits real I/O (reading the app manifest on
Skia/WASM/Windows), can complete after the control has unloaded. Its
continuation then re-assigned SplashScreenContent, undoing the Unloaded
teardown that releases the content for collection. Skip the late assignment
when the control has already unloaded, and wrap the fire-and-forget body in
try/catch per the async guidance.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 23, 2026 15:01
@nickrandolph
nickrandolph marked this pull request as ready for review July 23, 2026 15:02
@github-actions

Copy link
Copy Markdown

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.

✅ Ready to approve

The changes are cohesive, low-risk leak mitigations with targeted runtime regression tests; only a minor documentation typo was found.

Note: this review does not count toward required approvals for merging.

Review details
  • Files reviewed: 15/15 changed files
  • Comments generated: 1
  • Review effort level: Low

Note

Your feedback helps us improve the quality of this feature.
Please use 👍 or 👎 to tell us whether this assessment is correct.

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 223830 has failed on Uno Toolkit - CI.

@nickrandolph
nickrandolph enabled auto-merge July 23, 2026 16:08
The runtime-test engine's WaitForLoaded treats an element with
ActualWidth/ActualHeight == 0 as not-yet-loaded, so SetContentAndWait on a bare
empty Grid timed out deterministically before the test body ran (the desktop
runtime-tests failure). Give the root an explicit size so it loads and the
subscribe/dispose detachment assertion actually executes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 24, 2026 07:37
@github-actions

Copy link
Copy Markdown

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.

⚠️ Not ready to approve

ResponsiveExtension.Connect’s teardown disposable currently captures the host strongly, which can prevent HardSelfReferences sweeping from ever succeeding under the UNO14502 workaround and reintroduce an ALC pin.

Review details
  • Files reviewed: 15/15 changed files
  • Comments generated: 1
  • Review effort level: Low

Note

Your feedback helps us improve the quality of this feature.
Please use 👍 or 👎 to tell us whether this assessment is correct.

@nickrandolph
nickrandolph merged commit 058d641 into main Jul 24, 2026
25 checks passed
@nickrandolph
nickrandolph deleted the dev/nr/wasm-alc-sweeps-tk branch July 24, 2026 15:01
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.

4 participants