Skip to content

fix(macos): Keep closed NSWindows alive until AppKit is done - #25201

Merged
ajpinedam merged 7 commits into
masterfrom
dev/mazi/macos-window-lifetime
Oct 27, 2026
Merged

ajpinedam merged 7 commits into
masterfrom
dev/mazi/macos-window-lifetime

Conversation

@MartinZikmund

@MartinZikmund MartinZikmund commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

GitHub Issue: closes #25326, part of #25139

PR Type:

🐞 Bugfix

What changed? 🚀

Fixes the macOS WebGPU lane dying with Segmentation fault: 11 in ~16 of 19 runs, always in Given_WebView2 When_ExecuteScriptAsync*. The 15–60 s silence before it is createdump writing a ~1.9 GB core, not a hang.

Split out of #25140 (part of the WebGPU lane stabilization tracked in #25139). The crash-report collection for the macOS lane is in #25197.

  • Evidence: 7 core dumps from builds 238391, 238360 and 238251. In all of them the main thread crashes in objc_release during an autorelease-pool drain, releasing an already-freed object. That object is still referenced by a managed MacOSNativeOverlappedPresenter._handle, so it's a closed secondary UNOWindow (from Given_MultiWindowAccessibility, closed ~10 min earlier). A later WKWebView attach triggers the release.
  • Cause: UNOWindow kept releasedWhenClosed at its default YES. Under ARC, AppKit's release on close takes the reference held by the static windows set, so the window is freed mid-close while handles still point at it. Before this change, windows were never removed from that set.
  • Fix (root-cause fix for the early dealloc): releasedWhenClosed = NO; detach the rendering view while the window is alive; drop the windows reference on a later main-queue turn.
  • Not pinned: which WebGPU-only component (MTKView external present, wgpu's occlusion check, or AppKit AX/KVO tables) keeps the stale pointer. The Skia/Metal lane frees windows the same way but doesn't crash.
  • Test: When_Secondary_Windows_Closed_Then_WebView_Still_Works (SkiaMacOS) repeats the sequence. Whether it fails without the fix is unproven, because the CI crash wasn't deterministic.

Results (CI builds 238511 and 238573, every WebGPU lane forced on)

WebGPU lane Failed tests, all attempts Before (8-day window, builds with test failures)
Desktop macOS 0 (full run, no segfault) 5 / 19 (+ segfault in ~16 / 19)

In run 238573 the multi-window tests, then all WebView2 ExecuteScriptAsync* tests and the new regression test passed.

The Objective-C change was only compiled by CI (it can't be built on Windows). More runs on master after merge will confirm the fix.

PR Checklist ✅

🤖 Generated with Claude Code

https://claude.ai/code/session_01TP1JtY64etkfxxGCms44aN

Copilot AI balanced review requested due to automatic review settings October 10, 2026 21: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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added the platform/macos 🍏 Categorizes an issue or PR as relevant to the macOS platform label Oct 10, 2026
@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 19s —— View job


Review of PR #25201

Verdict: fix-first (minor). The change is small and well-reasoned.

  • Issues: 1 medium, 0 high, 0 low.
  • Medium: the fix delays the free, but managed handles can still dangle afterwards. See the inline comment.
  • Test: When_Secondary_Windows_Closed_Then_WebView_Still_Works is a reasonable regression test. As the PR notes, nobody has shown it failing without the fix, so there is no red/green evidence. It is not skipped or ignored.
  • Validation: I checked this by reading the code only. I did not build or run anything, and the Objective-C change can't be built on Linux.
  • Style: the PR title and the rest of the change follow the repo conventions.

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 238848 found UI Test snapshots differences: skia-linux-screenshots: 118, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 118 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • ClipboardTests.png-dark
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • DisplayInformation.png-dark
    • DoubleImageBrushInList.png-dark
    • DoubleImageBrushInList.png
    • Focus_FocusVisual_Properties.png-dark
    • Focus_FocusVisual_Properties.png
    • ImageBrushAlignmentXY.png-dark
    • ImageBrushAlignmentXY.png
    • DynamicFont.png-dark
    • DynamicFont.png
  • skia-windows-screenshots: 2458 changed over 2486

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png
    • AppBar_KeyBoard.png-dark
    • Application_DispatcherShutdownMode.png-dark
    • AppWindowTitleBar Properties.png-dark
    • ArcSegment.png-dark
    • AuthenticationBroker_Cancel.png
    • AutoBorderStretchwithtopmargin.png
    • AutomationProperties_Landmark.png
    • AutoSizedTopLeft.png
    • AutoSuggestBoxChosenSuggestion.png-dark
    • BackGesture.png-dark
    • BackGesture.png
    • Basics.png-dark
    • Basics.png
    • BitmapIcon_Foreground.png-dark
    • BitmapIcon_Foreground.png
    • BorderTopwithmargins.png-dark
    • BorderTopwithmargins.png
    • Border_AntiAlias.png-dark
    • Border_AntiAlias.png

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 238848 has failed on Uno.UI - CI.

@morning4coffe-dev morning4coffe-dev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified the UNOWindow.m change (releasedWhenClosed = NO in init, view detach and main-queue removal from the static windows set in windowWillClose) and the new Given_WebView2 test against the PR head and the PR base. The test helpers it uses (WindowHelper.WaitFor, WaitForLoaded, WaitForIdle) exist. WinUI parity does not apply: this is native macOS plumbing.

Findings, most severe first:

  1. Medium: the fix changes the object lifetime from "never freed" to "freed one main-queue turn after close". Before this PR windows kept every closed window alive, so a stale managed handle (MacOSNativeOverlappedPresenter._handle) pointed at a live object. After it, the window is deallocated once the block runs, and any managed handle or AppKit-side reference that still points at it dangles. The PR body states the holder of the stale pointer is not identified. The change therefore moves the free without removing the dangling reference, which does not meet the root-cause bar. Please either identify and clear the holder (for example, invalidate the managed handle on close), or show that nothing retains the window after windowWillClose.

  2. Low (question): the comment says the removal runs "once AppKit has finished closing the window". A main-queue block is not guaranteed to run after the close call stack unwinds; it can drain inside a nested run loop (event tracking, modal session). Please confirm this is safe in that case, or move the removal to a point that AppKit guarantees has passed (for example, the end of the close sequence).

  3. Low: -dealloc now calls [windows removeObject:self] on an object that the set can no longer hold at that point, so the call is a no-op. Either remove it or leave a comment.

  4. Low: the regression test has no red/green evidence (the PR body says so). Please run it on the parent commit, or state that the CI crash was nondeterministic so the test cannot be shown to fail. As written it guards the sequence, not the root cause.

Validation: code review (diff plus surrounding code in UNOWindow.m at the PR head). Compile: not built, Objective-C on macOS only. Runtime: none run by me; the CI results in the PR body are the author's and were not verified.

@MartinZikmund MartinZikmund added the 7.0 PRs only. For issues, use the Release field. label Oct 14, 2026
MartinZikmund and others added 2 commits October 27, 2026 13:15
UNOWindow left releasedWhenClosed at its default (YES). Under ARC,
AppKit's release on close takes the reference held by the `windows`
set, so a closed secondary window was freed mid-close while managed
handles and AppKit bookkeeping still pointed at it. Crash dumps of the
macOS WebGPU runtime-test lane show a later autorelease-pool drain
releasing exactly such a freed window, killing the process (SIGSEGV
in objc_release).

Turn releasedWhenClosed off, detach the rendering view while the
window is still alive, and drop the owning reference on a later turn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L4YBGyfjv1uKVn6FUFxSEF
@ajpinedam
ajpinedam force-pushed the dev/mazi/macos-window-lifetime branch from 0df9bcb to 20c3227 Compare October 27, 2026 17:29
@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ajpinedam's task in 20s —— View job


Review of PR #25201

Verdict: fix-first (minor)

  • Issues: 0 high, 1 medium, 2 low, all posted inline.
  • Cross-cutting: the releasedWhenClosed = NO change fixes the free that happens in the middle of the close. The remaining stale-pointer invariant is unresolved, and the PR says which component holds it is not pinned. Please label the fix as hardening until that is resolved.
  • Test: When_Secondary_Windows_Closed_Then_WebView_Still_Works is not skipped or ignored. It has no red/green evidence, and the PR explains that the CI crash was nondeterministic.
  • Validation: this was a code review only. Nothing was compiled or run. The Objective-C change doesn't build on Linux, and I didn't check the CI results quoted in the PR body.
  • Other: the title and commits follow Conventional Commits.

Removing a closed window from `windows` frees it. Queue that from a
-close override, after [super close] returns, rather than from
windowWillClose:, which runs inside -close. The block then can't run
in a run loop nested in -close. Drop -dealloc: the set holds the
window, so it is never in the set when deallocated.

Claude-Session: https://claude.ai/code/session_01DtUZ4zXC6g5yoXN9Rdt2yx
MacOSNativeOverlappedPresenter kept the window handle it was created
with, so a call after the window closed reached the freed NSWindow and
crashed the app. Read the handle on each call: closing the window
clears it.

Claude-Session: https://claude.ai/code/session_01DtUZ4zXC6g5yoXN9Rdt2yx
Master now carries its own fix for the over-released NSWindow
(49f4bcf): releasedWhenClosed = NO, and the window leaves `windows`
in windowWillClose:, while AppKit keeps it alive until `close`
returns. Keep that version. This branch's queued removal and -close
override are no longer needed, and -dealloc stays as on master. The
rendering view is still detached before the window leaves the set.

Claude-Session: https://claude.ai/code/session_01DtUZ4zXC6g5yoXN9Rdt2yx
@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ajpinedam's task in 29s —— View job


Review of PR #25201 (re-review after the latest pushes)

Verdict: ship, with one optional follow-up.

  • Issues: 0 high, 0 medium, 1 low.
  • Earlier concerns are addressed.
    • Dangling presenter handle: MacOSNativeOverlappedPresenter now reads _window.Handle on each call. MacOSWindowNative.Destroyed() zeroes that handle in the close callback, before windowWillClose removes the window from windows. Presenter calls after close become no-ops, and State returns Restored.
    • dispatch_async removal: the deferred removal is gone. [windows removeObject:self] runs synchronously at the end of windowWillClose, and the code comment says AppKit keeps the window alive until close returns. This removes the nested-run-loop timing concern from the earlier reviews.
    • dealloc: [windows removeObject:self] in dealloc is still there. It is harmless, but it is now redundant.
  • Low (optional): the other managed registries that hold a window pointer weren't audited. MacOSWindowHost.Register(Handle, ...) is one. Confirm each is unregistered before the native window is freed, as the code comment claims.
  • Tests: When_Closed_Then_Presenter_Calls_Do_Nothing is a deterministic regression test for the presenter fix. When_Secondary_Windows_Closed_Then_WebView_Still_Works guards the original crash sequence. Neither is skipped or ignored. As the PR notes, the CI crash was nondeterministic, so no red/green run exists for the WebView test.
  • Labeling: the managed-handle invalidation and releasedWhenClosed = NO fix the known early free, so they are root-cause fixes for it. Which component dereferenced the stale pointer is still unpinned. The PR body should say so, as it already does.
  • Validation: this was a code review only. Nothing was compiled or run, and the Objective-C change doesn't build on Linux. I did not check the CI results quoted in the PR body.

@ajpinedam

Copy link
Copy Markdown
Contributor

Update after the review rounds (the Claude reviews of Oct 10 and today, and the review from morning4coffe-dev).

Master now has its own fix for the over-release (49f4bcf, from #25492). I merged master into this branch and kept master's native close code, so this PR's queued removal is gone. On top of master, the PR now adds three things: detaching the rendering view in windowWillClose:, the presenter fix below, and the tests. The PR description above still describes the original change.

  • Stale managed handle (the medium in all three reviews): fixed in c8ae320. MacOSNativeOverlappedPresenter now reads the window handle on each call and skips the native call once the window has closed. The new Given_AppWindow.When_Closed_Then_Presenter_Calls_Do_Nothing crashes the app (exit 139) without the fix, on both Metal and WebGPU, and passes with it.
  • "A closed window was never freed before this PR": it was freed. With releasedWhenClosed at YES, AppKit's close-time release took the reference windows held. A small AppKit program on macOS 27.0.1 showed the window deallocated right after close, with the set still pointing at it. Master's fix removes that over-release, which matches the crash stack. With the presenter fix, the presenter no longer keeps the handle that the crash dumps found.
  • Nested run loop: no longer applies. With master's code, the window survives until close has returned and the autorelease pool around it drains, for both close and performClose:.
  • dealloc no-op: this PR no longer changes dealloc.
  • Red/green: the WebView test still can't be shown failing, because the CI crash wasn't deterministic. The new presenter test can.
  • The WebView test now closes its secondary windows in finally (2c85c8a).

Validation on macOS 27.0.1 with Xcode 27.1:

  • Compile: the native library, Uno.UI.Runtime.MacOS and the runtime tests build with analyzers on. Xcode 27 needs MACOSX_DEPLOYMENT_TARGET=12.0 passed locally; the project's 10.15 target is unchanged.
  • Runtime: the desktop SamplesApp ran Given_AppWindow, Given_WebView2 and Given_MultiWindowAccessibility on Metal and on WebGPU: 33 passed, 12 skipped, 0 failed on each.

@ajpinedam
ajpinedam enabled auto-merge October 27, 2026 17:52
@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 241727 found UI Test snapshots differences: skia-linux-screenshots: 118, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 118 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ClipboardTests.png-dark
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • DropDownButtonPage.png-dark
    • Examples.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_Enumeration.png-dark
    • DoubleImageBrushInList.png-dark
    • DoubleImageBrushInList.png
    • ImageBrushAlignmentXY.png-dark
    • ImageBrushAlignmentXY.png
    • Focus_FocusVisual_Properties.png-dark
  • skia-windows-screenshots: 2458 changed over 2492

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png-dark
    • AppBarToggleButtonTest.png-dark
    • ApplicationViewSpanningRectsPage.png-dark
    • AppWindowFeatures.png-dark
    • AppWindowTitleBar Properties.png
    • Attributed_text_FontSize_Changing.png-dark
    • AuthenticationBroker_Demo.png
    • AutoBorderStretchwithrightmargin.png
    • AutomationProperties_Relations.png
    • AutomationProperties_StructureAndProps.png-dark
    • BackGesture.png-dark
    • BackGesture.png
    • Basics Pivot Test.png-dark
    • Basics Pivot Test.png
    • Battery.png-dark
    • Battery.png
    • BezierSegment.png-dark
    • BezierSegment.png
    • BitmapIcon_Sizing.png-dark
    • BitmapIcon_Sizing.png

@mergify

mergify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@ajpinedam
ajpinedam merged commit c9edce1 into master Oct 27, 2026
51 checks passed
@ajpinedam
ajpinedam deleted the dev/mazi/macos-window-lifetime branch October 27, 2026 20:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

7.0 PRs only. For issues, use the Release field. platform/macos 🍏 Categorizes an issue or PR as relevant to the macOS platform

Projects

None yet

Development

Successfully merging this pull request may close these issues.

macOS: closing a secondary window frees the NSWindow while managed handles still reference it, causing a later segfault

6 participants