Program hangs at exit when a still-running dedicated task waits on a pool task (`task_manager::~task_manager`)

Aperta
#16,815 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
20/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva

Direzione di ricerca

Read src/runtime/object.cpp, especially task_manager::~task_manager, spawn_worker, enqueue_core, and wait_for; then inspect tests/compile/task_wait_during_shutdown.lean from the linked open PR #15743, which already covers this scenario. Reproduce the hang with the issue's minimal input.lean program. Done means the dedicated task's IO.wait returns 42 and shutdown exits on its own; the issue says the existing PR addresses this work.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug
Prerequisites
  • Check that your issue is not already filed:
    https://github.com/leanprover/lean4/issues
  • Reduce the issue to a minimal, self-contained, reproducible test case.
    Avoid dependencies to Mathlib or Batteries.
  • Test your test case against the latest nightly release, for example on
    https://live.lean-lang.org/#project=lean-nightly
    (You can also use the settings there to switch to “Lean nightly”)
  • When reporting a perceived soundness bug: Does it affect lake check --paranoid?
    If in doubt, please reach out on [email protected] for responsible disclosure.
    (Not a soundness bug.)
Description

Note on existing PRs: open PR #15743 ("fix: dead locks and memory leaks in task manager finalization", not merged as of 2026-11-27) would fix this issue; its test tests/compile/task_wait_during_shutdown.lean covers a dedicated task that waits on a pool task queued during exit. There is no issue tracking the bug itself (the closed issue #12094 is a different shutdown deadlock), so this issue documents it, with a reproduction on nightly-2026-11-26, as the issue PR #15743 can close.

The task manager destructor sets m_shutting_down (object.cpp:1006), joins the standard workers, which exit once the queue is empty, and then waits for the dedicated workers (object.cpp:1016). A dedicated task that then spawns a pool task only queues it, because spawn_worker returns at once during shutdown (object.cpp:857-859), and its IO.wait (wait_for, not in the pool, so no compensation) blocks forever, and the destructor with it. The destructor does wait for running dedicated tasks to finish, so their normal work must still be able to complete.

The program's main starts a task at Task.Priority.dedicated (priority 9) which sleeps 300 ms, then spawns an ordinary priority-0 pooled task and waits for it with the documented IO.wait, and prints inner=42 when it gets the result; main itself prints main done and returns, so the emitted exit path calls lean_finalize_task_manager(). That deletes the manager, whose destructor sets m_shutting_down, finds no standard worker to join, and then waits for m_num_dedicated_workers == 0 - but by then the dedicated worker is blocked in task_manager::wait_for on the pooled task, which sits in m_queues and can never be dequeued because spawn_worker refuses to create any worker while m_shutting_down is true. Nothing ever wakes either waiter. The program's stdout is only main done, and the process ends after 1 s only because the program armed a 1 s one-shot libuv timer whose continuation calls IO.Process.exit 0 on the event-loop thread; that watchdog never fires in a correct run (the same program with IO.sleep 0 instead of IO.sleep 300, so that the inner pool task is spawned before the shutdown starts, prints main done / inner=42 and exits 0 on its own after 0.4 s). The required behaviour is that the IO.wait on the pooled task returns its result and that the exit-path finalization returns instead of hanging forever, so the program must print main done and inner=42 and exit 0 on its own.

Documented behavior it contradicts, from the docstring of IO.wait (src/Init/System/IO.lean:566):

Waits for the task to finish, then returns its result.

Context
  • Affected function: task_manager::~task_manager (src/runtime/object.cpp), reached from lean_finalize_task_manager in the emitted main
  • Upstream: no existing issue found. Open PR #15743 fixes this (see the note above); the closed issue #12094 is a different shutdown deadlock. The cited code is unchanged in nightly-2026-11-26.
Steps to Reproduce
  1. Save the following as input.lean (imports only Init/Std):
import Std

open Std.Internal.UV

initialize setT : Unit ← do
  Std.Async.System.setEnvVar "LEAN_MAIN_USE_THREAD" "0"
  Std.Async.System.setEnvVar "LEAN_NUM_THREADS" "1"

def main : IO Unit := do
  -- Only fires if the process is still running after one second: its
  -- continuation runs inline on the libuv event-loop thread.
  let timer ← Timer.mk 1000 false
  let tp ← timer.next
  let _ ← IO.mapTask (fun (_ : Option Unit) => (IO.Process.exit 0 : IO Unit)) tp.result? (sync := true)
  -- A dedicated task (priority 9) that needs an ordinary pooled task once the
  -- main thread has returned and the standard workers are gone.
  let _ ← IO.asTask (prio := 9) do
    IO.sleep 300
    let p ← IO.asTask (prio := 0) (pure (42 : Nat))
    let r ← IO.wait p
    match r with
    | .ok v => IO.println s!"inner={v}"
    | .error _ => IO.println "inner error"
  IO.println "main done"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog

Expected behavior:

main done
inner=42

exit status 0, without the 1 s watchdog firing.

Actual behavior:

main done

inner=42 is never printed; the process only terminates after 1.0 s because the watchdog timer calls IO.Process.exit 0 (exit status 0). Without the watchdog (same program with the three timer lines removed) the process hangs forever at exit (killed by a 10 s timeout). Same result in 3 of 3 runs.

Versions

Lean (version 4.38.0-nightly-2026-11-26, arm64-apple-darwin24.6.0, commit e1228b8b45918ece1a00d68e5fc5e6a685ca59ee, Release)
macOS 26.6.2 (arm64)

Additional Information

Root cause analysis. ~task_manager is called from lean_finalize_task_manager on the emitted exit path with a live manager that still owns one dedicated worker (m_num_dedicated_workers = 1, created by main's own IO.asTask (prio := 9)), with no standard worker (m_std_workers empty) and m_shutting_down false at entry. It sets m_shutting_down = true (object.cpp:1006) and then waits on m_dedicated_finished_cv for m_num_dedicated_workers == 0 (object.cpp:1016) while leaving its still-running dedicated worker unable to finish - that worker's IO.wait is blocked in wait_for with its dependency queued (m_queues_size = 1) and no worker to run it (m_std_workers empty, m_idle_std_workers = 0), because the only spawn_worker call (from enqueue_core) returned immediately with m_shutting_down true without adding a thread. So the destructor never returns, the task's IO.wait never yields 42 and the program never runs to its end. No callee hands it a wrong value: spawn_worker's early return while m_shutting_down (object.cpp:857-859) and enqueue_core's push + bounded spawn (object.cpp:826-834) do exactly what their code says, and wait_for correctly blocks until t->m_value is set. The state that makes them unusable (m_shutting_down true while a dedicated worker still runs tasks that need the pool) is set by the destructor itself.

Suggested fix: the shutdown must not make a still-running dedicated worker's pooled dependencies unrunnable, e.g. wait for the dedicated workers before stopping the pool, or allow the compensating worker in wait_for/spawn_worker during shutdown. spawn_worker's deliberate early return, enqueue_core's bounded spawn and wait_for's block for a dedicated (in_pool == false) waiter are not the fault by themselves.

Impact

A program whose main returns while a dedicated-priority task is still running and later uses the thread pool hangs at exit instead of terminating.

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Lingua principale
Lean
Stelle
10.3k
Fork
1.1k
Merge medio
16h 45m
PR unite (30g)
361

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di leanprover/lean4

Tutte le issue di leanprover/lean4

Issue simili

Altre issue su Backend & API Design

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.