Skip to content

Fix #647: multi-window teardown ACCESS_VIOLATION (0xC0000005) - #673

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 5 commits into
mainfrom
azchohfi-fix-647-multiwindow-dispose-av
Jun 26, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 5 commits into
mainfrom
azchohfi-fix-647-multiwindow-dispose-av

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #647.

Root cause

This is the 0xC0000005 ACCESS_VIOLATION multi-window teardown bug (distinct from the already-fixed #537 / #642 0xC0000374 WinUI TitleBar heap corruption — the dock floating window uses ExtendsContentIntoTitleBar=true and 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):

  1. Spurious app teardown via primary-window election. The NativeDockingTearOff batch opens a tear-off floating preview window through ReactorApp. In that isolated batch nothing else is registered with ReactorApp, so RegisterWindow elected the floating preview as the fallback PrimaryWindow. 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 shared Window reused by every fixture.

  2. SystemBackdrop write on a dead window. The next fixture (T05) reused that now-natively-destroyed shared window and its mount wrote Window.SystemBackdrop, which faults with an unmanaged ACCESS_VIOLATION (0xC0000005) deep in the WinUI backdrop interop — a fault no try/catch can trap. BackdropApplier.Reset() had the same hazard: it unconditionally nulled _window.SystemBackdrop even 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 new CloseNativeWindowOnce() guarded by _nativeCloseRequested, so the underlying Window.Close() happens at most once regardless of how many close paths converge (programmatic Close, owner-close cascade, app exit). Dispose() was already idempotent (_disposed latch). Adds internal ExcludeFromShutdownPolicy.
  • BackdropApplier — a process-wide closed-window registry (ConditionalWeakTable<Window, object>, weak-keyed so collected windows don't leak), marked when a window's Closed fires, consulted before every SystemBackdrop write in both Apply() and Reset(). Reset(bool windowClosed = false) skips the AV-prone set_SystemBackdrop on a torn-down window. This is the genuine, defense-in-depth fix for the documented set_SystemBackdrop AV path.
  • ReactorHost — marks the window closed in the registry on Window.Closed (the handler is wired in the host ctor, before ReactorWindow.OnNativeClosed, so the guard is set ahead of any teardown), and passes windowClosed to Reset().
  • ReactorApp / DockFloatingWindow — docking tear-off floating windows open with ExcludeFromShutdownPolicy=true, so they are never elected PrimaryWindow and closing one cannot trigger OnPrimaryWindowClosed and 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:

  • M1 (correctness / api-ergonomics) — unified primary election. The unregister re-election path could re-elect an excluded tear-off as primary after the real primary closed, re-introducing the exact invariant this PR establishes. Both election sites (initial registration and unregister re-election) now route through a single ElectPrimaryWindow helper that returns the first non-ExcludeFromShutdownPolicy window, else null — so the two sites cannot drift apart and an excluded window can neither become nor remain primary.
  • H1 (test-coverage) — election-exclusion selftest. Window647_PrimaryElectionExcludesAuxiliary opens 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 asserts PrimaryWindow goes null rather than the excluded aux. This is M1's regression guard.
  • M2 (test-coverage) — backdrop closed-window registry selftest. Window647_BackdropSkipsClosedWindow applies a live backdrop, marks the window closed, then asserts both Apply (different kind) and Reset skip the SystemBackdrop write — 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.
  • M3 (test-coverage) — idempotent native close selftest. Window647_NativeCloseIsIdempotent drives two converging Close() calls at one window, asserts the native Window.Closed fires exactly once, then opens and renders another window to confirm the process stays healthy.
  • L1 (docs). Specs 036 (new §6.4) and 045 document that docking floating windows are excluded from primary election / OnPrimaryWindowClosed and that Window.Close() is idempotent; docs/guide/windows.md (+ its .md.dt template) gained the same caveats; CHANGELOG [Unreleased] ### Fixed has a Multi-window batch teardown 0xC0000005 ACCESS_VIOLATION at process exit (general dispose-ordering) #647 entry.

Red → green evidence (ARM64, one process)

dotnet build tests\Reactor.AppTests.Host -p:Platform=ARM64 -m:1
dotnet run --project tests\Reactor.AppTests.Host -p:Platform=ARM64 --no-build -- --self-test --filter "NativeDockingTearOff"
Result
Before T01–T04 pass, process dies at T05 mount — exit -1073741819 (0xC0000005) in BackdropApplier.Apply → set_SystemBackdrop
After exit 0, # Total failures: 0, T01 through T14 all green

New 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 (the NativeDockingTearOff batch, the new Window647 fixtures, 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 print 0 failures and then exit non-zero for this reason.

Notes

  • The T08b/T12b/T12c test-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.
  • Pre-existing, unrelated and not touched here: a WindowLevel_RuntimeFlip_Topmost flake and perf_bench XAML failures.
  • Native link.exe fails on ARM64, so no full NativeAOT link was run; selftests run fine.

Co-authored-by: Copilot [email protected]

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]>
Comment thread src/Reactor/Hosting/ReactorHost.cs Fixed
…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]>
Comment thread src/Reactor/Hosting/ReactorHost.cs Fixed
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]>

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

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 native Window.Close() is requested at most once across converging close paths.
  • Add a process-wide “closed window” registry in BackdropApplier and consult it on both Apply() and Reset() to skip SystemBackdrop writes after Window.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.

Comment thread docs/guide/windows.md Resolved
Comment thread docs/_pipeline/templates/windows.md.dt Resolved
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]>
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit 1c4c86a into main Jun 26, 2026
30 of 31 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-fix-647-multiwindow-dispose-av branch June 26, 2026 04:46
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants