Move startup and shutdown work off the GUI thread #980

Manually merged
johnny9 merged 1 commit from pr/qt6-async-01-lifecycle into qt6 2026-10-12 23:39:14 +00:00 AGit
johnny9 commented 2026-10-02 21:44:21 +00:00 (Migrated from github.com)

Startup and shutdown can stop event processing while waiting for backend locks, storage or workers. Run initialization and interruption on owned workers. Stop query producers and drain accepted work before releasing Core, while keeping the GUI event loop available.

Add shared worker queues and asynchronous thread retirement. Adapt existing wallet workers so this PR can shut down safely before the later wallet feature changes are applied.

Regression tests cover blocked initialization, worker retirement, discarded results and wallet shutdown.

Fixes #788
Fixes #959

Startup and shutdown can stop event processing while waiting for backend locks, storage or workers. Run initialization and interruption on owned workers. Stop query producers and drain accepted work before releasing Core, while keeping the GUI event loop available. Add shared worker queues and asynchronous thread retirement. Adapt existing wallet workers so this PR can shut down safely before the later wallet feature changes are applied. Regression tests cover blocked initialization, worker retirement, discarded results and wallet shutdown. Fixes #788 Fixes [#959](https://github.com/bitcoin-core/gui-qml/issues/959)
pseudoramdom (Migrated from github.com) reviewed 2026-10-02 23:08:13 +00:00
pseudoramdom (Migrated from github.com) commented 2026-10-02 23:05:04 +00:00

Doing Cmd+Q can hang onboarding and startup indefinitely


[Assisted by codex]

Cmd+Q or Dock Quit during onboarding exits its nested event loop, but the new final drain repeatedly calls loop.exec() after Qt has set its application quit flag. These calls return immediately, so the queued drain completion never runs and the GUI spins indefinitely. RunBackendStage has the same problem at backendstage.h:33, even after its worker finishes. Reproduced using native macOS termination with the exact PR executor code. Defer application Quit throughout bootstrap and draining, or run these stages within the main application event loop. The existing window-close test does not exercise native Quit.

Doing Cmd+Q can hang onboarding and startup indefinitely ---- [Assisted by codex] Cmd+Q or Dock Quit during onboarding exits its nested event loop, but the new final drain repeatedly calls loop.exec() after Qt has set its application quit flag. These calls return immediately, so the queued drain completion never runs and the GUI spins indefinitely. RunBackendStage has the same problem at backendstage.h:33, even after its worker finishes. Reproduced using native macOS termination with the exact PR executor code. Defer application Quit throughout bootstrap and draining, or run these stages within the main application event loop. The existing window-close test does not exercise native Quit.
pseudoramdom (Migrated from github.com) commented 2026-10-02 23:07:48 +00:00

Wallet notification cleanup can deadlock migration rollback


[Codex assisted]

Shutdown queues destruction of pending notification-owned wallet interfaces behind the active controller command. Migration rollback can itself be waiting for those interfaces to disappear: Core calls WaitForDeleteWallet when a watch-only wallet loaded successfully but a later solvables-wallet load failed. Meanwhile consumeWalletNotifications stops consuming after shutdown starts. This creates a circular wait and prevents walletsDrained. A controlled loader test reproduced it; releasing pending interfaces through an independent executor made the test pass. Retire these references independently of the migration queue. The real Core rollback path was traced, but a real migration failure was not injected.

Wallet notification cleanup can deadlock migration rollback ---- [Codex assisted] Shutdown queues destruction of pending notification-owned wallet interfaces behind the active controller command. Migration rollback can itself be waiting for those interfaces to disappear: Core calls `WaitForDeleteWallet` when a watch-only wallet loaded successfully but a later solvables-wallet load failed. Meanwhile consumeWalletNotifications stops consuming after shutdown starts. This creates a circular wait and prevents walletsDrained. A controlled loader test reproduced it; releasing pending interfaces through an independent executor made the test pass. Retire these references independently of the migration queue. The real Core rollback path was traced, but a real migration failure was not injected.
pseudoramdom commented 2026-10-03 15:41:17 +00:00 (Migrated from github.com)

ACK d2f4efd39b7a7eab2e521d5b69b006d6e83a687b.
Both the startup hang and deadlocks are resolved.

ACK d2f4efd39b7a7eab2e521d5b69b006d6e83a687b. Both the startup hang and deadlocks are resolved.
johnny9 commented 2026-10-03 21:57:05 +00:00 (Migrated from github.com)

Im not liking the async join class and trying to clean this up a bit but it should be good to go very shortly

Im not liking the async join class and trying to clean this up a bit but it should be good to go very shortly
jarolrod (Migrated from github.com) reviewed 2026-10-03 23:33:37 +00:00
jarolrod (Migrated from github.com) commented 2026-10-03 23:33:37 +00:00

commenting that this was addressed starting in 89d613f6d3ae with the quit handler, with further startup-dialog handling in 858fc91d0125.

commenting that this was addressed starting in 89d613f6d3ae with the quit handler, with further startup-dialog handling in 858fc91d0125.
jarolrod (Migrated from github.com) reviewed 2026-10-03 23:34:05 +00:00
jarolrod (Migrated from github.com) commented 2026-10-03 23:34:05 +00:00

commenting that this is addressed in 89d613f6d3ae by retiring pending wallet notifications on a separate executor, independently of the migration command.

commenting that this is addressed in 89d613f6d3ae by retiring pending wallet notifications on a separate executor, independently of the migration command.
jarolrod (Migrated from github.com) reviewed 2026-10-03 23:42:47 +00:00
jarolrod (Migrated from github.com) left a comment

Just some thoughts if we keep the async join here: could the worker notify the GUI when it's done instead of polling every 1 ms? Would also be nice to keep the ownership and drain tracking in one place, so it's easier to follow when everything has actually finished.

Just some thoughts if we keep the async join here: could the worker notify the GUI when it's done instead of polling every 1 ms? Would also be nice to keep the ownership and drain tracking in one place, so it's easier to follow when everything has actually finished.
johnny9 commented 2026-10-04 00:20:00 +00:00 (Migrated from github.com)

Just some thoughts if we keep the async join here: could the worker notify the GUI when it's done instead of polling every 1 ms? Would also be nice to keep the ownership and drain tracking in one place, so it's easier to follow when everything has actually finished.

Yeah the polling was the first thing to clean up. It should be using an event instead.

Can see if the worker registry can make it clear

> Just some thoughts if we keep the async join here: could the worker notify the GUI when it's done instead of polling every 1 ms? Would also be nice to keep the ownership and drain tracking in one place, so it's easier to follow when everything has actually finished. Yeah the polling was the first thing to clean up. It should be using an event instead. Can see if the worker registry can make it clear
jarolrod (Migrated from github.com) reviewed 2026-10-04 15:48:30 +00:00
jarolrod (Migrated from github.com) commented 2026-10-04 15:48:30 +00:00

This introduces a reset regression on macOS. The window settings model still reads and writes through default QSettings, which uses the organization domain, bitcoincore.org. This constructor explicitly uses BitcoinCore, so we're clearing a different preferences store.

Tested on macOS with Qt 6.9:

  1. Set regtest=1 in bitcoin.conf, without passing -regtest on the command line.
  2. Enable Minimize to tray and Minimize on close through the GUI, then exit.
  3. Restart with -resetguisettings, complete onboarding, and check Window behavior.

The base (a91f4b4774f2) clears both preferences; this head leaves both enabled. Passing -regtest explicitly hides the issue because the early reset already clears the right network's settings. With config-only network selection, we depend on this later reset.

This constructor also forces NativeFormat, ignoring the format and redirected location used by -test-settings-dir. That part isn't macOS-specific. I separately reproduced the organization mismatch with native macOS settings, so the reset failure isn't just a test-harness artifact.

Moving this work onto the worker makes sense. Could we preserve Qt's effective settings identity and only supply the resolved network's application name? Something like:

const QSettings defaults;
QSettings settings{
    defaults.format(),
    defaults.scope(),
    defaults.organizationName(),
    ChainQSettingsName(
        QString::fromStdString(gArgs.GetChainTypeString()).toUpper())
};

I built and tested this change with the same GUI reproduction, and both preferences reset correctly. It keeps the work on the worker and lets Qt handle the platform differences. Would be good to add coverage for the config-only network case too.

This introduces a reset regression on macOS. The window settings model still reads and writes through default QSettings, which uses the organization domain, `bitcoincore.org`. This constructor explicitly uses `BitcoinCore`, so we're clearing a different preferences store. Tested on macOS with Qt 6.9: 1. Set `regtest=1` in bitcoin.conf, without passing `-regtest` on the command line. 2. Enable Minimize to tray and Minimize on close through the GUI, then exit. 3. Restart with `-resetguisettings`, complete onboarding, and check Window behavior. The base (`a91f4b4774f2`) clears both preferences; this head leaves both enabled. Passing `-regtest` explicitly hides the issue because the early reset already clears the right network's settings. With config-only network selection, we depend on this later reset. This constructor also forces `NativeFormat`, ignoring the format and redirected location used by `-test-settings-dir`. That part isn't macOS-specific. I separately reproduced the organization mismatch with native macOS settings, so the reset failure isn't just a test-harness artifact. Moving this work onto the worker makes sense. Could we preserve Qt's effective settings identity and only supply the resolved network's application name? Something like: ```cpp const QSettings defaults; QSettings settings{ defaults.format(), defaults.scope(), defaults.organizationName(), ChainQSettingsName( QString::fromStdString(gArgs.GetChainTypeString()).toUpper()) }; ``` I built and tested this change with the same GUI reproduction, and both preferences reset correctly. It keeps the work on the worker and lets Qt handle the platform differences. Would be good to add coverage for the config-only network case too.
jarolrod commented 2026-10-04 23:24:38 +00:00 (Migrated from github.com)

Tested ACK f4a4cc4a774eaf2d97294cd3154185000939a9b4

Rechecked the reset regression and startup/shutdown paths on macOS with Qt 6.9. My concerns are addressed. The GUI stays responsive during slow backend work, and I didn’t see a meaningful performance regression against the base.

Edit: withdrawing ack here as I’ve found some new issues

~~Tested ACK f4a4cc4a774eaf2d97294cd3154185000939a9b4~~ Rechecked the reset regression and startup/shutdown paths on macOS with Qt 6.9. My concerns are addressed. The GUI stays responsive during slow backend work, and I didn’t see a meaningful performance regression against the base. Edit: withdrawing ack here as I’ve found some new issues
jarolrod (Migrated from github.com) reviewed 2026-10-05 01:48:07 +00:00
jarolrod (Migrated from github.com) commented 2026-10-05 01:48:07 +00:00

I tried the fatal-error path after shutdown had already started, and the dialog opens with its Shut down button disabled.

Reproduced on macOS with Qt 6.9 by injecting an exception just before appShutdown(). The C++ shutdown path disables QQuickWindow::contentItem(), but this re-enables ApplicationWindow.contentItem. Those are different items, so the outer one stays disabled. Re-enabling the same item from C++ made the button work.

The QML test misses this because it disables the inner item too. I’d have the regression test exercise the actual C++ shutdown path so it catches that difference.

I tried the fatal-error path after shutdown had already started, and the dialog opens with its Shut down button disabled. Reproduced on macOS with Qt 6.9 by injecting an exception just before appShutdown(). The C++ shutdown path disables QQuickWindow::contentItem(), but this re-enables ApplicationWindow.contentItem. Those are different items, so the outer one stays disabled. Re-enabling the same item from C++ made the button work. The QML test misses this because it disables the inner item too. I’d have the regression test exercise the actual C++ shutdown path so it catches that difference.
jarolrod (Migrated from github.com) reviewed 2026-10-05 01:49:04 +00:00
jarolrod (Migrated from github.com) commented 2026-10-05 01:49:05 +00:00

std::exit() still runs static destructors, which seems to defeat the intent of skipping cleanup after a fatal exception.

I injected an exception after real Core initialization, with RPC enabled, then acknowledged the fatal dialog. On macOS/Qt 6.9 with a debug build, I got a segfault during thread-pool teardown/logging in one run and the HTTP server’s joinable-thread assertion in another.

Changing this to std::_Exit(EXIT_FAILURE) made the same checks exit with status 1. If we can’t safely continue or drain Core here, that seems like the appropriate primitive.

The current mock-based fatal-exit tests don’t exercise this static teardown. Would be good to cover the real initialized node too.

std::exit() still runs static destructors, which seems to defeat the intent of skipping cleanup after a fatal exception. I injected an exception after real Core initialization, with RPC enabled, then acknowledged the fatal dialog. On macOS/Qt 6.9 with a debug build, I got a segfault during thread-pool teardown/logging in one run and the HTTP server’s joinable-thread assertion in another. Changing this to std::_Exit(EXIT_FAILURE) made the same checks exit with status 1. If we can’t safely continue or drain Core here, that seems like the appropriate primitive. The current mock-based fatal-exit tests don’t exercise this static teardown. Would be good to cover the real initialized node too.
jarolrod (Migrated from github.com) reviewed 2026-10-05 01:49:55 +00:00
jarolrod (Migrated from github.com) commented 2026-10-05 01:49:55 +00:00

Minor: this message doesn’t seem to reach the wallet selector.

I held an Activity read/fee preview open, closed the wallet, then tried opening it again before the work finished. The row looks closed and is still clickable, but clicking it gives no feedback. Retrying after cleanup works.

The selector uses the wallet-load-state signals for its error display, while this only sets walletLoadError. Emitting the existing load-error state made the failure visible in a control build.

I wouldn’t block on this, but showing a closing state—or surfacing this message—would make it clear why the wallet isn’t opening yet.

Minor: this message doesn’t seem to reach the wallet selector. I held an Activity read/fee preview open, closed the wallet, then tried opening it again before the work finished. The row looks closed and is still clickable, but clicking it gives no feedback. Retrying after cleanup works. The selector uses the wallet-load-state signals for its error display, while this only sets walletLoadError. Emitting the existing load-error state made the failure visible in a control build. I wouldn’t block on this, but showing a closing state—or surfacing this message—would make it clear why the wallet isn’t opening yet.
johnny9 commented 2026-10-05 15:16:54 +00:00 (Migrated from github.com)

Updated to a592a2122fa07725f112a29c5fd9fd3c1c2fcaf9 with fixes and regression coverage for all three recent findings:

  • Fatal dialog controls: fatal errors re-enable the same QQuickWindow::contentItem() that the C++ shutdown path disables. The real GUI test enters that shutdown path and verifies the fatal button is enabled while normal navigation stays disabled.
  • Fatal process exit: fatal acknowledgement uses std::_Exit(EXIT_FAILURE) to bypass unsafe static teardown. Real initialized-node tests keep RPC/HTTP workers active and require exit status 1; an atexit sentinel also catches regressions in the child-process tests.
  • Reopening a retiring wallet: the existing load-error state now reaches the wallet selector. A blocked-worker regression connects the controller to the real WalletListModel, checks two failed retries, then verifies successful reopening and a cleared error after retirement.

The coverage audit also found and fixed an initialization/shutdown ordering bug: a shutdown queued behind initialization must skip appShutdown() if initialization throws. Tests cover both exception types, ordinary initialization failure, worker readiness failure, late wallet-command completion, and completion callbacks that destroy their executor.

A pre-existing startup issue is also fixed: an already-onboarded profile selected by config now skips onboarding when the default directory is absent. This has six isolated GUI cases registered with CTest and twelve settings/command-line precedence cases.

Updated to a592a2122fa07725f112a29c5fd9fd3c1c2fcaf9 with fixes and regression coverage for all three recent findings: - [Fatal dialog controls](https://github.com/bitcoin-core/gui-qml/pull/980#discussion_r4180172950): fatal errors re-enable the same `QQuickWindow::contentItem()` that the C++ shutdown path disables. The real GUI test enters that shutdown path and verifies the fatal button is enabled while normal navigation stays disabled. - [Fatal process exit](https://github.com/bitcoin-core/gui-qml/pull/980#discussion_r4180175727): fatal acknowledgement uses `std::_Exit(EXIT_FAILURE)` to bypass unsafe static teardown. Real initialized-node tests keep RPC/HTTP workers active and require exit status 1; an `atexit` sentinel also catches regressions in the child-process tests. - [Reopening a retiring wallet](https://github.com/bitcoin-core/gui-qml/pull/980#discussion_r4180178500): the existing load-error state now reaches the wallet selector. A blocked-worker regression connects the controller to the real `WalletListModel`, checks two failed retries, then verifies successful reopening and a cleared error after retirement. The coverage audit also found and fixed an initialization/shutdown ordering bug: a shutdown queued behind initialization must skip `appShutdown()` if initialization throws. Tests cover both exception types, ordinary initialization failure, worker readiness failure, late wallet-command completion, and completion callbacks that destroy their executor. A pre-existing startup issue is also fixed: an already-onboarded profile selected by config now skips onboarding when the default directory is absent. This has six isolated GUI cases registered with CTest and twelve settings/command-line precedence cases.
johnny9 (Migrated from github.com) reviewed 2026-10-05 15:22:11 +00:00
johnny9 (Migrated from github.com) commented 2026-10-03 17:46:34 +00:00

do we need to have a timer for this?

do we need to have a timer for this?
johnny9 (Migrated from github.com) commented 2026-10-03 17:42:59 +00:00

comments shouldnt be necessary, lets remove and see if readability needs to be improved or if these comments were just excess.

comments shouldnt be necessary, lets remove and see if readability needs to be improved or if these comments were just excess.
johnny9 (Migrated from github.com) commented 2026-10-03 17:42:21 +00:00

drained what? lets make this clearer

drained what? lets make this clearer
johnny9 (Migrated from github.com) reviewed 2026-10-05 15:30:37 +00:00
johnny9 (Migrated from github.com) commented 2026-10-05 15:30:37 +00:00

Renamed to workDrained in 21b5111d8c8c1c81292259b2ce09d6503df3f5de, including both emission paths, the shutdown coordinator connection, and the existing typed/runtime signal spies. The node, executor and shutdown tests plus real GUI startup/shutdown with IPC pass in normal, ASan/LSan/UBSan/integer and TSan builds. Pinned clang-tidy passed; supplemental lint has no new findings.

Renamed to `workDrained` in 21b5111d8c8c1c81292259b2ce09d6503df3f5de, including both emission paths, the shutdown coordinator connection, and the existing typed/runtime signal spies. The node, executor and shutdown tests plus real GUI startup/shutdown with IPC pass in normal, ASan/LSan/UBSan/integer and TSan builds. Pinned clang-tidy passed; supplemental lint has no new findings.
johnny9 (Migrated from github.com) reviewed 2026-10-05 15:30:39 +00:00
johnny9 (Migrated from github.com) commented 2026-10-05 15:30:39 +00:00

The explanatory shutdown comment has been removed from NodeModel::requestShutdown() in the current head (21b5111d8c8c1c81292259b2ce09d6503df3f5de). Closing this as addressed.

The explanatory shutdown comment has been removed from `NodeModel::requestShutdown()` in the current head (21b5111d8c8c1c81292259b2ce09d6503df3f5de). Closing this as addressed.
AndreaDiazCorreia (Migrated from github.com) reviewed 2026-10-07 20:00:56 +00:00
AndreaDiazCorreia (Migrated from github.com) left a comment

I'm still reviewing this PR, but I had a question in the meantime: does it also fix #788, or am I missing something?

From the crash report, it looks like the app exits through a native quit (Cmd+Q / Dock Quit) without calling appShutdown(), so NodeContext::background_init_thread is still joinable when ~NodeContext runs and std::terminate is called. With QmlQuitHandler routing QEvent::Quit into the shutdown coordinator, every exit path should now go through appShutdown() first.

If that's right, it might be worth adding "Fixes #788" to the description.

I'm still reviewing this PR, but I had a question in the meantime: does it also fix #788, or am I missing something? From the crash report, it looks like the app exits through a native quit (Cmd+Q / Dock Quit) without calling `appShutdown()`, so `NodeContext::background_init_thread` is still joinable when `~NodeContext` runs and `std::terminate` is called. With `QmlQuitHandler` routing `QEvent::Quit` into the shutdown coordinator, every exit path should now go through `appShutdown()` first. If that's right, it might be worth adding "Fixes #788" to the description.
johnny9 commented 2026-10-07 21:03:33 +00:00 (Migrated from github.com)

@AndreaDiazCorreia Added Fixes #788 to the PR description.

@AndreaDiazCorreia Added `Fixes #788` to the PR description.
AndreaDiazCorreia (Migrated from github.com) reviewed 2026-10-09 02:02:23 +00:00
AndreaDiazCorreia (Migrated from github.com) commented 2026-10-09 02:02:12 +00:00

This dropped the PrintExceptionContinue call. When I trigger the test fatal exception, the popup shows it but nothing ends up in debug.log. Was that on purpose?

This dropped the `PrintExceptionContinue` call. When I trigger the test fatal exception, the popup shows it but nothing ends up in `debug.log`. Was that on purpose?
AndreaDiazCorreia (Migrated from github.com) commented 2026-10-09 02:00:12 +00:00

The error callback doesn't keep the pending work like the success one does. If the first history load fails right after a new transaction notification, I only see that one transaction afterwards, with no error shown. Should the error path keep the work too?

The error callback doesn't keep the pending work like the success one does. If the first history load fails right after a new transaction notification, I only see that one transaction afterwards, with no error shown. Should the error path keep the work too?
jarolrod commented 2026-10-10 18:42:39 +00:00 (Migrated from github.com)

tACK 4a7a3148

All issues are addressed. I agree it can be merged.

tACK 4a7a3148 All issues are addressed. I agree it can be merged.
hebasto commented 2026-10-11 08:08:07 +00:00 (Migrated from github.com)

Please rebase.

Please rebase.
johnny9 commented 2026-10-11 13:22:59 +00:00 (Migrated from github.com)

rebased

rebased
jarolrod commented 2026-10-11 23:18:45 +00:00 (Migrated from github.com)

re-ACK beb55f04e3

re-ACK beb55f04e3d146545bc5859fc95a89bd05547c5a
Sign in to join this conversation.
No description provided.