Skip to content

Crash at exit: a GPU render still running on a worker thread segfaults in the NVIDIA Vulkan driver #620

Closed

Description

@cajax

Summary

If the process exits while a render job on an lc-job-N preview worker is inside the GPU path (wgpu → Vulkan
vkCreateCommandPool), it segfaults in libnvidia-glcore. The pool's workers are detached, and nothing on the way
out waits for them or stops GPU work. So main returns, process teardown begins, and a render is still calling
into the driver.

  • Users: quitting while previews or an export are rendering on the GPU can end in a SIGSEGV instead of a clean
    exit. Our safety net cannot catch a SIGSEGV (the panic hook, and the catch_unwind around the GPU render at
    crates/gpu/src/lib.rs:350), so the user gets a crash report or core dump and no message. on_exit saves
    preferences and the library before the process ends, and exports are written atomically, so we don't expect
    data loss (not verified). It is still a crash, and under "Never crash" that outranks feature work.
  • Developers: test binaries that use the GPU intermittently exit with 139 after printing test result: ok.

Environment

Reproduction

On the PR #601 branch, first remove the test-only workaround: delete the h.settle(..) calls in demo(),
slow_import() and bracket() in crates/ui-egui/src/tests_activity.rs and in demo() in
crates/ui-egui/src/lightroom_import.rs (added in f8fc7f0). Then build once and
run the test binary in a loop:

BIN=$(cargo test -p lightcraft-ui-egui --lib --no-run 2>&1 | grep -o '([^)]*lightcraft_ui_egui-[0-9a-f]*)' | tr -d '()' | tail -1)
n=60; segv=0
for i in $(seq "$n"); do
  "$BIN" lightroom tests_activity >/dev/null 2>&1
  [ $? -eq 139 ] && segv=$((segv + 1))   # 139 = killed by SIGSEGV
done
echo "$segv/$n runs segfaulted"

Observed on the machine above:

Run Segfaults at exit
cargo test -p lightcraft-ui-egui --lib -- lightroom tests_activity (17 tests, before the merge test existed), no workaround 1 of 20
the same set with --skip export --skip quit (no export renders) 1 of 30
only the export and quit tests 0 of 30
lightroom_import::tests alone / tests_activity::scan + ::import / the remaining stack tests 0 of 40 each
tests_activity::final_merge_shows_a_row_and_cancels alone (imports three synthetic DNGs, ends quickly), no settle in its setup 3 of 15
pre-existing tests_panels tests_zoom tests_masking tests_offline 0 of 40
with the workaround: merge test only / full set (18 tests) 0 of 20 / 0 of 30

The crash needs no export: it comes from preview renders of the library the test opened. It shows up more often the
sooner the process exits after those renders start.

The backtrace below came from gdb -batch -ex run -ex bt --args "$BIN" lightroom tests_activity --skip export --skip quit
(caught on the 4th run). gdb then aborted
itself ("stack smashing detected"), so there is no dump of all threads.

A related one-off: the real app (cargo run -p lightcraft) once segfaulted on quit while a GPU export render was in
flight. It did not happen again in 3 reruns. It is probably the same mechanism on a different thread (export),
but that is unconfirmed.

Backtrace (trimmed)

test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 399 filtered out; finished in 1.26s
...
Thread 74 "lc-job-1" received signal SIGSEGV, Segmentation fault.
#0  0x00007fffe8c40a30 in ?? ()
#1  0x00007fffba7f7a95 in ?? () from /usr/lib/x86_64-linux-gnu/libnvidia-glcore.so.595.91.07
#2  ash::device::Device::create_command_pool (self=0x7fffe8c40c48, ...)   ash-0.38.0+1.3.281/src/device.rs:2562
#3  wgpu_hal::vulkan::device::create_command_encoder                      src/vulkan/device.rs:1383
#5  wgpu_core::command::allocator::CommandAllocator::acquire_encoder      src/command/allocator.rs:42
#6  wgpu_core::device::resource::Device::create_command_encoder           src/device/resource.rs:2610
#9  wgpu::api::device::Device::create_command_encoder                     src/api/device.rs:208
#10 lightcraft_gpu::ctx::Gpu::encoder (self=<lightcraft_gpu::GPU>)         crates/gpu/src/ctx.rs:492
#11 lightcraft_gpu::render::Cx::new                                       crates/gpu/src/render.rs:144
#12 lightcraft_gpu::render::render                                        crates/gpu/src/render.rs:589
#13-#18 (closure inside std::panic::catch_unwind)                         crates/gpu/src/lib.rs:350
#19 lightcraft_gpu::render                                                crates/gpu/src/lib.rs:350
#20 lightcraft_engine::media::develop                                     crates/engine/src/media.rs:806
*** stack smashing detected ***: terminated        <- gdb itself, unwinding further

Root cause

The following was checked in the code, at the PR #601 head unless noted.

  1. Pool workers are detached and outlive their pool. JobPool::start spawns lc-job-{i} and drops the
    JoinHandle (let _ = …spawn(…), crates/preview/src/pool.rs:87). take checks shutdown only before it
    picks up a job (pool.rs:159–172). impl Drop for JobPool (pool.rs:175–180) sets shutdown, calls
    notify_all and returns without joining. A job that is already running keeps running after the pool, its owner
    Renderer (crates/ui-egui/src/render.rs:177, up to 6 workers) and the app are gone.
  2. Those jobs use the GPU. View and export render jobs set gpu = self.cache.is_none()
    (crates/engine/src/media.rs:762). That goes into develop (media.rs:800–806) and then
    lightcraft_gpu::render (crates/gpu/src/lib.rs:333).
  3. The device is never shut down. It is the process-wide static GPU: OnceLock<Result<ctx::Gpu, String>>
    (crates/gpu/src/lib.rs:172), and Rust never drops statics. Nothing in crates/gpu stops new work or drains
    in-flight work at exit: grepping for shutdown, atexit and quiesce finds nothing. The only in-render counter
    (RenderScope / IN_RENDER, crates/gpu/src/ctx.rs:146–170) is thread-local.
  4. The quit path doesn't wait for workers.
    • on_exit (apps/lightcraft/src/main.rs:74–81) saves preferences and the library, and does nothing else.
      After eframe::run_native returns (main.rs:707), main returns.
    • The macOS menu-bar Quit calls on_exit and then std::process::exit(0) straight away (main.rs:62–63,
      PR fix(macos): prevent SIGILL crash on exit by replacing viewport close … #444), so any running worker is cut off in the middle of a call.
    • The close-request check (crates/ui-egui/src/lib.rs:736, which calls panels::notices::may_close at
      crates/ui-egui/src/panels/notices.rs:20) considers activity tasks and unsaved changes, not preview renders.
      In PR Issue #345: activity stack — one progress indicator for long-running tasks #601, "Quit Anyway" calls activity.cancel_all() (crates/engine/src/activity.rs:193), which sets
      cancel flags and returns without waiting.
    • Other detached workers:
      • Export: crates/ui-egui/src/export_task.rs:60. It renders through the same RenderJob, so on the GPU.
      • Photo Merge: crates/ui-egui/src/merge.rs:143. It renders on the CPU
        (lightcraft_pipeline::render, crates/engine/src/merge.rs:263), so it doesn't call the GPU itself. In the
        merge test the crashing thread was a pool worker rendering the imported DNGs.
      • AI Denoise: crates/engine/src/denoise.rs:1193. It runs lightcraft_gpu::nn (denoise.rs:269) on that
        module's own device. Suspected to have the same exposure; untested.
      • ImportRun::drop (crates/ui-egui/src/import.rs:287) and LightroomTask::drop
        (crates/ui-egui/src/lightroom_import.rs:120) follow the same signal-only pattern, but don't use the GPU.
  5. Mechanism (suspected, not proven). Exiting the process (main returning, or process::exit) runs atexit
    handlers and shared-library destructors while other threads keep running. The NVIDIA driver's teardown most
    likely frees state that the still-running vkCreateCommandPool call depends on. Frame #0 executes at an address
    in the same mapping as the ash Device (self=0x7fffe8c40c48 in Import: scan folders in the background (fixes Add Folder on network shares) #2), which fits the driver jumping through a
    dangling pointer.

Not verified:

  • Other Linux drivers (Mesa RADV / ANV / NVK), Windows DX12, macOS Metal.
  • The one app-quit segfault during an export.
  • AI Denoise's exposure (from reading the code only).
  • That LIGHTCRAFT_GPU=0 makes the loop above come out clean (expected, not run).

Proposed fix directions

  1. JobPool: on drop, signal and then join with a bounded wait.
    • Keep the JoinHandles. Drop sets shutdown, calls notify_all, then waits up to a deadline for workers to
      exit.
    • std's JoinHandle has no timed join, so count live workers under the existing mutex/condvar, or give each
      worker a done-channel and use recv_timeout. Join the workers that finished; detach the rest with a log line.
    • Also add an explicit JobPool::shutdown(timeout) -> bool, so owners stop the pool at a known point instead of
      depending on drop order. The macOS process::exit path never drops the app at all.
    • Queued jobs are already discarded on shutdown. The results channel is an unbounded std::sync::mpsc::channel,
      so a worker's send never blocks waiting for the owner.
  2. App quit path: wait for workers, bounded. Add one LightcraftApp::shutdown(deadline) and call it from
    on_exit (main.rs:74) and before std::process::exit(0) on the macOS menu path (main.rs:62). It cancels
    activity tasks, stops the render pool, then waits (one shared deadline) for the export, merge, denoise and import
    workers. To make that possible, keep their JoinHandles or done-channels instead of discarding them.
  3. GPU "shutting down" gate in crates/gpu.
    • lightcraft_gpu::begin_shutdown() sets a process-wide flag. render() (lib.rs:333) and nn check it
      before touching the device, and return None / an error, so no new GPU work starts during exit.
    • A process-wide in-flight counter (unlike the per-thread IN_RENDER) lets wait_idle(timeout) wait for renders
      already inside the device, then poll the device until submitted work completes.
    • This also covers threads that 1 and 2 miss.

Trade-offs:

  • Quit latency. A render already in flight has to finish, or the deadline runs out. A GPU preview or export
    render takes well under a second. A CPU-fallback 24 MP render, a merge or AI Denoise can take seconds. So: keep the
    deadline short (about 1–2 s), have long jobs check the cancel/shutdown flag where they can, and exit anyway after
    the deadline. That leaves today's risk in place, but rarer, and with the gate closed no new GPU calls start.
  • No deadlock in Drop. A plain join hangs if a job is blocked on something the owner thread holds: a lock,
    a channel only the UI thread drains, or a gate like the one in pool_priorities_dedupe_and_drop. Hence:
    • the wait is bounded;
    • the queue lock is not held while waiting;
    • a pool dropped on its own worker thread never joins that worker.
  • wasm32. There are no threads, so this stays a no-op.

Regression test idea

The segfault depends on the driver and on timing, so the test should check the invariant that is broken today: no
worker outlives the pool or app that owns it. Each test below fails on the current code.

  • crates/preview/src/tests.rs → pool_drop_waits_for_running_job:
    1. JobPool::new(1).
    2. Submit a job that sleeps about 200 ms and then sets an Arc<AtomicBool>.
    3. Wait until the job has started (queued() == 0).
    4. drop(pool).
    5. Assert the flag is set. Today it isn't, because drop returns immediately.
  • Companion pool_drop_is_bounded_when_a_job_never_ends: a job blocks on a gate that is never opened. Assert
    that drop returns within the deadline plus some slack. This covers the deadlock trade-off.
  • App level (crates/ui-egui, Headless): start an export with slow_writer (tests_activity.rs:181) and a
    loupe render, then call the new shutdown. Assert that it returns true and that no pool, export or merge worker
    is still alive (expose a live-worker count for tests).
  • Manual check on Linux + NVIDIA: the loop above, with the PR Issue #345: activity stack — one progress indicator for long-running tasks #601 workaround removed, gives 0 runs with exit
    139 out of 50 or more.

Context

Found while working on #345 (activity stack) in PR #601, and outside that PR's scope. PR #601 only works around the
crash in its own tests: their setups call Headless::settle, so no startup render is still running at exit. The
app's quit path is unchanged.

🤖 Generated with Claude Code

Activity

  1. cajax commented on Oct 10, 2026

    @cajax
    ContributorAuthor

    Fixed in #656

  2. added a commit that references this issue on Oct 27, 2026
  3. added 5 commits that reference this issue on Oct 27, 2026
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions