Skip to content

fix(alc): sweep collectible-ALC static-cache pins (WASM batch 1) - #23707

Merged
nickrandolph merged 21 commits into
masterfrom
dev/nr/wasm-alc-sweeps-uno
Aug 4, 2026
Merged

nickrandolph merged 21 commits into
masterfrom
dev/nr/wasm-alc-sweeps-uno

Conversation

@nickrandolph

Copy link
Copy Markdown
Contributor

Summary

Batch 1 of managed sweeps that release collectible-AssemblyLoadContext pins for a downstream host that loads previewed apps into their own collectible AssemblyLoadContexts and unloads them on reload. On WebAssembly AssemblyLoadContext.Unloading is never raised, so process-lifetime static caches that key on (or reference) an app's Assembly/Type/delegate keep the context alive after Unload(). Each cache is swept from the existing ALC cleanup hook (Application.CleanupNonDefaultAlcCaches, invoked from Window.CloseAlcWindow) or exposes an ALC-scoped removal called from a reachable teardown path — matching the established Style.ClearCachesForNonDefaultAlc / RemoveNonDefaultAlcEntries pattern.

Closes #23706

Sweeps landed

  1. ResourceLoader — ClearNonDefaultAlcAssemblies() drops previewed-app lookup assemblies (and their parsed-resource markers) from the process-lifetime _lookupAssemblies list; wired into the cleanup hook.
  2. UIElementNativeRegistrar._classNames (WASM) — ClearNonDefaultAlcEntries() drops the collectible-ALC Type keys of the element-type→registration-id map (invisible to a desktop-only guard). The JS-side registration map holds only strings (no ALC pin) and is intentionally left intact — its ids come from a shared counter, so deleting entries there could collide with live registrations.
  3. WindowId maps — AppWindow / ApplicationView / CoreDragDropManager each gain DestroyForWindowId, mirroring DisplayInformation.DestroyForWindowId, called from Window.CloseAlcWindow. These retained the closed window's instance and its event subscribers.
  4. CompositionTarget.Rendering (WASM) — ClearNonDefaultAlcHandlers() drops non-default-ALC subscribers from the static handler list; the per-frame dispatch now reuses a snapshot buffer instead of allocating a fresh List every frame.
  5. Hot-reload client status history — a terminal HotReloadClientOperation releases its raw Type[] (keeping the curated string list), and the local-operation history is capped to a ~100-entry ring buffer, so retained operations no longer pin every hot-reloaded collectible type.
  6. PagePool (WASM/managed Frame) — collapsed to a single lazily-created process-wide instance (each Frame previously overwrote a shared static with a new pool, orphaning the old one while its eternal 30s scavenger kept it alive); the scavenger is scheduled at most once and only when pooling is enabled; ClearNonDefaultAlcEntries() drops collectible page-type keys.
  7. Residual Type-keyed statics — HtmlElementHelper._cache (WASM) and FeatureConfiguration.Style.UseUWPDefaultStylesOverride gain a collectible-ALC key sweep.

Skipped (verified not an ALC pin)

  • Finding 5 — ImageBrush._naturalSizeCache: keyed by data-URI/URL strings, which carry no ALC identity — a memory-bloat concern, not a pin. Out of scope here; noted as a follow-up (hash/LRU the data-URI keys).
  • UnicodeText.ICU._lookupCache: keyed by native-delegate types declared inside the framework (default ALC); app types are never keys. Left unchanged.
  • Finding 2 JS map: strings only, no managed reference. See Paths are either not shown or shown not as in the UWP Designer #2 above.

Out of scope (follow-ups)

Hot-reload delta pipeline retention; image Blob URL lifetime; FontFamilyLoader caches.

Tests (red/green)

Each sweep is guarded by a test asserting a collectible-ALC-keyed entry is dropped while default-ALC / framework entries are kept:

  • Given_ResourceLoader_Alc (unit) — proven red by neutering the sweep (fails at the removal assertion), green with it.
  • Given_WindowId_Maps_Alc (unit)
  • Given_ResidualTypeStatics_Alc (unit)
  • Given_HotReloadClientOperation_Alc (runtime, HAS_UNO_WINUI)
  • WASM-only sweeps (2, 4, HtmlElementHelper) validated by the WASM build; runtime coverage tracked with the batch.

Notes

Local environment is flaky (package churn / Cecil locks); build+test were run where possible and CI validates the rest. See specs/048-wasm-alc-pin-sweeps/spec.md.

🤖 Generated with Claude Code

Copilot AI lite review requested due to automatic review settings July 9, 2026 15:01
@github-actions github-actions Bot added platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform area/automation Categorizes an issue or PR as relevant to project automation kind/documentation labels Jul 9, 2026
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


Nick Randolph seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

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 collectible AssemblyLoadContext (ALC) unload leaks on WebAssembly by sweeping process-lifetime static caches that retain app Assembly/Type/delegate references (since AssemblyLoadContext.Unloading is not raised on WASM). The sweeps are wired into the existing ALC cleanup hook (Application.CleanupNonDefaultAlcCaches via Window.CloseAlcWindow) or equivalent teardown paths, and are guarded by targeted unit/runtime tests.

Changes:

  • Added ALC-scoped cleanup APIs for several process-wide registries (lookup assemblies, WindowId maps, WASM UIElement registrar, CompositionTarget handlers, HtmlElementHelper, PagePool, Hot Reload operation retention).
  • Wired new sweeps into Application.CleanupNonDefaultAlcCaches / Window.CloseAlcWindow.
  • Added new unit/runtime tests and a batch spec documenting the findings/fixes.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/Uno.UWP/UI/ViewManagement/ApplicationView.cs Add DestroyForWindowId to release per-window registry entries.
src/Uno.UWP/Microsoft/UI/Windowing/AppWindow.cs Add DestroyForWindowId to release per-window registry entries.
src/Uno.UWP/ApplicationModel/Resources/ResourceLoader.static.cs Add sweep to drop non-default-ALC lookup assemblies and rebuild caches.
src/Uno.UWP/ApplicationModel/DataTransfer/DragDrop/Core/CoreDragDropManager.cs Add DestroyForWindowId to release per-window registry entries.
src/Uno.UI/UI/Xaml/Window/Window.alc.cs Invoke new DestroyForWindowId cleanup calls on ALC window close.
src/Uno.UI/UI/Xaml/UIElement.wasm.cs Add WASM registrar sweep for non-default-ALC Type keys.
src/Uno.UI/UI/Xaml/Style/Style.cs Extend non-default-ALC key sweeping to UseUWPDefaultStylesOverride.
src/Uno.UI/UI/Xaml/PagePool.cs Make pool process-wide; start scavenger only when enqueuing and pooling enabled; add ALC sweep.
src/Uno.UI/UI/Xaml/Media/CompositionTarget.wasm.cs Add ALC handler sweep; reuse a dispatch snapshot buffer to reduce per-frame allocations.
src/Uno.UI/UI/Xaml/HtmlElementHelper.wasm.cs Add sweep for non-default-ALC Type-keyed cache entries.
src/Uno.UI/UI/Xaml/Controls/Frame/Frame.legacy.cs Stop per-Frame pool creation; use the process-wide PagePool.Instance.
src/Uno.UI/UI/Xaml/Application.Alc.cs Wire new sweeps into CleanupNonDefaultAlcCaches.
src/Uno.UI.UnitTests/Windows_UI_Xaml/Given_WindowId_Maps_Alc.cs New unit test for WindowId map removals.
src/Uno.UI.UnitTests/Windows_UI_Xaml/Given_ResidualTypeStatics_Alc.cs New unit test for UseUWPDefaultStylesOverride ALC sweep.
src/Uno.UI.UnitTests/ResourceLoader/Given_ResourceLoader_Alc.cs New unit test for ResourceLoader ALC sweep.
src/Uno.UI.RuntimeTests/Tests/HotReload/Given_HotReloadClientOperation_Alc.cs New runtime test for hot-reload raw Type[] release on terminal state.
src/Uno.UI.RemoteControl/HotReload/ClientHotReloadProcessor.Common.Status.cs Cap local operation history and drop raw Type[] at terminal state.
specs/048-wasm-alc-pin-sweeps/spec.md New spec documenting Batch 1 findings, patterns, fixes, and verification.

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

Comment thread src/Uno.UI/UI/Xaml/PagePool.cs Resolved
Copilot AI review requested due to automatic review settings July 9, 2026 15:07

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

Copilot reviewed 18 out of 18 changed files in this pull request and generated 4 comments.

Comment thread src/Uno.UI/UI/Xaml/PagePool.cs Resolved
Comment thread src/Uno.UI/UI/Xaml/Window/Window.alc.cs Resolved
Copilot AI review requested due to automatic review settings July 9, 2026 15:36

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

Copilot reviewed 20 out of 20 changed files in this pull request and generated 3 comments.

Comment thread src/Uno.UI/UI/Xaml/PagePool.cs Resolved
Copilot AI review requested due to automatic review settings July 9, 2026 15:50

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

Copilot reviewed 20 out of 20 changed files in this pull request and generated 1 comment.

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

Copilot reviewed 20 out of 20 changed files in this pull request and generated 4 comments.

Comment thread src/Uno.UI/UI/Xaml/UIElement.wasm.cs Resolved
Comment thread src/Uno.UI/UI/Xaml/PagePool.cs Resolved
Comment thread src/Uno.UI/UI/Xaml/Application.Alc.cs Resolved
@nventive-devops

Copy link
Copy Markdown
Contributor

The build 221560 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 289, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ClipboardTests.png-dark
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • DisplayInformation.png-dark
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
    • Focus_FocusVisual_Properties.png-dark
    • ImageIconPage.png-dark
    • DropDownButtonPage.png-dark
    • DropDownButtonPage.png
    • Buttons.png-dark
    • Buttons.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Examples.png-dark
    • Examples.png
  • skia-windows-screenshots: 289 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png
    • DisplayInformation.png-dark
    • DisplayInformation.png
    • CameraCaptureUISample.png-dark
    • CameraCaptureUISample.png
    • DataTransferManager.png-dark
    • DataTransferManager.png
    • Haptics.VibrationDevice.png-dark
    • Haptics.VibrationDevice.png
    • AutomationPropertiesExtensions_Role.png
    • DownloadFileSavePickerTests.png-dark
    • DownloadFileSavePickerTests.png
    • ElevatedView_Dimensions.png-dark
    • ElevatedView_Dimensions.png
    • ElevatedView_Levels.png-dark
    • ElevatedView_Levels.png
    • Expander_ScrollView.png-dark
    • Expander_ScrollView.png
    • AutomationPropertiesExtensions_Role.png-dark
    • AuthenticationBroker_Demo.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background
    • UITests.Uno_Web.Http.CookieManagerTests
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems

Copilot AI review requested due to automatic review settings July 10, 2026 04:38

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

Copilot reviewed 20 out of 20 changed files in this pull request and generated 6 comments.

Comment thread specs/048-wasm-alc-pin-sweeps/spec.md Resolved
Comment thread src/Uno.UI/UI/Xaml/Application.Alc.cs Resolved
Comment thread specs/048-wasm-alc-pin-sweeps/spec.md Resolved
Comment thread specs/048-wasm-alc-pin-sweeps/spec.md Resolved
@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 221668 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2348, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • ClipboardTests.png-dark
    • Buttons.png-dark
    • Buttons.png
    • DisplayInformation.png-dark
    • DropDownButtonPage.png-dark
    • DropDownButtonPage.png
    • ImageIconPage.png-dark
    • ContextRequested.png-dark
    • ContextRequested.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Focus_FocusVisual_Properties.png-dark
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
    • Examples.png-dark
    • Examples.png
  • skia-windows-screenshots: 2348 changed over 2390

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBarButtonWithIconTest.png
    • AppWindowPresenters.png-dark
    • ArcSegment.png-dark
    • AutoSizedTopLeft.png-dark
    • BadgeNotificationTests.png
    • Basics_Automated.png
    • BindableDrawerLayout_ChangePane.png-dark
    • BorderCenteredwithmargins.png
    • BorderRightwithmargins.png
    • BorderTopwithmargins.png-dark
    • Border_CornerRadius.png-dark
    • Border_CornerRadius.png
    • Border_Simple_No_Background_With_TextBox.png-dark
    • Border_Simple_No_Background_With_TextBox.png
    • Button_Click_Verify_SynchronizationContext.png-dark
    • Button_Click_Verify_SynchronizationContext.png
    • Capture with overlap.png-dark
    • Capture with overlap.png
    • ClipboardTests.png-dark
    • ClipboardTests.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • UITests.Uno_Web.Http.CookieManagerTests

Copilot AI review requested due to automatic review settings July 10, 2026 06:29

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

Copilot reviewed 20 out of 20 changed files in this pull request and generated no new comments.

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 225366 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2348, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Focus_FocusVisual_Properties.png-dark
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
    • ImageIconPage.png-dark
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • DisplayInformation.png-dark
    • ContextRequested.png-dark
    • ContextRequested.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • ClipboardTests.png-dark
    • Examples.png-dark
    • Examples.png
    • ExpanderColorValidationPage.png-dark
    • ExpanderColorValidationPage.png
  • skia-windows-screenshots: 2348 changed over 2394

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBarButtonWithIconTest.png-dark
    • AppXamlDefinedResources.png-dark
    • AutoBorderStretchwithleftmargin.png
    • AutoSizedPathCentered.png-dark
    • AutoSuggestBox_Reason.png
    • Basics Pivot Test.png-dark
    • BeginTime_MultipleAnimations.png-dark
    • BitmapIcon_Generic.png-dark
    • BitmapImage_vs_SvgImageSource.png-dark
    • BitmapImage_vs_SvgImageSource.png
    • Border_AntiAlias.png-dark
    • Border_AntiAlias.png
    • Border_Simple.png-dark
    • Border_Simple.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Canvas_In_Canvas.png-dark
    • Canvas_In_Canvas.png
    • Clipping652.png-dark
    • Clipping652.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • UITests.Uno_Web.Http.CookieManagerTests
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems

@robot-nick

Copy link
Copy Markdown

Automated Multi-Agent Review — PR #23707 (WASM collectible-ALC pin sweeps, batch 1)

Posted by an automated two-panel review (6 requirements/spec agents + 7 code agents). This is a review comment, not an approval or rejection. Listed below are only the Blocker and Major findings that reached consensus across ≥2 agents in at least one panel (single-agent findings, Minors, Nits, and open contradictions are excluded per scope).


🔴 Blockers (consensus)

B1 — Unscoped / all-non-default sweeps destroy a live sibling ALC's state, and the destructive primitives are a cross-app DoS surface

Consensus: Panel 1 (P2 Architect, P3 Security, P5 Operability, P6 Red Team) + Panel 2 (C1 Correctness, C2 Security, C7 Red Team)

  • The ClearNonDefaultAlc* ("all non-default") sweeps drop every non-default-ALC entry, not just the dying ALC's. If the host ever runs more than one previewed app at once (the issue itself describes a "secondary-app window" / "secondary-ALC subscriber"), closing one window runs CleanupNonDefaultAlcCaches and strips the live sibling's ResourceLoader lookups, UIElementNativeRegistrar class-name registrations, CompositionTarget.Rendering handlers, HtmlElementHelper/PagePool keys → silent broken resource resolution and a frozen UI for an app that is still running.
  • The spec's own L44 admits all-non-default is unsafe for UseUWPDefaultStylesOverride ("never all-non-default") — yet the same pattern ships for the data caches (rows 1, 2, 4, 8). The sibling-clobber is only half-mitigated.
  • Code-level confirmation (C1/C2/C7): Window.CloseAlcWindow calls Application.CleanupNonDefaultAlcCaches(dyingAlc). If dyingAlc is ever null, the core silently downgrades to CleanupAllSecondaryAlcCaches() — an unscoped sweep that wipes every secondary ALC's state (Application.Alc.cs:1817–1828). Worse, the unscoped branch is internally inconsistent: Style.RemoveAlcScopedUserStyleOverrides(null) only drops unload-initiated keys while ResourceLoader.ClearNonDefaultAlcAssemblies() / CompositionTarget.ClearNonDefaultAlcHandlers() remove all non-default — so at global shutdown the Style override can leak and pin the very ALC the PR exists to free, while the other two sweeps destroy a live sibling.
  • Trust boundary (C2, fail-closed): CleanupNonDefaultAlcCaches / CleanupAllSecondaryAlcCaches are internal static destructive primitives. If previewed-app code can reach internal Uno.UI members (via InternalsVisibleTo or reflection on non-public methods), a malicious app can call CleanupAllSecondaryAlcCaches() to wipe every app's state, or pass a sibling's ALC to force-evict it — a cross-app eviction / DoS primitive.

Fixes

  • Never allow the unscoped sweep from CloseAlcWindow: if (dyingAlc is null) throw (or scoped no-op) so unscoped is only reachable via an explicit CleanupAllSecondaryAlcCaches() shutdown entry.
  • Make every sweep dying-ALC-scoped (key by Assembly/AssemblyLoadContext identity, matching the DestroyForWindowId pattern already used for row 3), not "all non-default."
  • Reconcile the Style vs ResourceLoader/ClearNonDefaultAlcHandlers scoping so all sweeps agree on "unscoped."
  • Verify/close the InternalsVisibleTo + reflection trust boundary; prefer gating the unscoped path behind a host-only sentinel.

B2 — Rows 2 & 7 have no unit test and rest solely on an unspecified, unowned WASM CI pin guard

Consensus: Panel 1 (P2 Architect, P4 Testability, P5 Operability, P6 Red Team)

  • Row 2 (UIElementNativeRegistrar._classNames) and the collectible-key half of row 7 (PagePool) ship no automated unit test; their only proof is a "downstream WASM runtime ALC pin guard (CI)" that is never named, never scoped to these caches, and is unowned (bus-factor-1).
  • This violates the issue's own acceptance criterion (issue L31: "each sweep is guarded by a red/green test").
  • The pin guard almost certainly exercises a single load→close→unload cycle, so it cannot catch the concurrent-sibling clobber of B1 — the most dangerous behavior is the least tested, and "green CI" gives false assurance about sibling safety.

Fixes

  • Add real unit tests for rows 2 and 7 (or an injectable WASM-simulated host) that assert a collectible entry is dropped and a default/sibling entry survives.
  • Make the pin guard a named, owned, required status check, and add a two-concurrent-app variant that closes only one app and asserts the survivor still renders and resolves resources.

🟠 Majors (consensus)

M1 — HotReload TypeCorrelationScope permanently leaks a terminal op's Type[] (defeats the PR's goal)

Consensus: Panel 2 (C1 Correctness, C7 Red Team) — ClientHotReloadProcessor.Common.Status.cs:267/283/298–301

TryDeferReleaseToTypeCorrelationScopes() assigns _retainingScopes = _activeTypeCorrelationScopes.Count (overwrites, not increments) and Retain appends to a plain List with no dedup. A duplicate terminalization (e.g. success→failed both calling ReportCompleted) adds the op twice; Dispose decrements per entry, driving _retainingScopes to −1, so ReleaseRetainedTypes() is never called. The op's raw Type[] (pinning the previewed-app ALC) is retained for the process lifetime — the exact leak this PR targets.

Fix: Track retained scopes in a dedup set (or HashSet); make the defer idempotent; guard the terminal-release block in ReportCompleted with an Interlocked flag so it runs exactly once.

M2 — Three WASM sweeps bypass RunCleanupStep, so a throw skips the visual-tree unpin walk

Consensus: Panel 2 (C3 Architecture, C7 Red Team) — Application.Alc.cs:1894/1900–1902/1910

UIElement.ClearNonDefaultAlcElementRegistrations(), CompositionTarget.ClearAlcHandlers(...)/ClearNonDefaultAlcHandlers(), and HtmlElementHelper.ClearNonDefaultAlcEntries() are called directly, unlike the other steps that go through RunCleanupStep. A throw in any of them skips every later step — including the visual-tree event-subscription unpin walk that is the central release mechanism. Window.CloseAlcWindow only logs and returns true, so teardown "succeeds" while the ALC stays pinned.

Fix: Wrap every sweep in RunCleanupStep / a DestroyForWindowIdSafe-style isolator so one failure cannot abort the rest.

M3 — ResourceLoader scoped rebuild is expensive and non-transactional

Consensus: Panel 2 (C4 Performance, C7 Red Team) — ResourceLoader.static.cs:3111–3238

ClearAlcAssemblies(dyingAlc) → RebuildLoaderResourcesFromSurvivors() synchronously re-parses every .upri of all surviving lookup assemblies on every Window.CloseAlcWindow — O(total surviving resource size), not the dying app. The apply-phase (RebuildLoaderResourcesFromSurvivors) clears every live loader's _resources then repopulates outside the parse try/catch; a non-whitelisted exception during repopulation can leave one or more loaders empty, breaking every survivor's resource lookups, not just the dying app's.

Fix: Run under the loader lock; build into per-loader temporary dictionaries and swap atomically; defer/coalesce the full re-parse off the close hot path (idle/RunIdleAsync).

M4 — Sweep synchronization gaps (locks on only 4 of N swept caches)

Consensus: Panel 2 (C1 Correctness, C7 Red Team) — Application.Alc.cs:1851–1922

UIElementNativeRegistrar, HtmlElementHelper, CompositionTarget, and PagePool added _*Gate locks, but DependencyProperty, Style, MetadataAPI, ResourceResolver, ClearNonDefaultAlcApplications perform unsynchronized foreach+Remove over their dictionaries. The PR's own comments admit the sweep "can reach this map from other teardown paths" and "Dictionary corrupts under concurrent mutation." An unguarded throw also skips the rest of the sweep (ties into M2).

Fix: Extend lock discipline to every swept cache, or serialize teardown to a single thread.

M5 — Whole approach over-relies on a single, unverified teardown seam (CloseAlcWindow)

Consensus: Panel 1 (P1 Product, P2 Architect, P6 Red Team)

Every sweep is contingent on the host routing teardown through Window.CloseAlcWindow → CleanupNonDefaultAlcCaches. The natural API for an unloading host is AssemblyLoadContext.Unload() directly; if the downstream host (or a future caller) calls Unload() without CloseAlcWindow, the hook never fires and every pin returns — the leak is fully reintroduced with zero signal. (Desktop/Skia Unloading does fire but is not wired.)

Fix: Also subscribe to AssemblyLoadContext.Unloading where it fires as a secondary seam; document that the WASM host MUST call CloseAlcWindow; add a guard/test asserting the sweep runs even if only Unload() is invoked on non-WASM.

M6 — No per-sweep fault/error isolation contract in the cleanup chokepoint

Consensus: Panel 1 (P2 Architect, P4 Testability)

The hook calls ResourceLoader, CompositionTarget, residual statics, PagePool, etc. sequentially. If one throws, the later sweeps (and WindowId teardown) may be skipped, silently re-leaking. No test asserts the contract (continue / abort / swallow).

Fix: Define and unit-test the contract: each sweep wrapped; an injected throw in one must not block siblings; assert sibling sweeps still execute.


✅ Consensus strengths (noted, not gating)

  • The headline per-frame allocation win is verified real (no List<T> allocated per frame; reuses a _snapshot buffer). (Panel 2 C4)
  • DestroyForWindowIdSafe correctly isolates each per-WindowId registry teardown; IsFromUnloadInitiatedAlc fails safe (valueIfUnknown:false) and avoids constructed-generic false positives. (Panel 2 C1, C2, C3, C7)
  • The spec's honest, explicit non-uniform coverage disclosure and documented skip rationale were consistently praised by all six requirements agents.

Scope note: this comment includes only Blocker/Major findings that reached multi-agent consensus. Single-agent Majors, Minors, Nits, and the open design contradictions (e.g. issue L31 "ALC-scoped" vs implemented …NonDefault… naming) were intentionally omitted. Generated by the review-panel-requirements + review-panel-code skills.

… paths

Addresses the multi-agent review on PR #23707 (WASM collectible-ALC pin sweeps).

- B1: the per-window entry CleanupNonDefaultAlcCaches now passes
  allowUnscopedDestructive:false; only the explicit global-shutdown entry
  CleanupAllSecondaryAlcCaches goes wide. A window close whose dying ALC could
  not be identified (dyingAlc null) now SKIPS the destructive sweeps instead of
  clobbering a live sibling app. Reconciled the global-shutdown scope so Style
  user overrides, ResourceLoader lookup assemblies and CompositionTarget
  handlers all go all-non-default together (new Style
  RemoveAllNonDefaultAlcUserStyleOverrides) — the Style override can no longer
  leak while the others clobber.
- M2/M6: every sweep in CleanupNonDefaultAlcCachesCore (including the three WASM
  sweeps and the rebuildable-cache block) now runs through RunCleanupStep, so a
  throw in one cannot abort the rest (the visual-tree unpin walk / per-WindowId
  teardown). RunCleanupStep made internal + unit-tested.
- M4: documented the teardown threading contract at the chokepoint and routed
  the previously-unguarded sweeps through the isolator so a concurrent-
  modification throw is contained rather than aborting the chain.
- B2: added unit tests asserting the collectible-key drop AND default/sibling
  survival for PagePool (GetPooledCount seam) and for the shared sweep engine
  AlcCacheSweep.RemoveNonDefaultAlcEntries (UIElementNativeRegistrar row 2 is a
  thin WASM/JS wrapper over it). Added an M6 fault-isolation test.
- M1: added a regression test proving a double-terminalized op under two
  overlapping type-correlation scopes releases its raw Type[] exactly once.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings August 1, 2026 22:00
@nickrandolph

Copy link
Copy Markdown
Contributor Author

Disposition — automated review (2 Blockers + 6 Majors)

All addressed in 4397516679. Note the review's line numbers were stale (they cite Application.Alc.cs:1817+/ResourceLoader.static.cs:3111 in files that are ~1k / ~475 lines); several items were already fixed by earlier commits on this branch. Verified each against current code.

# Disposition
B1 Fixed. The per-window entry CleanupNonDefaultAlcCaches now calls the core with allowUnscopedDestructive:false; only the explicit CleanupAllSecondaryAlcCaches (global shutdown) passes true. A CloseAlcWindow whose dyingAlc could not be identified (null) now skips the destructive sweeps instead of going wide — it can never clobber a live sibling. Reconciled global-shutdown scope: added Style.RemoveAllNonDefaultAlcUserStyleOverrides() so at CleanupAllSecondaryAlcCaches the Style overrides, ResourceLoader lookup assemblies and CompositionTarget handlers all go all-non-default together (previously the Style override sweep stayed unload-scoped and could leak while the others clobbered). Rebuildable caches (DependencyProperty/Style caches/UIElementNativeRegistrar/HtmlElementHelper) remain wide by design. Trust boundary — won't-fix w/ rationale: CleanupAllSecondaryAlcCaches is internal; Uno.UI does not grant InternalsVisibleTo to previewed/secondary apps (they are separately-compiled apps in collectible ALCs). There is no host↔previewed-app security boundary in this in-process architecture — a previewed app that could reflect over internal statics can already corrupt shared state directly — so a sentinel gate would add no protection against reflection.
B2 Fixed. Added Given_PagePool.When_ClearNonDefaultAlcEntries_Then_Collectible_Key_Dropped_And_Default_Kept (loads a collectible-ALC page-type key, asserts it is dropped and the default-ALC entry survives, via a new GetPooledCount seam). Row 2 (UIElementNativeRegistrar._classNames) is WASM/JS-interop bound and a thin wrapper over the shared engine AlcCacheSweep.RemoveNonDefaultAlcEntries; added Given_AlcCacheSweep.When_RemoveNonDefaultAlcEntries_Then_Collectible_Key_Dropped_And_Default_Kept covering that engine (drop collectible + keep default/sibling).
M1 Already guarded + regression test added. Current ReportCompleted uses a CAS on _result that returns early on any already-terminal state, so TryDeferReleaseToTypeCorrelationScopes runs at most once per op — a double ReportCompleted cannot register the op twice or drive _retainingScopes negative. TypeCorrelationScope.Dispose is already idempotent (Interlocked.Exchange(_disposed)). Added When_Double_Terminalized_Under_Overlapping_Scopes_Then_Types_Released_Exactly_Once to lock this in. No production change needed (the CAS is the once-flag).
M2 Fixed. The three WASM sweeps (UIElement.ClearNonDefaultAlcElementRegistrations, CompositionTarget.ClearAlcHandlers/ClearNonDefaultAlcHandlers, HtmlElementHelper.ClearNonDefaultAlcEntries) and the previously-direct rebuildable-cache block now all run through RunCleanupStep, so a throw can no longer skip later steps incl. the visual-tree unpin walk.
M3 Already addressed (transactional) + rationale on perf. RebuildLoaderResourcesFromSurvivors already parses into temporary dictionaries under per-assembly try/catch and applies via a non-throwing copy phase — a malformed .upri can no longer leave a loader empty (the "repopulate outside try/catch" gap is closed). The synchronous re-parse runs only on ALC unload (window close), not a per-frame hot path; deferring it to idle would open a window of stale/missing resource overrides, so it is kept synchronous by design.
M4 Documented + isolated. Added an explicit threading-contract comment at the chokepoint: the rebuildable Type-caches (DependencyProperty/Style/MetadataAPI/ResourceResolver) are populated and swept on the same UI/teardown thread; the four caches that carry _*Gate locks are precisely the ones additionally reachable off that thread (the WASM rendering frame callback and native element creation) — the asymmetry is intentional. Routing every sweep through RunCleanupStep also means an unexpected concurrent-modification throw is now contained instead of aborting the chain. Extending locks into the hot DP/Style registration paths was judged out of proportion for this WASM-sweep charter.
M5 Partially already wired + won't-fix the rest w/ rationale. AssemblyLoadContext.Unloading is already subscribed where it fires (ResourceResolver.alc.cs, DependencyObjectStore.alc.cs) for their ALC-scoped registrations. On WASM Unloading is never raised, so it cannot be the WASM seam; the host contract requiring CloseAlcWindow is documented in Window.alc.cs. Wiring the whole broad sweep to Unloading as a second desktop/Skia teardown seam is a design change beyond this PR's WASM-sweep scope.
M6 Fixed. RunCleanupStep made internal and unit-tested (Given_AlcCacheSweep.When_A_Cleanup_Step_Throws_Then_Later_Steps_Still_Run): an injected throw in one step must not prevent a later step from running.

Build (0 errors): Uno.UI.Skia, Uno.UI.Wasm, Uno.UI.RemoteControl.Skia, Uno.UI.UnitTests, Uno.UI.RuntimeTests.Skia all clean. Tests: 35 ALC-related unit tests pass (incl. the 4 new/changed); the M1 runtime test compiles and mirrors verified sibling tests.

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

Copilot reviewed 29 out of 29 changed files in this pull request and generated no new comments.

Suppressed comments (8)

src/Uno.UI/UI/Xaml/Media/CompositionTarget.wasm.cs:58

  • ClearNonDefaultAlcHandlers passes null into ClearAlcHandlersCore, but ClearAlcHandlersCore currently takes a non-nullable AssemblyLoadContext. With nullable enabled (and warnings-as-errors), this will fail the build. Make the scope parameter nullable so the global-teardown path can pass null as intended.
	internal static void ClearNonDefaultAlcHandlers()
		=> ClearAlcHandlersCore(scope: null);

src/Uno.UI/UI/Xaml/Application.Alc.cs:383

  • CleanupAllSecondaryAlcCaches calls CleanupNonDefaultAlcCachesCore(dyingAlc: null, ...), and the implementation checks dyingAlc is null, but the parameter is currently non-nullable AssemblyLoadContext. With nullable enabled (and warnings-as-errors), this will fail the build. Make dyingAlc nullable in the core method signature.
	internal static void CleanupAllSecondaryAlcCaches()
		=> CleanupNonDefaultAlcCachesCore(dyingAlc: null, allowUnscopedDestructive: true);

src/Uno.UI/UI/Xaml/Application.Alc.cs:372

  • Window.CloseAlcWindow can legitimately pass a null dyingAlc (when it can't be identified), but CleanupNonDefaultAlcCaches currently takes a non-nullable AssemblyLoadContext. With warnings-as-errors this will break the build at call sites. Accept a nullable ALC and let CleanupNonDefaultAlcCachesCore handle the null (skipping destructive sweeps).
	/// <param name="dyingAlc">
	/// The <see cref="AssemblyLoadContext"/> being torn down. REQUIRED: it scopes the DESTRUCTIVE
	/// removals below to that ALC so that, with two live secondary apps, closing one does not
	/// destroy the other's state. Global-shutdown paths, where no single dying ALC exists, must
	/// opt in to the wide sweep explicitly via <see cref="CleanupAllSecondaryAlcCaches"/>.
	/// </param>
	internal static void CleanupNonDefaultAlcCaches(AssemblyLoadContext dyingAlc)
		=> CleanupNonDefaultAlcCachesCore(dyingAlc, allowUnscopedDestructive: false);

src/Uno.UI/UI/Xaml/Style/Style.cs:65

  • Typo in log message: "entrie(s)" should be "entries".
			if (removed > 0 && _logger.IsEnabled(LogLevel.Debug))
			{
				_logger.Debug($"[ALC-CLEANUP] UseUWPDefaultStylesOverride: removed {removed} entrie(s) owned by dying ALC '{dyingAlc?.Name ?? "unload-initiated"}'.");
			}
		}

src/Uno.UI/UI/Xaml/Style/Style.cs:84

  • Typo in log message: "entrie(s)" should be "entries".
			if (removed > 0 && _logger.IsEnabled(LogLevel.Debug))
			{
				_logger.Debug($"[ALC-CLEANUP] UseUWPDefaultStylesOverride: removed {removed} entrie(s) from all non-default ALCs (global shutdown).");
			}

src/Uno.UI/UI/Xaml/Style/Style.cs:44

  • Typo in log message: "entrie(s)" should be "entries".

This issue also appears in the following locations of the same file:

  • line 61
  • line 81
			if (removed > 0 && _logger.IsEnabled(LogLevel.Debug))
			{
				_logger.Debug($"[ALC-CLEANUP] Style caches: removed {removed} non-default-ALC entrie(s).");
			}

src/Uno.UI/UI/Xaml/HtmlElementHelper.wasm.cs:59

  • Typo in log message: "entrie(s)" should be "entries".
		if (removed > 0 && typeof(HtmlElementHelper).Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug))
		{
			typeof(HtmlElementHelper).Log().Debug($"[ALC-CLEANUP] HtmlElementHelper: removed {removed} non-default-ALC tag cache entrie(s).");
		}

src/Uno.UWP/ApplicationModel/Resources/ResourceLoader.static.cs:182

  • Typo in log message: "assemblie(s)" should be "assemblies".
		if (_log.IsEnabled(LogLevel.Debug))
		{
			_log.LogDebug($"[ALC-CLEANUP] ResourceLoader: removed {removed.Count} lookup assemblie(s) and {removedMarkers} parsed-resource marker(s).");
		}

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 225369 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2348, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • DisplayInformation.png-dark
    • Buttons.png-dark
    • Buttons.png
    • Examples.png-dark
    • Examples.png
    • ExpanderColorValidationPage.png-dark
    • ExpanderColorValidationPage.png
    • ClipboardTests.png-dark
    • DropDownButtonPage.png-dark
    • ContextRequested.png-dark
    • DropDownButtonPage.png
    • ContextRequested.png
    • Focus_FocusVisual_Properties.png-dark
    • ImageIconPage.png-dark
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
  • skia-windows-screenshots: 2348 changed over 2394

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBarToggleButtonTest.png-dark
    • AppBarButtonWithIconTest.png
    • AppBarButtonWithIconTest.png-dark
    • AppWindowFeatures.png
    • AppWindowClosing.png-dark
    • AppWindowPresenters.png-dark
    • Attributed_text_Simple.png
    • Attributed_text_Supserscript.png-dark
    • AuthenticationBroker_Demo.png
    • AutoBorderStretchwithrightmargin.png
    • AutoSuggestBox_Icons.png
    • AutomationProperties_AutomationId.png
    • AutoSizedTopLeft.png
    • Basics Pivot Test.png
    • AutoSuggestBox_Keyboard.png-dark
    • BackGesture.png
    • BeginTime_MultipleAnimations.png
    • Basics.png-dark
    • Basics Pivot Test.png-dark
    • BitmapIcon_Sizing.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background
    • UITests.Uno_Web.Http.CookieManagerTests
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation

@autocarl autocarl left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third pass on exact head 43975166796b7bd79163def35631ca51b94780fb.

The previous stale-value finding is fixed for valid surviving resource assemblies, every current hosted check is green (70 successful; only the expected neutral/skipped checks remain), and the original local exit 134 was environmental: the test host could not locate libSkiaSharp.so. Supplying the matching native asset made the exact targeted set pass 13/13.

Two correctness issues remain in the revised scoped teardown. I reproduced both at this exact head with isolated tests:

  1. removing one secondary ALC also unregisters a still-live sibling Application;
  2. a malformed surviving .upri escapes the advertised per-assembly guard and leaves the removed ALC's merged override observable.

The two probes each passed while asserting the current faulty behavior (1/1 + 1/1). Details and fix direction are inline. Requesting changes on this revision.

Comment thread src/Uno.UI/UI/Xaml/Application.Alc.cs Resolved
Nick Randolph and others added 2 commits August 4, 2026 17:36
- the ALC -> Application registry is destructive state (populated only by
  each secondary app's constructor, never rebuilt on demand), so the
  cleanup step now removes only the dying ALC's entry when it is known,
  runs wide only at a genuine global shutdown, and is skipped when a
  per-window teardown cannot name its ALC
- add a registration-only removal helper: calling RemoveAlcApplication
  from inside the sweep would recurse back into the sweep
- update the destructive-sweep doc lists to include the registry
- tests: sibling registration survives the scoped sweep; unknown-ALC
  per-window teardown keeps all live registrations

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… rebuild

- ProcessResourceFile now surfaces malformed .upri content (bad magic,
  unsupported version, unreadable stream) as InvalidDataException, the
  data-format type the per-assembly rebuild guard already catches, so a
  malformed survivor is logged-and-skipped instead of aborting the
  rebuild before its apply phase and leaving the removed ALC's merged
  overrides observable
- AddLookupAssembly rolls back the just-added registration (and its
  parsed markers) when parsing throws, so a failed registration cannot
  linger among the survivors; the exception still reaches the caller
- tests: sweep with a malformed survivor completes and drops the dying
  ALC's override; failed registration throws InvalidDataException and
  is rolled back (malformed assembly emitted in-memory via
  ManagedPEBuilder)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings August 4, 2026 07:38

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

Copilot reviewed 29 out of 29 changed files in this pull request and generated no new comments.

Suppressed comments (9)

src/Uno.UI/UI/Xaml/Application.Alc.cs:384

  • CleanupNonDefaultAlcCaches is documented as requiring a non-null dyingAlc, but call sites intentionally pass null (unknown dying ALC) and the implementation branches on dyingAlc is null. The signature/docs should reflect the supported null value to avoid misleading callers and to keep nullable annotations accurate when enabled.
	/// <param name="dyingAlc">
	/// The <see cref="AssemblyLoadContext"/> being torn down. REQUIRED: it scopes the DESTRUCTIVE
	/// removals below to that ALC so that, with two live secondary apps, closing one does not
	/// destroy the other's state. Global-shutdown paths, where no single dying ALC exists, must
	/// opt in to the wide sweep explicitly via <see cref="CleanupAllSecondaryAlcCaches"/>.
	/// </param>
	internal static void CleanupNonDefaultAlcCaches(AssemblyLoadContext dyingAlc)
		=> CleanupNonDefaultAlcCachesCore(dyingAlc, allowUnscopedDestructive: false);

src/Uno.UI/UI/Xaml/Media/CompositionTarget.wasm.cs:72

  • ClearNonDefaultAlcHandlers() passes null to ClearAlcHandlersCore, and the logging uses scope?.Name, so the core method parameter should be nullable to match the supported semantics (null == all non-default ALCs).
	private static void ClearAlcHandlersCore(AssemblyLoadContext scope)

src/Uno.UI/UI/Xaml/Application.Alc.cs:412

  • CleanupNonDefaultAlcCachesCore is invoked with dyingAlc: null (global shutdown / unknown ALC) and branches on dyingAlc is null, so the parameter should be nullable for correctness and clarity.
	private static void CleanupNonDefaultAlcCachesCore(AssemblyLoadContext dyingAlc, bool allowUnscopedDestructive)

src/Uno.UI/UI/Xaml/Style/Style.cs:63

  • Typo in log message: "entrie(s)" should be "entries".
				_logger.Debug($"[ALC-CLEANUP] UseUWPDefaultStylesOverride: removed {removed} entrie(s) owned by dying ALC '{dyingAlc?.Name ?? "unload-initiated"}'.");

src/Uno.UI/UI/Xaml/Style/Style.cs:83

  • Typo in log message: "entrie(s)" should be "entries".
				_logger.Debug($"[ALC-CLEANUP] UseUWPDefaultStylesOverride: removed {removed} entrie(s) from all non-default ALCs (global shutdown).");

src/Uno.UWP/ApplicationModel/Resources/ResourceLoader.static.cs:169

  • ClearNonDefaultAlcAssemblies() removes the lookup assemblies and parsed markers, but does not rebuild merged loader resources. If any removed (collectible) assembly overwrote a host key, that overridden value can remain observable after the sweep, effectively letting a collectible app override outlive its ALC in the global-shutdown path.
	internal static void ClearNonDefaultAlcAssemblies()
		=> ClearAlcAssembliesCore(IsFromNonDefaultAlc, rebuildFromSurvivors: false);

src/Uno.UWP/ApplicationModel/Resources/ResourceLoader.static.cs:205

  • Typo in log message: "assemblie(s)" should be "assemblies".
		if (_log.IsEnabled(LogLevel.Debug))
		{
			_log.LogDebug($"[ALC-CLEANUP] ResourceLoader: removed {removed.Count} lookup assemblie(s) and {removedMarkers} parsed-resource marker(s).");
		}

src/Uno.UI/UI/Xaml/Style/Style.cs:44

  • Typo in log message: "entrie(s)" should be "entries".

This issue also appears in the following locations of the same file:

  • line 63
  • line 83
				_logger.Debug($"[ALC-CLEANUP] Style caches: removed {removed} non-default-ALC entrie(s).");

src/Uno.UI/UI/Xaml/HtmlElementHelper.wasm.cs:59

  • Typo in log message: "entrie(s)" should be "entries".
			typeof(HtmlElementHelper).Log().Debug($"[ALC-CLEANUP] HtmlElementHelper: removed {removed} non-default-ALC tag cache entrie(s).");

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 225638 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2348, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • DropDownButtonPage.png-dark
    • DropDownButtonPage.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_CurrentReading.png
    • Gamepad_Enumeration.png-dark
    • Gamepad_Enumeration.png
    • ClipboardTests.png-dark
    • ContextRequested.png-dark
    • ContextRequested.png
    • DisplayInformation.png-dark
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Focus_FocusVisual_Properties.png-dark
    • ImageIconPage.png-dark
    • Examples.png-dark
    • Examples.png
    • ExpanderColorValidationPage.png-dark
    • ExpanderColorValidationPage.png
  • skia-windows-screenshots: 2348 changed over 2394

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AppBarToggleButtonTest.png
    • Accessibility_ScreenReader.png
    • AppBar_KeyBoard.png-dark
    • AppWindowTitleBar Properties.png-dark
    • ApplicationViewSizing.png-dark
    • AppWindowPresenters.png
    • AuthenticationBroker_Demo.png
    • AppXamlDefinedResources.png-dark
    • AutoBorderStretchwithbottommargin.png-dark
    • AutomationProperties_AutomationId.png-dark
    • AutoBorderStretchwithrightmargin.png-dark
    • AutomationProperties_AutomationId.png
    • AutoSuggestBox_Description.png-dark
    • AutoSuggestBox_BitmapIcon.png-dark
    • AutoSuggestBox_Icons.png-dark
    • BasicAcrylicBrushTest.png-dark
    • BasicEnability.png-dark
    • BasicEnability.png
    • BorderWithNullBrushAndNonZeroThickness.png
    • BezierSegment.png
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • UITests.Uno_Web.Http.CookieManagerTests

@nickrandolph
nickrandolph merged commit 2fc0049 into master Aug 4, 2026
72 checks passed
@nickrandolph
nickrandolph deleted the dev/nr/wasm-alc-sweeps-uno branch August 4, 2026 12:09
@kazo0

kazo0 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

/unobot prepare-release --commit-message-pattern "ci: Set version to '{0}'"

@unodevops

Copy link
Copy Markdown
Contributor

The release branch release/stable/6.7 has been created from 3889778 and the PR #23956 has been created for the version bump.

@autocarl

autocarl commented Aug 4, 2026

Copy link
Copy Markdown

@nickrandolph I rechecked the merged head 1e6b388c77ed51be12b53dc16920b8a8d9ea4249 against the two findings in my last review.

The two original blockers are addressed:

  • 868530968e8a scopes the Application registry removal to the dying ALC and keeps live sibling registrations; the scoped and unknown-ALC regressions exercise the real registration path.
  • 1e6b388c77ed normalizes malformed .upri failures to InvalidDataException, keeps one malformed survivor from aborting the temporary rebuild, and removes a failed assembly registration.

The two affected test classes pass locally on the exact merged head: 10/10 under net10.0. The merge commit has no additional changes in the four touched source/test files, and the final hosted rollup is 69 success / 1 neutral / 1 skipped.

One correctness gap remains in the new registration rollback:

[MEDIUM] AddLookupAssembly can roll back the registration while leaving partially merged resource values observable.

ProcessResourceFile mutates the live loader incrementally: it adds the parsed marker, obtains the live _resources dictionary, and writes each pair at resources[key] = value. If a syntactically valid .upri declares multiple entries, successfully writes the first, and is then truncated before a later key/value, BinaryReader.ReadString throws EndOfStreamException (IOException). The new catch in AddLookupAssembly removes the assembly from _lookupAssemblies and removes its markers, but it does not restore the live resource dictionaries. The first value therefore remains observable even though ContainsLookupAssembly(assembly) is false.

The new rollback test uses a bad magic, so it throws before the marker and live dictionary are mutated and cannot detect this partial-parse case.

Please handle this in a follow-up patch/issue: make AddLookupAssembly parse into temporary dictionaries and apply only after the entire assembly succeeds, or rebuild from the surviving registrations on failure. A focused regression can emit one valid .upri with resourceCount = 2, include the first key/value, truncate before the second, then assert all three conditions: the expected exception is raised, the assembly is unregistered, and the first value is not visible.

So: I am satisfied with the two requested teardown fixes, but not with the full transactional claim of the new AddLookupAssembly rollback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/automation Categorizes an issue or PR as relevant to project automation kind/documentation platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Collectible-ALC static caches pin the context after unload (WASM batch)

10 participants