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

Open
#16,953 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
cpp

Research direction

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.

Written by the indexing model from the issue text.

Description

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.

Dominant language
Lean
Stars
10.5k
Forks
1.2k
Avg merge
19h 36m
Merged PRs (30d)
323

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from leanprover/lean4

All issues in leanprover/lean4

Similar issues

More Backend & API Design issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.