Repository navigation
fix(alc): sweep collectible-ALC static-cache pins (WASM batch 1) - #23707
Conversation
|
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. |
There was a problem hiding this comment.
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.
|
The build 221560 found UI Test snapshots differences: Details
|
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23707/wasm-skia-net9/index.html |
|
The build 221668 found UI Test snapshots differences: Details
|
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-23707/docs/index.html |
|
The build 225366 found UI Test snapshots differences: Details
|
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 surfaceConsensus: Panel 1 (P2 Architect, P3 Security, P5 Operability, P6 Red Team) + Panel 2 (C1 Correctness, C2 Security, C7 Red Team)
Fixes
B2 — Rows 2 & 7 have no unit test and rest solely on an unspecified, unowned WASM CI pin guardConsensus: Panel 1 (P2 Architect, P4 Testability, P5 Operability, P6 Red Team)
Fixes
🟠 Majors (consensus)M1 — HotReload
|
… 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]>
Disposition — automated review (2 Blockers + 6 Majors)All addressed in
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. |
There was a problem hiding this comment.
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
ClearNonDefaultAlcHandlerspassesnullintoClearAlcHandlersCore, butClearAlcHandlersCorecurrently takes a non-nullableAssemblyLoadContext. With nullable enabled (and warnings-as-errors), this will fail the build. Make thescopeparameter nullable so the global-teardown path can passnullas intended.
internal static void ClearNonDefaultAlcHandlers()
=> ClearAlcHandlersCore(scope: null);
src/Uno.UI/UI/Xaml/Application.Alc.cs:383
CleanupAllSecondaryAlcCachescallsCleanupNonDefaultAlcCachesCore(dyingAlc: null, ...), and the implementation checksdyingAlc is null, but the parameter is currently non-nullableAssemblyLoadContext. With nullable enabled (and warnings-as-errors), this will fail the build. MakedyingAlcnullable in the core method signature.
internal static void CleanupAllSecondaryAlcCaches()
=> CleanupNonDefaultAlcCachesCore(dyingAlc: null, allowUnscopedDestructive: true);
src/Uno.UI/UI/Xaml/Application.Alc.cs:372
Window.CloseAlcWindowcan legitimately pass a nulldyingAlc(when it can't be identified), butCleanupNonDefaultAlcCachescurrently takes a non-nullableAssemblyLoadContext. With warnings-as-errors this will break the build at call sites. Accept a nullable ALC and letCleanupNonDefaultAlcCachesCorehandle 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).");
}
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23707/wasm-skia-net9/index.html |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-23707/docs/index.html |
|
The build 225369 found UI Test snapshots differences: Details
|
autocarl
left a comment
There was a problem hiding this comment.
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:
- removing one secondary ALC also unregisters a still-live sibling
Application; - a malformed surviving
.upriescapes 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.
- 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]>
There was a problem hiding this comment.
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
CleanupNonDefaultAlcCachesis documented as requiring a non-nulldyingAlc, but call sites intentionally pass null (unknown dying ALC) and the implementation branches ondyingAlc is null. The signature/docs should reflect the supportednullvalue 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()passesnulltoClearAlcHandlersCore, and the logging usesscope?.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
CleanupNonDefaultAlcCachesCoreis invoked withdyingAlc: null(global shutdown / unknown ALC) and branches ondyingAlc 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).");
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23707/wasm-skia-net9/index.html |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-23707/docs/index.html |
|
The build 225638 found UI Test snapshots differences: Details
|
|
/unobot prepare-release --commit-message-pattern "ci: Set version to '{0}'" |
|
@nickrandolph I rechecked the merged head The two original blockers are addressed:
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]
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 So: I am satisfied with the two requested teardown fixes, but not with the full transactional claim of the new |
Summary
Batch 1 of managed sweeps that release collectible-
AssemblyLoadContextpins for a downstream host that loads previewed apps into their own collectible AssemblyLoadContexts and unloads them on reload. On WebAssemblyAssemblyLoadContext.Unloadingis never raised, so process-lifetime static caches that key on (or reference) an app'sAssembly/Type/delegate keep the context alive afterUnload(). Each cache is swept from the existing ALC cleanup hook (Application.CleanupNonDefaultAlcCaches, invoked fromWindow.CloseAlcWindow) or exposes an ALC-scoped removal called from a reachable teardown path — matching the establishedStyle.ClearCachesForNonDefaultAlc/RemoveNonDefaultAlcEntriespattern.Closes #23706
Sweeps landed
ResourceLoader—ClearNonDefaultAlcAssemblies()drops previewed-app lookup assemblies (and their parsed-resource markers) from the process-lifetime_lookupAssemblieslist; wired into the cleanup hook.UIElementNativeRegistrar._classNames(WASM) —ClearNonDefaultAlcEntries()drops the collectible-ALCTypekeys 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.AppWindow/ApplicationView/CoreDragDropManagereach gainDestroyForWindowId, mirroringDisplayInformation.DestroyForWindowId, called fromWindow.CloseAlcWindow. These retained the closed window's instance and its event subscribers.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 freshListevery frame.HotReloadClientOperationreleases its rawType[](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.PagePool(WASM/managed Frame) — collapsed to a single lazily-created process-wide instance (eachFramepreviously 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.Type-keyed statics —HtmlElementHelper._cache(WASM) andFeatureConfiguration.Style.UseUWPDefaultStylesOverridegain a collectible-ALC key sweep.Skipped (verified not an ALC pin)
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.Out of scope (follow-ups)
Hot-reload delta pipeline retention; image Blob URL lifetime;
FontFamilyLoadercaches.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)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