Repository navigation
fix: weak-subscription / static-pin sweeps for collectible ALCs (batch 3) - #1608
Conversation
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
6 similar comments
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
64f8fce to
f5647a4
Compare
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
|
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
1 similar comment
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
|
|
…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.
966f52e to
6b718fb
Compare
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
There was a problem hiding this comment.
⚠️ 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 aConditionalWeakTableto 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.
|
|
- 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]>
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
There was a problem hiding this comment.
⚠️ 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.
|
|
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]>
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
There was a problem hiding this comment.
✅ 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.
|
|
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]>
|
Azure Static Web Apps: Your stage site is ready! Visit it here: https://polite-field-01aa64f0f-1608.eastus2.azurestaticapps.net |
There was a problem hiding this comment.
⚠️ 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.
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'sLoaderAllocatoralive for the process lifetime.The weak self-detaching handler reuses the
CreateWeakHandlertemplate established for theSafeAreaglobal-event subscriptions: aWeakReference<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 #1607Findings (see
specs/alc-weak-subscription-sweeps/recap.md)ResponsiveHelper.InitializeIfNeeded— strongXamlRoot.Changedlambda → weak self-detaching handler + internalReset()purge hook.DependencyObjectExtensions._dependencyPropertyReflectionCache—Type-keyed staticDictionary→ConditionalWeakTable<Type, Dictionary<string, …>>so the ownerType(and its ALC) is held weakly.NavigationBar→SystemNavigationManager.BackRequested— strong sub → weak self-detaching handler (keeps theUnloadedfast path).ResponsiveExtension—HardSelfReferences/ staticWindowSizeChanged/TrackedInstancesaccumulation → weakWindowSizeChangedsubscription +Unloaded-hooked removal + dead-instance sweep onConnect.FrameworkElementExtensions.SubscribeToNestedElements— disposable never invoked recorded unsubscribe actions → invoke eachUnsubscribe()on dispose.ExtendedSplashScreen— staticInstance+ retained splash bitmap → releaseInstance+ splash content onUnloaded(Android: recycle the bitmap).Out of scope (follow-ups):
ShadowsCachedispose-on-evict,StatusBarteardown,ResponsiveViewslot cache.Tests
Each fix ships with red/green runtime leak tests (
#if DEBUG, undersrc/Uno.Toolkit.RuntimeTests/Tests/*LeakTests.cs) proving the subscription is now weak/detached or that the cache entry dies with itsType/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.RuntimeTestsbuild clean onnet9.0(0 warnings, 0 errors).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