Repository navigation
Fix #647: multi-window teardown ACCESS_VIOLATION (0xC0000005) - #673
Merged
Alexandre Zollinger Chohfi (azchohfi) merged 5 commits intoJun 26, 2026
Merged
Alexandre Zollinger Chohfi (azchohfi) merged 5 commits into
Alexandre Zollinger Chohfi (azchohfi) merged 5 commits into
Conversation
A second native Window.Close()/SystemBackdrop write on an already-torn-down window re-entered native teardown and faulted with an unmanaged ACCESS_VIOLATION (0xC0000005) that corrupted the WinUI backdrop interop for later windows in the same process. In the NativeDockingTearOff selftest batch a tear-off floating preview window was elected the app's fallback PrimaryWindow; closing it fired ShutdownPolicy.OnPrimaryWindowClosed -> Application.Exit(), tearing down every window mid-batch, and the next fixture's mount AV'd writing SystemBackdrop on the dead shared window. Fixes: - ReactorWindow: route all native closes through CloseNativeWindowOnce() so Window.Close() happens at most once (programmatic close, owner cascade, app exit). Dispose() was already idempotent. - BackdropApplier: process-wide closed-window registry (weak-keyed on Window) consulted before every SystemBackdrop write in Apply() and Reset(); Reset now takes windowClosed. Skips the AV-prone set_SystemBackdrop on a window whose native surface is gone. - ReactorHost: marks the window closed in the registry on Window.Closed, before disposing, and passes windowClosed to Reset(). - ReactorApp/DockFloatingWindow: docking tear-off floating windows open with ExcludeFromShutdownPolicy=true so they are never elected PrimaryWindow and closing them cannot tear the whole app down mid-process. NativeDockingTearOff batch: was exit -1073741819 (0xC0000005) at T05; now exit 0 (T01-T14, 0 failures). Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
requested a review
from Chris Anderson (codemonkeychris)
as a code owner
June 25, 2026 22:22
…elftests + docs M1: extract ElectPrimaryWindow helper shared by initial registration and unregister re-election so an ExcludeFromShutdownPolicy window can never be elected or re-elected PrimaryWindow. H1/M2/M3: add WindowLifecycleHardeningFixtures selftests: - Window647_PrimaryElectionExcludesAuxiliary (covers the M1 re-election path) - Window647_BackdropSkipsClosedWindow (closed-window registry gates Apply + Reset) - Window647_NativeCloseIsIdempotent (native close fires exactly once) L1: document the teardown invariants in specs 036 (new 6.4) / 045, docs/guide/windows.md (+ template), and add a CHANGELOG [Unreleased] Fixed #647 entry. Co-authored-by: Copilot <[email protected]>
Resolve the 8 github-code-quality[bot] inline comments with behavior-preserving edits: - ReactorApp.ElectPrimaryWindow: replace the implicitly-filtering foreach with Array.Find(predicate). - BackdropApplier.Reset / ReactorHost dispose / test cleanup catches: replace bare/generic catch blocks with typed, logged catches (no silent swallows). The framework Reset catch narrows to the realistic managed setter failures; the host dispose call logs anything unexpected. - WindowLifecycleHardeningFixtures.CloseAndSettle: filter the source with .Where(...) instead of an in-loop null continue. Re-verified ARM64: Window647 + NativeDockingTearOff batches exit 0, 0 failures. Co-authored-by: Copilot <[email protected]>
Follow the repo's standard non-fatal catch pattern (used in Reconciler, ElementPool, ObservableTreeTracker) so the best-effort backdrop reset on host dispose no longer swallows OutOfMemoryException / StackOverflowException. Co-authored-by: Copilot <[email protected]>
Contributor
There was a problem hiding this comment.
Pull request overview
Hardens multi-window teardown behavior to prevent WinUI 0xC0000005 ACCESS_VIOLATION crashes during sequential selftest batches by (1) preventing auxiliary/docking tear-off windows from ever becoming ReactorApp.PrimaryWindow, (2) making native window close idempotent, and (3) gating all Window.SystemBackdrop writes once a window’s native surface is gone. Adds selftest regression fixtures and updates specs/guide/changelog to document the invariants.
Changes:
- Add
ReactorWindow.CloseNativeWindowOnce()to ensure nativeWindow.Close()is requested at most once across converging close paths. - Add a process-wide “closed window” registry in
BackdropApplierand consult it on bothApply()andReset()to skipSystemBackdropwrites afterWindow.Closed. - Exclude docking floating windows from primary election via
excludeFromShutdownPolicy, unify primary election logic, and add selftest fixtures + documentation updates for #647.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs | Registers the three new #647 regression selftests in both the name list and constructor switch. |
| tests/Reactor.AppTests.Host/SelfTest/Fixtures/WindowLifecycleHardeningFixtures.cs | Adds selftests covering primary election exclusion, backdrop write suppression after close, and idempotent native close. |
| src/Reactor/Hosting/ReactorWindow.cs | Adds native-close idempotency guard and introduces ExcludeFromShutdownPolicy for auxiliary windows. |
| src/Reactor/Hosting/ReactorHost.cs | Marks windows closed early on Window.Closed and passes “windowClosed” into backdrop reset during dispose. |
| src/Reactor/Hosting/ReactorApp.cs | Adds exclude flag plumbing in OpenWindowCore and unifies primary election to skip excluded windows (on register + unregister). |
| src/Reactor/Hosting/BackdropApplier.cs | Implements closed-window registry + guards for SystemBackdrop writes in Apply and Reset. |
| src/Reactor/Docking/Native/DockFloatingWindow.cs | Opens docking floating windows via OpenWindowCore(... excludeFromShutdownPolicy: true) to avoid primary election hazards. |
| docs/specs/045-docking-windows-design.md | Documents docking floating windows being excluded from primary election as part of #647 hardening. |
| docs/specs/036-window-design.md | Adds a new section documenting the three invariants for multi-window teardown safety (#647). |
| docs/guide/windows.md | Updates user guide caveats for idempotent close and primary-election behavior for excluded auxiliary windows. |
| docs/_pipeline/templates/windows.md.dt | Mirrors the same guide updates in the doc template source. |
| CHANGELOG.md | Adds an Unreleased “Fixed” entry describing the #647 crash and the three reinforcing mitigations. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address Copilot review: the lead-in 'first opened window' contradicted the rest of the bullet, which explains that shutdown-policy-excluded auxiliary windows are skipped during primary election (and PrimaryWindow can remain null if only excluded windows are open). Mirror the fix in the template source and the generated guide. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
merged commit Jun 26, 2026
1c4c86a
into
main
30 of 31 checks passed
Alexandre Zollinger Chohfi (azchohfi)
deleted the
azchohfi-fix-647-multiwindow-dispose-av
branch
June 26, 2026 04:46
This was referenced Jun 27, 2026
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 30, 2026
… access violation (#767) The full self-test suite (~600 fixtures in one process) faulted with 0xC0000005 at final process teardown — distinct from the mid-run multi-window fault fixed in #647/#673, and reproducible only for the whole suite. Root cause is a WinUI framework use-after-free walked over the harness's accumulated, never-disposed state: Environment.Exit runs the loader's TLS destructors into the XAML core's freed tear-off map, and Application.Exit double-releases the caption-buttons UI Automation provider inside CTitleBar::Uninitialize. The self-test runner now flushes the TAP stream then calls TerminateProcess(GetCurrentProcess(), exitCode) — a teardown-free hard exit that runs neither the loader's TLS destructors nor WinUI's window-close cascade, while preserving the exact 0/1 exit code. A new CI regression guard (SelfTestBatch.HostProcessExitsCleanly_NoTeardownCrash) fails if the Host ever again exits with anything other than 0 or 1. Test infrastructure only; no product code changed. Co-authored-by: Copilot App <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #647.
Root cause
This is the 0xC0000005 ACCESS_VIOLATION multi-window teardown bug (distinct from the already-fixed #537 / #642
0xC0000374WinUITitleBarheap corruption — the dock floating window usesExtendsContentIntoTitleBar=trueand does not render that control, so #537 is structurally inapplicable).Two native re-entrancy hazards combined to fault and poison later windows in the same process (all selftests run sequentially in one Host process):
Spurious app teardown via primary-window election. The
NativeDockingTearOffbatch opens a tear-off floating preview window throughReactorApp. In that isolated batch nothing else is registered withReactorApp, soRegisterWindowelected the floating preview as the fallbackPrimaryWindow. When T04 closed it,ShutdownPolicy.OnPrimaryWindowClosed(the default) fired →SafeExit→Application.Exit(), which synchronously tore down every open window mid-batch — including the harness's sharedWindowreused by every fixture.SystemBackdropwrite on a dead window. The next fixture (T05) reused that now-natively-destroyed shared window and its mount wroteWindow.SystemBackdrop, which faults with an unmanagedACCESS_VIOLATION(0xC0000005) deep in the WinUI backdrop interop — a fault notry/catchcan trap.BackdropApplier.Reset()had the same hazard: it unconditionally nulled_window.SystemBackdropeven when the window/AppWindow was already torn down.A redundant second native
Window.Close()(programmatic close + owner-close cascade + app-exit prep converging on one window) is the same class of re-entry hazard.What changed
ReactorWindow— all native closes route through a newCloseNativeWindowOnce()guarded by_nativeCloseRequested, so the underlyingWindow.Close()happens at most once regardless of how many close paths converge (programmaticClose, owner-close cascade, app exit).Dispose()was already idempotent (_disposedlatch). Adds internalExcludeFromShutdownPolicy.BackdropApplier— a process-wide closed-window registry (ConditionalWeakTable<Window, object>, weak-keyed so collected windows don't leak), marked when a window'sClosedfires, consulted before everySystemBackdropwrite in bothApply()andReset().Reset(bool windowClosed = false)skips the AV-proneset_SystemBackdropon a torn-down window. This is the genuine, defense-in-depth fix for the documentedset_SystemBackdropAV path.ReactorHost— marks the window closed in the registry onWindow.Closed(the handler is wired in the host ctor, beforeReactorWindow.OnNativeClosed, so the guard is set ahead of any teardown), and passeswindowClosedtoReset().ReactorApp/DockFloatingWindow— docking tear-off floating windows open withExcludeFromShutdownPolicy=true, so they are never electedPrimaryWindowand closing one cannot triggerOnPrimaryWindowClosedand tear the whole app down. In real apps the main window registers first, so this is a no-op there; it only corrects the abnormal case where a transient docking surface would otherwise become primary.Applied pr-review findings
The five pr-review findings raised against the original fix are now applied:
ElectPrimaryWindowhelper that returns the first non-ExcludeFromShutdownPolicywindow, elsenull— so the two sites cannot drift apart and an excluded window can neither become nor remain primary.Window647_PrimaryElectionExcludesAuxiliaryopens a real primary + an excluded tear-off + a second real primary, closes the first primary and asserts re-election picks the non-excluded window (not the array head), then closes the last real primary and assertsPrimaryWindowgoesnullrather than the excluded aux. This is M1's regression guard.Window647_BackdropSkipsClosedWindowapplies a live backdrop, marks the window closed, then asserts bothApply(different kind) andResetskip theSystemBackdropwrite — including via a freshly constructed applier, proving it is the process-wide registry (not per-instance last-applied state, and not an exception swallow) doing the skip.Window647_NativeCloseIsIdempotentdrives two convergingClose()calls at one window, asserts the nativeWindow.Closedfires exactly once, then opens and renders another window to confirm the process stays healthy.OnPrimaryWindowClosedand thatWindow.Close()is idempotent;docs/guide/windows.md(+ its.md.dttemplate) gained the same caveats; CHANGELOG[Unreleased] ### Fixedhas a Multi-window batch teardown 0xC0000005 ACCESS_VIOLATION at process exit (general dispose-ordering) #647 entry.Red → green evidence (ARM64, one process)
-1073741819(0xC0000005) inBackdropApplier.Apply → set_SystemBackdrop# Total failures: 0, T01 through T14 all greenNew regression fixtures (
--filter "Window647"): exit 0, all three green. Full selftest suite (ARM64):# Total failures: 0— the cross-fixture poisoning is gone (previously the AV killed the process mid-suite).Known issue (not introduced here, tracked separately)
A residual process-exit (final-shutdown) native AV remains only when the entire selftest suite runs together: every test reports pass (
# Total failures: 0) and the TAP summary prints, then the process faults during final teardown after all fixtures have completed. It does not reproduce in any subset I ran (theNativeDockingTearOffbatch, the newWindow647fixtures,Window,AspectRatio, and other windowing subsets all exit 0), and it is independent of this change (the same shutdown-time fault behavior predates this PR). It is a separate, pre-existing final-shutdown issue, out of scope for #647, and is tracked as its own follow-up in #680. Reviewers should expect the full-suite run to print0 failuresand then exit non-zero for this reason.Notes
T08b/T12b/T12ctest-side double-close guards mentioned in the issue do not exist on this branch (searched — no matches), so there is nothing to remove. Now that the framework makes redundant native close idempotent, any such test-side guards would be unnecessary going forward.WindowLevel_RuntimeFlip_Topmostflake andperf_benchXAML failures.link.exefails on ARM64, so no full NativeAOT link was run; selftests run fine.Co-authored-by: Copilot [email protected]