Skip to content

Quitting during a fit can abort with "QThread: Destroyed while thread is still running" #382

Open

Description

@rozyczko

Problem

Closing the app while a fit or a Bayesian sampling run is in progress can abort the process with

QThread: Destroyed while thread is still running

Analysis is the parent of the FitterWorker thread. When the application quits, Analysis is destroyed while the thread is still running, and Qt aborts.

This risk existed before #380, but #380 makes it worse. The live fit preview connects previewRequested with Qt.BlockingQueuedConnection. If the event loop has stopped while the worker is parked in that blocking emit, the worker never returns, even after stop(). So a shutdown handler cannot simply call stop() and wait(): it has to keep processing events while it waits.

Proposed fix

PyBackend is a QML singleton, so Analysis can connect to aboutToQuit itself, and main.py needs no change. aboutToQuit is emitted after the event loop has stopped but before anything is destroyed. At that point processEvents() still delivers posted events, including the blocking-queued preview call a parked worker is waiting on.

# analysis.py
from PySide6.QtCore import QCoreApplication

#: Longest wait for a running fit or sampling to stop when the application quits.
#: One lmfit/DFO evaluation of a large model can take seconds.
QUIT_WAIT_S = 5.0

class Analysis(QObject):
    def __init__(...):
        ...
        app = QCoreApplication.instance()
        if app is not None:
            app.aboutToQuit.connect(self._stop_worker_for_quit)

    @Slot()
    def _stop_worker_for_quit(self) -> None:
        """Stop a running fit or sampling and wait for its thread before Qt tears down."""
        worker = self._fitter_thread
        if worker is None or not worker.isRunning():
            return
        # Detach first: the preview, finished and failed slots then see a stale
        # worker and return at once. No redraw, dialog or project record while quitting.
        self._fitter_thread = None
        self._fitting_logic.stop_fit()
        worker.stop()
        deadline = time.monotonic() + QUIT_WAIT_S
        while not worker.wait(50):  # ms
            QCoreApplication.processEvents()
            if time.monotonic() > deadline:
                logger.warning('The fit was still running %.0f s after quitting', QUIT_WAIT_S)
                break

What happens on quit with this handler:

  1. If the worker is parked, processEvents() delivers its pending preview. _on_fit_preview sees a stale sender and returns, so the worker resumes.
  2. The worker sees the stop flag. lmfit and DFO raise from the next progress callback; BUMPS and DREAM stop through abort_test. The worker emits failed, which is dropped as stale.
  3. run() returns and wait() succeeds, usually within one evaluation or step.

Notes:

  • Timeout. If the wait times out (one very long evaluation), the process still aborts, as it does today. The only stronger option is to keep the thread object alive past Analysis (worker.setParent(None) plus a module-level reference). That leaves the process exit racing a running thread, so a log line is the better trade-off.
  • Nothing recorded. Because the worker is detached first, quitting during a fit records no run and emits no externalFittingChanged. No redraw or autosave runs during teardown.

Test

  1. Start a real FitterWorker whose method blocks in _progress_callback, with preview_interval_s=1 and a monkeypatched clock.
  2. Connect previewRequested to analysis._on_fit_preview with Qt.BlockingQueuedConnection.
  3. Wait until the worker is parked, call _stop_worker_for_quit(), and assert not worker.isRunning().

This test also gives the blocking preview connection the real-thread coverage it does not have yet.

Should be fixed before the 1.6 release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    [priority] high[scope] bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions