Skip to content

Face scan deadlocks when two scan jobs need the same demo scene (rayon work-stealing vs. the scene cache's OnceLock) #630

Closed

Description

@cajax

Summary

The background face scan can deadlock forever. Its photo jobs run as rayon jobs in a process-wide scan pool
(ThreadPool::install). For a demo photo, each job loads the procedural scene through demo::scene_pixels, which
generates the scene with a rayon par_chunks_mut inside a process-wide OnceLock::get_or_init. A scan-pool thread
that steals a chunk of that generation and then waits in a nested join may pick up another scan job for the same
scene. That job parks on the OnceLock, on top of the chunk the generation is waiting for. The generation never ends,
so the OnceLock is never filled, and every other caller of that scene waits forever too.

Impact:

  • Product, verified in one process with one session. I ran lightcraft-cli mcp --library (a debug build of the
    Have a progress bar for every long running task #345 branch) on a library holding only the demo photos, with recognition on and a few virtual copies of a demo photo
    that has face regions. On 4 CPUs the scan deadlocked in 5–8 runs out of 20; on 22 threads, in 1–2 out of 10. A
    deadlocked scan never indexes another face. Any later request for that scene at that size waits forever too, and
    faces.index from the MCP client blocked the session thread, so the server stopped answering. Libraries of real
    files are not affected by this particular wait. But every new library starts with the demo photos
    (apps/lightcraft/src/main.rs:7-8), so they are what a new user tries face recognition on.
  • Tests. tests_face_recognize hangs in about half the runs on this 22-thread machine and never finishes. The
    synchronous tests have no deadline, so the whole cargo test run blocks. Two parallel tests that each run the
    background scan are enough.

By the project's never-crash standard this counts as a crash: the work in progress is lost, nothing reports an
error, and the guard around command dispatch (guard::catch, which is on the stuck session thread's stack) only
catches panics.

Environment

  • Linux x86_64 (Ubuntu 26.04.1, kernel 7.0), 22 hardware threads, 31 GiB RAM.
  • NVIDIA RTX 500 Ada (laptop), driver 595.91.07. The GPU is not involved. No thread in the hung test process is
    in wgpu / lightcraft_gpu code; the NVIDIA driver's threads are idle in futex / condvar waits. It hangs about as
    often with LIGHTCRAFT_GPU=0 (7/15 against 10/20), and the hung CLI process had no GPU threads at all. The
    deadlock happens while the scene is being generated, before anything is developed.
  • rustc 1.99.0 (b940084d7 2026-09-28), rayon 1.12.0, rayon-core 1.13.0, wgpu 30.0.1.
  • Test binary built from the Have a progress bar for every long running task #345 branch (e7fc6f7) with the workspace feature set. The files involved
    (crates/engine/src/demo.rs, crates/engine/src/faces_worker.rs, crates/engine/src/media.rs,
    crates/scenes/src/paint.rs) are identical on main. main has the two the_background_pump_* tests; the branch
    adds a third test that pumps (face_scan_row_follows_pending_photos).

Reproduce

Run the engine's lib test binary directly (from cargo test -p lightcraft-engine --lib --no-run). A run counts as
hung when it is still going after 30 s; a passing run of the module takes 2–5 s.

./engine-tests tests_face_recognize      # default thread count (22 here)
tests run (tests_face_recognize:: prefix omitted; several names with --exact) threads hung
the whole module (12 tests) default 10/20
the whole module, LIGHTCRAFT_GPU=0 default 7/15
the whole module --test-threads 1 0/10
the three tests that pump (the_background_pump_* ×2, face_scan_row_follows_pending_photos) default 18/20
the_background_pump_indexes_by_itself_once_recognition_is_on + the_background_pump_saves_what_it_embeds_for_the_next_launch (both on main) default 15/20
the_background_pump_indexes_by_itself_once_recognition_is_on + face_scan_row_follows_pending_photos default 13/20
the_background_pump_indexes_by_itself_once_recognition_is_on alone default 0/10
the_background_pump_indexes_by_itself_once_recognition_is_on + indexing_embeds_each_face_once_and_reports_progress default 0/15
the nine tests that don't pump (--skip the three) default 0/15

Smallest reliable repro, about 75 %:

./engine-tests --exact \
  tests_face_recognize::the_background_pump_indexes_by_itself_once_recognition_is_on \
  tests_face_recognize::the_background_pump_saves_what_it_embeds_for_the_next_launch

Two sessions that both run the background scan are needed, and enough. A test that calls faces.index / faces.suggest
on its own thread never causes the hang: that thread is not a rayon worker. It is only ever a victim.

Under cargo test, a hung run shows five or six tests "running for over 60 seconds". The pump tests then fail on
their own 60 s / 120 s deadlines. The tests that call faces.index / faces.suggest synchronously
(indexing_embeds_each_face_once_and_reports_progress, suggestions_come_from_the_named_faces_and_are_never_applied,
embeddings_are_cached_beside_the_library_and_reset_for_another_model) never return. Every thread sits in
futex_do_wait. A hung run also leaves its lc-facerec-* folder behind in the temp dir.

One session, as the product runs it

lightcraft-cli mcp --library DIR (debug build of the branch), one process and one session per run. Setup:

  • The library holds only the demo photos: photo 1 has face regions [Ann, unnamed] and photo 2 has [unnamed]. Any
    demo library whose photos have face regions works, e.g. after Detect Faces; I used one a test had left behind.
  • HOME, XDG_*, LIGHTCRAFT_FACE_MODELS and LIGHTCRAFT_DENOISE_MODELS point at a scratch folder.

Then, via MCP run_command:

  1. faces.models.install {path, acknowledged: true} with the tests' tiny model
    (lightcraft_faces::synthetic::tiny_embedder_model(64) written to a file). Installing switches recognition on.
  2. faces.models.select {id}.
  3. Optionally faces.setName {id: 2, index: 0, name: "Bob"}, so photo 2 ranks first next to photo 1.
  4. library.select {ids: [N]}, then photo.virtualCopy {ids: [N]} 7 times.
  5. faces.pump {pace: "full"} every 50 ms.

A passing run indexes every face in 1.2–2.8 s. A hung run stays at indexedFaces: 0 with inFlight: 5–6 forever,
and a following faces.index {budgetMs: 60000} never answers.

configuration hung
7 copies of photo 1, 22 threads 0/10
photo 2 named + 7 copies of photo 1, 22 threads 3/30 (plus 1/2 under gdb)
7 copies of photo 2, 22 threads 2/10
photo 2 named + 7 copies of photo 1, taskset -c 0-3 8/20
7 copies of photo 1, taskset -c 0-3 5/20
control: photos 1 and 2, no virtual copies 0/20

available_parallelism follows the CPU affinity, so taskset -c 0-3 sizes the scan pools and workers as on a
4-core machine (3 workers here). The test matrix above was running on the same machine at the same time, so the
absolute rates are rough. The gdb dump of a hung CLI run shows the same cycle (second block below).

Where it is stuck

With ptrace_scope at 1, gdb cannot attach to a running process, so it launched the binary itself:
gdb -batch -ex run -ex "thread apply all bt" --args ./engine-tests tests_face_recognize, interrupted after 90 s.
set print frame-arguments none is needed, otherwise gdb 17.1 aborts with "stack smashing detected" while printing a
frame. Generic parameters are elided. "(paint chunk)" marks frames whose types carry
lightcraft_scenes::paint::render::{closure_env#0}, i.e. pieces of the scene's par_chunks_mut. Line numbers are
from the branch build.

Thread 18 "lightcraft-face" (scan pool): the only thread inside a scene OnceLock initializer
  #7    rayon_core::registry::WorkerThread::wait_until_cold        <- waiting for a stolen half
  #9    rayon_core::join::join_context::{closure#0}
  #11   rayon::iter::plumbing::bridge_producer_consumer::helper     (paint chunk)
        ... 9 more nested join levels of the same par_chunks_mut ...
  #129  lightcraft_scenes::paint::render                            crates/scenes/src/paint.rs:205
  #131  lightcraft_scenes::Scene::render_fit                        crates/scenes/src/lib.rs:75
  #132  lightcraft_engine::demo::scene_pixels::{closure#1}          crates/engine/src/demo.rs:130  <- get_or_init running
  #141  lightcraft_engine::demo::scene_pixels                       crates/engine/src/demo.rs:130
  #142  lightcraft_engine::media::SourceRef::load_source            crates/engine/src/media.rs:254
  #143  lightcraft_engine::media::RenderJob::run                    crates/engine/src/media.rs:755
  #144  lightcraft_engine::faces_worker::process::{closure#1}       crates/engine/src/faces_worker.rs:187
  #150  lightcraft_engine::faces_worker::process_in_background::{closure#0}   faces_worker.rs:319
  #151  rayon_core::thread_pool::ThreadPool::install::{closure#0}   (scan job A)

Thread 28 "lightcraft-face" (scan pool; thread 24 is the same)
  #2    std::sys::sync::once::futex::Once::call                     <- parked: the init is RUNNING on thread 18
  #6    std::sync::once_lock::OnceLock::get_or_init
  #7    lightcraft_engine::demo::scene_pixels                       crates/engine/src/demo.rs:130
  #9    lightcraft_engine::media::RenderJob::run                    crates/engine/src/media.rs:755
  #10   lightcraft_engine::faces_worker::process::{closure#1}       crates/engine/src/faces_worker.rs:187
  #17   rayon_core::thread_pool::ThreadPool::install::{closure#0}   (scan job B: another session, same scene)
  #28   rayon_core::registry::WorkerThread::execute
  #29   rayon_core::registry::WorkerThread::wait_until_cold         <- B was picked up while waiting here
  #31   rayon_core::join::join_context::{closure#0}                 (paint chunk)
        ... #31-#104 are all paint chunks: stolen pieces of thread 18's generation ...
  #110  rayon_core::registry::main_loop                             <- started as an idle pool thread

Threads 19-23, 26, 31, 32 (scan pool): parked in join_context inside paint chunks, waiting for halves that threads
  24 and 28 hold.
Threads 10, 25, 33 (face workers): rayon_core::latch::LockLatch::wait_and_reset <- ThreadPool::install
  <- faces_worker::process_in_background (faces_worker.rs:321) <- Worker::start's loop (faces_worker.rs:349)
Threads 2, 6, 9 (tests: persist / index / suggest): Once::call <- demo::scene_pixels (demo.rs:130)
  <- RenderJob::run <- faces_worker::process <- face_recognize::imp::embed_photo <- imp::index / imp::suggest
  <- Session::execute
22 global-pool threads idle; 3 NVIDIA threads idle; no frame in wgpu or lightcraft_gpu.

A wait on a std::sync::Once parks only while an initialization is running, and thread 18 is the only thread inside
one, so threads 2, 6, 9, 24 and 28 all wait on thread 18's slot. For the same reason the paint chunks under threads 24
and 28 can only belong to thread 18's generation. (This is inferred from the stacks; the slot addresses were not
printed.)

Single session, lightcraft-cli mcp --library (photo 2 named, 7 virtual copies of photo 1), launched by gdb and
interrupted after 40 s:

Threads 8 and 24 (scan pool): each initializing one of the two demo scenes (scene_pixels::{closure#1}, demo.rs:130
  -> render_fit -> paint.rs:205), parked in joins of their par_chunks_mut.
Thread 21 (scan pool):
  #2    std::sys::sync::once::futex::Once::call                     <- parked on a scene OnceLock
  #7    lightcraft_engine::demo::scene_pixels                       crates/engine/src/demo.rs:130
  #15   lightcraft_engine::faces_worker::process                    crates/engine/src/faces_worker.rs:183
  #29   rayon_core::registry::WorkerThread::wait_until_cold         <- scan job picked up while waiting
        ... paint chunks, #52 another wait_until_cold, more paint chunks, #69 wait_until_cold ...
  #72   rayon_core::registry::main_loop
Threads 10-15, 18-20, 22, 23 (scan pool): parked in joins inside paint chunks. Threads 16, 17: idle.
Thread 9 (scan pool): a scan job parked on a scene OnceLock with nothing beneath it (harmless on its own).
Threads 4-7 (face workers): LockLatch::wait_and_reset <- ThreadPool::install <- process_in_background.
Thread 1 "lightcraft-cli" (session thread, MCP request faces.index):
  #2    std::sys::sync::once::futex::Once::call
  #7    lightcraft_engine::demo::scene_pixels                       crates/engine/src/demo.rs:130
  #16   lightcraft_engine::cmd::face_recognize::imp::embed_photo    crates/engine/src/cmd/face_recognize.rs:348
  #17   lightcraft_engine::cmd::face_recognize::imp::index          crates/engine/src/cmd/face_recognize.rs:391
  #24   lightcraft_engine::guard::catch                             crates/engine/src/guard.rs:22
  #27   lightcraft_mcp::headless::{impl#3}::call                    crates/mcp/src/headless.rs:129
  #50   lightcraft_cli::mcp                                         apps/lightcraft-cli/src/main.rs:345
No GPU threads: nothing had reached the develop step.

Root cause

Verified (code read and matched against the dump):

  1. The scene cache waits. scene_pixels (crates/engine/src/demo.rs:111-133) keeps one
    Arc<OnceLock<Arc<Rgb32f>>> per (scene, size) in a process-wide cache and generates the pixels inside
    slot.get_or_init(|| Arc::new(scene.render_fit(max_edge))) (demo.rs:130). Its doc comment
    (demo.rs:100-107) says concurrent requests wait for one generation. render_fit → paint::render is a rayon
    par_chunks_mut (crates/scenes/src/paint.rs:205). A caller that finds the slot RUNNING parks in a futex until it
    is filled; it does not help the generation and does not run other rayon work.
  2. Scan jobs are rayon jobs in a shared pool. process_in_background runs each photo as
    scan_pool(pace).install(|| process(..)) (crates/engine/src/faces_worker.rs:318-324). The pools are three
    process-wide statics (faces_worker.rs:292-309). Up to max_workers() worker threads (faces_worker.rs:334-361)
    each inject one job. The same pool threads also run every job's inner parallel work, including the scene's
    par_chunks_mut.
  3. rayon runs injected jobs on top of a waiting join. A pool thread whose join has its other half stolen runs other
    jobs of its pool while it waits (WorkerThread::wait_until_cold), injected install jobs included. That job sits
    on top of the waiting frame, which cannot resume until the job returns.
  4. The cycle. Scan job A initializes scene X (thread 18). Threads 24 and 28 steal chunks of X. While they wait in
    nested joins, they pick up scan jobs B and C for the same X and park on X's OnceLock, with X's chunks beneath them.
    So X never completes, thread 18 waits for those chunks forever, and every later caller of X joins the wait. In the
    single-session dump two generations are in progress at once (threads 8 and 24). I did not work out which scene
    each waiter there waits for, so the cycle may run through both. The callers here are the face workers in install, and the tests' synchronous faces.index / faces.suggest →
    embed_photo → process (crates/engine/src/cmd/face_recognize.rs:346-348, :391).
  5. When it started. Before d9457e6 ("generate each procedural demo scene once per process", 2026-10-09),
    SourceRef::load_source called scene.render_fit directly and nothing in a scan job could wait. The scan pool with
    install came the day before (24f87a9, 2026-10-08). The doc comment on process_in_background
    (faces_worker.rs:311-317) already names this hazard for the memory gate ("a job running on a pool thread that
    waits inside a nested rayon call can pick up another job to run on top of itself"). The scene cache added a second
    wait of that kind.

Why the tests hit it: every session in the test process shares the scene cache and the scan pools, and setup uses
Session::with_demo() (crates/engine/src/tests_face_recognize.rs:22-31). So the pump tests running in parallel
(tests_face_recognize.rs:214-249, :251-292, and on the branch face_scan_row_follows_pending_photos) submit scan
jobs for the same two demo scenes (photos 1 and 2, sorted ids) into the same pool. With one test thread there is
never a second scan job for a scene, and it never hangs.

Not explained: why CI has passed with these tests. It is not because CI runners have few cores; small pools are more
exposed (see the 4-CPU single-session rates). Possibly the passing runs predate d9457e6, or the timing on the runners
differs. I have not looked at the CI history.

Test-only or product?

Product: yes, verified with one session per process (the CLI's MCP server, above). The trigger is two scan jobs
in flight at once for the same scene at the same size. Each of the 24 demo scenes is unique, so in one session that
takes virtual copies: photo.virtualCopy clones the photo with its source and its face regions
(crates/engine/src/cmd/organize.rs:69-101). The scan renders every photo at 2048 px (faces_worker::EDGE), which
selects the Preview source level, so every copy asks for the same scene slot. Different photos never collide; the
control shows 0/20.

  • CLI / MCP (verified). faces.index, and faces.suggest / faces.evaluate with a budget, embed on the session
    thread. After a deadlock they wait forever, and the server stops answering.
  • Desktop app (suspected, not run). The engine code is the same, and a new library starts with the demo photos
    (apps/lightcraft/src/main.rs:7-8). The trigger: a recognition model installed, plus face regions on a demo photo
    (Detect Faces) or the YuNet detector installed (then unsearched virtual copies get scanned too), plus virtual copies
    of that photo. The window's own thread only calls faces.pump and faces.suggest {budgetMs: 0}
    (crates/ui-egui/src/panels/faces.rs:554, :668), and neither waits. So I expect the scan to stall silently, with
    the "Finding faces" row stuck, rather than the window freezing. But a later render of that scene at the Preview level
    that the session's source cache doesn't serve (the loupe, on a JobPool render thread) would also wait forever.
  • Real-file libraries: not affected by this wait. scene_pixels is only used for Source::Demo
    (crates/engine/src/media.rs:254). A scan job's file decodes count as interactive at the memory gate and never wait
    (crates/engine/src/files.rs:524-565, faces_worker.rs:311-317). The underlying hazard still applies to them:
    any blocking wait reachable from a scan job can deadlock the pool.
  • Several sessions in one process happen only in tests today, which is why the tests hit it so much more often.

Fix directions

  1. Never park a rayon worker on a scene slot (small, local). Replace the OnceLock slot with a small state under
    the cache's mutex (empty / generating / ready) and a condvar:

    • A rayon worker (rayon::current_thread_index().is_some()) never waits. It uses a ready slot, claims an empty
      one, and generates a private copy when another thread is generating.
    • Plain threads (the UI's render JobPool, the session thread, test threads) wait on the condvar as today. Their
      wait never sits on top of a chunk, and once no worker waits, every generation finishes.

    OnceLock::get_or_init and OnceLock::set both block while another thread is initializing, so neither may be
    called from a worker. The cost is a duplicate generation only when a scan job races another request for the same
    scene.

  2. Make the scan pool safe by construction. Today any blocking wait reachable from process can deadlock the
    pool: this slot, the memory gate the doc comment warns about, and whatever comes next. Options:

    • One pool per worker (the pace's pool threads split between the workers). Each pool's queue then only ever holds
      the one job its threads are already running, so no other scan job can land on top of a chunk. A job of another
      worker waiting for the scene then waits at the top of its own pool's stack, as thread 9 above does, which is
      harmless.
    • At minimum, a debug assertion in every blocking wait reachable from a scan job (the scene slot,
      WorkGate::acquire) that it is not on a scan-pool thread, e.g. a thread-local set by the pools'
      start_handler.
  3. Don't "fix" it by serializing the tests (--test-threads 1, a test mutex) or by giving each test its own scenes.
    That hides a deadlock the product can hit (see above).

  4. Minor: the synchronous tests have no deadline, so a hang blocks the whole cargo test run instead of failing one
    test. A hung run also leaves lc-facerec-* folders behind.

Regression test

Per the never-crash rule, the fix lands with a test that fails (instead of hanging the suite) before it:

  • Deterministic unit test in demo.rs. Split the cache from the generator, e.g.
    fn cached(key, generate: impl FnOnce() -> Rgb32f), so a test can hold a generation open. Thread G starts
    generating key K with a generator that blocks on a channel. Then, on a thread of a small rayon::ThreadPool, call
    cached(K, ..) and report back through a channel. Assert with recv_timeout(5 s) that it returns. Before the fix
    the pool thread parks on the slot and the assertion fails; after, it returns its own copy. Release G (from a drop
    guard, so a failing run leaves no parked thread), and check that both callers got identical pixels and the slot
    holds one. A second case: a plain thread asking for K while G generates still waits, and gets G's pixels.
  • End-to-end stress test with a watchdog. One demo session with the tiny model installed (as setup does), face
    regions on photo 1, and 7 virtual copies of it (photo.virtualCopy). Call faces.pump {pace: "full"} in a loop
    and assert every face is indexed within 60 s. Run the session on a spawned thread and wait with recv_timeout so a
    regression fails instead of hanging. This one is not deterministic. The same setup through the CLI hung in 5–8 of 20
    runs on 4 CPUs and 1–2 of 10 on 22 threads, so it backs up the unit test rather than replacing it.

Found while working on #345 / PR #601 (the activity-stack row for the face scan). It is outside that PR:

  • The code involved is identical on main and came from d9457e6 and 24f87a9, not from the branch.
  • The two pump tests that hang together (15/20) exist on main unchanged.
  • It also hung on 52c0f67, before the branch's newest change.

main itself was not built for this.

🤖 Generated with Claude Code

Activity

  1. added a commit that references this issue on Oct 10, 2026
  2. AlexChambers commented on Oct 10, 2026

    @AlexChambers
    Contributor

    #557 fixes this exact deadlock: the same mechanism, a rayon worker re-entering scene_pixels's OnceLock for the scene it's already generating. Each scene now has one render at a time; a rayon worker renders it serially on its own thread, so it never picks up other queued jobs mid-render, and everyone else waits on a condvar. Its tests time out instead of hanging on the old code (the stress test hangs 3 of 3 times there), and the two face tests that originally hung pass. It's independent of #601.

  3. cajax commented on Oct 10, 2026

    @cajax
    ContributorAuthor

    Fixed in #557

  4. added a commit that references this issue on Oct 10, 2026
  5. added a commit that references 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