IO.asTask with a pure body silently runs the work on the spawning thread

オープン
#16,459 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
20/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
c

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

code-generator
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):

  1. Document the pitfall and the recommended pattern on the task-spawning
    primitives.
  2. Treat lean_io_as_task / lean_task_spawn as floating barriers in
    floatLetIn (never float computations out of closures flowing into them).
  3. 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 returning IO and pass the
    call to asTask, so the opaque call boundary blocks the float.
主要言語
Lean
スター
10.3k
フォーク
1.1k
平均マージ
19時間 8分
マージ済み PR(30日)
421

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

leanprover/lean4 のほかの issue

leanprover/lean4 の issue をすべて見る

似ている issue

Compilers の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。