task_manager::resolve_core calls m_task_finished_cv.notify_all() on every completion, causing thundering-herd wakeups

Aperta
#16,953 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à
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
cpp

Direzione di ricerca

Start with src/runtime/object.cpp, especially task_manager::resolve_core and the wait_for/wait_any paths that use m_task_finished_cv; the issue includes a Lean benchmark reproducer. Read how task completion and waiter synchronization interact, then verify that unrelated completions no longer wake task-specific waiters while IO.waitAny still works. The scope is concurrency-sensitive and spans runtime behavior.

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

Descrizione

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 master (4.38.0-pre, commit 3158840ce555).
Description

In src/runtime/object.cpp, task_manager uses a single process-wide m_task_finished_cv for all threads blocked in wait_for (Task.get / IO.wait / Async.block) and wait_any (IO.waitAny). Every task or promise completion in resolve_core unconditionally calls m_task_finished_cv.notify_all(), waking every waiting thread across the entire process to contend on m_mutex, check t->m_value != nullptr, and go back to sleep (O(waiters × completions)).

Context

We hit this bottleneck in a multithreaded Std.Net / Std.Async server workload: replacing Async.block waits with per-waiter parking cut Std.Net TCP echo latency from 97 µs → 75 µs (-23%) and context switches from 2.9 → 1.7 (-41%) at 16 concurrent connections.

Steps to Reproduce

Compile and run the following benchmark (lean --c=bench.c bench.lean && leanc -O3 -DNDEBUG bench.c -leanshared -lleanshared -o bench && ./bench), which parks 32 dedicated threads in IO.wait on distinct unresolved promises while resolving 10,000 unrelated promises:

def main : IO Unit := do
  let numSleepers := 32
  let numCompletions := 10000
  let mut sleepers : Array (IO.Promise Unit × Task (Except IO.Error Unit)) := #[]
  let ready ← IO.mkRef 0
  for _ in [:numSleepers] do
    let p ← IO.Promise.new
    let t ← IO.asTask (prio := .dedicated) do
      ready.modify (· + 1)
      let _ ← IO.wait p.result?
    sleepers := sleepers.push (p, t)
  while (← ready.get) < numSleepers do
    IO.sleep 1
  IO.sleep 20

  let t0 ← IO.monoNanosNow
  for i in [:numCompletions] do
    let p ← IO.Promise.new
    p.resolve i
  let t1 ← IO.monoNanosNow

  for (p, t) in sleepers do
    p.resolve ()
    let _ ← IO.wait t

  IO.println s!"elapsed: {(t1 - t0) / 1000} us"

Expected behavior: Unrelated promise resolutions do not wake threads waiting on different tasks (O(1) per completion).

Actual behavior: Every resolution wakes all 32 sleeping threads (~68 ms for 10,000 empty resolutions, 0.51 s kernel sys time, 21,069 involuntary context switches on macOS arm64).

Versions
  • 4.38.0-pre (master commit 3158840ce555275ad679a47fd224d887b45d3d88, macOS arm64)
Additional Information

A zero-per-wait-allocation fix is straightforward:

  • Add struct lean_task_waiter * m_waiters to lean_task_imp (freed when the task completes).
  • Use a lazy thread-local condition_variable via MK_THREAD_LOCAL_GET_DEF and a stack-allocated lean_task_waiter node linked onto imp->m_waiters in wait_for.
  • In resolve_core, detach imp->m_waiters and notify only waiters of that task while holding m_mutex (before handle_finished, which may unlock for sync := true dependents).
  • Gate m_task_finished_cv.notify_all() behind an m_wait_any_count > 0 check for IO.waitAny (so even the 0-waiter fast path skips notify_all).

Measured on macOS arm64 (4.38.0-pre):

Metric (10k unrelated resolutions, 32 sleeping waiters) master With targeted waiters
Elapsed time 68,020 µs 912 µs (74.6× faster)
Kernel sys time 0.51 s 0.01 s
Involuntary context switches 21,069 184 (114× fewer)
CPU cycles 1.29 B 39.6 M

Prototype branch with targeted waiters + regression test (prepared with AI assistance and reviewed/tested locally — 171/171 task/async/promise/wait/server tests passing):
https://github.com/nathanrs/lean4/compare/master...task-manager-targeted-wakeup

Impact

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.5k
Fork
1.2k
Merge medio
19h 36m
PR unite (30g)
323

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.