IO.asTask with a pure body silently runs the work on the spawning thread
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 20/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Tech stack
- c
- Domain
- compilers, performance
Research direction
The reproduction is the AsTaskHoist.lean program, and the cause is visible in the generated C, where the busyU64 call sits in the spawning loop before lean_io_as_task. Start with the floatLetIn compiler pass and the closure built for IO.asTask, then compare the pure-body and bound-body variants. Done means both run their work on worker threads, or the docstrings for IO.asTask, BaseIO.asTask and Task.spawn state the eager-evaluation behaviour.
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.
- Test your test case against the latest stable release (
leanprover/lean4:v4.35.0).
Description
When the body of an IO.asTask is a pure computation, floatLetIn hoists the payload out of the task closure and evaluates it eagerly on the spawning thread. The spawned task then only wraps a precomputed value. Results are correct, but the program silently loses all parallelism.
Related: #16436 (floatLetIn moving an ST.Prim.Ref.get past a later write) — same pass, here with a performance (rather than correctness) consequence.
Context
Found while parallelizing an adaptive meshing kernel that batches CPU-bound work across cores. IO.asTask do pure (work x) measured slower than the sequential baseline; only after inspecting the generated C did the cause become clear. This pattern — asTask around a pure computation — is the natural way to write "run this on a worker", so other users are likely hitting this without noticing (no error, no warning, just no speedup).
Steps to Reproduce
Self-contained, no dependencies:
/-- Allocation-free busy loop. -/
def busyU64 (n seed : UInt64) : UInt64 := Id.run do
let mut acc := seed
for i in [0:n.toNat] do
acc := (acc + i.toUInt64) * 2654435761 % 4294967291
return acc
def main (args : List String) : IO Unit := do
let n := args[0]!.toNat!
let rounds := args[1]!.toNat!
-- Sequential baseline
let t0 ← IO.monoMsNow
let mut a0 : UInt64 := 0
for r in [0:rounds] do a0 := a0 + busyU64 n.toUInt64 r.toUInt64
IO.println s!"sequential: {(← IO.monoMsNow) - t0} ms (acc={a0})"
-- asTask with a pure body
let t1 ← IO.monoMsNow
let tasks1 ← (Array.range rounds).mapM fun r =>
IO.asTask (prio := .dedicated) do
pure (busyU64 n.toUInt64 r.toUInt64)
let mut a1 : UInt64 := 0
for t in tasks1 do
match t.get with | .ok v => a1 := a1 + v | .error _ => pure ()
IO.println s!"asTask (pure body): {(← IO.monoMsNow) - t1} ms (acc={a1})"
-- asTask with a body that depends on a monadic bind
let t2 ← IO.monoMsNow
let tasks2 ← (Array.range rounds).mapM fun r =>
IO.asTask (prio := .dedicated) do
let tick ← IO.monoMsNow
pure (busyU64 n.toUInt64 (r.toUInt64 + tick.toUInt64))
let mut a2 : UInt64 := 0
for t in tasks2 do
match t.get with | .ok v => a2 := a2 + v | .error _ => pure ()
IO.println s!"asTask (bound body): {(← IO.monoMsNow) - t2} ms (acc={a2})"
lean -R . AsTaskHoist.lean -o a.o -c a.c
leanc -O3 -o astask_hoist a.c
./astask_hoist 100000000 8
Output (16-core Apple Silicon):
sequential: 3387 ms
asTask (pure body): 3382 ms -- no parallelism
asTask (bound body): 424 ms -- ~8x, as expected
The generated C for the pure-body variant shows the payload evaluated in the
spawning loop, before the closure is created:
v___x_204_ = l_busyU64(v___x_202_, v___x_203_); // payload, spawning thread
v___x_205_ = lean_box_uint64(v___x_204_);
v___f_206_ = lean_alloc_closure((void*)(...lam__0...), 2, 1);
lean_closure_set(v___f_206_, 0, v___x_205_); // closure captures the result
v___x_208_ = lean_io_as_task(v___f_206_, v___x_207_);
The bound-body variant correctly keeps lean_io_mono_ms_now() and l_busyU64(...)
inside the task closure, where they run on the worker thread.
Expected behavior: both variants run in parallel — or, if hoisting is
considered working-as-intended, the docstrings for IO.asTask, BaseIO.asTask,
and Task.spawn state that pure bodies may be evaluated at the spawn site, and
a recommended pattern for deferred execution is documented.
Actual behavior: asTask (pure e) evaluates e eagerly on the calling
thread; the task degenerates to Task.pure.
Versions
Lean (version 4.35.0, arm64-apple-darwin) (stock toolchain); also reproduced
on a custom stage1 build of master. macOS 26.3.1, 16-core Apple Silicon.
Additional Information
The same applies to Task.spawn (fun _ => e) when e ignores the Unit
argument, for the same reason: the payload does not mention the closure's
parameter (or the IO world token), so it may float.
The semantics are result-preserving — this is purely an evaluation-order issue,
which Lean's semantics deliberately leaves unspecified. The problem is the
silent violation of the performance contract of the concurrency primitives.
Possible directions (not exclusive):
- Document the pitfall and the recommended pattern on the task-spawning
primitives. - Treat
lean_io_as_task/lean_task_spawnas floating barriers in
floatLetIn(never float computations out of closures flowing into them). - Provide a blessed combinator taking an explicit thunk,
e.g.IO.asTask' (f : Unit → IO α), whose body is guaranteed to run on the
worker.
Workarounds meanwhile:
- Make the task body depend on a value produced by a monadic bind inside the
body (as in the third variant above). - Or route the work through a
@[noinline]function returningIOand pass the
call toasTask, so the opaque call boundary blocks the float.
- Dominant language
- Lean
- Stars
- 10.3k
- Forks
- 1.1k
- Avg merge
- 19h 8m
- Merged PRs (30d)
- 421
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from leanprover/lean4
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
leanprover/lean4#16681 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
leanprover/lean4#16305 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 86/100
leanprover/lean4#16299 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
leanprover/lean4#16257 ·
Maintainers usually reply within 1 day
-
`IO.FS.realPath` reports every failure as `noFileOrDirectory` instead of classifying by `errno`Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
leanprover/lean4#15683 ·
Maintainers usually reply within 1 day
All issues in leanprover/lean4
Similar issues
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
swc-project/swc-next-issues#817 ·
-
Magma mode: div:=, mod:= and the other keyword assignments (join:=, meet:=, diff:=, sdiff:=, and:=, or:=, xor:=) are refusedPossibly taken A pull request linked to this issue is open or already merged. Open
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
sagemathinc/sagebrush#1683 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
Maintainers usually reply within 1 day
-
microts: a model local that every branch assigns raises unused_assignments in the generated RustOpenbug
Difficulty 2/5 1-3 hours Newbie friendliness 80/100
pocket-stack/pocketjs#756 ·
-
bot-triaged module: aotinductor module: compile-time module: inductor module: performance module: rocm oncall: export oncall: pt2 triaged
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
Maintainers usually reply within 1 day