From b23806cbf92b0a0a31301f783ec985eb77b63a84 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 22:14:01 +0100 Subject: [PATCH 01/59] MPI: run tasks that asked for no thread on any free thread of their rank, start the others pinned execute!(::ThreadProc) binds the function to the processor's thread, and MPI's execute! hands every task to its inner thread, so an MPI task waits behind whatever occupies that thread without yielding (a long kernel, a rank-local task) even when nobody asked for that thread: the scheduler merely named it. A task whose scope leaves every thread of its rank open now runs inline in the pooled, migratable task that executes it, so Julia puts it on whichever thread is free. A task whose scope excludes some thread of its rank asked for a thread and stays bound to the processor the scheduler picked within that scope: an ExactScope (explicit pinning, and every Datadeps task), but also a union of only some threads of the rank. The decision looks at the scope the scheduler placed the task under (TaskSpec.scope), so it includes Datadeps' exact scope and the scopes of chunk arguments. A union that names every thread of the rank (scope(mpi_rank=r)) is not a request. Measured on a 2 ranks x 8 threads cluster (three threads of rank 0 kept busy by non-yielding tasks, eight short tasks scoped to rank 0 placed round robin): the task that the scheduler placed on a busy thread waited 3.32 s (of 4 s) before, and all eight finished within 0.23 s with this change. Uniform-placement benchmarks of 128 uneven tasks, 2 ranks x 16 threads: makespan 1.60 s (6.4x of ideal) -> 0.36-0.40 s. Second part: start the task of an MPI processor pinned to its inner thread. The scheduler pins each task to its processor's thread through task_tid_for_processor, which had no method for MPIProcessor, so MPI tasks started migratable. execute!(::ThreadProc) then missed its inline fast path (already on the processor's thread) and, for every task, created a second task pinned to the thread, scheduled it and waited for it. Measured inside execute! on a dependent chain at 4 ranks x 16 threads: 160-190 us per task for that hand-over, 7 us once the task starts pinned. task_tid_for_processor now also receives the task. MPIProcessor{ThreadProc} returns the tid of its inner processor, for processors of this rank, and leaves a task that asked for no thread unpinned. Because that decision now differs per task, the pooled task slots (pinned or made migratable once, when a slot is created, then reused for later tasks) are kept in two caches: a migratable task that reused a slot an earlier pinned task had created stayed bound to that thread. Dependent chain of tasks pinned to a non-driver thread (4 ranks x 16 threads, 3000 links, two runs each): same rank 458 / 414 -> 284 / 254 us per link, alternating between two ranks 572 / 557 -> 296 / 307. Tests: test/mpi/free_threads.jl (new). With three of four threads busy, sixteen rank-scoped tasks finish in under 1.5 s while the busy tasks still have a second to run; a task scoped to two busy threads of the rank stays on one of them (this fails if only an ExactScope counted as a request); an explicit thread is kept. spawn.jl checks the thread of tasks with a compute_scope or exact scope; threads.jl (Datadeps) is unchanged. --- ext/MPIExt.jl | 81 ++++++++++++++++++++++++++++-- src/sch/Sch.jl | 29 +++++++---- test/mpi/cpu.jl | 1 + test/mpi/free_threads.jl | 104 +++++++++++++++++++++++++++++++++++++++ test/mpi/spawn.jl | 11 +++-- 5 files changed, 211 insertions(+), 15 deletions(-) create mode 100644 test/mpi/free_threads.jl diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 0d2d640ab..342ee9d58 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2429,6 +2429,81 @@ function mpi_execute_bcast_plan(f, args, proc::MPIProcessor) return (; need_type_bcast=false, nothrow, inferred) end +# --- Running a task on a free thread of its rank -------------------------------------- +# +# `execute!(::ThreadProc)` binds the function to the processor's thread, so an MPI task +# waits behind anything that occupies that thread without yielding (a long kernel, a +# rank-local task), whichever thread the scheduler happened to name. A task whose scope +# leaves every thread of its rank open did not ask for a thread: the choice is the +# runtime's and need not be kept, so it runs on whichever thread of its rank is free. +# A task whose scope excludes some thread of its rank (an `ExactScope`, which is what +# Datadeps and explicit pinning use, or a union of only some threads) did ask for one: +# it stays on the thread of the processor the scheduler picked within that scope. + +# Does `scope` leave out a thread of the rank of `proc`? +function mpi_thread_requested(proc::MPIProcessor, scope) + (scope === nothing || scope isa Dagger.AnyScope || scope === Dagger.DefaultScope()) && return false + nthreads = count(p -> p isa Dagger.ThreadProc, ensure_children!(proc.comm)) + if scope isa Dagger.UnionScope + # A union of `ExactScope`s (what `scope(mpi_rank=...)` builds) is the common shape: count + # the distinct threads of this rank it names instead of testing every thread against it + named = 0 + for sub in scope.scopes + if sub isa Dagger.ExactScope && sub.processor isa MPIProcessor{Dagger.ThreadProc} + p = sub.processor + (p.rank == proc.rank && p.comm == proc.comm) && (named += 1) + else + return mpi_thread_requested_slow(proc, scope) + end + end + return named < nthreads + end + return mpi_thread_requested_slow(proc, scope) +end +function mpi_thread_requested_slow(proc::MPIProcessor, scope) + for inner in ensure_children!(proc.comm) + inner isa Dagger.ThreadProc || continue + Dagger.proc_in_scope(MPIProcessor(inner, proc.comm, proc.rank), scope) || return true + end + return false +end + +# The task that runs `execute!` is a pooled, migratable task with its TLS in place, so +# the function can simply be called: Julia runs it on whichever thread is free +function mpi_run_unbound(f, args...; kwargs...) + if Dagger.task_logging_enabled() + Dagger.TimespanLogging.prof_task_put!(Dagger.get_tls().sch_handle.thunk_id.id) + end + try + return @invokelatest f(args...; kwargs...) + catch err + err isa InterruptException && rethrow() + rethrow(CapturedException(err, catch_backtrace())) + end +end + +# Start the task of an MPI processor already pinned to the thread of its inner processor. +# Without this the task is migratable, and `execute!(::ThreadProc)` then misses its inline +# fast path: it creates a second task pinned to the thread, schedules it and waits, which +# measured 160-190 us per task (a dependent chain of tasks pinned to one thread: 387 us per +# link at 4 ranks x 16 threads, of which 161 us was this hand-over). Only for processors of +# this rank, and not for a task that asked for no particular thread. `task.scope` is the +# scope the scheduler placed the task under (it includes Datadeps' exact scope and the scopes +# of chunk arguments), the same one `mpi_execute_inner` looks at. +function Dagger.Sch.task_tid_for_processor(proc::MPIProcessor{Dagger.ThreadProc}, task) + proc.rank == MPI.Comm_rank(proc.comm) || return nothing + mpi_thread_requested(proc, task.scope) || return nothing + return Dagger.Sch.task_tid_for_processor(proc.innerProc) +end + +function mpi_execute_inner(proc::MPIProcessor, f, args...; kwargs...) + if proc.innerProc isa ThreadProc && Dagger.in_task() && + !mpi_thread_requested(proc, Dagger.get_tls().task_spec.scope) + return mpi_run_unbound(f, args...; kwargs...) + end + return execute!(proc.innerProc, f, args...; kwargs...) +end + # A task that is not part of a Datadeps region (no tag option) generates ref ids only while it # is moved to and executed on its processor, never during planning, so once `execute!` returns # nobody takes another id for its thunk id and its sub-counter is dead. Without this the table @@ -2484,7 +2559,7 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) # type on every rank so chunktype stays SPMD-uniform. if !plan.need_type_bcast && plan.nothrow if islocal - result = execute!(proc.innerProc, f, raw_args...; kwargs...) + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) space = mpi_result_space(result, proc) return tochunk(result, proc, space; type=plan.inferred) else @@ -2498,7 +2573,7 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) if !plan.need_type_bcast if islocal result = try - execute!(proc.innerProc, f, raw_args...; kwargs...) + mpi_execute_inner(proc, f, raw_args...; kwargs...) catch err @opcounter :execute_bcast_send_yield bcast_meta_yield(proc.comm, proc.rank, tag, (:error, mpi_wire_exception(err))) @@ -2521,7 +2596,7 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) # Non-concrete return type: full status + type/space (or error) broadcast if islocal result = try - execute!(proc.innerProc, f, raw_args...; kwargs...) + mpi_execute_inner(proc, f, raw_args...; kwargs...) catch err @opcounter :execute_bcast_send_yield bcast_meta_yield(proc.comm, proc.rank, tag, (:error, mpi_wire_exception(err))) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 50763132c..50ddae717 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1736,6 +1736,10 @@ proc_state(proc::Processor) = proc_state(Dagger.get_tls().sch_uid, proc) task_tid_for_processor(::Processor) = nothing task_tid_for_processor(proc::Dagger.ThreadProc) = proc.tid +# The thread the task for `task` should run on at `proc`. An acceleration whose processor wraps +# a `ThreadProc` overrides this so the task starts pinned where `execute!(::ThreadProc)` would +# otherwise have to create a second pinned task, hand the call over and wait for it. +task_tid_for_processor(proc::Processor, task) = task_tid_for_processor(proc) stealing_permitted(::Processor) = true stealing_permitted(proc::Dagger.ThreadProc) = proc.owner != 1 || proc.tid != 1 @@ -1918,16 +1922,23 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re # completes before the record exists, and DoTaskSpec's cleanup # loop then burned a sleep(0.1) per lost race — the dominant # multithreaded wall-time cost for small tasks. - @reusable_tasks :start_processor_runner!_task_cache 32 t->begin - tid = task_tid_for_processor(to_proc) - if tid !== nothing - Dagger.set_task_tid!(t, tid) - else - Dagger.set_task_migratable!(t) + # N.B. A pooled task is pinned (or made migratable) once, when its slot is created, and the + # slot is then reused for later tasks. The thread decision can differ per task (an + # acceleration that pins only the tasks that asked for a thread), so tasks that start + # pinned and tasks that start migratable must not share slots: a migratable task that + # reused a pinned slot would stay bound to that thread. + task_tid = task_tid_for_processor(to_proc, task) + if task_tid === nothing + @reusable_tasks :start_processor_runner!_task_cache_migratable 32 t->Dagger.set_task_migratable!(t) "thunk" DoTaskSpec(to_proc, return_queue, task, cancel_token) t->begin + lock(istate.queue) do _ + tasks[thunk_id] = t + end end - end "thunk" DoTaskSpec(to_proc, return_queue, task, cancel_token) t->begin - lock(istate.queue) do _ - tasks[thunk_id] = t + else + @reusable_tasks :start_processor_runner!_task_cache 32 t->Dagger.set_task_tid!(t, task_tid) "thunk" DoTaskSpec(to_proc, return_queue, task, cancel_token) t->begin + lock(istate.queue) do _ + tasks[thunk_id] = t + end end end end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index ba97dfd08..3c14f52b4 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -147,6 +147,7 @@ end include("spawn.jl") include("noaliasing_args.jl") +include("free_threads.jl") @testset "Datadeps" begin diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl new file mode 100644 index 000000000..f09edd5d9 --- /dev/null +++ b/test/mpi/free_threads.jl @@ -0,0 +1,104 @@ +# An MPI task whose thread nobody asked for runs on any free +# thread of its rank instead of waiting behind a busy one. +hog_busy(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; 1) # does not yield +free_quick(x::Int) = x + 1 +free_where() = Threads.threadid() + +@testset "Free MPI threads" begin + if Threads.nthreads() >= 3 + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + rank0 = sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid) + # Warm up first: the first fetch of a task compiles for a second on slow nodes, which would be measured otherwise + foreach(fetch, Dagger.with_options(; scope=Dagger.scope(mpi_rank=0)) do + [Dagger.@spawn(free_quick(i)) for i in 1:16] + end) + foreach(fetch, [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(0.01)) for p in rank0]) + MPI.Barrier(comm) + # Occupy every thread of rank 0 but the first with a pinned (so bound) task that never yields + hogs = [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(2.5)) for p in rank0[2:end]] + sleep(0.3) + MPI.Barrier(comm) + t0 = time() + # Scope = the whole rank, 16 tasks: the scheduler names every thread in turn, busy ones included + tasks = Dagger.with_options(; scope=Dagger.scope(mpi_rank=0)) do + [Dagger.@spawn(free_quick(i)) for i in 1:16] + end + vals = fetch.(tasks) + elapsed = time() - t0 + @test vals == [i + 1 for i in 1:16] + # Before tasks ran on free threads, the tasks the scheduler places on a busy thread wait for the hogs (measured: 3.3 s of 4 s) + rank == 0 && @test elapsed < 1.5 # the hogs still have a second to run + # An explicit thread is still a promise + where = fetch(Dagger.@spawn scope=Dagger.ExactScope(last(rank0)) free_where()) + @test where == last(rank0).innerProc.tid + foreach(wait, hogs) + end + MPI.Barrier(comm) +end + +# A scope that names some threads of a rank is a request for one of them, not only an +# `ExactScope`: the task must stay on a thread of the scope even while all of them are busy. +@testset "Free MPI threads respect a scope that names threads" begin + if Threads.nthreads() >= 3 + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + rank0 = sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid) + subset = rank0[2:3] + subset_tids = [p.innerProc.tid for p in subset] + subset_scope = Dagger.UnionScope(map(Dagger.ExactScope, subset)) + # Warm up the task shapes first + foreach(fetch, [Dagger.@spawn(scope=subset_scope, free_where()) for _ in 1:4]) + foreach(fetch, [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(0.01)) for p in subset]) + MPI.Barrier(comm) + # Both threads of the scope are busy for a while. A task that did not care would run on + # another thread at once; these must wait for one of the two. + hogs = [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(1.0)) for p in subset] + sleep(0.3) + MPI.Barrier(comm) + tasks = [Dagger.@spawn(scope=subset_scope, free_where()) for _ in 1:6] + tids = fetch.(tasks) + @test all(in(subset_tids), tids) + # The same through `compute_scope`, and with a scope that names every thread of the rank + tasks = [Dagger.@spawn(compute_scope=subset_scope, free_where()) for _ in 1:6] + @test all(in(subset_tids), fetch.(tasks)) + foreach(wait, hogs) + all_threads = Dagger.UnionScope(map(Dagger.ExactScope, rank0)) + MPI.Barrier(comm) + hogs = [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(2.5)) for p in rank0[2:end]] + sleep(0.3) + MPI.Barrier(comm) + t0 = time() + vals = fetch.([Dagger.@spawn(scope=all_threads, free_quick(i)) for i in 1:8]) + @test vals == [i + 1 for i in 1:8] + rank == 0 && @test time() - t0 < 1.5 # the hogs still have a second to run + foreach(wait, hogs) + end + MPI.Barrier(comm) +end + +# The task of an MPI processor starts pinned to the thread of its inner processor, so +# `execute!(::ThreadProc)` runs the function inline instead of creating a second pinned task +# and waiting for it (measured: 160-190 us per task). A task that asked for no particular +# thread starts migratable. +@testset "MPI task starts pinned to its processor's thread" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + mine = first(sort(filter(p -> p.rank == rank, cpus); by=p -> p.innerProc.tid)) + others = filter(p -> p.rank != rank, cpus) + tid_for = Dagger.Sch.task_tid_for_processor + spec(scope) = (; scope = scope) # the hook only reads `task.scope` + # (a rank with one thread has none to choose from: its exact scope leaves nothing out) + nthr = count(p -> p.rank == rank, cpus) + @test tid_for(mine, spec(Dagger.ExactScope(mine))) == (nthr > 1 ? mine.innerProc.tid : nothing) + # A task that did not ask for a thread is not pinned + @test tid_for(mine, spec(nothing)) === nothing + @test tid_for(mine, spec(Dagger.DefaultScope())) === nothing + @test tid_for(mine, spec(Dagger.AnyScope())) === nothing + # A processor of another rank has no thread here + isempty(others) || @test tid_for(first(others), spec(Dagger.ExactScope(first(others)))) === nothing + # And it runs where it was pinned + if rank == 0 + @test fetch(Dagger.@spawn(scope=Dagger.ExactScope(mine), free_where())) == mine.innerProc.tid + else + fetch(Dagger.@spawn(scope=Dagger.ExactScope(first(filter(p -> p.rank == 0, cpus))), free_where())) + end + MPI.Barrier(comm) +end diff --git a/test/mpi/spawn.jl b/test/mpi/spawn.jl index 5a87f385f..83c3d37ec 100644 --- a/test/mpi/spawn.jl +++ b/test/mpi/spawn.jl @@ -1,18 +1,23 @@ # Plain eager tasks need a uniform placement decision even when ranks make # progress at different speeds. Check actual execution, scopes, and locality. +# A task whose scope excludes some thread of its rank asked for a thread, and must run on the +# processor's thread. Any other task runs on whichever thread of its rank is free (see +# `free_threads.jl`), so only its rank is the planner's choice. mpi_spawn_location(x=nothing) = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid(), x) mpi_spawn_value() = (sleep(0.05); 42) mpi_spawn_value_fast(i) = 42 + i - i mpi_spawn_checked(i::Int) = i > 0 ? i : error("negative") -function check_spawn_placements(tasks, allowed, value=nothing) +function check_spawn_placements(tasks, allowed, value=nothing; pinned=false) placements = Dagger.Processor[] for task in tasks proc = fetch(task; raw=true).processor push!(placements, proc) @test proc in allowed @test Dagger.check_uniform(proc) - @test fetch(task) == (proc.rank, proc.innerProc.tid, value) + loc = fetch(task) + @test loc[1] == proc.rank && loc[3] == value + pinned && @test loc[2] == proc.innerProc.tid end @test [count(==(p), placements) for p in allowed] == fill(4, length(allowed)) end @@ -50,7 +55,7 @@ end end foreach(wait, tasks) Dagger.check_uniformity!(true) - check_spawn_placements(tasks, allowed) + check_spawn_placements(tasks, allowed; pinned=label in ("compute scope", "exact scope")) end @testset "Chunk owner preference" begin From 9efc4653c864a1cc94eb00edd74d4e62905751fc Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 22:16:58 +0100 Subject: [PATCH 02/59] mpi: a task on a communicator of one rank skips the status/type protocol With one rank (a one-rank job, or a rank-local graph on COMM_SELF) there is nobody to tell about the status, the type or the space of a result, so execute! runs the function and stamps its result without planning or broadcasting. Laptop, 4 threads, plain independent @spawn under MPI with one rank, interleaved 4 times: 16.05 -> 15.32 us per task (shared memory 11.7 us). --- ext/MPIExt.jl | 8 ++++++++ test/mpi/free_threads.jl | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 342ee9d58..fe414efdf 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2552,6 +2552,14 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) return tochunk(nothing, proc, space; type=dest_type) end + # A communicator of one rank (a one-rank job, or a rank-local graph): nobody to tell about the + # status, the type or the space of the result, so there is nothing to plan or to broadcast + if MPI.Comm_size(proc.comm) == 1 + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) + space = mpi_result_space(result, proc) + return tochunk(result, proc, space; type=typeof(result)) + end + plan = mpi_execute_bcast_plan(f, args, proc) # Concrete + nothrow: type/space known locally and the call cannot throw, diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index f09edd5d9..6779c5501 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -102,3 +102,15 @@ end end MPI.Barrier(comm) end + +# In a job of one rank every task is on a communicator of one rank: nobody to tell about its +# status or result type, so none is sent. The result must still be right, and a failure rethrown. +if nranks == 1 + @testset "Task on a one-rank communicator" begin + @test fetch(Dagger.@spawn(free_quick(41))) == 42 + @test fetch(Dagger.@spawn(identity(nothing))) === nothing + t = Dagger.@spawn(error("one-rank failure")) + @test_throws Exception fetch(t) + @test fetch(Dagger.@spawn(free_quick(1))) == 2 # still working afterwards + end +end From c0909f23b8b2b20ab5684af838d6746e6946eaf9 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 22:17:56 +0100 Subject: [PATCH 03/59] mpi: keep freed tile memory in the heap (mallopt) when the acceleration starts Datadeps slots and received tiles are libc buffers of tens to hundreds of KB, allocated and freed in every region. With glibc's defaults each is a fresh mmap or a trimmed heap top, so every use pays page faults. mallopt keeps up to 16 MB buffers in the heap and never trims it. This is a process-wide setting and is never undone. A tiled factorization on 2 nodes x 1 rank x 32 threads ran about 10 % faster on our cluster; not re-measured on upstream. Linux/glibc only; a no-op elsewhere. --- ext/MPIExt.jl | 2 ++ src/memory-spaces.jl | 24 ++++++++++++++++++++++++ test/mpi/free_threads.jl | 12 ++++++++++++ 3 files changed, 38 insertions(+) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index fe414efdf..7a16529ac 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2664,6 +2664,8 @@ function initialize_acceleration!(a::MPIAcceleration) a.comm in comms end already && return + # Tiles crossing ranks are libc buffers allocated and freed per region: keep their pages in the heap + Dagger.tune_malloc!() if !MPI.Initialized() MPI.Init(;threadlevel=:multiple) end diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bfc5afb8f..f4c8fe4e2 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -138,6 +138,30 @@ copy: the buffer's contents are established later by Datadeps' copy-to phase. alloc_uninit(::CPURAMMemorySpace, ::Type{<:Array{T,N}}, dims::Dims{N}) where {T,N} = alloc_libc_array(T, dims) +""" + tune_malloc!() -> Bool + +Keep freed memory in the process heap instead of returning it to the system (glibc only): a +buffer of up to 16 MB comes from the heap, not from its own `mmap`, and the heap's free top is +not trimmed. Datadeps slots and received tiles are libc buffers of tens to hundreds of KB that +are allocated and freed in every region; with glibc's defaults each one is a fresh `mmap` or a +trimmed heap top, so every use pays page faults (received tiles at ~0.7 GB/s). Called when the +MPI acceleration starts (where tiles cross ranks). Returns whether the settings were applied; +a no-op elsewhere. +""" +function tune_malloc!() + Sys.islinux() || return false + try + # mallopt parameters: M_TRIM_THRESHOLD = -1, M_TOP_PAD = -2, M_MMAP_THRESHOLD = -3 + ok = ccall(:mallopt, Cint, (Cint, Cint), -3, 16 << 20) == 1 + ok &= ccall(:mallopt, Cint, (Cint, Cint), -1, typemax(Int32)) == 1 + ok &= ccall(:mallopt, Cint, (Cint, Cint), -2, 256 << 20) == 1 + return ok + catch + return false + end +end + """ slot_may_be_uninit(from_space, to_space, ::Type{T}) -> Bool diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index 6779c5501..dd22eeec3 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -114,3 +114,15 @@ if nranks == 1 @test fetch(Dagger.@spawn(free_quick(1))) == 2 # still working afterwards end end + +# The acceleration keeps freed tile memory in the heap (glibc mallopt); it is a no-op elsewhere +@testset "tune_malloc!" begin + ok = Dagger.tune_malloc!() + @test ok isa Bool + # Idempotent + @test Dagger.tune_malloc!() == ok + # Allocating and freeing a tile-sized libc buffer still works with the settings in place + A = Dagger.alloc_libc_array(Float64, (256, 256)) + A .= 1.0 + @test sum(A) == 256 * 256 +end From 2bf92a25688870e08362c0257043b186454fdb23 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 22:36:52 +0100 Subject: [PATCH 04/59] mpi: the broadcast relay is migratable from 4 default threads on Task + sticky=false still starts on the creator's thread when the creator is thread-bound (the driver, once Distributed has used @async). The relay then shares the driver's thread, and a driver parked in a blocking MPI call (an MPI.Allgather or Barrier in user code) stops it from forwarding the broadcasts the other ranks wait for: a cross-rank cycle that hung the full MPI suite across two nodes (found with a task-backtrace watchdog: three ranks in MPI_Allgather at 100 % CPU, the fourth's relay dead of the send timeout). The relay is made migratable from 4 default threads on. Below that it keeps the old placement: a migratable relay is a polling loop that keeps a thread busy and, at 2 threads per rank, competes with the tasks for the only free thread. That hung the delegation test at 4 ranks x 2 threads (cluster 3 of 3 runs, MPICH laptop 1 of 5, old placement 0 of 5; pinning the relay to the last thread was worse, 3 of 5). From 4 threads on it passes (4 and 8 threads, 2 nodes). test/mpi/relay.jl: restarts the relay from a thread-bound driver and checks it forwards while the last rank's driver is busy. On macOS with Julia 1.13 a Task made by a thread-bound driver did not start on its thread, so this test also passes without the change there; it guards the placement, it does not reproduce the cluster hang. --- ext/MPIExt.jl | 14 +++++++++++++- test/mpi/cpu.jl | 1 + test/mpi/relay.jl | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 test/mpi/relay.jl diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 7a16529ac..0cef7e66b 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1595,8 +1595,20 @@ function start_bcast_relay!(accel_comm::MPI.Comm) lock(BCAST_STATES) do states states[accel_comm] = state end + # The relay is a polling loop that keeps a thread busy. From 4 default threads on it is migratable: a + # `Task` made on a thread-bound task (the driver, once Distributed has used `@async`) starts on its + # creator's thread even with `sticky = false`, and a driver parked in a blocking MPI call (an + # `MPI.Allgather` or `Barrier` in user code) would then stop it from forwarding the broadcasts the other + # ranks wait for: a cross-rank cycle that hung the full MPI suite across two nodes. Below 4 threads a + # migratable relay competes with the tasks for the only free thread and hung the delegation test at + # 4 ranks x 2 threads, so there it keeps the creator's thread. + migratable = Threads.nthreads(:default) >= 4 t = Task(() -> bcast_relay_loop(state)) - t.sticky = false + if migratable + Dagger.set_task_migratable!(t) + else + t.sticky = false + end schedule(t) Dagger.Sch.errormonitor_tracked("mpi_bcast_relay", t) state.relay = t diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 3c14f52b4..519e4bc44 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -148,6 +148,7 @@ end include("spawn.jl") include("noaliasing_args.jl") include("free_threads.jl") +include("relay.jl") @testset "Datadeps" begin diff --git a/test/mpi/relay.jl b/test/mpi/relay.jl new file mode 100644 index 000000000..d57c35299 --- /dev/null +++ b/test/mpi/relay.jl @@ -0,0 +1,40 @@ +# The broadcast relay must keep forwarding while the driver thread is busy. A relay that shares the +# driver's thread stalls behind a driver parked in a blocking call (a long non-yielding computation, +# an `MPI` collective), and the ranks that wait for what it forwards wait with it. +relay_union_value() = rand() < 2 ? 1 : "never" # non-concrete result type: broadcast to every rank +relay_stamp(x) = time() +relay_hog(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; nothing) + +@testset "Broadcast relay is independent of the driver thread" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pin(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + # A driver that has scheduled an `@async` task (Distributed's transport does) is thread-bound for + # good, and a `Task` it creates starts on its thread even with `sticky = false`. Restart the relay + # from such a driver, as a session that used Distributed first would have started it. + wait(@async nothing) + @test Base.current_task().sticky + MPI.Barrier(comm) + MPIExt.stop_bcast_relay!(accel.comm) + MPIExt.start_bcast_relay!(accel.comm) + MPI.Barrier(comm) + # Whatever its placement, it forwards broadcasts + w = Dagger.@spawn scope=pin(0) relay_union_value() + @test fetch(Dagger.@spawn scope=pin(nranks - 1) relay_stamp(w)) isa Float64 + MPI.Barrier(comm) + if nranks >= 2 && Threads.nthreads(:default) >= 4 + # The last rank's driver is busy for 1.5 s without yielding. Rank 0 produces a value whose type + # is broadcast, and a task on the last rank consumes it: it can only start once that rank's relay + # has delivered the value, so its start time measures the relay, not the driver. + t0 = time() + x = Dagger.@spawn scope=pin(0) relay_union_value() + s = Dagger.@spawn scope=pin(nranks - 1) relay_stamp(x) + if rank == nranks - 1 + sleep(0.2) # let the tasks be planned + relay_hog(1.5) + end + started = fetch(s) + # The hog still has well over a second to run when the task starts + rank == nranks - 1 || @test started - t0 < 1.0 + MPI.Barrier(comm) + end +end From 7e6c0b3702ed97cc6c0436bb5c89f97915bb3b37 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 22:37:00 +0100 Subject: [PATCH 05/59] mpi: a migratable broadcast relay no longer spins on yield() The relay spun 4096 yield() calls after every message. On a multi-threaded scheduler each yield() puts the task back on the shared queue and wakes a sleeping thread to run it, so one polling loop kept most of a rank's threads out of sleep. A migratable relay now sleeps 100 us between probes from the first idle iteration; a relay that stays on the driver's thread (fewer than 4 default threads) keeps the spin, because it shares that thread and must yield to the tasks there. Measured with the relay migratable: one cross-rank dependency in a Datadeps chain 2.2-2.9 ms against 0.37-0.44 ms without the spin (2 ranks x 4 threads, laptop). On our cluster, 2 ranks x 32 threads, a rank used 181-216 CPU seconds per region against 44 for the same work without the spin, and its kernels ran 6-14 % slower while the spin was on. Not re-measured on upstream master. A migratable relay on only 2 default threads is not used. --- ext/MPIExt.jl | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 0cef7e66b..36881e5c2 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1527,7 +1527,7 @@ const BCAST_RELAY_HEARTBEAT_ITERS = 1000 # forward the raw bytes to this rank's tree children, then deliver the payload. # Forwarding is NOT gated by datadeps task dispatch — that is what breaks the # forwarder wait-cycle. -function bcast_relay_loop(state::BcastState) +function bcast_relay_loop(state::BcastState, spin_iters::Int=BCAST_RELAY_SPIN_ITERS) comm = state.bcast_comm rank = MPI.Comm_rank(comm) sz = MPI.Comm_size(comm) @@ -1543,7 +1543,7 @@ function bcast_relay_loop(state::BcastState) got, msg, stat = MPI.Improbe(MPI.ANY_SOURCE, MPI.ANY_TAG, comm, MPI.Status) if !got idle += 1 - if idle <= BCAST_RELAY_SPIN_ITERS || !may_backoff + if idle <= spin_iters || !may_backoff yield() else # N.B. `Libc.systemsleep`, not `sleep`: `sleep` parks the @@ -1603,7 +1603,11 @@ function start_bcast_relay!(accel_comm::MPI.Comm) # migratable relay competes with the tasks for the only free thread and hung the delegation test at # 4 ranks x 2 threads, so there it keeps the creator's thread. migratable = Threads.nthreads(:default) >= 4 - t = Task(() -> bcast_relay_loop(state)) + # A migratable relay that spins on `yield()` wakes another thread with every call (the task goes back to + # the shared queue), which keeps most of a rank's threads out of sleep; it sleeps between probes at once. + # One that stays on the driver's thread shares that thread and must yield to the tasks there. + spin_iters = migratable ? 0 : BCAST_RELAY_SPIN_ITERS + t = Task(() -> bcast_relay_loop(state, spin_iters)) if migratable Dagger.set_task_migratable!(t) else From 24299865ae2c5e4ec596466a4353db0972cee8bf Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 16 Oct 2026 21:54:25 +0200 Subject: [PATCH 06/59] Let an acceleration complete a task without a thunk (elide_task!) A process that takes no part in executing a task (it neither runs it nor owns data it reads) still builds, schedules and dispatches a thunk for it under an SPMD acceleration, only to stamp an empty result. Measured on our cluster (4 ranks x 16 threads), that is 168 us per task on such a process against 188 us on the task's owner; 165 of the 170 us are scheduling and submission. Core support, inert unless an acceleration opts in (default elides nothing, switch off by default: Dagger.elide_foreign_tasks!(true) or JULIA_DAGGER_ELIDE_FOREIGN_TASKS=1, read at startup): * eager_launch! asks elide_task!(accel, spec, task) first (driver-level tasks only). Task ids are still taken in eager_spawn, so they stay uniform. The first submission starts the eager scheduler, which takes an id of its own; with elision that start is made at the same point in the id sequence whether or not the first task is elided. * DTask gains 'stub' (the placeholder result, nothing for ordinary tasks) and 'owner' (the rank/worker known to own the result at spawn, -1 if unknown). istaskstarted accounts for a stub. Later submissions use the placeholder in place of the task (eager_process_elem_submission_to_local!), and a syncdep on an elided task, which has no thunk and is already finished, adds no edge. * Sch.task_failed! is called once from store_result! when a failure is recorded (the task's own error, a failed argument move, an upstream failure), so an acceleration can tell processes that cannot see it. It must not block. * fetch of a task with a known owner calls fetch_failed_uniform! when the future holds an error, so an acceleration can keep the ids its successful fetch takes uniform on the processes that fail before getting there. No behaviour change with the switch off (test/allocations.jl unchanged: task spawn 183 allocations, bound 500). --- src/Dagger.jl | 4 ++++ src/acceleration.jl | 12 +++++++++++ src/dtask.jl | 21 ++++++++++++++++-- src/sch/util.jl | 17 +++++++++++++++ src/submission.jl | 52 +++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 100 insertions(+), 6 deletions(-) diff --git a/src/Dagger.jl b/src/Dagger.jl index 2b988a956..468767c49 100644 --- a/src/Dagger.jl +++ b/src/Dagger.jl @@ -186,6 +186,10 @@ function __init__() delete!(SYSTEM_UUIDS, myid()) system_uuid() + # Read at startup, not at precompile time: a `const` initialized from the + # environment would be baked into the compiled image + ELIDE_FOREIGN_TASKS[] = get(ENV, "JULIA_DAGGER_ELIDE_FOREIGN_TASKS", "0") in ("1", "true") + @static if !isdefined(Base, :get_extension) @require Distributions="31c24e10-a181-5473-b8eb-7969acd0382f" begin include(joinpath(dirname(@__DIR__), "ext", "DistributionsExt.jl")) diff --git a/src/acceleration.jl b/src/acceleration.jl index e4eea0973..1584662f5 100644 --- a/src/acceleration.jl +++ b/src/acceleration.jl @@ -75,6 +75,18 @@ compatible_processors(accel::Union{Acceleration,Nothing}, scope::AbstractScope=g uniform_execution(::DistributedAcceleration) = false uniform_execution() = uniform_execution(current_acceleration()) +""" + fetch_failed_uniform!(accel) + +Called when `fetch` of a task with a known owner (`DTask.owner`) throws because the +task failed on this process. Under uniform execution a fetch of a task that did +not fail takes part in a broadcast, which takes a task-id-derived tag on every +process; a process that fails before it gets there must take the same ids, or the +ids (and tags) of everything that follows differ across processes. Does nothing +by default. +""" +fetch_failed_uniform!(::Acceleration) = nothing + # SPMD uniformity checking. Under a uniform-execution acceleration (e.g. MPI), # planning-time values are hashed and compared across ranks to catch divergence # early. Core datadeps calls `check_uniform` unconditionally; the real checks diff --git a/src/dtask.jl b/src/dtask.jl index 29fecce51..41ced380e 100644 --- a/src/dtask.jl +++ b/src/dtask.jl @@ -74,16 +74,21 @@ mutable struct DTask uid::UInt future::ThunkFuture metadata::DTaskMetadata + # Result placeholder of a task this process never built a `Thunk` for (see + # `elide_task!`); `nothing` for every ordinary task. + stub::Any + # Rank/worker known to own this task's result at spawn time, `-1` when unknown + owner::Int thunk_ref::DRef - DTask(uid, future, metadata) = new(uid, future, metadata) + DTask(uid, future, metadata) = new(uid, future, metadata, nothing, -1) end const EagerThunk = DTask Base.isready(t::DTask) = isready(t.future) Base.istaskdone(t::DTask) = isready(t.future) -Base.istaskstarted(t::DTask) = isdefined(t, :thunk_ref) +Base.istaskstarted(t::DTask) = t.stub !== nothing || isdefined(t, :thunk_ref) function Base.wait(t::DTask) if !istaskstarted(t) throw(ConcurrencyViolationError("Cannot `wait` on an unlaunched `DTask`")) @@ -95,6 +100,18 @@ function Base.fetch(t::DTask; raw=false, move_value=!raw, unwrap=!raw, uniform=f if !istaskstarted(t) throw(ConcurrencyViolationError("Cannot `fetch` an unlaunched `DTask`")) end + if t.owner >= 0 + # The owner learns of a failure from its own task, every other process from + # a message, and a fetch must do the same on all of them: see + # `fetch_failed_uniform!` + value = try + fetch(t.future; move_value=false, unwrap=false, uniform) + catch + fetch_failed_uniform!(current_acceleration()) + rethrow() + end + return move_value ? move(OSProc(), value) : value + end return fetch(t.future; move_value, unwrap, uniform) end function waitany(tasks::Vector{DTask}) diff --git a/src/sch/util.jl b/src/sch/util.jl index 58804e56f..540d81c02 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -126,8 +126,25 @@ function store_result!(state, thunk, value; error::Bool=false) thunk.cache_ref = Some{Any}(value) end @atomic thunk.errored = error + error && task_failed!(thunk, value) return true end + +""" + task_failed!(thunk, value) + +Called once, by whoever recorded the failure of `thunk` (its own error or an +upstream's), while the scheduler lock is held. Accelerations whose other +processes cannot see this failure on their own override it for the tasks they +need to tell; it must not block. Does nothing by default. +""" +function task_failed!(thunk, value) + accel = thunk.options.acceleration + accel === nothing || task_failed!(accel, thunk, value) + return +end +task_failed!(::Dagger.Acceleration, thunk, value) = nothing + function clear_result!(state, thunk) @assert islocked(state.lock) thunk.cache_ref = nothing diff --git a/src/submission.jl b/src/submission.jl index 2f8102a4d..7674b6299 100644 --- a/src/submission.jl +++ b/src/submission.jl @@ -184,11 +184,17 @@ eager_submit_internal!(ctx, state, task, tid, payload::Tuple{<:AnyPayload}) = lock(state.thunk_dict) local thunk try - thunk = Dagger.payload(state.thunk_dict)[dep.id.id] + # N.B. A task elided on this process has no thunk and is already + # finished: it contributes no edge + thunk = get(Dagger.payload(state.thunk_dict), dep.id.id, nothing) finally unlock(state.thunk_dict) end - @inbounds syncdeps_vec[idx] = ThunkSyncdep(thunk) + @inbounds syncdeps_vec[idx] = thunk === nothing ? ThunkSyncdep() : ThunkSyncdep(thunk) + end + # Drop the placeholders left for elided tasks + if any(dep -> dep.id === nothing && dep.thunk === nothing, syncdeps_vec) + filter!(dep -> !(dep.id === nothing && dep.thunk === nothing), syncdeps_vec) end if !isempty(syncdeps_vec) || any(arg->istask(value(arg)), fargs) if options.syncdeps === nothing @@ -391,7 +397,10 @@ function eager_process_elem_submission_to_local!(arg::Argument) @assert !(T <: Thunk) "Cannot use `Thunk`s in `@spawn`/`spawn`" if T <: DTask task = value(arg)::DTask - if istaskstarted(task) + if task.stub !== nothing + # No thunk exists here: the placeholder result is the argument + arg.value = task.stub + elseif istaskstarted(task) #=FIXME:UNIQUE=# arg.value = Sch.ThunkID(Int(task.uid), task.thunk_ref) end @@ -401,7 +410,9 @@ function eager_process_elem_submission_to_local(arg::TypedArgument{T}) where T @assert !(T <: Thunk) "Cannot use `Thunk`s in `@spawn`/`spawn`" if T <: DTask task = value(arg)::DTask - if istaskstarted(task) + if task.stub !== nothing + return TypedArgument(arg.pos, task.stub) + elseif istaskstarted(task) #=FIXME:UNIQUE=# tid = Sch.ThunkID(Int(task.uid), task.thunk_ref) # Preserve the argument position by re-wrapping in a TypedArgument; @@ -538,10 +549,43 @@ end chunktype(t::DTask) = t.metadata.return_type +""" + ELIDE_FOREIGN_TASKS + +Opt-in switch (`Dagger.elide_foreign_tasks!`, or the environment variable +`JULIA_DAGGER_ELIDE_FOREIGN_TASKS=1` at startup) for [`elide_task!`](@ref). +""" +const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) # set from the environment in `__init__` +elide_foreign_tasks!(on::Bool=true) = (ELIDE_FOREIGN_TASKS[] = on) + +""" + elide_task!(accel::Acceleration, spec::DTaskSpec, task::DTask) -> Bool + +Give the acceleration the chance to complete `task` without building, scheduling +or running a `Thunk` for it, because this process takes no part in executing it +and nothing it does can depend on the outcome. When it returns `true`, `task` +must be complete: its future filled and `task.stub` set to a placeholder +result that downstream submissions can use in place of the task. The default +elides nothing. +""" +elide_task!(::Acceleration, spec, task) = false + function eager_launch!(pair::DTaskPair) spec = pair.spec task = pair.task + # Tasks this process only has to account for (never run or source data for) + # skip the thunk entirely + if ELIDE_FOREIGN_TASKS[] && !Dagger.in_task() + # The first real submission starts the eager scheduler, which takes a task + # id of its own. Elision must not change which process consumes which + # ids (they feed the uniform MPI tags), so start it here, at the same + # point in the id sequence, whether or not this task is elided. + Sch.EAGER_STATE[] === nothing && myid() == 1 && Sch.init_eager() + accel = spec.options.acceleration + accel !== nothing && elide_task!(accel, spec, task) && return + end + # Assign a name, if specified eager_assign_name!(spec, task) From f574158ff40b2eb9a55b4c52ee8bdbfbd46825e8 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 16 Oct 2026 21:54:25 +0200 Subject: [PATCH 07/59] MPI: owner elision with failure-only task status Implements elide_task! for MPIAcceleration (off by default, see the previous commit). A rank elides a task when * its scope is a single ExactScope(::MPIProcessor) of another rank, * it owns none of the arguments (an owner has to send its data); every argument is a plain value, an MPIRef chunk without a scope restriction, or an earlier task whose owner is known, * the return type is concrete and uniformity checks are off (they are collective), and * the task has no tag option (Datadeps tasks keep the old protocol). It builds no thunk: it takes the task id as before and stamps exactly the placeholder execute! stamps on a non-owner, ref id included (execute! first takes an id for the task's tag, so the result is the task's second id). Failure-only status. A task that may throw made the owner broadcast :ok/:error and every other rank wait for it, coupling every rank to every task. For these tasks (mpi_failure_only) the owner now reports only failures: Sch.task_failed! sends the error asynchronously on the task's tag, covering an error in the task, in moving its arguments and upstream failures alike; nobody waits for success. A rank that later needs the task's data (argument move, fetch) stops waiting when the failure arrives: such waits install the ref they wait on behalf of (POISON_REF) and mpi_deadlock_detect, which every polling wait goes through, throws the failure stored in the relay's (owner, tag) slot. fetch of a task whose owner fails keeps task ids uniform (fetch_failed_uniform!): a successful fetch takes a generic id on every rank, so the owner that throws first takes the same. Measured with benchmark/suites/tasks.jl on our cluster (AMD Opteron 6272), 4 ranks x 16 threads per node, median of 7, switch on vs off, same nodes (1/2/4 nodes = 4/8/16 ranks): tasks pinned to another rank, seen from rank 0, 256 tasks 46.5 / 44.5 / 66.9 ms -> 5.0 / 4.8 / 4.8 ms (~19 us per foreign task, 14x at 16 ranks) ... bodies that may throw 43.7 / 50.9 / 46.2 -> 5.0 / 4.9 / 4.9 ms round robin over all ranks, 256 tasks 44.6 / 58.9 / 47.8 ms -> 15.3 / 10.6 / 8.1 ms (5.9x at 16 ranks) ... bodies that may throw 38.5 / 37.5 / 39.7 -> 16.1 / 11.0 / 7.9 ms fan-in tree, 256 leaves 95.5 / 98.4 / 134.2 -> 39.9 / 29.1 / 20.5 ms (6.5x) all-to-all exchange step 15.4 / 36.3 / 124.9 -> 9.3 / 15.3 / 33.3 ms (3.7x) dependent hops 55.4 / 66.2 / 64.8 -> 49.6 / 54.0 / 51.5 ms unscoped (never elided) 11.0 / 12.8 / 15.9 -> 13.5 / 11.6 / 14.4 ms (noise) Per-rank time is now ~ (own tasks) x 170 us + (foreign tasks) x 20 us instead of (all tasks) x 170 us. --- ext/MPIExt.jl | 192 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 190 insertions(+), 2 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 36881e5c2..4b9f43c64 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1299,6 +1299,8 @@ end # rather than a wait. A real cycle still trips them, just once the work that # does not depend on it has drained. function mpi_deadlock_detect(timer::DeadlockTimer, rank, tag, kind, srcdest) + # A wait on a task's result ends in that task's error when its owner failed + POISON_REF[] === nothing || mpi_check_poison() timer.detect || return timer progress = MPI_PROGRESS[] if progress != timer.last_progress @@ -1680,6 +1682,45 @@ function bcast_meta_yield(comm::MPI.Comm, root::Integer, tag, value=nothing) end end +# --- Failure-only task status --------------------------------------------------- +# +# `execute!` of a task that may throw makes the owner broadcast `:ok`/`:error` and +# every other rank wait for it, so every rank is coupled to every task. For the +# tasks `elide_task!` handles (see "Owner elision") the status is instead sent +# *only on failure*: ranks never wait for success, and a rank that later needs the +# task's data -- an argument move or a fetch -- stops waiting when the failure +# arrives. The failure is the `(:error, ex)` payload of the owner's broadcast on +# the task's tag, which the relay keeps in the task's (root, tag) slot; the data +# the task produced carries that tag in its ref id (`MPIRefID.tid`), so a wait on +# a `MPIRef` can look the failure up. Waits install the ref they are on behalf of +# in `POISON_REF`, and every polling wait already goes through +# `mpi_deadlock_detect`, which checks it. + +const POISON_REF = ScopedValue{Union{MPIRef,Nothing}}(nothing) + +function mpi_check_poison() + ref = POISON_REF[]::MPIRef + ref.id.generic && return + state = lock(BCAST_STATES) do states + get(states, ref.comm, nothing) + end + state === nothing && return + err = nothing + @lock state.cond begin + slot = get(state.slots, (ref.rank, UInt32(ref.id.tid)), nothing) + if slot !== nothing && !isempty(slot.values) + msg = slot.values[1] + msg isa Tuple && first(msg) === :error && (err = msg[2]) + end + end + err === nothing || throw(err) + return +end + +# Run `f` (a wait on data of `ref`'s task) so that it ends in that task's error +mpi_poisonable(f, ref::MPIRef) = + Dagger.ELIDE_FOREIGN_TASKS[] ? with(f, POISON_REF => ref) : f() + WeakChunk(c::Chunk{T,H}) where {T,H<:MPIRef} = WeakChunk(c.handle.rank, c.handle.id.id, WeakRef(c), T) function MemPool.poolget(ref::MPIRef; uniform::Bool=uniform_execution()) @@ -1689,7 +1730,9 @@ function MemPool.poolget(ref::MPIRef; uniform::Bool=uniform_execution()) if ref.rank == MPI.Comm_rank(ref.comm) return bcast_yield(ref.comm, ref.rank, tag, poolget(ref.innerRef)) else - return bcast_yield(ref.comm, ref.rank, tag) + return mpi_poisonable(ref) do + bcast_yield(ref.comm, ref.rank, tag) + end end else return poolget(ref.innerRef) @@ -2326,7 +2369,9 @@ function move(src::MPIProcessor, dst::MPIProcessor, x::Chunk) send_yield(value, dst.comm, dst.rank, tag) return nothing elseif local_rank == dst.rank - value = recv_yield(dst.comm, x.handle.rank, tag) + value = mpi_poisonable(x.handle) do + recv_yield(dst.comm, x.handle.rank, tag) + end return move(from, dst, value) end return nothing @@ -2595,6 +2640,20 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) # Concrete but may throw: broadcast only status (no T/space on the wire). # Type inference still skips metadata; poison keeps SPMD aligned on error. if !plan.need_type_bcast + if mpi_failure_only(Dagger.in_task() ? Dagger.get_tls().task_spec.options : nothing) + # Status only on failure (see "Failure-only task status"): nobody waits + # for success, so a rank that is not the owner stamps its placeholder at once + if islocal + # N.B. A failure reaches the other ranks from `task_failed!`, which + # covers every way this task can fail, not only an error in `f` + result = execute!(proc.innerProc, f, raw_args...; kwargs...) + space = mpi_result_space(result, proc) + return tochunk(result, proc, space; type=plan.inferred) + else + space = memory_space(nothing, proc)::MPIMemorySpace + return tochunk(nothing, proc, space; type=plan.inferred) + end + end if islocal result = try mpi_execute_inner(proc, f, raw_args...; kwargs...) @@ -2786,4 +2845,133 @@ accel_matches_proc(accel::MPIAcceleration, proc::MPIClusterProc) = true accel_matches_proc(accel::MPIAcceleration, proc::MPIProcessor) = true accel_matches_proc(accel::MPIAcceleration, proc) = false +# --- Owner elision -------------------------------------------------------------- +# +# Under SPMD every rank builds, places and "executes" every task, whether or not +# it takes part: a rank that neither runs a task nor owns data the task reads pays +# nearly the full planning cost (measured: 168 us against the owner's 188 us) only +# to stamp an empty result. A task qualifies for elision on a rank when +# +# * its scope is a single `ExactScope(::MPIProcessor)`, so its rank is known at +# spawn time, on every rank, without consulting the scheduler; +# * that rank is not this one, and this rank owns none of its arguments (an owner +# has to send its data, so it takes part in the move); +# * its return type is concrete (a non-concrete one needs the type broadcast to every +# rank), and it reports failures only: `execute!` then does not make the other +# ranks wait for its status (see "Failure-only task status"); +# * every argument is a plain value, an `MPIRef` chunk with no scope restriction, +# or an earlier task whose owner is known and is not this rank. +# +# Such a task skips thunk creation, scheduling, dispatch and the placeholder +# execution; the rank only takes the task id (done by `eager_spawn`, so ids and +# tags stay uniform) and builds the same placeholder result `execute!` would have. +# Uniformity checks are collective over all ranks, so they disable elision. + +# The single MPI processor `opts` restricts a task to, or `nothing`. `scope=` sets +# both `scope` and `compute_scope`; accept either, or both when equal. +function mpi_scope_processor(opts::Options) + scope = if opts.compute_scope === nothing + opts.scope + elseif opts.scope === nothing || opts.scope == opts.compute_scope + opts.compute_scope + else + nothing + end + scope isa Dagger.ExactScope || return nothing + proc = scope.processor + return proc isa MPIProcessor ? proc : nothing +end + +# At spawn time the scheduler has not yet filled in the execution or result scope +function mpi_task_processor(opts::Options) + (opts.exec_scope === nothing && opts.result_scope === nothing) || return nothing + return mpi_scope_processor(opts) +end + +# Whether the owner of this task reports only failures (see "Failure-only task +# status"). Decided from the task's own options alone, so every rank agrees; it +# holds for every task `elide_task!` may elide. Uniformity checks are collective +# and so rule it out, as does an explicit tag (Datadeps tasks, whose copies and +# waits do not know about failures that arrive this way). +mpi_failure_only(::Nothing) = false +mpi_failure_only(opts::Options) = + Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing && + mpi_scope_processor(opts) !== nothing + +# Whether `local_rank` takes part in moving `v` to the task's rank, or cannot tell +function mpi_arg_participates(v, local_rank::Int) + if v isa Dagger.DTask + v.stub !== nothing && return mpi_arg_participates(v.stub, local_rank) + return v.owner < 0 || v.owner == local_rank + elseif v isa Chunk + v.handle isa MPIRef || return true + v.scope isa Dagger.AnyScope || return true + return v.handle.rank == local_rank + elseif v isa Dagger.WeakChunk + return true + end + return false +end + +# The owner tells everyone when a failure-only task fails, whatever the cause: an +# error in the task, in moving its arguments, or an upstream failure. This runs +# under the scheduler lock, so the send is handed to another task. +function Dagger.Sch.task_failed!(::MPIAcceleration, thunk, value) + opts = thunk.options + mpi_failure_only(opts) || return + proc = mpi_scope_processor(opts) + MPI.Comm_rank(proc.comm) == proc.rank || return + ex = mpi_wire_exception(value isa Dagger.DTaskFailedException ? value.ex : value) + tag = UInt32(thunk.id) + Dagger.Sch.errormonitor_tracked("mpi_task_failed", Threads.@spawn begin + bcast_meta_yield(proc.comm, proc.rank, tag, (:error, ex)) + end) + return +end + +# A fetch that throws on the owner still has to take the generic id that the +# broadcast of a successful fetch takes on every other rank (see `poolget`) +function Dagger.fetch_failed_uniform!(::MPIAcceleration) + Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && take_ref_id!() + return +end + +function Dagger.elide_task!(accel::MPIAcceleration, spec, task) + CHECK_UNIFORMITY[] && return false + opts = spec.options + proc = mpi_task_processor(opts) + proc === nothing && return false + # Later submissions use this to decide about their own arguments, and `fetch` + # to stay uniform when the task fails. Only failure-only tasks have an owner. + mpi_failure_only(opts) || return false + task.owner = proc.rank + local_rank = MPI.Comm_rank(proc.comm) + proc.rank == local_rank && return false + (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false + opts.restore === nothing || return false + T = task.metadata.return_type + (isconcretetype(T) && T !== Union{}) || return false + fargs = spec.fargs + f = Dagger.value(fargs[1]) + (f isa Function || f isa Type) || return false + for i in 2:length(fargs) + arg = fargs[i] + Dagger.ispositional(arg) || return false + mpi_arg_participates(Dagger.value(arg), local_rank) && return false + end + # The placeholder `execute!` stamps on a non-owner, with the id it would get + space = memory_space(nothing, proc)::MPIMemorySpace + # N.B. `execute!` first takes a ref id for the task's tag when the task has no + # tag option (`to_tag()`), so the result chunk is the second id of its task. + # The owner builds the real chunk with that id, and every rank must agree on it. + stub = with(DATADEPS_THUNK_ID => Int64(task.uid)) do + opts.tag === nothing && take_ref_id!() + tochunk(nothing, proc, space; type=T) + end + mpi_cleanup_tid(task.uid) + task.stub = stub + put!(task.future, stub) + return true +end + end # module MPIExt From 1529bdf4c7f576a453dd0bc81cb5076aeb2bbb61 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 16 Oct 2026 21:54:25 +0200 Subject: [PATCH 08/59] test: owner elision (test/mpi/elide.jl) 45 assertions per rank at 3 ranks x 4 threads: results, placeholders and uniform ids/chunk identity on every rank; chains and a consumer on a third rank; a rank that owns an argument takes part; tagged and unscoped tasks are not elided; a failing task gives every rank an error without hanging, also for tasks that consume its result, and later SPMD work and ids still agree. Building it found three real divergences, all fixed in the commits above: a rank that elided its first task did not start the eager scheduler and took one id fewer; the placeholder and the real chunk had different ref ids; after a failed fetch the generic ids differed between ranks and later collectives hung. --- test/mpi/cpu.jl | 1 + test/mpi/elide.jl | 93 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 test/mpi/elide.jl diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 519e4bc44..286e7575c 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -149,6 +149,7 @@ include("spawn.jl") include("noaliasing_args.jl") include("free_threads.jl") include("relay.jl") +include("elide.jl") @testset "Datadeps" begin diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl new file mode 100644 index 000000000..d1ab31f77 --- /dev/null +++ b/test/mpi/elide.jl @@ -0,0 +1,93 @@ +# Owner elision (`Dagger.elide_foreign_tasks!`): a rank that neither runs a task nor +# owns its data builds no thunk for it. The program must still be indistinguishable: +# same task ids on every rank, same results, same behaviour of later SPMD work. +elide_inc(x::Int) = x + 1 # concrete, cannot throw: elidable +elide_add(a::Int, b::Int) = a + b +elide_throws(x::Int) = x > 0 ? error("elide_throws") : x # may throw, concrete Int +elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) + +@testset "Owner elision" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pinned(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + # Uniformity checks are collective over all ranks and so disable elision + Dagger.check_uniformity!(false) + Dagger.elide_foreign_tasks!(true) + try + @testset "pinned tasks: results, stubs, uniform ids" begin + for target in 0:nranks-1 + t = Dagger.@spawn scope=pinned(target) elide_inc(41) + wait(t) + @test (t.stub !== nothing) == (rank != target) + @test t.owner == target + @test fetch(t) == 42 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + # the placeholder and the real chunk agree on type and space + chunk = fetch(t; raw=true) + @test chunk.chunktype === Int + @test allequal(MPI.Allgather(hash((chunk.handle.rank, chunk.handle.id, chunk.chunktype)), comm)) + end + end + + @testset "dependent chains" begin + # a chain on one rank, then a consumer on another + a = Dagger.@spawn scope=pinned(0) elide_inc(1) + b = Dagger.@spawn scope=pinned(0) elide_inc(a) + c = Dagger.@spawn scope=pinned(nranks-1) elide_add(b, a) + @test fetch(c) == 3 + 2 + @test (a.stub !== nothing) == (rank != 0) + @test (c.stub !== nothing) == (rank != nranks - 1 && rank != 0) # rank 0 owns a and b: it sends them + # many tasks across all ranks + tasks = [Dagger.@spawn(scope=pinned(i % nranks), elide_inc(i)) for i in 1:4nranks] + @test fetch.(tasks) == [i + 1 for i in 1:4nranks] + @test count(t -> t.stub !== nothing, tasks) == 4nranks - 4 + end + + @testset "tasks that must not be elided" begin + # a rank that owns an argument takes part + x = Dagger.tochunk(10, proc_for_rank(0), space_for_rank(0)) + t = Dagger.@spawn scope=pinned(nranks-1) elide_inc(x) + @test (t.stub !== nothing) == (rank != 0 && rank != nranks - 1) + @test fetch(t) == 11 + # unknown owner: a task without a pinned scope is placed by the scheduler + u = Dagger.@spawn elide_inc(1) + @test u.stub === nothing + w = Dagger.@spawn scope=pinned(nranks-1) elide_inc(u) + @test w.stub === nothing + @test fetch(w) == 3 + # a tagged task keeps the status broadcast + v = Dagger.@spawn scope=pinned(0) tag=UInt32(12345) elide_inc(1) + @test v.stub === nothing + @test fetch(v) == 2 + end + + @testset "tasks that may throw" begin + # success: elided like any other, nobody waits for a status + ok = Dagger.@spawn scope=pinned(0) elide_throws(0) + @test (ok.stub !== nothing) == (rank != 0) + @test fetch(ok) == 0 + # failure: every rank sees an error, none hangs + bad = Dagger.@spawn scope=pinned(0) elide_throws(1) + @test (bad.stub !== nothing) == (rank != 0) + @test_throws Exception fetch(bad) + # ... and so does a task that consumes the failed task's result, wherever it runs + for target in 0:nranks-1 + dep = Dagger.@spawn scope=pinned(target) elide_inc(bad) + @test_throws Exception fetch(dep) + end + # a failure far from the data: the consumer's own rank learns of it on the move + far = Dagger.@spawn scope=pinned(nranks-1) elide_add(bad, 1) + @test_throws Exception fetch(far) + end + + @testset "later SPMD work is unaffected" begin + y = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) fill(2.0, 8) + s = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) sum(y) + @test fetch(s) == 16.0 + @test allequal(MPI.Allgather(Int(s.uid), comm)) + end + finally + Dagger.elide_foreign_tasks!(false) + Dagger.check_uniformity!(true) + end + MPI.Barrier(comm) +end From f7727ae3161ddd10abfa3e2337f69feaa08ca805 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 16 Oct 2026 23:18:44 +0200 Subject: [PATCH 09/59] MPI: elide tasks scoped to a whole rank, not only to one thread The first version elided a task only when its scope was a single ExactScope(::MPIProcessor), which makes the application pin every task to a thread. A spectator needs only the owner's rank, not its thread, so a scope that names a whole rank (Dagger.scope(mpi_rank=r), a UnionScope of the ExactScopes of that rank's processors) is enough: the scheduler keeps choosing the thread, and the rank that elides the task stamps its placeholder with a fixed representative processor of that rank (the chunk's processor is not part of its identity). * mpi_union_scope_processor works out which rank a union scope names, once per scope object (scopes are shared by every task spawned under a with_options block); several ranks, other scope kinds, or mixed contents elide nothing. * mpi_scope_processor is also what decides failure-only status at execution time, so a rank-scoped task reports only failures like a thread-scoped one. test/mpi/elide.jl gains 27 assertions (72 per rank at 3 ranks x 4 threads): a rank-level scope elides on every other rank with uniform ids and chunk identity, sixteen tasks under one with_options scope are spread over several threads of the owner, a chain across two rank scopes, a failing task and its consumer, and a scope that allows several ranks elides nothing. --- ext/MPIExt.jl | 47 +++++++++++++++++++++++++++++++++++++++++------ test/mpi/elide.jl | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 6 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 4b9f43c64..d689e43ca 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2867,19 +2867,54 @@ accel_matches_proc(accel::MPIAcceleration, proc) = false # tags stay uniform) and builds the same placeholder result `execute!` would have. # Uniformity checks are collective over all ranks, so they disable elision. -# The single MPI processor `opts` restricts a task to, or `nothing`. `scope=` sets -# both `scope` and `compute_scope`; accept either, or both when equal. +# A processor of the one rank `opts` restricts a task to, or `nothing` when the scope +# allows several ranks (or is not a scope of MPI processors). Only its rank and +# communicator are meaningful: a scope that names a whole rank, as +# `Dagger.scope(mpi_rank=r)` does, leaves the choice of thread to the scheduler, and a +# rank that elides the task never learns which thread that was. `scope=` sets both +# `scope` and `compute_scope`; accept either, or both when equal. function mpi_scope_processor(opts::Options) scope = if opts.compute_scope === nothing opts.scope - elseif opts.scope === nothing || opts.scope == opts.compute_scope + elseif opts.scope === nothing || opts.scope === opts.compute_scope || opts.scope == opts.compute_scope opts.compute_scope else nothing end - scope isa Dagger.ExactScope || return nothing - proc = scope.processor - return proc isa MPIProcessor ? proc : nothing + if scope isa Dagger.ExactScope + proc = scope.processor + return proc isa MPIProcessor ? proc : nothing + elseif scope isa Dagger.UnionScope + return mpi_union_scope_processor(scope) + end + return nothing +end + +# Scopes are reused (a `with_options(scope=...)` block hands the same object to every +# task spawned under it), so what a union scope names is worked out once per scope. +const MPI_UNION_SCOPE_CACHE = LockedObject(Dict{UInt,Tuple{Any,Any}}()) + +function mpi_union_scope_processor(scope::Dagger.UnionScope) + key = objectid(scope) + hit = lock(MPI_UNION_SCOPE_CACHE) do cache + get(cache, key, nothing) + end + # `===`: the entry keeps the scope alive, so a hit cannot be a recycled objectid + hit !== nothing && hit[1] === scope && return hit[2] + proc = nothing + scopes = scope.scopes + if !isempty(scopes) && all(sc -> sc isa Dagger.ExactScope && sc.processor isa MPIProcessor, scopes) + first_proc = first(scopes).processor + if all(sc -> sc.processor.rank == first_proc.rank && sc.processor.comm == first_proc.comm, scopes) + # The same processor on every rank, whatever order the scopes came in + proc = argmin(short_name, [sc.processor for sc in scopes]) + end + end + lock(MPI_UNION_SCOPE_CACHE) do cache + length(cache) >= 256 && empty!(cache) + cache[key] = (scope, proc) + end + return proc end # At spawn time the scheduler has not yet filled in the execution or result scope diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index d1ab31f77..55a11309a 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -5,6 +5,7 @@ elide_inc(x::Int) = x + 1 # concrete, cannot throw: elidable elide_add(a::Int, b::Int) = a + b elide_throws(x::Int) = x > 0 ? error("elide_throws") : x # may throw, concrete Int elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) +elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw @testset "Owner elision" begin cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) @@ -28,6 +29,43 @@ elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) end end + @testset "rank-level scope: the scheduler picks the thread" begin + # `scope(mpi_rank=r)` names a rank, not a thread; the rank is all a spectator needs + for target in 0:nranks-1 + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_inc(1) + wait(t) + @test (t.stub !== nothing) == (rank != target) + @test t.owner == target + @test fetch(t) == 2 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + chunk = fetch(t; raw=true) + @test chunk.handle.rank == target + @test allequal(MPI.Allgather(hash((chunk.handle.rank, chunk.handle.id, chunk.chunktype)), comm)) + end + # one scope object shared by many tasks (a `with_options` block): the owner spreads them over its threads + target = nranks - 1 + tasks = Dagger.with_options(; scope=Dagger.scope(mpi_rank=target)) do + [Dagger.@spawn(elide_where()) for _ in 1:16] + end + where = fetch.(tasks) + @test all(w -> w[1] == target, where) + @test length(unique(last.(where))) >= min(2, Threads.nthreads()) + @test count(t -> t.stub !== nothing, tasks) == (rank == target ? 0 : 16) + # a chain across two rank-level scopes, and a failure + a = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) elide_inc(1) + b = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_add(a, 10) + @test fetch(b) == 12 + bad = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) elide_throws(1) + @test (bad.stub !== nothing) == (rank != 0) + @test_throws Exception fetch(bad) + dep = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_inc(bad) + @test_throws Exception fetch(dep) + # several ranks allowed: the rank is the scheduler's choice, nothing is elided + multi = Dagger.@spawn scope=Dagger.scope(mpi_ranks=:) elide_inc(1) + @test multi.stub === nothing + @test fetch(multi) == 2 + end + @testset "dependent chains" begin # a chain on one rank, then a consumer on another a = Dagger.@spawn scope=pinned(0) elide_inc(1) From eb28578e007bb7720a7c415f374dfb5711c4614a Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 17 Oct 2026 08:13:56 +0200 Subject: [PATCH 10/59] MPI: place tasks without a scope at spawn time so that they can be elided Tasks without a scope were never elided, because the scheduler places them and so no rank knows the owner when the task is created. The placement rule is deterministic and identical on every rank (canonical candidate order, the rank that owns the first MPI argument first, rotation by task id), so elide_task! now applies it at spawn time and pins the task to the result with an ExactScope. The scheduler is handed the decision instead of making it, so it cannot disagree with the ranks that elide the task (which would leave the task running nowhere). Left to the scheduler, and nothing elided, whenever the owner cannot be decided at spawn time: an argument whose owner is unknown (a task not placed this way, a weak chunk, a chunk with a scope restriction), a result or execution scope, a processor list, a retry/restore hook, a tag, syncdeps, or a processor that would reject the function or an argument. All of these conditions are uniform across ranks. Measured with benchmark/suites/tasks.jl on our cluster (AMD Opteron 6272), 4 ranks x 16 threads per node, median of 7, switch on vs the previous commit's build with the switch off (same nodes; 1/2/4 nodes = 4/8/16 ranks): unscoped, 64 tasks 7.5 / 10.9 / 12.1 ms -> 5.1 / 1.8 / 2.0 ms unscoped, 256 tasks, may throw 33.1 / 33.2 / 34.8 ms -> 20.1 / 12.5 / 11.1 ms all-to-all exchange step 13.7 / 32.4 / 99.1 ms -> 9.1 / 14.7 / 37.2 ms fan-in tree, 256 leaves 90.4 / 92.8 / 91.6 ms -> 42.9 / 29.6 / 21.8 ms tasks pinned to another rank 45.3 / 41.1 / 40.8 ms -> 5.2 / 5.1 / 5.2 ms test/mpi/elide.jl: 84 assertions per rank at 3 ranks x 4 threads, including that the scheduler runs every such task exactly on the rank the spawn-time rule named (round robin reaches every rank, data affinity, chains, a failing task). --- ext/MPIExt.jl | 87 +++++++++++++++++++++++++++++++++++++++++++++++ test/mpi/elide.jl | 42 +++++++++++++++++++---- 2 files changed, 123 insertions(+), 6 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index d689e43ca..20b76381f 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2971,9 +2971,96 @@ function Dagger.fetch_failed_uniform!(::MPIAcceleration) return end +# --- Placement at spawn for tasks without a scope ---------------------------------- +# +# A task without a scope is placed by the scheduler, so no rank knows the owner when +# the task is created. The placement rule is deterministic and identical on every +# rank, though: the cached canonical order of the candidate processors, the rank that +# owns the task's first MPI argument moved to the front, then a rotation by the task +# id. `elide_task!` therefore applies that rule at spawn time and pins the task to the +# result with an ExactScope: the scheduler is handed a decision instead of making it, +# so it cannot disagree with the ranks that elide the task. Whatever cannot be +# decided at spawn time (an argument whose owner is unknown, a result scope, a +# processor list, a processor that rejects the function or an argument) is left to +# the scheduler and nothing is elided. + +struct MPIPlacementRequest + id::Int + pref::Union{Int,Nothing} +end +Dagger.task_processor_preference(::MPIAcceleration, req::MPIPlacementRequest, state) = req.pref + +# Rank that owns `v`, `nothing` for a plain value (the scheduler ignores those when it +# looks for the owner), `-1` when it cannot be told at spawn time +function mpi_arg_owner(v) + if v isa Dagger.DTask + v.stub !== nothing && return mpi_arg_owner(v.stub) + return v.owner + elseif v isa Chunk + v.handle isa MPIRef || return -1 + v.scope isa Dagger.AnyScope || return -1 + return v.handle.rank + elseif v isa Dagger.WeakChunk + return -1 + end + return nothing +end + +function mpi_preplace!(accel::MPIAcceleration, spec, task) + opts = spec.options + opts.exec_scope === nothing && opts.result_scope === nothing && opts.proclist === nothing && + (opts.single === nothing || opts.single == 0) && opts.restore === nothing && + opts.tag === nothing || return false + (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false + scope = if opts.compute_scope === nothing + opts.scope + elseif opts.scope === nothing || opts.scope === opts.compute_scope || opts.scope == opts.compute_scope + opts.compute_scope + else + return false + end + scope === nothing && (scope = Dagger.DefaultScope()) + fargs = spec.fargs + f = Dagger.value(fargs[1]) + (f isa Function || f isa Type) || return false + pref = nothing + for i in 2:length(fargs) + arg = fargs[i] + Dagger.ispositional(arg) || return false + owner = mpi_arg_owner(Dagger.value(arg)) + owner === nothing && continue + owner < 0 && return false + pref === nothing && (pref = owner) + end + state = Dagger.Sch.EAGER_STATE[] + state === nothing && return false + ctx = Dagger.Sch.eager_context() + procs = filter(p -> haskey(state.worker_chans, root_worker_id(p)), Dagger.Sch.procs_to_use(ctx, state.sch_options)) + isempty(procs) && return false + # The scheduler's own rule (`schedule_one!`): the compatible processors, re-ordered under uniform + # execution by the canonical key with the owner of the first MPI argument in front, then rotated by the id + candidates = Processor[p for p in Dagger.Sch.compatible_processors_cached(accel, scope, procs)] + isempty(candidates) && return false + Dagger.select_processors_uniform!(candidates, accel, MPIPlacementRequest(Int(task.uid), pref), nothing) + proc = first(candidates) + proc isa MPIProcessor || return false + # What `can_use_proc` would check of the processor the scheduler picks first + Dagger.proc_in_scope(proc, scope) || return false + Dagger.iscompatible_func(proc, opts, typeof(f)) || return false + for i in 2:length(fargs) + Dagger.iscompatible_arg(proc, opts, chunktype(Dagger.value(fargs[i]))) || return false + end + opts.compute_scope = Dagger.ExactScope(proc) + return true +end + function Dagger.elide_task!(accel::MPIAcceleration, spec, task) CHECK_UNIFORMITY[] && return false opts = spec.options + # Tasks without a scope are placed here, so that every rank knows the owner + if mpi_task_processor(opts) === nothing && opts.compute_scope === nothing && opts.scope === nothing + mpi_preplace!(accel, spec, task) + end proc = mpi_task_processor(opts) proc === nothing && return false # Later submissions use this to decide about their own arguments, and `fetch` diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 55a11309a..a7ba97be3 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -66,6 +66,42 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete @test fetch(multi) == 2 end + @testset "tasks without a scope: placed at spawn" begin + # The owner follows the deterministic placement rule and is decided when the + # task is created, so every other rank can elide it. The scheduler must + # then run it exactly where the rule said. + n = nranks * Threads.nthreads() + tasks = [Dagger.@spawn(elide_inc(i)) for i in 1:2n] + @test fetch.(tasks) == [i + 1 for i in 1:2n] + @test all(t -> t.owner >= 0, tasks) + @test all(t -> fetch(t; raw=true).handle.rank == t.owner, tasks) + @test all(t -> allequal(MPI.Allgather(Int(t.uid), comm)), tasks[1:4]) + @test count(t -> t.stub !== nothing, tasks) == count(t -> t.owner != rank, tasks) + @test all(r -> any(t -> t.owner == r, tasks), 0:nranks-1) # round robin reaches every rank + # data affinity: a task that reads an MPI chunk runs on the chunk's rank + x = Dagger.tochunk(10, proc_for_rank(0), space_for_rank(0)) + y = Dagger.@spawn elide_inc(x) + @test y.owner == 0 + @test fetch(y) == 11 + @test (y.stub !== nothing) == (rank != 0) + # a chain without scopes stays on one rank, and a scoped producer is followed + u1 = Dagger.@spawn scope=pinned(nranks-1) elide_inc(1) + u2 = Dagger.@spawn elide_inc(u1) + u3 = Dagger.@spawn elide_add(u2, u1) + @test u2.owner == nranks - 1 && u3.owner == nranks - 1 + @test fetch(u3) == 3 + 2 + # an argument whose owner is unknown at spawn time: left to the scheduler + lazy = Dagger.@spawn scope=Dagger.scope(mpi_ranks=:) elide_inc(1) + z = Dagger.@spawn elide_inc(lazy) + @test lazy.stub === nothing && z.stub === nothing + @test fetch(z) == 3 + # a failing task without a scope: every rank sees an error and none hangs + bad = Dagger.@spawn elide_throws(1) + @test_throws Exception fetch(bad) + dep = Dagger.@spawn elide_inc(bad) + @test_throws Exception fetch(dep) + end + @testset "dependent chains" begin # a chain on one rank, then a consumer on another a = Dagger.@spawn scope=pinned(0) elide_inc(1) @@ -86,12 +122,6 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete t = Dagger.@spawn scope=pinned(nranks-1) elide_inc(x) @test (t.stub !== nothing) == (rank != 0 && rank != nranks - 1) @test fetch(t) == 11 - # unknown owner: a task without a pinned scope is placed by the scheduler - u = Dagger.@spawn elide_inc(1) - @test u.stub === nothing - w = Dagger.@spawn scope=pinned(nranks-1) elide_inc(u) - @test w.stub === nothing - @test fetch(w) == 3 # a tagged task keeps the status broadcast v = Dagger.@spawn scope=pinned(0) tag=UInt32(12345) elide_inc(1) @test v.stub === nothing From 68e413e2a69bebdb7a3935faf7f1f349fbda90f3 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 18 Oct 2026 11:05:45 +0200 Subject: [PATCH 11/59] MPI: elide a task whose chunk arguments carry a scope restriction that fits its own scope A rank skipped elision for any task with a chunk argument whose scope was not AnyScope, and a DArray block has one: every task that reads a block was planned in full by every rank (measured in one of our applications: 181 us on a rank that neither runs the task nor owns the block, against 28 us for a chunk without a restriction). A chunk's scope only matters through constrain(task scope, chunk scope) in the scheduler, which fails the task when the two cannot be satisfied together. Compute that chain on the rank that elides (the same one the scheduler computes) and elide when it is valid; an invalid one keeps the ordinary protocol, which reports the failure as before. Test: test/mpi/elide.jl, 'chunk arguments with a scope restriction' (a chunk of the target rank with a rank scope, also with a pinned task; a contradicting scope is not elided and fails). It fails on the old rule and passes on the new one (3 ranks x 2 threads). --- ext/MPIExt.jl | 17 +++++++++++++++-- test/mpi/elide.jl | 30 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 20b76381f..66465e200 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2939,8 +2939,9 @@ function mpi_arg_participates(v, local_rank::Int) v.stub !== nothing && return mpi_arg_participates(v.stub, local_rank) return v.owner < 0 || v.owner == local_rank elseif v isa Chunk + # N.B. A scope restriction on the chunk (a `DArray` block has one) only matters through + # `constrain(task scope, chunk scope)`, which `elide_task!` checks for the task as a whole v.handle isa MPIRef || return true - v.scope isa Dagger.AnyScope || return true return v.handle.rank == local_rank elseif v isa Dagger.WeakChunk return true @@ -3076,10 +3077,22 @@ function Dagger.elide_task!(accel::MPIAcceleration, spec, task) fargs = spec.fargs f = Dagger.value(fargs[1]) (f isa Function || f isa Type) || return false + # The scope the scheduler would compute for the task: the owner fails the task when it is invalid + # (task scope, result scope and every argument chunk's scope must agree), so a scope that can be + # satisfied is all a rank that elides the task needs to know. An invalid one keeps the ordinary + # protocol, which reports the failure as before. + scope = Dagger.constrain(@something(opts.compute_scope, opts.scope, Dagger.DefaultScope()), + @something(opts.result_scope, Dagger.AnyScope())) + scope isa Dagger.InvalidScope && return false for i in 2:length(fargs) arg = fargs[i] Dagger.ispositional(arg) || return false - mpi_arg_participates(Dagger.value(arg), local_rank) && return false + val = Dagger.value(arg) + mpi_arg_participates(val, local_rank) && return false + if val isa Chunk + scope = Dagger.constrain(scope, val.scope) + scope isa Dagger.InvalidScope && return false + end end # The placeholder `execute!` stamps on a non-owner, with the id it would get space = memory_space(nothing, proc)::MPIMemorySpace diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index a7ba97be3..1309ee7a9 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -4,6 +4,7 @@ elide_inc(x::Int) = x + 1 # concrete, cannot throw: elidable elide_add(a::Int, b::Int) = a + b elide_throws(x::Int) = x > 0 ? error("elide_throws") : x # may throw, concrete Int +elide_len(x::Vector{Int}) = length(x) # concrete, cannot throw elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw @@ -102,6 +103,35 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete @test_throws Exception fetch(dep) end + @testset "chunk arguments with a scope restriction (as a DArray block has)" begin + # A chunk owned by `target` whose scope names that rank: a rank that neither runs the task nor + # owns the chunk elides the task. The restriction only matters if it contradicts the task's scope. + # N.B. `tochunk(x, proc, scope)` would place the chunk on rank 0 (the owner of plain values), so the memory + # space is given as well. + target = nranks - 1 + data = fill(5, 4) + restricted = Dagger.tochunk(data, proc_for_rank(target), space_for_rank(target), Dagger.scope(mpi_rank=target)) + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_len(restricted) + wait(t) + @test (t.stub !== nothing) == (rank != target) + @test fetch(t) == 4 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + # ... and when the chunk is also an argument of a task pinned to one processor of that rank + t2 = Dagger.@spawn scope=pinned(target) elide_len(restricted) + wait(t2) + @test (t2.stub !== nothing) == (rank != target) + @test fetch(t2) == 4 + if nranks > 1 + # A scope that contradicts the task's is not elided: the scheduler of the owner fails the task + other = (target + 1) % nranks + clash = Dagger.tochunk(data, proc_for_rank(other), space_for_rank(other), Dagger.scope(mpi_rank=other)) + t3 = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_len(clash) + @test t3.stub === nothing + @test_throws Exception fetch(t3) + @test allequal(MPI.Allgather(Int(t3.uid), comm)) + end + end + @testset "dependent chains" begin # a chain on one rank, then a consumer on another a = Dagger.@spawn scope=pinned(0) elide_inc(1) From dcdd50f010edcd01627cebfde22510e11c4bad3a Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 18 Oct 2026 11:18:18 +0200 Subject: [PATCH 12/59] MPI: record where the blocks of an array live, so a task that reads one is elided on the other ranks Under MPI the tasks that make the blocks of a DArray run inside a Datadeps region (they carry a tag, are not elidable and have no owner), so every task reading a block counted its argument as of unknown owner and was planned in full by every rank: 181 us per task on a rank that neither runs it nor owns the block, against 28 us for a per_rank chunk, in one of our applications (it had to stop using DArray). The placement itself is the same grid on every rank: each block's compute scope is one processor. Add DTask.placed, set it from the placement code through a new hook (note_chunk_placement!, called by emit_chunk_tasks! and the staging path of darray.jl, no-op by default), and let the MPI elision logic read it in mpi_arg_participates / mpi_arg_owner. DTask.placed is separate from DTask.owner on purpose: owner also switches fetch to the failure-only path, which is wrong for Datadeps tasks. Also let a task without a scope use a scope-restricted chunk's rank as its placement preference, after checking that the chosen processor is inside every chunk argument's scope. Test: test/mpi/elide.jl 'DArray blocks ...' (recorded rank equals the holder, consumers elided on all other ranks, a task on a third rank, uniform ids; 3 ranks x 2 threads). --- ext/MPIExt.jl | 21 ++++++++++++++++++--- src/acceleration.jl | 10 ++++++++++ src/array/darray.jl | 4 +++- src/dtask.jl | 6 +++++- src/procgrid.jl | 1 + test/mpi/elide.jl | 31 +++++++++++++++++++++++++++++++ 6 files changed, 68 insertions(+), 5 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 66465e200..5dc65d361 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2840,6 +2840,17 @@ function post_stage_array_chunks!(accel::MPIAcceleration, tasks, eltype::Type{T} return tasks end +# The block grid of an array is the same on every rank, so a block placed on one processor has a +# known rank at spawn time. The tasks that make the blocks run inside a Datadeps region (they +# cannot be elided and are not failure-only), but the tasks that read a block can: they only +# need to know who owns it (`mpi_arg_participates`). +function Dagger.note_chunk_placement!(accel::MPIAcceleration, task, scope) + if accel.comm == MPI.COMM_WORLD && scope isa Dagger.ExactScope && scope.processor isa MPIProcessor + task.placed = scope.processor.rank + end + return +end + accel_matches_proc(accel::MPIAcceleration, proc::MPIOSProc) = true accel_matches_proc(accel::MPIAcceleration, proc::MPIClusterProc) = true accel_matches_proc(accel::MPIAcceleration, proc::MPIProcessor) = true @@ -2937,7 +2948,9 @@ mpi_failure_only(opts::Options) = function mpi_arg_participates(v, local_rank::Int) if v isa Dagger.DTask v.stub !== nothing && return mpi_arg_participates(v.stub, local_rank) - return v.owner < 0 || v.owner == local_rank + # `placed`: the rank a block of an array was put on (it does not make the task failure-only) + where = v.owner >= 0 ? v.owner : v.placed + return where < 0 || where == local_rank elseif v isa Chunk # N.B. A scope restriction on the chunk (a `DArray` block has one) only matters through # `constrain(task scope, chunk scope)`, which `elide_task!` checks for the task as a whole @@ -2996,10 +3009,9 @@ Dagger.task_processor_preference(::MPIAcceleration, req::MPIPlacementRequest, st function mpi_arg_owner(v) if v isa Dagger.DTask v.stub !== nothing && return mpi_arg_owner(v.stub) - return v.owner + return v.owner >= 0 ? v.owner : v.placed elseif v isa Chunk v.handle isa MPIRef || return -1 - v.scope isa Dagger.AnyScope || return -1 return v.handle.rank elseif v isa Dagger.WeakChunk return -1 @@ -3050,6 +3062,9 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) Dagger.iscompatible_func(proc, opts, typeof(f)) || return false for i in 2:length(fargs) Dagger.iscompatible_arg(proc, opts, chunktype(Dagger.value(fargs[i]))) || return false + # The scheduler also constrains the task's scope by that of every chunk argument + val = Dagger.value(fargs[i]) + val isa Chunk && !Dagger.proc_in_scope(proc, val.scope) && return false end opts.compute_scope = Dagger.ExactScope(proc) return true diff --git a/src/acceleration.jl b/src/acceleration.jl index 1584662f5..e7bbd0cc8 100644 --- a/src/acceleration.jl +++ b/src/acceleration.jl @@ -324,6 +324,16 @@ default_procgrid(accel, nblocks::NTuple{N,Int}) where N = nothing "Acceleration-specific finalization after array chunk tasks are spawned." post_stage_array_chunks!(accel::Acceleration, tasks, eltype::Type, nd::Int) = tasks +""" + note_chunk_placement!(accel, task::DTask, scope) + +Called for every task that produces a block of an array, with the compute scope the block was +placed with (a single processor for the deterministic placements: every rank computes the same +grid). An acceleration that wants to know at spawn time where a block lives records it here; +the default does nothing. +""" +note_chunk_placement!(::Acceleration, task, scope) = nothing + default_processor(space::CPURAMMemorySpace) = OSProc(space.owner) default_memory_space(accel::DistributedAcceleration) = CPURAMMemorySpace(myid()) # Chunk records must be labeled with the space the value actually resides in diff --git a/src/array/darray.jl b/src/array/darray.jl index cf6d36593..05d371aa3 100644 --- a/src/array/darray.jl +++ b/src/array/darray.jl @@ -617,7 +617,7 @@ function stage(ctx::Context, d::Distribute) shape = size(chunks) scope = procgrid_scope(d.procgrid, I) options = Options(compute_scope=scope) - Dagger.spawn(options, shape, chunks...) do shape, parts... + t = Dagger.spawn(options, shape, chunks...) do shape, parts... if prod(shape) == 0 return Array{T}(undef, shape) end @@ -625,6 +625,8 @@ function stage(ctx::Context, d::Distribute) ps = reshape(Any[parts...], shape) collect(treereduce_nd(dimcatfuncs, ps)) end + note_chunk_placement!(current_acceleration(), t, scope) + t end cs = post_stage_array_chunks!(current_acceleration(), cs, T, Nd) else diff --git a/src/dtask.jl b/src/dtask.jl index 41ced380e..7b44846a9 100644 --- a/src/dtask.jl +++ b/src/dtask.jl @@ -79,9 +79,13 @@ mutable struct DTask stub::Any # Rank/worker known to own this task's result at spawn time, `-1` when unknown owner::Int + # Rank/worker the placement code (`emit_chunk_tasks!`) put this task's result on, `-1` when + # not known at spawn time. Unlike `owner` it changes nothing about `fetch`; it only lets an + # acceleration decide about the *consumers* of the result (see `note_chunk_placement!`). + placed::Int thunk_ref::DRef - DTask(uid, future, metadata) = new(uid, future, metadata, nothing, -1) + DTask(uid, future, metadata) = new(uid, future, metadata, nothing, -1, -1) end const EagerThunk = DTask diff --git a/src/procgrid.jl b/src/procgrid.jl index c23d311b8..9150f1e2c 100644 --- a/src/procgrid.jl +++ b/src/procgrid.jl @@ -121,6 +121,7 @@ function emit_chunk_tasks!(domainchunks, procgrid, eltype::Type{T}, spawn_chunk: scope = procgrid === nothing ? default_scope : procgrid_scope(procgrid, I) i = LinearIndices(domainchunks)[I] tasks[i] = spawn_chunk(scope, I, i) + note_chunk_placement!(current_acceleration(), tasks[i], scope) end end # Under SPMD/MPI (uniform execution) the chunk-placement tasks must run diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 1309ee7a9..03743ad0c 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -5,6 +5,7 @@ elide_inc(x::Int) = x + 1 # concrete, cannot throw: elidable elide_add(a::Int, b::Int) = a + b elide_throws(x::Int) = x > 0 ? error("elide_throws") : x # may throw, concrete Int elide_len(x::Vector{Int}) = length(x) # concrete, cannot throw +elide_blocksum(x::Matrix{Float64}) = sum(x) elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw @@ -132,6 +133,36 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete end end + @testset "DArray blocks: where they live is known when the task that reads one is spawned" begin + # The blocks of an array are tasks of a Datadeps region (not elidable themselves), but their placement is + # the same grid on every rank: the consumers of a block are planned in full only by ranks that take part + A = zeros(Blocks(2, 2), Float64, 2 * nranks, 2) + blocks = vec(A.chunks) + placed = [b.placed for b in blocks] + @test all(>=(0), placed) + held = [fetch(b; raw=true).handle.rank for b in blocks] + @test placed == held # what was recorded is where the block is + @test allequal(MPI.Allgather(hash(placed), comm)) + for (i, b) in enumerate(blocks) + o = placed[i] + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=o) elide_blocksum(b) + wait(t) + @test (t.stub !== nothing) == (rank != o) # every other rank elides it + @test fetch(t) == 0.0 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + end + if nranks >= 3 + # on another rank than the block's: the block's rank sends the data (takes part), a third rank elides + o = placed[1] + other = (o + 1) % nranks + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=other) elide_blocksum(blocks[1]) + wait(t) + @test (t.stub !== nothing) == (rank != o && rank != other) # every rank outside the transfer elides + @test fetch(t) == 0.0 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + end + end + @testset "dependent chains" begin # a chain on one rank, then a consumer on another a = Dagger.@spawn scope=pinned(0) elide_inc(1) From 69d5d1eec97d2c00cbef84bc264714e82319ad37 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 18 Oct 2026 13:54:25 +0200 Subject: [PATCH 13/59] MPI: compute the scope chain of chunk arguments only when a chunk carries a restriction The elision check I added for scope-restricted chunk arguments computed constrain(compute scope, result scope) for every task. For a task scoped to a whole rank that is a union scope with one entry per thread, and constrain on it costs time proportional to the thread count: the foreign-rank planning cost of a rank-scoped task went from 38-43 us to 69-76 us at 16 threads (interleaved runs of the builds before and after), and 123-130 us at 32 threads, against ~20 us for an ExactScope. The result scope is always nothing for a task that gets here, so start the chain from the compute scope and only for the arguments that carry a restriction, in a function of its own. --- ext/MPIExt.jl | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 5dc65d361..5f7293597 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -3070,6 +3070,24 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) return true end +# The scheduler constrains a task's scope by the scope of every chunk argument and fails the task when they +# cannot be satisfied together; a rank that elides the task only needs to know that they can. The result scope is +# `nothing` for every task that gets here (`mpi_task_processor` refuses one), so the chain starts from the compute scope. +# N.B. Computed only for chunk arguments that carry a restriction: `constrain` on the union scope of a whole rank +# costs time proportional to its size, which showed up as +30 us per task at 16 threads when it ran for every task. +function mpi_chunk_scopes_fit(opts::Options, fargs) + scope = nothing + for i in 2:length(fargs) + val = Dagger.value(fargs[i]) + val isa Chunk || continue + val.scope isa Dagger.AnyScope && continue + scope === nothing && (scope = @something(opts.compute_scope, opts.scope, Dagger.DefaultScope())) + scope = Dagger.constrain(scope, val.scope) + scope isa Dagger.InvalidScope && return false + end + return true +end + function Dagger.elide_task!(accel::MPIAcceleration, spec, task) CHECK_UNIFORMITY[] && return false opts = spec.options @@ -3092,23 +3110,12 @@ function Dagger.elide_task!(accel::MPIAcceleration, spec, task) fargs = spec.fargs f = Dagger.value(fargs[1]) (f isa Function || f isa Type) || return false - # The scope the scheduler would compute for the task: the owner fails the task when it is invalid - # (task scope, result scope and every argument chunk's scope must agree), so a scope that can be - # satisfied is all a rank that elides the task needs to know. An invalid one keeps the ordinary - # protocol, which reports the failure as before. - scope = Dagger.constrain(@something(opts.compute_scope, opts.scope, Dagger.DefaultScope()), - @something(opts.result_scope, Dagger.AnyScope())) - scope isa Dagger.InvalidScope && return false for i in 2:length(fargs) arg = fargs[i] Dagger.ispositional(arg) || return false - val = Dagger.value(arg) - mpi_arg_participates(val, local_rank) && return false - if val isa Chunk - scope = Dagger.constrain(scope, val.scope) - scope isa Dagger.InvalidScope && return false - end + mpi_arg_participates(Dagger.value(arg), local_rank) && return false end + mpi_chunk_scopes_fit(opts, fargs) || return false # The placeholder `execute!` stamps on a non-owner, with the id it would get space = memory_space(nothing, proc)::MPIMemorySpace # N.B. `execute!` first takes a ref id for the task's tag when the task has no From 1281f282c1d357fa8367813ea0f67cfe44ad0d12 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 18 Oct 2026 16:51:21 +0200 Subject: [PATCH 14/59] MPI: type the processor `elide_task!` works with `mpi_scope_processor` returns an entry of `MPI_UNION_SCOPE_CACHE`, a `Dict{UInt,Tuple{Any,Any}}`, so its inferred type was `Any` and everything `elide_task!` did with the processor (field reads, `memory_space`, `tochunk(...; type=T)`) was a dynamic dispatch, once per planned task. Assert `Union{Nothing,MPIProcessor}` at the two return sites. Rank that only plans a foreign task (2 ranks x 4 threads, M-series, 20000 tasks, spawn+wait): 1.37 -> 1.24 us per task, 2135 -> 1895 B per task. test/mpi elide, spawn and free_threads pass at 3 ranks. --- ext/MPIExt.jl | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 5f7293597..08d6cf598 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2884,14 +2884,18 @@ accel_matches_proc(accel::MPIAcceleration, proc) = false # `Dagger.scope(mpi_rank=r)` does, leaves the choice of thread to the scheduler, and a # rank that elides the task never learns which thread that was. `scope=` sets both # `scope` and `compute_scope`; accept either, or both when equal. -function mpi_scope_processor(opts::Options) - scope = if opts.compute_scope === nothing +function mpi_task_scope(opts::Options) + return if opts.compute_scope === nothing opts.scope elseif opts.scope === nothing || opts.scope === opts.compute_scope || opts.scope == opts.compute_scope opts.compute_scope else nothing end +end + +function mpi_scope_processor(opts::Options)::Union{Nothing,MPIProcessor} + scope = mpi_task_scope(opts) if scope isa Dagger.ExactScope proc = scope.processor return proc isa MPIProcessor ? proc : nothing @@ -2929,7 +2933,7 @@ function mpi_union_scope_processor(scope::Dagger.UnionScope) end # At spawn time the scheduler has not yet filled in the execution or result scope -function mpi_task_processor(opts::Options) +function mpi_task_processor(opts::Options)::Union{Nothing,MPIProcessor} (opts.exec_scope === nothing && opts.result_scope === nothing) || return nothing return mpi_scope_processor(opts) end From dc36340c890729b723140bed6811873a830d72ea Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 18 Oct 2026 16:51:21 +0200 Subject: [PATCH 15/59] MPI: read DATADEPS_THUNK_ID once in take_ref_id! The branch read the scoped value twice (`!= 0`, then the value). A scoped value is a walk of the scope chain and `take_ref_id!` runs for every task, and twice for every elided one; one lookup saves the other. Planning a foreign task (same setup as the previous commit): 1.24 -> 1.16 us per task, 1895 -> 1831 B per task. --- ext/MPIExt.jl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 08d6cf598..a290386a7 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -850,8 +850,9 @@ function take_ref_id!() if Dagger.in_task() tid = sch_handle().thunk_id.id id = next_ref_sub_id!(tid) - elseif DATADEPS_THUNK_ID[] != 0 - tid = DATADEPS_THUNK_ID[] + elseif (dtid = DATADEPS_THUNK_ID[]) != 0 + # One lookup: a scoped value is a walk of the scope chain, and this runs for every task + tid = dtid id = next_ref_sub_id!(tid) else if current_task() !== Base.roottask From afd80d25438d380f98210274f562b87cdbe5fe10 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 23:11:24 +0100 Subject: [PATCH 16/59] MPI: plan a rank-scoped task on a foreign rank as cheaply as an ExactScope task A rank scope (Dagger.scope(mpi_rank=r)) is a UnionScope with one ExactScope per thread. elide_task! asked what it names three times per task (mpi_task_processor twice, mpi_failure_only once), each time through a cache keyed by objectid(scope) behind a lock, and objectid of a UnionScope hashes its whole tuple of processors, so the lookup cost grew with the thread count. A profile of a rank that only plans put most samples in mpi_union_scope_processor. elide_task! now resolves the processor once and hands it to mpi_failure_only. The cache is keyed by a function of the scope's contents (length and three members; `===` confirms a hit) and read without a lock (copy-on-write table). The key is deliberately not the scope's address: for a statically typed immutable the compiler may pass a fresh box, so such an "address" differs per call and the cache never hits. On our cluster, 2 ranks x 32 threads, a rank plans a task the other rank runs, us per task: rank scope 60.1 -> 22.2 (ExactScope 18-24), plain task with an argument owned by the other rank 61.2 -> 36.0. Not re-measured on upstream master. Tests: test/mpi/elide.jl (same rank for equal scopes, no entry per equal scope object, no stale answer for a replaced scope). --- ext/MPIExt.jl | 63 +++++++++++++++++++++++++++++++++++------------ test/mpi/elide.jl | 24 ++++++++++++++++++ 2 files changed, 71 insertions(+), 16 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index a290386a7..064d548e1 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2908,14 +2908,34 @@ end # Scopes are reused (a `with_options(scope=...)` block hands the same object to every # task spawned under it), so what a union scope names is worked out once per scope. -const MPI_UNION_SCOPE_CACHE = LockedObject(Dict{UInt,Tuple{Any,Any}}()) +# +# The key is not `objectid(scope)`: a `UnionScope` holds a tuple with one `ExactScope` per +# processor, and `objectid` hashes all of it, which made a plain rank scope +# (`Dagger.scope(mpi_rank=r)`, one entry per thread) cost time proportional to the thread +# count, several times per task. It is not the scope's address either: for a statically +# typed immutable the compiler may pass a fresh box, so an "address" can differ on every +# call and the cache would never hit. The key is a function of the contents (length and +# three members); `===` on a hit confirms it, and a miss only costs a recomputation. +# Reads take no lock: the table is replaced as a whole. +function mpi_union_key(scope::Dagger.UnionScope) + s = scope.scopes + n = length(s) + h = hash(n) + if n > 0 + h = hash(s[1], h); h = hash(s[n], h); h = hash(s[(n >> 1) + 1], h) + end + return UInt(h) +end + +mutable struct MPIUnionScopeCache + @atomic table::Dict{UInt,Tuple{Any,Any}} +end +const MPI_UNION_SCOPE_CACHE = MPIUnionScopeCache(Dict{UInt,Tuple{Any,Any}}()) +const MPI_UNION_SCOPE_CACHE_LOCK = ReentrantLock() function mpi_union_scope_processor(scope::Dagger.UnionScope) - key = objectid(scope) - hit = lock(MPI_UNION_SCOPE_CACHE) do cache - get(cache, key, nothing) - end - # `===`: the entry keeps the scope alive, so a hit cannot be a recycled objectid + key = mpi_union_key(scope) + hit = get((@atomic MPI_UNION_SCOPE_CACHE.table), key, nothing) hit !== nothing && hit[1] === scope && return hit[2] proc = nothing scopes = scope.scopes @@ -2926,9 +2946,11 @@ function mpi_union_scope_processor(scope::Dagger.UnionScope) proc = argmin(short_name, [sc.processor for sc in scopes]) end end - lock(MPI_UNION_SCOPE_CACHE) do cache - length(cache) >= 256 && empty!(cache) - cache[key] = (scope, proc) + lock(MPI_UNION_SCOPE_CACHE_LOCK) do + old = @atomic MPI_UNION_SCOPE_CACHE.table + table = length(old) >= 256 ? Dict{UInt,Tuple{Any,Any}}() : copy(old) + table[key] = (scope, proc) + @atomic MPI_UNION_SCOPE_CACHE.table = table end return proc end @@ -2945,9 +2967,15 @@ end # and so rule it out, as does an explicit tag (Datadeps tasks, whose copies and # waits do not know about failures that arrive this way). mpi_failure_only(::Nothing) = false -mpi_failure_only(opts::Options) = - Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing && - mpi_scope_processor(opts) !== nothing +function mpi_failure_only(opts::Options) + Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing || return false + return mpi_failure_only(opts, mpi_scope_processor(opts)) +end +# With the task's processor already worked out (`elide_task!` needs it for other things too) +function mpi_failure_only(opts::Options, proc::Union{Nothing,MPIProcessor}) + Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing || return false + return proc !== nothing +end # Whether `local_rank` takes part in moving `v` to the task's rank, or cannot tell function mpi_arg_participates(v, local_rank::Int) @@ -3096,15 +3124,18 @@ end function Dagger.elide_task!(accel::MPIAcceleration, spec, task) CHECK_UNIFORMITY[] && return false opts = spec.options - # Tasks without a scope are placed here, so that every rank knows the owner - if mpi_task_processor(opts) === nothing && opts.compute_scope === nothing && opts.scope === nothing + # Tasks without a scope are placed here, so that every rank knows the owner. + # N.B. The processor a union scope names is looked up once per task: it is the same + # answer every time, and each lookup is a hash-table probe on every task. + proc = mpi_task_processor(opts) + if proc === nothing && opts.compute_scope === nothing && opts.scope === nothing mpi_preplace!(accel, spec, task) + proc = mpi_task_processor(opts) end - proc = mpi_task_processor(opts) proc === nothing && return false # Later submissions use this to decide about their own arguments, and `fetch` # to stay uniform when the task fails. Only failure-only tasks have an owner. - mpi_failure_only(opts) || return false + mpi_failure_only(opts, proc) || return false task.owner = proc.rank local_rank = MPI.Comm_rank(proc.comm) proc.rank == local_rank && return false diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 03743ad0c..2594bcacb 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -62,6 +62,30 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete @test_throws Exception fetch(bad) dep = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_inc(bad) @test_throws Exception fetch(dep) + # What a rank scope names is cached under a key made from its contents and confirmed with `===`: two equal scopes + # built separately resolve to the same rank and share one entry, scopes of different ranks never share an + # answer, and a scope that is dropped and replaced by another one cannot return the old answer. + for target in 0:nranks-1 + s1 = Dagger.scope(mpi_rank=target); s2 = Dagger.scope(mpi_rank=target) + @test s1 == s2 + for s in (s1, s2, s1, s2) + o = Dagger.Options(; scope=s) + p = MPIExt.mpi_scope_processor(o) + @test p isa MPIExt.MPIProcessor && p.rank == target + end + end + for round in 1:20, target in 0:nranks-1 + o = Dagger.Options(; scope=Dagger.scope(mpi_rank=target)) # a new scope object every time + @test MPIExt.mpi_scope_processor(o).rank == target + GC.gc(false) + end + # equal scope objects rebuilt on the way to the planner must not each get a cache entry + MPIExt.mpi_union_scope_processor(Dagger.scope(mpi_rank=rank)) + n1 = length(MPIExt.MPI_UNION_SCOPE_CACHE.table) + for _ in 1:20 + MPIExt.mpi_union_scope_processor(Dagger.scope(mpi_rank=rank)) + end + @test length(MPIExt.MPI_UNION_SCOPE_CACHE.table) == n1 # several ranks allowed: the rank is the scheduler's choice, nothing is elided multi = Dagger.@spawn scope=Dagger.scope(mpi_ranks=:) elide_inc(1) @test multi.stub === nothing From aaa4192c6431e9e731f8677bf5685f91223ea9fe Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 23 Oct 2026 17:28:55 +0200 Subject: [PATCH 17/59] Scopes: constrain(::UnionScope, ::AnyScope) is the union itself The generic constrain(::UnionScope, y) wrapped y in a union and rebuilt a new UnionScope of every member (Set, hashing, a fresh tuple). schedule_one! does constrain(compute_scope, AnyScope()) for every task without a result scope, so a task scoped to a rank (a union of its 32 thread processors) paid ~90 us and ~11 KB of garbage for nothing: profile of the owner side, 1754 of 4875 samples in constrain(::UnionScope, ::AnyScope); 19 KB/task and 246 ms GC per 20000 tasks against 8 KB/task for an ExactScope task. AnyScope allows everything, so the answer is x. --- src/scopes.jl | 5 +++++ test/scopes.jl | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/scopes.jl b/src/scopes.jl index 1cbf7a703..3bab511bb 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -222,6 +222,11 @@ function constrain(x::UnionScope, y::UnionScope) isempty(zs) && return InvalidScope(x, y) UnionScope(zs) end +# Everything is allowed by `AnyScope`: the answer is `x` itself. Without this the generic method below wraps `AnyScope` in a +# union and rebuilds a new `UnionScope` of all of `x`'s scopes (a `Set`, hashing, a fresh tuple): for the union of one rank's +# processors that was ~90 us and 11 KB of garbage for every task the scheduler placed (`schedule_one!` constrains the compute +# scope by `AnyScope()` when there is no result scope). +constrain(x::UnionScope, ::AnyScope) = x constrain(x::UnionScope, y) = constrain(x, UnionScope((y,))) Base.isless(::NodeScope, ::NodeScope) = false diff --git a/test/scopes.jl b/test/scopes.jl index c448bf2ca..11b091a30 100644 --- a/test/scopes.jl +++ b/test/scopes.jl @@ -286,3 +286,14 @@ rmprocs([wid1, wid2]) end + +@testset "UnionScope constrained by AnyScope is itself" begin + u = Dagger.UnionScope([Dagger.ExactScope(Dagger.ThreadProc(1, t)) for t in 1:8]) + # `schedule_one!` does this for every task without a result scope; it must neither rebuild the union nor change it + @test Dagger.constrain(u, Dagger.AnyScope()) === u + @test Dagger.constrain(Dagger.AnyScope(), u) === u + @test Dagger.constrain(u, Dagger.AnyScope(), Dagger.AnyScope()) === u + # and a union is still narrowed by something that is not AnyScope + narrowed = Dagger.constrain(u, Dagger.ExactScope(Dagger.ThreadProc(1, 3))) + @test narrowed isa Dagger.UnionScope && length(narrowed.scopes) == 1 +end From 8fadfc0811e9a1b4e75dcb682cf59e52c8bab231 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 23:12:28 +0100 Subject: [PATCH 18/59] MPI: an elided task's placeholder names the processor its owner runs it on A rank that elides a task (it neither runs it nor sources its data) stamps a placeholder result. For a task scoped to a whole rank its processor came from mpi_union_scope_processor, a fixed member of the union, while the owner's scheduler picks the thread inside the rank by rotation (select_processors_uniform!). The ranks therefore disagreed on chunk.processor: with free threads and elision on, test/mpi/spawn.jl had 35 failures at 2 ranks x 4 threads (62 on our cluster), all check_uniform(proc) or the spread over threads ([16, 0, 0, 0] on the spectator against [4, 4, 4, 4] on the owner). On CPU only the checks notice; with several GPUs per rank the placeholder would name another device. Under uniform execution the owner takes the candidate at mod(id - 1, n) + 1 of the scope's processors in canonical order (the owner rank is either the whole candidate list or not in it). The placeholder now uses the same index, from a lock-free cache of the ordered processors per union scope, so the per-task cost does not grow with the thread count. Test: test/mpi/elide.jl, the processors stamped on 16 tasks of one rank scope agree across ranks; fails without the change. --- ext/MPIExt.jl | 44 +++++++++++++++++++++++++++++++++++++++++++- test/mpi/elide.jl | 4 ++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 064d548e1..7474f66f2 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2955,6 +2955,46 @@ function mpi_union_scope_processor(scope::Dagger.UnionScope) return proc end +# The processors of a single-rank union scope in the order the owner's scheduler sees them +# (`select_processors_uniform!`: the canonical order), so that a rank which elides the task +# can stamp its placeholder with the processor the owner will pick: under uniform execution +# that is the candidate at `mod(id - 1, n) + 1` (`select_processors_uniform!`; the owner rank +# is either the whole candidate list or not in it, so no preferred block shortens it). +# `mpi_union_scope_processor` names a fixed member, which gives the right rank but, on a +# non-owner, another thread than the owner's: the placeholder and the real result then +# disagreed on `chunk.processor`. Same content-keyed, lock-free cache as above. +const MPI_UNION_ORDER_CACHE = MPIUnionScopeCache(Dict{UInt,Tuple{Any,Any}}()) +const MPI_UNION_ORDER_CACHE_LOCK = ReentrantLock() +function mpi_union_scope_ordered(accel::MPIAcceleration, scope::Dagger.UnionScope)::Union{Nothing,Vector{Processor}} + key = mpi_union_key(scope) + hit = get((@atomic MPI_UNION_ORDER_CACHE.table), key, nothing) + hit !== nothing && hit[1] === scope && return hit[2]::Union{Nothing,Vector{Processor}} + ordered = nothing + if mpi_union_scope_processor(scope) !== nothing + ordered = Processor[sc.processor for sc in scope.scopes] + unique!(ordered) + # Without a task: the canonical order only, no rotation + Dagger.select_processors_uniform!(ordered, accel) + end + lock(MPI_UNION_ORDER_CACHE_LOCK) do + old = @atomic MPI_UNION_ORDER_CACHE.table + table = length(old) >= 256 ? Dict{UInt,Tuple{Any,Any}}() : copy(old) + table[key] = (scope, ordered) + @atomic MPI_UNION_ORDER_CACHE.table = table + end + return ordered +end + +# The processor the owner's scheduler will run task `uid` on, when its scope names one +# rank; `proc` (the scope's fixed member) otherwise +function mpi_planned_processor(accel::MPIAcceleration, opts::Options, proc::MPIProcessor, uid)::MPIProcessor + scope = mpi_task_scope(opts) + scope isa Dagger.UnionScope || return proc + ordered = mpi_union_scope_ordered(accel, scope) + ordered === nothing && return proc + return ordered[mod(Int(uid) - 1, length(ordered)) + 1]::MPIProcessor +end + # At spawn time the scheduler has not yet filled in the execution or result scope function mpi_task_processor(opts::Options)::Union{Nothing,MPIProcessor} (opts.exec_scope === nothing && opts.result_scope === nothing) || return nothing @@ -3152,7 +3192,9 @@ function Dagger.elide_task!(accel::MPIAcceleration, spec, task) mpi_arg_participates(Dagger.value(arg), local_rank) && return false end mpi_chunk_scopes_fit(opts, fargs) || return false - # The placeholder `execute!` stamps on a non-owner, with the id it would get + # The placeholder `execute!` stamps on a non-owner, with the id it would get, on the + # processor the owner will run it on + proc = mpi_planned_processor(accel, opts, proc, task.uid) space = memory_space(nothing, proc)::MPIMemorySpace # N.B. `execute!` first takes a ref id for the task's tag when the task has no # tag option (`to_tag()`), so the result chunk is the second id of its task. diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 2594bcacb..34a7598d2 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -53,6 +53,10 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete @test all(w -> w[1] == target, where) @test length(unique(last.(where))) >= min(2, Threads.nthreads()) @test count(t -> t.stub !== nothing, tasks) == (rank == target ? 0 : 16) + # A spectator's placeholder names the processor the owner ran the task on (it used to name a fixed + # member of the scope, so the ranks disagreed on `chunk.processor`) + stamped = [(p.rank, p.innerProc.tid) for p in (fetch(t; raw=true).processor for t in tasks)] + @test allequal(MPI.Allgather(hash(stamped), comm)) # a chain across two rank-level scopes, and a failure a = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) elide_inc(1) b = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_add(a, 10) From a7b8cef6b4a487479a61a61d011c0b81582b8669 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 27 Nov 2026 07:45:39 +0100 Subject: [PATCH 19/59] Owner elision: switch it with Dagger.elide_foreign_tasks!, not an environment variable The flag is a plain Ref read at submission time and set by Dagger.elide_foreign_tasks!(on); it stays off by default. No environment variable is read, so nothing depends on the state of the process at startup. --- src/Dagger.jl | 4 ---- src/submission.jl | 10 ++++++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/Dagger.jl b/src/Dagger.jl index 468767c49..2b988a956 100644 --- a/src/Dagger.jl +++ b/src/Dagger.jl @@ -186,10 +186,6 @@ function __init__() delete!(SYSTEM_UUIDS, myid()) system_uuid() - # Read at startup, not at precompile time: a `const` initialized from the - # environment would be baked into the compiled image - ELIDE_FOREIGN_TASKS[] = get(ENV, "JULIA_DAGGER_ELIDE_FOREIGN_TASKS", "0") in ("1", "true") - @static if !isdefined(Base, :get_extension) @require Distributions="31c24e10-a181-5473-b8eb-7969acd0382f" begin include(joinpath(dirname(@__DIR__), "ext", "DistributionsExt.jl")) diff --git a/src/submission.jl b/src/submission.jl index 7674b6299..69394cb1d 100644 --- a/src/submission.jl +++ b/src/submission.jl @@ -550,12 +550,14 @@ end chunktype(t::DTask) = t.metadata.return_type """ - ELIDE_FOREIGN_TASKS + elide_foreign_tasks!(on::Bool=true) -Opt-in switch (`Dagger.elide_foreign_tasks!`, or the environment variable -`JULIA_DAGGER_ELIDE_FOREIGN_TASKS=1` at startup) for [`elide_task!`](@ref). +Switch owner elision on or off for this process (off by default); see +[`elide_task!`](@ref). The flag is read each time a task is submitted, so it can be +changed at run time. Under SPMD every rank must call it with the same value at the +same point of the program. """ -const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) # set from the environment in `__init__` +const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) elide_foreign_tasks!(on::Bool=true) = (ELIDE_FOREIGN_TASKS[] = on) """ From 6368a881c867fff1537c17edab303df009d68c91 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 27 Nov 2026 07:47:48 +0100 Subject: [PATCH 20/59] test: owner elision is off by default and nothing is elided while it is off --- test/mpi/elide.jl | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 34a7598d2..9db66711e 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -14,6 +14,16 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete pinned(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) # Uniformity checks are collective over all ranks and so disable elision Dagger.check_uniformity!(false) + # The switch is off by default and read at run time: with it off nothing is elided + @testset "switch off: nothing is elided" begin + @test !Dagger.ELIDE_FOREIGN_TASKS[] + for target in 0:nranks-1 + t = Dagger.@spawn scope=pinned(target) elide_inc(41) + @test fetch(t) == 42 + @test t.stub === nothing + @test t.owner < 0 + end + end Dagger.elide_foreign_tasks!(true) try @testset "pinned tasks: results, stubs, uniform ids" begin From 859a1591e5066fd3b7f1bc82f8a322ac19cd1310 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 27 Nov 2026 09:47:58 +0100 Subject: [PATCH 21/59] Owner elision: changing the switch waits for the tasks already submitted Whether a task reports only failures is decided when it runs (execute! and task_failed! read the flag), not when it is submitted. A task submitted with the switch on that ran after it was turned off made its owner send the ordinary status while the ranks that had elided it waited for nothing, and the reverse left the ranks that planned it in full waiting for a status that never came. elide_foreign_tasks! now waits until the eager scheduler has no task in flight before it changes the value, and refuses to change it from inside a task. The docstring was also attached to the flag, not the function. The new testset fails without the wait (the owner's task is still running when the switch returns). --- src/submission.jl | 23 +++++++++++++++++++++-- test/mpi/elide.jl | 12 ++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/submission.jl b/src/submission.jl index 69394cb1d..926f44caf 100644 --- a/src/submission.jl +++ b/src/submission.jl @@ -549,6 +549,8 @@ end chunktype(t::DTask) = t.metadata.return_type +const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) + """ elide_foreign_tasks!(on::Bool=true) @@ -556,9 +558,26 @@ Switch owner elision on or off for this process (off by default); see [`elide_task!`](@ref). The flag is read each time a task is submitted, so it can be changed at run time. Under SPMD every rank must call it with the same value at the same point of the program. + +Whether a task reports only failures is decided when it runs, so a change of the flag +first waits until the tasks already submitted have finished (a task submitted under +the old value that ran under the new one would leave the other ranks waiting for a +status that never comes). It therefore must not be called from inside a task. """ -const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) -elide_foreign_tasks!(on::Bool=true) = (ELIDE_FOREIGN_TASKS[] = on) +function elide_foreign_tasks!(on::Bool=true) + if ELIDE_FOREIGN_TASKS[] != on + in_task() && throw(ArgumentError("`elide_foreign_tasks!` cannot change the flag from inside a task")) + state = Sch.EAGER_STATE[] + if state !== nothing + # N.B. The long-lived root thunk of the eager scheduler holds one credit + while state.running_count[] > 1 + sleep(0.001) + end + end + ELIDE_FOREIGN_TASKS[] = on + end + return on +end """ elide_task!(accel::Acceleration, spec::DTaskSpec, task::DTask) -> Bool diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 9db66711e..588075eb2 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -6,6 +6,7 @@ elide_add(a::Int, b::Int) = a + b elide_throws(x::Int) = x > 0 ? error("elide_throws") : x # may throw, concrete Int elide_len(x::Vector{Int}) = length(x) # concrete, cannot throw elide_blocksum(x::Matrix{Float64}) = sum(x) +elide_slow_throws(x::Int) = (sleep(0.5); x > 0 ? error("elide_slow_throws") : x) elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw @@ -246,6 +247,17 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete @test_throws Exception fetch(far) end + @testset "changing the switch waits for the tasks in flight" begin + # Whether a task reports only failures is decided when it runs: a task submitted with the + # switch on must not run with it off (the ranks that elided it would wait for a status). + bad = Dagger.@spawn scope=pinned(0) elide_slow_throws(1) + Dagger.elide_foreign_tasks!(false) + @test isready(bad) # the owner's task was waited for + Dagger.elide_foreign_tasks!(true) + @test_throws Exception fetch(bad) # and every rank still sees the failure + @test_throws Exception fetch(Dagger.@spawn scope=pinned(0) Dagger.elide_foreign_tasks!(false)) + end + @testset "later SPMD work is unaffected" begin y = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) fill(2.0, 8) s = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) sum(y) From 58761b97b1afb4de795bdb5e752fb388bf191aef Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 27 Nov 2026 09:47:58 +0100 Subject: [PATCH 22/59] Owner elision: world communicator only, and document it Task ids, tags and failure tags are those of the world communicator. A failure-only decision for a processor of another communicator would use them, so such tasks are never failure-only or elided and take the ordinary path. Adds the section on owner elision to the MPI docs. --- docs/src/mpi.md | 20 ++++++++++++++++++++ ext/MPIExt.jl | 5 ++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/src/mpi.md b/docs/src/mpi.md index a28e124e1..91442826f 100644 --- a/docs/src/mpi.md +++ b/docs/src/mpi.md @@ -346,6 +346,26 @@ hooks — `Dagger.mpi_device_direct`, `Dagger.mpi_device_sync`, `Dagger.mpi_library_gpu_aware`, and `Dagger.mpi_remap_space` — are overridable per backend for advanced setups. +## Skipping tasks a rank takes no part in (owner elision) + +Under SPMD every rank plans every task, including tasks it neither runs nor owns +data for. `Dagger.elide_foreign_tasks!(true)` lets such a rank skip the thunk, +scheduling and placeholder execution of a task (it only takes the task id, so ids +and tags stay equal on every rank). It is off by default, and every rank must set +it to the same value at the same point of the program; changing it waits for the +tasks already submitted. + +A task is only elided when its scope names a single rank, its return type is +concrete, it has no explicit tag, and this rank owns none of its arguments. +Tasks inside Datadeps regions and inside other tasks are never elided, and +neither are tasks of another communicator or while `check_uniformity!(true)` is +on. + +The consequence to be aware of: the owner of an elided task reports only +failures. A rank that never fetches the task or consumes its result does not wait +for it and does not notice that it finished or failed; a rank that does consume +it sees the owner's error. + ## Collecting and fetching results `collect(DA)` performs a deterministic, rank-uniform gather: it returns the full diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 7474f66f2..825c38e15 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -3014,7 +3014,8 @@ end # With the task's processor already worked out (`elide_task!` needs it for other things too) function mpi_failure_only(opts::Options, proc::Union{Nothing,MPIProcessor}) Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing || return false - return proc !== nothing + # Only the world communicator: ids and failure tags of other graphs are not uniform + return proc !== nothing && proc.comm == MPI.COMM_WORLD end # Whether `local_rank` takes part in moving `v` to the task's rank, or cannot tell @@ -3163,6 +3164,8 @@ end function Dagger.elide_task!(accel::MPIAcceleration, spec, task) CHECK_UNIFORMITY[] && return false + # Placement, ids and failure tags here are those of the world communicator only + accel.comm == MPI.COMM_WORLD || return false opts = spec.options # Tasks without a scope are placed here, so that every rank knows the owner. # N.B. The processor a union scope names is looked up once per task: it is the same From 74e45ebe30a55c029db6c6c913b6f92ce487b0ed Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 27 Nov 2026 08:00:28 +0100 Subject: [PATCH 23/59] MPI: a task failure is broadcast only under a valid tag, and the error is logged when it is not task_failed! sent the failure of a failure-only task as UInt32(thunk.id). MPI only guarantees tags up to MPI.tag_ub() (Open MPI: 8388607), so on a long run the Isend of the failure died with MPI_ERR_TAG inside a spawned task and the actual exception was lost, leaving work that depended on the task unfinished. mpi_failure_tag now returns nothing for an id that is not a valid tag, and the failure is logged together with its exception instead. Test: test/mpi/failure_tag.jl (the tag function, and a failing failure-only task whose id is past tag_ub is logged and nothing throws); the logging test fails without the change. --- ext/MPIExt.jl | 17 ++++++++++++++++- test/mpi/cpu.jl | 1 + test/mpi/failure_tag.jl | 26 ++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 test/mpi/failure_tag.jl diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 825c38e15..1e4e50661 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -3036,6 +3036,13 @@ function mpi_arg_participates(v, local_rank::Int) return false end +# The tag a failure is broadcast under, or `nothing` when the id cannot be one: MPI only guarantees tags up +# to `MPI.tag_ub()` (32767 at the least), and Open MPI's is 8388607. +function mpi_failure_tag(id::Integer) + 0 <= id < MPI.tag_ub() || return nothing + return UInt32(id) +end + # The owner tells everyone when a failure-only task fails, whatever the cause: an # error in the task, in moving its arguments, or an upstream failure. This runs # under the scheduler lock, so the send is handed to another task. @@ -3045,7 +3052,15 @@ function Dagger.Sch.task_failed!(::MPIAcceleration, thunk, value) proc = mpi_scope_processor(opts) MPI.Comm_rank(proc.comm) == proc.rank || return ex = mpi_wire_exception(value isa Dagger.DTaskFailedException ? value.ex : value) - tag = UInt32(thunk.id) + tag = mpi_failure_tag(thunk.id) + if tag === nothing + # The id is no valid tag (a long run on an MPI with a small `tag_ub`), so nobody can be waiting under it: + # the failure is on the task for whoever fetches it here. Say what it was instead of dying in `Isend` + # with MPI_ERR_TAG and losing the exception. + id = thunk.id + @error "Task failed; not broadcast (id $id is not a valid MPI tag)" exception=value + return + end Dagger.Sch.errormonitor_tracked("mpi_task_failed", Threads.@spawn begin bcast_meta_yield(proc.comm, proc.rank, tag, (:error, ex)) end) diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 286e7575c..e5fe048c8 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -150,6 +150,7 @@ include("noaliasing_args.jl") include("free_threads.jl") include("relay.jl") include("elide.jl") +include("failure_tag.jl") @testset "Datadeps" begin diff --git a/test/mpi/failure_tag.jl b/test/mpi/failure_tag.jl new file mode 100644 index 000000000..6ce2aa1ed --- /dev/null +++ b/test/mpi/failure_tag.jl @@ -0,0 +1,26 @@ +# A failure broadcast needs a valid MPI tag: an id past `MPI.tag_ub()` (a long run on an MPI with a small limit) +# used to die in `Isend` with MPI_ERR_TAG, and the actual exception was lost. +@testset "failure broadcast tag" begin + ext = Base.get_extension(Dagger, :MPIExt) + ub = Int(MPI.tag_ub()) + @test ext.mpi_failure_tag(5) == UInt32(5) + @test ext.mpi_failure_tag(ub - 1) == UInt32(ub - 1) + @test ext.mpi_failure_tag(ub) === nothing + @test ext.mpi_failure_tag(ub + 12345) === nothing + @test ext.mpi_failure_tag(-1) === nothing + + # A failing failure-only task whose id is no tag: logged with its exception, nothing is sent, nothing throws. + me = MPI.Comm_rank(MPI.COMM_WORLD) + old = Dagger.ELIDE_FOREIGN_TASKS[] + Dagger.check_uniformity!(false) + Dagger.elide_foreign_tasks!(true) + try + opts = Dagger.Options(; scope=Dagger.ExactScope(first(filter(p -> p.rank == me, mpi_procs())))) + thunk = Dagger.Thunk(identity, nothing => 1; id=ub + 5, options=opts) + accel = Dagger.current_acceleration() + @test_logs (:error, r"not broadcast") match_mode=:any Dagger.Sch.task_failed!(accel, thunk, ErrorException("boom")) + finally + Dagger.elide_foreign_tasks!(old) + Dagger.check_uniformity!(true) + end +end From 8741fa9a99431472a6e9bc349fcde24ea8c8e813 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:32:44 -0700 Subject: [PATCH 24/59] Create ThreadProcs for the default thread pool, not 1:nthreads() `__init__` registered `ThreadProc(myid(), tid)` for `tid in 1:Threads.nthreads()`. `nthreads()` counts only the default pool, but Julia numbers the interactive pool first: with an interactive thread (the default since Julia 1.12, or `-t N,1` on 1.10/1.11) thread 1 is interactive and the default pool is threads 2:N+1. So Dagger ran tasks on the interactive thread, where the main task and the REPL live, and never used the last default thread. Measured on Julia 1.12 with `-t 4` (found while checking ThreadPinning.jl against #810): Dagger's ThreadProcs were tids [1, 2, 3, 4], and the CPU pinned to tid 5 never ran Dagger work. This loop dates from 2020-2021, before interactive threads existed, so using thread 1 was never a decision. Register the default pool's tids (`Threads.threadpooltids(:default)`, available since 1.9) instead. Dagger now never schedules tasks on an interactive thread: Julia reserves those for short, latency-sensitive work, and they are where the REPL and usually the eager scheduler's own loop run. Everything that meant "the first thread" by writing a literal 1 now asks for it: - The eager scheduler's long-lived thunk was pinned to `ExactScope(ThreadProc(1, 1))`, which no longer exists when thread 1 is interactive; pin it to the first default-pool thread. - The precompile workload registered `__cpu_thread_1__` directly (`__init__` has not run yet), and that Dict is saved in the package image. `__init__` used to overwrite that entry; now that it registers other names, a stale ThreadProc(1, 1) would survive into every session. Register the first default thread and delete the callback at the end of the workload. `Threads.nthreads()` elsewhere sizes parallel work by the default pool's size, which is still correct. `stealing_permitted` still excludes worker 1's thread 1 (the main thread); when that thread is interactive there is simply no ThreadProc for it. Tests that scheduled on `ThreadProc(1, 1)` or `thread=1` (or on a worker's threads 1 and 2) only passed on 1.12+ because tasks could run on the interactive thread; they now use the real first threads. CI's 1.12+ multithreaded jobs (`-t auto`) have an interactive thread, but 1.10/1.11 do not, so the processors suite also starts a `-t 2,1` subprocess and checks that ThreadProcs are exactly the default pool, that tasks pinned to each run there, and that no task runs on the interactive thread. That test fails on master. Co-Authored-By: Claude Opus 5.5 --- src/Dagger.jl | 6 ++++- src/precompile.jl | 11 +++++++-- src/sch/eager.jl | 4 +++- src/threadproc.jl | 40 +++++++++++++++++++++++++++++++ test/allocations.jl | 5 ++-- test/datadeps.jl | 6 +++-- test/gpu.jl | 2 +- test/options.jl | 8 +++---- test/processors.jl | 55 +++++++++++++++++++++++++++++++++++++++++++ test/scheduler.jl | 10 ++++---- test/scopes.jl | 17 +++++++------ test/streaming.jl | 5 ++-- test/task-affinity.jl | 2 +- test/thunk.jl | 3 ++- 14 files changed, 145 insertions(+), 29 deletions(-) diff --git a/src/Dagger.jl b/src/Dagger.jl index 2b988a956..a9525bc90 100644 --- a/src/Dagger.jl +++ b/src/Dagger.jl @@ -222,7 +222,11 @@ function __init__() end end end - for tid in 1:Threads.nthreads() + # Not `1:Threads.nthreads()`: that counts the default pool but numbers it + # from 1, which is wrong whenever an interactive thread exists (it takes + # thread 1). We would then run tasks on the interactive thread and never + # on the last default thread. + for tid in default_pool_tids() add_processor_callback!("__cpu_thread_$(tid)__") do ThreadProc(myid(), tid) end diff --git a/src/precompile.jl b/src/precompile.jl index 7bb63f567..8a06c1e13 100644 --- a/src/precompile.jl +++ b/src/precompile.jl @@ -1,7 +1,13 @@ @compile_workload begin system_uuid() - add_processor_callback!("__cpu_thread_1__") do - ThreadProc(1, 1) + # `__init__` has not run yet, so register the one thread the workload + # needs (the default pool's first, which is not thread 1 when an + # interactive thread exists), and remove it again below: this Dict is + # saved in the package image, and `__init__` registers the real threads. + precompile_tid = first_default_tid() + precompile_cb = Symbol("__cpu_thread_$(precompile_tid)__") + add_processor_callback!(precompile_cb) do + ThreadProc(1, precompile_tid) end # FIXME: t1 = @spawn 1+1 t1 = spawn(+, 1, 1) @@ -90,6 +96,7 @@ @assert isempty(Sch.WORKER_MONITOR_CHANS) @assert isempty(Sch.WORKER_MONITOR_TASKS) ID_COUNTER[] = 1 + delete_processor_callback!(precompile_cb) # Clear the precompile-time UUID cache so it is not baked into the compiled # image; __init__ re-populates it from the shared UUID file at load time. delete!(SYSTEM_UUIDS, myid()) diff --git a/src/sch/eager.jl b/src/sch/eager.jl index 6c1283472..07af905da 100644 --- a/src/sch/eager.jl +++ b/src/sch/eager.jl @@ -45,7 +45,9 @@ function init_eager() # wakes up. Further testing is needed. sched_task = @task try sopts = SchedulerOptions(;allow_errors=true) - opts = Dagger.Options((;scope=Dagger.ExactScope(Dagger.ThreadProc(1, 1)), + # The first default-pool thread, not thread 1: when an interactive + # thread exists it is thread 1, and Dagger has no processor for it. + opts = Dagger.Options((;scope=Dagger.ExactScope(Dagger.ThreadProc(1, Dagger.first_default_tid())), occupancy=Dict(Dagger.ThreadProc=>0), time_util=Dict(Dagger.ThreadProc=>0))) Dagger.compute(ctx, Dagger._delayed(eager_thunk, opts)(); diff --git a/src/threadproc.jl b/src/threadproc.jl index 13955ca45..9095833df 100644 --- a/src/threadproc.jl +++ b/src/threadproc.jl @@ -2,11 +2,51 @@ ThreadProc <: Processor Julia CPU (OS) thread, identified by Julia thread ID. + +Dagger creates one `ThreadProc` per thread of Julia's default thread pool, and +none for interactive threads (see `Dagger.default_pool_tids`). """ struct ThreadProc <: Processor owner::Int tid::Int end + +""" + default_pool_tids() -> Vector{Int} + +The IDs of this process's default-pool threads: the threads that Dagger creates +a [`ThreadProc`](@ref) for, and so the only threads that run Dagger tasks. + +Interactive threads are left out. Julia starts one by default since 1.12 (and +with `julia -t N,M` before that), and numbers them first, so thread 1 is then +interactive and the default pool is threads `2:N+1`; `Threads.nthreads()` counts +only the default pool. The main task (and the REPL) run on thread 1 in that +case. Julia reserves interactive threads for short, latency-sensitive work, and +running arbitrary tasks there would make the REPL, and anything else that +expects that thread to respond quickly, wait behind them. +""" +default_pool_tids() = Threads.threadpooltids(:default) + +# `first(default_pool_tids())` without allocating a vector: Julia numbers the +# interactive pool first, so the default pool starts right after it (this is +# how `Threads.threadpooltids` itself computes the range). +first_default_tid() = Threads.threadpoolsize(:interactive) + 1 + +# Worker `pid`'s lowest-numbered CPU thread processor, for code that means "the +# worker's first thread". Not `ThreadProc(pid, 1)`: when the worker has an +# interactive thread, that is thread 1, and Dagger has no processor for it. +function first_thread_proc(pid::Int=myid()) + first_proc = nothing + for proc in get_processors(OSProc(pid)) + proc isa ThreadProc || continue + if first_proc === nothing || proc.tid < first_proc.tid + first_proc = proc + end + end + first_proc === nothing && error("Worker $pid has no CPU thread processors") + return first_proc::ThreadProc +end + iscompatible(proc::ThreadProc, opts, f, args...) = true iscompatible_func(proc::ThreadProc, opts, f) = true iscompatible_arg(proc::ThreadProc, opts, x) = true diff --git a/test/allocations.jl b/test/allocations.jl index 5b70e402b..e009d40b3 100644 --- a/test/allocations.jl +++ b/test/allocations.jl @@ -124,8 +124,9 @@ function alloc_bound(name) bytes=ceil(Int, b.bytes * ALLOC_BOUND_MULTIPLIER)) end -# Pin all work to one processor so results are topology-independent. -const ALLOC_TEST_SCOPE = Dagger.scope(worker=1, thread=1) +# Pin all work to one processor so results are topology-independent. (The +# first default-pool thread: thread 1 is interactive whenever one exists.) +const ALLOC_TEST_SCOPE = Dagger.scope(worker=1, thread=Dagger.first_default_tid()) fmt_bytes(b) = b < 1024 ? "$(b) B" : b < 1024^2 ? string(round(b / 1024; digits=1), " KiB") : diff --git a/test/datadeps.jl b/test/datadeps.jl index 30944ccf2..9b9b6a973 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1025,7 +1025,9 @@ function test_datadeps(;args_chunks::Bool, @test proc in scope_procs end for proc in scope_procs - proc == Dagger.ThreadProc(1, 1) && continue + # These few tasks need not reach the processor running the eager + # scheduler's thunk (worker 1's first default-pool thread) + proc == Dagger.first_thread_proc(1) && continue @test proc in exec_procs end @@ -1135,7 +1137,7 @@ end for nt in (1, 2) if nprocs() >= nw && Threads.nthreads() >= nt @testset "$nw Workers, $nt Threads" begin - Dagger.with_options(;scope=Dagger.scope(workers=1:nw, threads=1:nt)) do + Dagger.with_options(;scope=Dagger.scope(workers=1:nw, threads=Dagger.default_pool_tids()[1:nt])) do test_datadeps(;args_chunks, args_thunks, args_loc) end end diff --git a/test/gpu.jl b/test/gpu.jl index 4f19c1d55..771d269b7 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -110,7 +110,7 @@ end A = rand(Float64, 128) B = zeros(Float64, 128) - Dagger.with_options(scope=Dagger.scope(worker=1,thread=1)) do + Dagger.with_options(scope=Dagger.scope(worker=1,thread=Dagger.first_default_tid())) do fetch(Dagger.@spawn Kernel(copy_kernel)(B, A; ndrange=length(A))) Dagger.gpu_synchronize(:CPU) end diff --git a/test/options.jl b/test/options.jl index 0b2e737ef..ee5da2fe8 100644 --- a/test/options.jl +++ b/test/options.jl @@ -19,7 +19,7 @@ end end Dagger.move(from::Union{OSProc,Dagger.ThreadProc}, to::Dagger.ThreadProc, sf::SpecialFunc) = - (to.owner == 1 && to.tid == 1) ? SpecialFunc(1) : sf + (to.owner == 1 && to.tid == Dagger.first_default_tid()) ? SpecialFunc(1) : sf end option_default_target(x; ignored=nothing) = x @@ -114,12 +114,12 @@ end sf = SpecialFunc(0) obj = Dagger.tochunk(42) if nprocs() > 1 - Dagger.with_options(;scope=Dagger.ExactScope(Dagger.ThreadProc(first_wid,1))) do + Dagger.with_options(;scope=Dagger.ExactScope(Dagger.first_thread_proc(first_wid))) do @test fetch(Dagger.@spawn sf(obj)) == 0 @test fetch(Dagger.@spawn sf(obj)) == 0 end end - Dagger.with_options(;scope=Dagger.ExactScope(Dagger.ThreadProc(1,1)), meta=true) do + Dagger.with_options(;scope=Dagger.ExactScope(Dagger.first_thread_proc(1)), meta=true) do @test fetch(Dagger.@spawn sf(obj)) == 43 @test fetch(Dagger.@spawn sf(obj)) == 43 end @@ -130,7 +130,7 @@ end # filter, or reorder them, however many tasks are spawned. scoped_props = Symbol[:scope] Dagger.with_options(; propagates=scoped_props, - scope=Dagger.ExactScope(Dagger.ThreadProc(1,1))) do + scope=Dagger.ExactScope(Dagger.first_thread_proc(1))) do @test fetch(Dagger.@spawn 1+1) == 2 @test fetch(Dagger.@spawn 1+1) == 2 end diff --git a/test/processors.jl b/test/processors.jl index 0544da90a..4adbe7365 100644 --- a/test/processors.jl +++ b/test/processors.jl @@ -101,4 +101,59 @@ end end @test Dagger.num_processors(;all=true) == length(all_procs) end + + @testset "ThreadProcs are the default thread pool" begin + # Holds however this process was started, including with an + # interactive thread (Julia 1.12's default). + thread_tids(pid) = sort!([p.tid for p in get_processors(OSProc(pid)) if p isa ThreadProc]) + @test thread_tids(myid()) == Threads.threadpooltids(:default) + @test Dagger.first_default_tid() == first(Threads.threadpooltids(:default)) + + # Make sure an interactive thread exists, whatever the Julia version or + # the flags this suite was started with. It takes thread 1, so the + # default pool is threads 2 and 3. + script = """ + using Dagger + default_tids = Threads.threadpooltids(:default) + interactive_tids = Threads.threadpooltids(:interactive) + threadprocs = sort!([p for p in Dagger.get_processors(Dagger.OSProc()) + if p isa Dagger.ThreadProc]; by=p->p.tid) + proc_tids = [p.tid for p in threadprocs] + # Where a task pinned to each ThreadProc actually runs + exact_tids = [fetch(Dagger.@spawn scope=Dagger.ExactScope(p) Threads.threadid()) + for p in threadprocs] + # Where unconstrained tasks run + sleep_tid() = (sleep(0.05); Threads.threadid()) + free_tids = sort!(unique(fetch.([Dagger.@spawn sleep_tid() for _ in 1:16]))) + println(repr((; default_tids, interactive_tids, proc_tids, exact_tids, + free_tids))) + """ + # Resolve packages and preferences (the transport) like this process + load_path = join(Base.load_path(), Sys.iswindows() ? ';' : ':') + cmd = addenv(`$(Base.julia_cmd()) --startup-file=no -t 2,1 -e $script`, + "JULIA_LOAD_PATH" => load_path) + out = IOBuffer() + child = run(pipeline(cmd; stdout=out, stderr=out); wait=false) + deadline = time() + 600 + while process_running(child) && time() < deadline + sleep(0.5) + end + process_running(child) && kill(child, Base.SIGKILL) + wait(child) + output = String(take!(out)) + @test success(child) + if !success(child) + println(stderr, "Interactive-thread subprocess output:\n", output) + else + result = eval(Meta.parse(last(split(chomp(output), '\n')))) + @test result.interactive_tids == [1] + @test result.default_tids == [2, 3] + # A ThreadProc for every default thread, and none for the + # interactive one + @test result.proc_tids == result.default_tids + @test result.exact_tids == result.default_tids + @test isempty(intersect(result.free_tids, result.interactive_tids)) + @test result.free_tids ⊆ result.default_tids + end + end end diff --git a/test/scheduler.jl b/test/scheduler.jl index 23292605d..1fa1dc85c 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -391,8 +391,8 @@ end end state = Dagger.Sch.EAGER_STATE[] - tproc1_1 = Dagger.ThreadProc(1, 1) - tproc2_1 = Dagger.ThreadProc(first(workers()), 1) + tproc1_1 = Dagger.first_thread_proc(1) + tproc2_1 = Dagger.first_thread_proc(first(workers())) procs = [tproc1_1, tproc2_1] # Ensure that this worker has been used at least once @@ -779,7 +779,7 @@ end @testset "Cancellation" begin # Ready task cancellation start_time = time_ns() - t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=1) sleep(100) + t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=Dagger.first_default_tid()) sleep(100) Dagger.cancel!(t) @test timedwait(()->istaskdone(t), 10) == :ok if istaskdone(t) @@ -789,7 +789,7 @@ end # Running task cancellation start_time = time_ns() - t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=1) sleep(100) + t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=Dagger.first_default_tid()) sleep(100) sleep(0.1) # Give the scheduler a chance to schedule the task Dagger.cancel!(t) @test timedwait(()->istaskdone(t), 10) == :ok @@ -800,7 +800,7 @@ end # Normal task execution start_time = time_ns() - t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=1) yield() + t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=Dagger.first_default_tid()) yield() @test timedwait(()->istaskdone(t), 10) == :ok if istaskdone(t) @test (time_ns() - start_time) * 1e-9 < 100 diff --git a/test/scopes.jl b/test/scopes.jl index c448bf2ca..bc724ffb7 100644 --- a/test/scopes.jl +++ b/test/scopes.jl @@ -27,7 +27,10 @@ ps1_ch = Dagger.tochunk(nothing, OSProc(), ps1) ps2_ch = Dagger.tochunk(nothing, OSProc(), ps2) - es1, es2 = ExactScope(Dagger.ThreadProc(wid1, 1)), ExactScope(Dagger.ThreadProc(wid2, 2)) + # The workers' first two threads: not 1 and 2 when they have an + # interactive thread (Julia 1.12+ adds one to `-t2`) + t1, t2 = remotecall_fetch(Dagger.default_pool_tids, wid1) + es1, es2 = ExactScope(Dagger.ThreadProc(wid1, t1)), ExactScope(Dagger.ThreadProc(wid2, t2)) es1_ch = Dagger.tochunk(nothing, OSProc(), es1) es2_ch = Dagger.tochunk(nothing, OSProc(), es2) @@ -96,11 +99,11 @@ # One process ts = fetch.([Dagger.@spawn exact_scope_test(isodd(i) ? es1_ch : es2_ch) for i in 1:20]) @test all(x->x.owner==wid1, ts[1:2:20]) - @test all(x->x.owner==wid2&&x.tid==2, ts[2:2:20]) + @test all(x->x.owner==wid2&&x.tid==t2, ts[2:2:20]) # Same process t = fetch(Dagger.@spawn exact_scope_test(es1_ch, es1_ch)) - @test t.owner == wid1 && t.tid == 1 + @test t.owner == wid1 && t.tid == t1 # Different process, different processor for (ch1, ch2) in [(es1_ch, es2_ch), (es2_ch, es1_ch)] @@ -108,7 +111,7 @@ end # Same process, different processor - es1_2 = ExactScope(Dagger.ThreadProc(wid1, 2)) + es1_2 = ExactScope(Dagger.ThreadProc(wid1, t2)) es1_2_ch = Dagger.tochunk(nothing, OSProc(), es1_2) for (ch1, ch2) in [(es1_ch, es1_2_ch), (es1_2_ch, es1_ch)] @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason<"Current scope and argument Chunk scope are not compatible:" fetch(Dagger.@spawn ch1 + ch2) @@ -255,13 +258,13 @@ @test all(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid1))) @test !any(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid2))) - scope = Dagger.scope(worker=wid1, thread=2) + scope = Dagger.scope(worker=wid1, thread=t2) comp_procs = Dagger.compatible_processors(scope) @test Dagger.num_processors(scope) == length(comp_procs) @test length(comp_procs) == 1 @test !all(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid1))) @test !all(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid2))) - @test Dagger.ThreadProc(wid1, 2) in comp_procs + @test Dagger.ThreadProc(wid1, t2) in comp_procs scope = Dagger.scope(workers=[wid1, wid2]) comp_procs = Dagger.compatible_processors(scope) @@ -275,7 +278,7 @@ @testset "scope comparison" begin scope1 = Dagger.scope(worker=wid1) - scope2 = Dagger.scope(worker=wid1, thread=1) + scope2 = Dagger.scope(worker=wid1, thread=t1) @test issubset(scope2, scope1) @test !issubset(scope1, scope2) @test issetequal(scope1, scope1) diff --git a/test/streaming.jl b/test/streaming.jl index 6e0b57f66..afcb8549c 100644 --- a/test/streaming.jl +++ b/test/streaming.jl @@ -412,12 +412,13 @@ Base.take!(b::ParkSignalBuffer) = take!(b.inner) end all_scopes = [Dagger.ExactScope(proc) for proc in Dagger.all_processors()] +# Each worker's first thread is not thread 1 when it has an interactive thread for idx in 1:5 if idx == 1 - scopes = [Dagger.scope(worker = 1, thread = 1)] + scopes = [Dagger.ExactScope(Dagger.first_thread_proc(1))] scope_str = "Worker 1" elseif idx == 2 && nprocs() > 1 - scopes = [Dagger.scope(worker = 2, thread = 1)] + scopes = [Dagger.ExactScope(Dagger.first_thread_proc(2))] scope_str = "Worker 2" else scopes = all_scopes diff --git a/test/task-affinity.jl b/test/task-affinity.jl index 58a7b5c21..f773859f8 100644 --- a/test/task-affinity.jl +++ b/test/task-affinity.jl @@ -40,7 +40,7 @@ availscopes = shuffle!(Dagger.ExactScope.(availprocs)) numscopes = length(availscopes) - master_proc = Dagger.ThreadProc(1, 1) + master_proc = Dagger.first_thread_proc(1) master_scope = Dagger.ExactScope(master_proc) @testset "scope, compute_scope and result_scope" begin diff --git a/test/thunk.jl b/test/thunk.jl index f1490170b..dc91a707b 100644 --- a/test/thunk.jl +++ b/test/thunk.jl @@ -388,7 +388,8 @@ end @testset "parent fetch child, one thread" begin # Issue #282 - s = p -> p == Dagger.ThreadProc(1, 1) + thread1 = Dagger.first_thread_proc(1) + s = p -> p == thread1 f = (x) -> 10 + x g = (x) -> fetch(Dagger.@spawn proclist=s f(x)) fetch(Dagger.@spawn proclist=s g(10)) From ebc75f24c16f4b48598b6479161cf1638ba16afa Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:32:44 -0700 Subject: [PATCH 25/59] procgrid: assign worker IDs to each worker's first default thread An integer `assignment` array maps each block to "the first CPU thread of the worker" (as docs/src/darray.md says), but the code built `ThreadProc(proc, 1)`. When the worker has an interactive thread, thread 1 is that thread, which no longer has a ThreadProc, so blocks were placed on a processor the scheduler does not know. Use the worker's lowest-numbered registered ThreadProc instead. Co-Authored-By: Claude Opus 5.5 --- src/procgrid.jl | 2 +- test/array/allocation.jl | 6 +++++- test/processors.jl | 6 +++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/procgrid.jl b/src/procgrid.jl index c23d311b8..bd9cc9dda 100644 --- a/src/procgrid.jl +++ b/src/procgrid.jl @@ -103,7 +103,7 @@ function build_procgrid(assignment::AssignmentType{N}, sizeA::NTuple{N,Int}, elseif assignment isa AbstractArray{<:Int, N} missingprocs = filter(p -> p ∉ procs(), assignment) isempty(missingprocs) || error("Specified workers are not available: $missingprocs") - return DenseProcGrid([ThreadProc(proc, 1) for proc in assignment]) + return DenseProcGrid([first_thread_proc(proc) for proc in assignment]) elseif assignment isa AbstractArray{<:Processor, N} missingprocs = filter(p -> p ∉ availprocs, assignment) isempty(missingprocs) || error("Specified processors are not available: $missingprocs") diff --git a/test/array/allocation.jl b/test/array/allocation.jl index 4548f3ed1..645b76a75 100644 --- a/test/array/allocation.jl +++ b/test/array/allocation.jl @@ -471,8 +471,12 @@ test_assignment_strategy(:cyclicrow, get_cyclicrow_procgrid) test_assignment_strategy(:cycliccol, get_cycliccol_procgrid) @testset "OSProc ID Array Assignment (AbstractArray{<:Int, N})" begin + # Each worker's first CPU thread, which is not thread 1 when the worker + # has an interactive thread + first_tid(proc) = proc == myid() ? first(Threads.threadpooltids(:default)) : + remotecall_fetch(() -> first(Threads.threadpooltids(:default)), proc) function get_random_threadprocs(proc_ids) - [ThreadProc(proc, 1) for proc in proc_ids] + [ThreadProc(proc, first_tid(proc)) for proc in proc_ids] end rand_osproc_ids_A = rand(procs(), 3, 2, 2) diff --git a/test/processors.jl b/test/processors.jl index 4adbe7365..8b9a214b8 100644 --- a/test/processors.jl +++ b/test/processors.jl @@ -125,8 +125,11 @@ end # Where unconstrained tasks run sleep_tid() = (sleep(0.05); Threads.threadid()) free_tids = sort!(unique(fetch.([Dagger.@spawn sleep_tid() for _ in 1:16]))) + # Worker-ID assignment picks the worker's first CPU thread + A = Dagger.distribute(ones(4, 4), Dagger.Blocks(2, 2), fill(1, 2, 2)) + grid_tids = sort!(unique([fetch(c; raw=true).processor.tid for c in A.chunks])) println(repr((; default_tids, interactive_tids, proc_tids, exact_tids, - free_tids))) + free_tids, grid_tids))) """ # Resolve packages and preferences (the transport) like this process load_path = join(Base.load_path(), Sys.iswindows() ? ';' : ':') @@ -154,6 +157,7 @@ end @test result.exact_tids == result.default_tids @test isempty(intersect(result.free_tids, result.interactive_tids)) @test result.free_tids ⊆ result.default_tids + @test result.grid_tids == [first(result.default_tids)] end end end From 59f827a255b9d57afe51074d17465bf294447f71 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:32:44 -0700 Subject: [PATCH 26/59] MPIExt: run spectator copies on a default-pool thread Ranks that are neither end of an in-place copy execute it on a plain ThreadProc so that no unrelated GPU context is activated. That was `ThreadProc(myid(), 1)`, which is the interactive thread whenever one exists (test/mpi/run.jl's `--threads=2` gives each rank one on Julia 1.12). Use the first default-pool thread, which Dagger actually schedules on. `first_default_tid` does not allocate, since this runs for every copy on every spectator rank. Co-Authored-By: Claude Opus 5.5 --- ext/MPIExt.jl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index aa068553a..871939173 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2502,7 +2502,9 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) elseif local_rank == from_space.rank first(processors(from_space.innerSpace)) else - ThreadProc(myid(), 1) + # The first default-pool thread; thread 1 is interactive + # whenever an interactive thread exists. + ThreadProc(myid(), Dagger.first_default_tid()) end execute!(local_proc, f, raw_args...; kwargs...) space = memory_space(nothing, proc)::MPIMemorySpace From 60dfb7a9a63b625d1ee299e916f0554421489db4 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:32:44 -0700 Subject: [PATCH 27/59] AGENTS.md: thread 1 is not always a Dagger thread Record why `1:nthreads()` and literal thread 1 are wrong once an interactive thread exists, and which CI configurations can see it. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 03120cce2..5c5b849ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1108,3 +1108,20 @@ this section verbatim). Each entry is one bullet starting with `- `. (`mpi_slot_alloc`) rather than copying it afterwards; the copy leaves a GC-managed buffer of the same size behind, which for 16 8 MB slots per region was 989 MiB of GC allocation and 35 collections over 8 regions. + +102. **Thread 1 is not always a Dagger thread.** Julia numbers interactive + threads first and, since 1.12, starts one by default (`-t N` means N + default threads plus one interactive; `-t N,1` does the same on 1.10 and + 1.11). Thread 1 is then interactive, the main task and REPL run on it, and + the default pool is threads `2:N+1`. `Threads.nthreads()` counts only the + default pool, so `1:nthreads()` is the wrong set: registering ThreadProcs + for it ran Dagger tasks on the interactive thread and never on the last + default thread. ThreadProcs come from `default_pool_tids()`; where code + means "the first thread", use `first_default_tid()` (or, for another + worker, its lowest-tid ThreadProc), never a literal `1`. A scope naming a + thread with no processor (`ExactScope(ThreadProc(1, 1))`) fails to + schedule rather than falling back, so a stray literal breaks only on + configurations with an interactive thread. In CI those are the 1.12+ + multithreaded jobs (`-t auto`) and MPI ranks (`--threads=2`), not 1.10/1.11 + or the distributed job (`JULIA_NUM_THREADS=1`); the processors suite runs a + `-t 2,1` subprocess so every version covers it. From 9c080ee47d7553b424b07bb80bf90e6e9c5b67e1 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:45:13 -0700 Subject: [PATCH 28/59] Show how to migrate exact CPU scopes to default-pool threads Review finding 1 on PR #841 (blocker): Published thread-1 placements fail when thread 1 is interactive Requested: address as reported; the solution below is the agent's. Explain that exact CPU scopes use the selected worker's Julia thread IDs. The task-affinity and explicit DArray examples discover each worker's processors before selecting a thread. Integer assignments document their first-default-thread behavior as another migration path. On Julia 1.12.6 the old chunk-argument example failed when the selected worker's thread 1 was interactive. The revised examples passed 10/10 checks across workers with zero, one and two interactive threads. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/darray.md | 27 ++++++++++++++-------- docs/src/task-affinity.md | 48 +++++++++++++++++++++++++++------------ 2 files changed, 52 insertions(+), 23 deletions(-) diff --git a/docs/src/darray.md b/docs/src/darray.md index 76d909290..566765f69 100644 --- a/docs/src/darray.md +++ b/docs/src/darray.md @@ -244,12 +244,13 @@ The `assignment` argument accepts the following values: * `AbstractArray{<:Int, N}`: * Provide an integer **N**-dimensional array of worker IDs. The dimension **N** must match the number of dimensions of the `DArray`. - * Dagger maps blocks to worker IDs in a block-cyclic manner according to this processor-array. The block at index `(i,j,...)` is assigned to the first CPU thread of the worker with ID `assignment[mod1(i, size(assignment,1)), mod1(j, size(assignment,2)), ...]`. This pattern repeats block-cyclically across all dimensions. + * The block at index `(i,j,...)` is assigned to the first default-pool CPU thread of the worker with ID `assignment[mod1(i, size(assignment,1)), mod1(j, size(assignment,2)), ...]`. This pattern repeats block-cyclically across all dimensions. * `AbstractArray{<:Processor, N}`: * Provide an **N**-dimensional array of `Processor` objects. The dimension **N** must match the number of dimensions of the `DArray` blocks. * Blocks are mapped in a block-cyclic manner according to the `Processor` objects in the assignment array. The block at index `(i,j,...)` is assigned to the processor at `assignment[mod1(i, size(assignment,1)), mod1(j, size(assignment,2)), ...]`. This pattern repeats block-cyclically across all dimensions. + * Each explicit `ThreadProc(worker, tid)` must name a registered default-pool thread on that worker. If existing code uses `ThreadProc(worker, 1)` to mean the first CPU thread, use an integer worker assignment or look up its registered CPU processors as shown below. #### Examples and Usage @@ -265,7 +266,10 @@ The `assignment` argument works similarly for `DArray`, `DVector`, and `DMatrix` * `rand`, `randn`, `sprand`, `ones`, `zeros`: Functions to create DArrays with initial values, also supporting `assignment`. -Here are some examples using a setup with one master process and three worker processes. +Here are some examples using one master process and three worker processes. The +sample outputs show a configuration without interactive threads. Julia assigns +interactive thread IDs first when that pool is enabled, so the default-pool IDs +can differ across workers. First, let's create some sample arrays for `distribute` (and constructor functions): @@ -419,7 +423,7 @@ M = zeros(5, 5, 5) # 3D array # distribute(sprand(7,11, 0.2), Blocks(2, 2), assignment_2d) ``` - The assignment is an integer matrix of worker IDs, the blocks are assigned in block-cyclic manner to the first CPU thread of each worker. The assignment for `Ad` (and `Rd`) would be: + The assignment is an integer matrix of worker IDs. Blocks are assigned in a block-cyclic manner to the first default-pool CPU thread of each worker. The assignment for `Ad` (and `Rd`) would be: ```julia 4×6 Matrix{Dagger.ThreadProc}: @@ -431,21 +435,26 @@ M = zeros(5, 5, 5) # 3D array 4. **Block-Cyclic Assignment with Processor Array:** + This example assumes at least three default-pool threads on each process. + ```julia - assignment_2d = [Dagger.ThreadProc(3, 2) Dagger.ThreadProc(1, 1); - Dagger.ThreadProc(4, 3) Dagger.ThreadProc(2, 2)] + cpu_procs(worker) = sort!([p for p in Dagger.get_processors(Dagger.OSProc(worker)) + if p isa Dagger.ThreadProc]; by=p -> p.tid) + cpus1, cpus2, cpus3, cpus4 = cpu_procs.(1:4) + + assignment_2d = [cpus3[2] cpus1[1]; cpus4[3] cpus2[2]] Ad = distribute(A, Blocks(2, 2), assignment_2d) # DMatrix(A, Blocks(2, 2), assignment_2d) - assignment_1d = [Dagger.ThreadProc(2,1), Dagger.ThreadProc(3,1), Dagger.ThreadProc(1,1), Dagger.ThreadProc(4,1)] + assignment_1d = [cpus2[1], cpus3[1], cpus1[1], cpus4[1]] vd = distribute(v, Blocks(3), assignment_1d) # DVector(v, Blocks(3), assignment_1d) - assignment_3d = cat([Dagger.ThreadProc(1,1) Dagger.ThreadProc(2,1); Dagger.ThreadProc(3,1) Dagger.ThreadProc(4,1)], - [Dagger.ThreadProc(4,1) Dagger.ThreadProc(3,1); Dagger.ThreadProc(2,1) Dagger.ThreadProc(1,1)], dims=3) + assignment_3d = cat([cpus1[1] cpus2[1]; cpus3[1] cpus4[1]], + [cpus4[1] cpus3[1]; cpus2[1] cpus1[1]], dims=3) Md = distribute(M, Blocks(2, 2, 2), assignment_3d) # DArray(M, Blocks(2, 2, 2), assignment_3d) - Rd = rand(Blocks(2, 2), 7, 11; assignment=assignment_2d)) + Rd = rand(Blocks(2, 2), 7, 11; assignment=assignment_2d) # distribute(rand(7,11), Blocks(2, 2), assignment_2d) ``` diff --git a/docs/src/task-affinity.md b/docs/src/task-affinity.md index 53303923e..53aacd731 100644 --- a/docs/src/task-affinity.md +++ b/docs/src/task-affinity.md @@ -4,6 +4,21 @@ Dagger's allows for precise control over task placement and result availability For more information on how scopes work, see [Scopes](@ref). +CPU scopes use the selected worker's Julia thread IDs. Dagger registers only +default-pool threads as CPU processors. If Julia gives thread 1 to the +interactive pool, a scope limited to that thread has no eligible CPU processor. +To migrate `thread=1` code that meant the first compute thread, use the first +registered CPU thread ID on the target worker. + +The examples below assume processes 1 through 4 each have at least four default +threads. Look up their IDs once before constructing the scopes. + +```julia +cpu_tids(worker) = sort!([p.tid for p in Dagger.get_processors(Dagger.OSProc(worker)) + if p isa Dagger.ThreadProc]) +tids1, tids2, tids3, tids4 = cpu_tids.(1:4) +``` + --- ## Task Scopes @@ -26,10 +41,11 @@ Like `scope`, `compute_scope` also specifies where a Dagger task can execute. Th **Example:** ```julia -g1 = Dagger.@spawn scope=Dagger.scope(worker=2,thread=3) compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) f(x,y) -g2 = Dagger.@spawn compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) f(x,y) +compute_scope = Dagger.scope((worker=1, thread=tids1[2]), (worker=3, thread=tids3[1])) +g1 = Dagger.@spawn scope=Dagger.scope(worker=2, thread=tids2[3]) compute_scope=compute_scope f(x,y) +g2 = Dagger.@spawn compute_scope=compute_scope f(x,y) ``` -Tasks `g1` and `g2` execute on either thread 2 of worker 1, or thread 1 of worker 3. The `scope` argument to `g1` is ignored. Their result can be accessed by any worker. +Tasks `g1` and `g2` execute on either the second default thread of worker 1 or the first default thread of worker 3. The `scope` argument to `g1` is ignored. Their result can be accessed by any worker. --- @@ -39,9 +55,9 @@ The result_scope limits the processors from which a task's result can be accesse **Example:** ```julia -g = Dagger.@spawn result_scope=Dagger.scope(worker=3, threads=[1, 3, 4]) f(x,y) +g = Dagger.@spawn result_scope=Dagger.scope(worker=3, threads=tids3[[1, 3, 4]]) f(x,y) ``` -The result of `g` is accessible only from threads 1, 3 and 4 of worker process 3. The task's execution may happen anywhere on threads 1, 3 and 4 of worker 3. +The result of `g` is accessible only from the first, third, and fourth default threads of worker 3. The task may execute on any of those threads. --- @@ -51,9 +67,10 @@ When `scope`/`compute_scope` and `result_scope` are specified, the scheduler exe **Example:** ```julia -g = Dagger.@spawn scope=Dagger.scope(worker=3,thread=2) compute_scope=Dagger.scope(worker=2) result_scope=Dagger.scope((worker=2, thread=2), (worker=4, thread=2)) f(x,y) +result_scope = Dagger.scope((worker=2, thread=tids2[2]), (worker=4, thread=tids4[2])) +g = Dagger.@spawn scope=Dagger.scope(worker=3, thread=tids3[2]) compute_scope=Dagger.scope(worker=2) result_scope=result_scope f(x,y) ``` -The task `g` computes on thread 2 of worker 2 (as it's the intersection of compute and result scopes), but accessng its result is restricted to thread 2 of worker 2 and thread 2 of worker 4. +The task `g` computes on the second default thread of worker 2, the intersection of the compute and result scopes. The second default threads of workers 2 and 4 can access its result. --- @@ -76,10 +93,11 @@ chunk_proc = Dagger.OSProc(3) # not important, just needs to be a valid processo g(x, y) = x * 2 + y * 3 g_chunk = Dagger.tochunk(g, chunk_proc, chunk_scope) h1 = Dagger.@spawn scope=Dagger.scope(worker=3) g_chunk(10, 11) -h2 = Dagger.@spawn compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) g_chunk(20, 21) -h3 = Dagger.@spawn scope=Dagger.scope(worker=2,thread=3) compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) g_chunk(30, 31) +compute_scope = Dagger.scope((worker=1, thread=tids1[2]), (worker=3, thread=tids3[1])) +h2 = Dagger.@spawn compute_scope=compute_scope g_chunk(20, 21) +h3 = Dagger.@spawn scope=Dagger.scope(worker=2, thread=tids2[3]) compute_scope=compute_scope g_chunk(30, 31) h4 = Dagger.@spawn result_scope=Dagger.scope(worker=3) g_chunk(40, 41) -h5 = Dagger.@spawn scope=Dagger.scope(worker=3,thread=2) compute_scope=Dagger.scope(worker=3) result_scope=Dagger.scope(worker=3,threads=[2,3]) g_chunk(50, 51) +h5 = Dagger.@spawn scope=Dagger.scope(worker=3, thread=tids3[2]) compute_scope=Dagger.scope(worker=3) result_scope=Dagger.scope(worker=3, threads=tids3[2:3]) g_chunk(50, 51) ``` In all these cases (`h1` through `h5`), the tasks get executed on any processor within `chunk_scope` and its result is accessible only within `chunk_scope`. @@ -105,8 +123,9 @@ Task `h` executes on any worker within the intersection of `scope` and `arg_scop If `arg_scope` and `compute_scope` do not intersect, the scheduler throws an exception. Otherwise, execution happens on the intersection of the effective compute scope (which will be `compute_scope` if provided, otherwise `scope`) and `arg_scope`. ```julia -h1 = Dagger.@spawn compute_scope=Dagger.scope((worker=1, thread=2), (worker=2, thread=1)) g(arg, 11) -h2 = Dagger.@spawn scope=Dagger.scope(worker=2,thread=3) compute_scope=Dagger.scope((worker=1, thread=2), (worker=2, thread=1)) g(arg, 21) +compute_scope = Dagger.scope((worker=1, thread=tids1[2]), (worker=2, thread=tids2[1])) +h1 = Dagger.@spawn compute_scope=compute_scope g(arg, 11) +h2 = Dagger.@spawn scope=Dagger.scope(worker=2, thread=tids2[3]) compute_scope=compute_scope g(arg, 21) ``` Tasks `h1` and `h2` execute on any processor within the intersection of the `compute_scope` and `arg_scope`. `scope` is ignored if `compute_scope` is specified. The result is accessible from any processor. @@ -126,6 +145,7 @@ Task `h` executes on any processor within the intersection of `arg_scope` and `r When `scope`/`compute_scope`, `result_scope`, and `Chunk` argument scopes are all used, the scheduler executes the task on the intersection of `arg_scope`, the effective compute scope (which is `compute_scope` if provided, otherwise `scope`), and `result_scope`. If no intersection exists, the scheduler throws an exception. ```julia -h = Dagger.@spawn scope=Dagger.scope(worker=3,thread=2) compute_scope=Dagger.scope(worker=2) result_scope=Dagger.scope((worker=2, thread=2), (worker=4, thread=2)) g(arg, 31) +result_scope = Dagger.scope((worker=2, thread=tids2[2]), (worker=4, thread=tids4[2])) +h = Dagger.@spawn scope=Dagger.scope(worker=3, thread=tids3[2]) compute_scope=Dagger.scope(worker=2) result_scope=result_scope g(arg, 31) ``` -Task `h` computes on thread 2 of worker 2 (as it's the intersection of `arg_scope`, `compute_scope`, and `result_scope`), and its result access is restricted to thread 2 of worker 2 or thread 2 of worker 4. +Task `h` computes on the second default thread of worker 2, the intersection of `arg_scope`, `compute_scope`, and `result_scope`. The second default threads of workers 2 and 4 can access its result. From 0ec9b8993d5b5ab9e7cf6f49d81b94df1b3efa96 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:50:21 -0700 Subject: [PATCH 29/59] Resolve each worker once per integer processor grid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding 3 on PR #841 (should-fix): Integer DArray assignment rescans each worker’s processor set per grid entry Requested: address as reported; the solution below is the agent's. Snapshot available worker IDs once and reuse each worker's first registered CPU processor across its entries. Fill the final processor array directly and keep the existing direct path for empty and singleton grids so they need no lookup table. On Julia 1.12.6 at -t 4,1, a 256-by-256 grid with one repeated worker ID went from 262189 allocations and 11536008 bytes to 51 allocations and 1050784 bytes per call. The singleton stayed at 46 allocations and 1744 bytes. These are minima of five GC-delta samples after ten warmup calls. The probe also checked inferred grid types, processor IDs and invalid worker rejection. The processor grid suite passed 1782/1782. Written by an AI agent on jpsamaroo's review feedback. --- src/procgrid.jl | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/procgrid.jl b/src/procgrid.jl index bd9cc9dda..d7fb4a046 100644 --- a/src/procgrid.jl +++ b/src/procgrid.jl @@ -101,9 +101,21 @@ function build_procgrid(assignment::AssignmentType{N}, sizeA::NTuple{N,Int}, error("Unsupported assignment symbol: $assignment, use :arbitrary, :blockrow, :blockcol, :cyclicrow or :cycliccol") end elseif assignment isa AbstractArray{<:Int, N} - missingprocs = filter(p -> p ∉ procs(), assignment) + available_workers = procs() + missingprocs = filter(p -> p ∉ available_workers, assignment) isempty(missingprocs) || error("Specified workers are not available: $missingprocs") - return DenseProcGrid([first_thread_proc(proc) for proc in assignment]) + if length(assignment) <= 1 + return DenseProcGrid([first_thread_proc(pid) for pid in assignment]) + end + # Match the grid's element type so repeated entries reuse the same box. + first_procs = Dict{Int,Processor}() + grid = Array{Processor,N}(undef, size(assignment)) + for (index, pid) in enumerate(assignment) + grid[index] = get!(first_procs, pid) do + first_thread_proc(pid) + end + end + return DenseProcGrid{N}(grid) elseif assignment isa AbstractArray{<:Processor, N} missingprocs = filter(p -> p ∉ availprocs, assignment) isempty(missingprocs) || error("Specified processors are not available: $missingprocs") From 6e38727efb1723746b6be540b97f95f1f6f3a0ff Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sun, 29 Nov 2026 18:44:13 -0700 Subject: [PATCH 30/59] test: exercise an MPI copy with a separate spectator Review finding F4 (should-fix) on PR #841: The MPI spectator change needs final-head evidence and a lasting three-rank case. Use a copy modifier that records the actual execution thread before the ordinary move. Check the payload on every rank and the thread on each spectator. The focused probe passed on three MPICH ranks with two default threads and one interactive thread each. Written by an AI agent on jpsamaroo's review feedback. --- test/mpi/cpu.jl | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 78ae0d054..8c2a46c21 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -61,6 +61,30 @@ proc_for_rank(r) = first(filter(p->p.rank == r, mpi_procs())) space_for_rank(r) = MPIExt.MPIMemorySpace(Dagger.CPURAMMemorySpace(1), comm, r) rank_scope(r) = Dagger.ExactScope(proc_for_rank(r)) +struct SpectatorThreadCopy end +const spectator_copy_tid = Ref(0) +function Dagger.move!(::SpectatorThreadCopy, to_space::MPIExt.MPIMemorySpace, + from_space::MPIExt.MPIMemorySpace, to::Dagger.Chunk, from::Dagger.Chunk) + spectator_copy_tid[] = Threads.threadid() + return Dagger.move!(identity, to_space, from_space, to, from) +end + +@testset "MPI copy spectators use the default thread pool" begin + if nranks >= 3 + src_space, dst_space = space_for_rank(0), space_for_rank(1) + payload = collect(1:4) + src = Dagger.tochunk(payload, proc_for_rank(0), src_space) + dst = Dagger.tochunk(zeros(Int, 4), proc_for_rank(1), dst_space) + copy_task = Dagger.@spawn scope=rank_scope(1) meta=true Dagger.move!( + SpectatorThreadCopy(), dst_space, src_space, dst, src) + wait(copy_task) + if rank >= 2 + @test spectator_copy_tid[] == first(Threads.threadpooltids(:default)) + end + @test fetch(dst) == payload + end +end + # Rank pairs for slot tests (mirrors Distributed's worker pairs), including a # same-rank pair to check that origin slots alias the original data const rank_pairs = if nranks >= 3 From 5450ce2f6c9ad6ee6096a65d8c47b02c5cff7526 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sun, 29 Nov 2026 18:44:13 -0700 Subject: [PATCH 31/59] test: assign DArray tiles to a worker with a different thread pool Review finding F3 (should-fix) on PR #841: The mixed-pool grid regression has no committed test. Run the placement test with one interactive thread on the driver and two on the worker. Verify that integer assignments use the worker's own first default thread and that the tile data survives collection. Written by an AI agent on jpsamaroo's review feedback. --- test/processors.jl | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/test/processors.jl b/test/processors.jl index 8b9a214b8..570a28669 100644 --- a/test/processors.jl +++ b/test/processors.jl @@ -114,6 +114,10 @@ end # default pool is threads 2 and 3. script = """ using Dagger + const Distributed = parentmodule(Dagger.myid) + using .Distributed + worker = only(addprocs(1; exeflags=`--project=\$(Base.active_project()) -t 2,2`)) + @everywhere using Dagger default_tids = Threads.threadpooltids(:default) interactive_tids = Threads.threadpooltids(:interactive) threadprocs = sort!([p for p in Dagger.get_processors(Dagger.OSProc()) @@ -122,14 +126,22 @@ end # Where a task pinned to each ThreadProc actually runs exact_tids = [fetch(Dagger.@spawn scope=Dagger.ExactScope(p) Threads.threadid()) for p in threadprocs] - # Where unconstrained tasks run + # Where tasks scoped to this worker run without an exact thread sleep_tid() = (sleep(0.05); Threads.threadid()) - free_tids = sort!(unique(fetch.([Dagger.@spawn sleep_tid() for _ in 1:16]))) + free_tids = sort!(unique(fetch.( + [Dagger.@spawn scope=Dagger.scope(worker=myid()) sleep_tid() for _ in 1:16]))) # Worker-ID assignment picks the worker's first CPU thread A = Dagger.distribute(ones(4, 4), Dagger.Blocks(2, 2), fill(1, 2, 2)) grid_tids = sort!(unique([fetch(c; raw=true).processor.tid for c in A.chunks])) + worker_first_tid = first(remotecall_fetch(Threads.threadpooltids, worker, :default)) + data = reshape(collect(1:16), 4, 4) + B = Dagger.distribute(data, Dagger.Blocks(2, 2), fill(worker, 2, 2)) + mixed_grid = unique([fetch(c; raw=true).processor for c in B.chunks]) + mixed_grid_ok = mixed_grid == [Dagger.ThreadProc(worker, worker_first_tid)] && + collect(B) == data + rmprocs(worker) println(repr((; default_tids, interactive_tids, proc_tids, exact_tids, - free_tids, grid_tids))) + free_tids, grid_tids, worker_first_tid, mixed_grid_ok))) """ # Resolve packages and preferences (the transport) like this process load_path = join(Base.load_path(), Sys.iswindows() ? ';' : ':') @@ -158,6 +170,8 @@ end @test isempty(intersect(result.free_tids, result.interactive_tids)) @test result.free_tids ⊆ result.default_tids @test result.grid_tids == [first(result.default_tids)] + @test result.worker_first_tid == 3 + @test result.mixed_grid_ok end end end From d63a9d517c6473a3914bc1e60cdac999a1137ca2 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sun, 29 Nov 2026 20:35:15 -0700 Subject: [PATCH 32/59] test: assert processor placement inside the subprocess Julia prerelease jobs can include trailing output after a successful child run. The parent treated that line as the result and raised field errors. Run all nine placement assertions inside the child and use the exit status, preserving captured stdout and stderr for diagnostics. Written by an AI agent on jpsamaroo's review feedback. --- test/processors.jl | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/test/processors.jl b/test/processors.jl index 48e3f2a6c..d2ecbaa23 100644 --- a/test/processors.jl +++ b/test/processors.jl @@ -122,7 +122,7 @@ end # the flags this suite was started with. It takes thread 1, so the # default pool is threads 2 and 3. script = """ - using Dagger + using Dagger, Test const Distributed = parentmodule(Dagger.myid) using .Distributed worker = only(addprocs(1; exeflags=`--project=\$(Base.active_project()) -t 2,2`)) @@ -149,8 +149,17 @@ end mixed_grid_ok = mixed_grid == [Dagger.ThreadProc(worker, worker_first_tid)] && collect(B) == data rmprocs(worker) - println(repr((; default_tids, interactive_tids, proc_tids, exact_tids, - free_tids, grid_tids, worker_first_tid, mixed_grid_ok))) + @testset "Interactive-thread subprocess" begin + @test interactive_tids == [1] + @test default_tids == [2, 3] + @test proc_tids == default_tids + @test exact_tids == default_tids + @test isempty(intersect(free_tids, interactive_tids)) + @test free_tids ⊆ default_tids + @test grid_tids == [first(default_tids)] + @test worker_first_tid == 3 + @test mixed_grid_ok + end """ # Resolve packages and preferences (the transport) like this process load_path = join(Base.load_path(), Sys.iswindows() ? ';' : ':') @@ -168,19 +177,6 @@ end @test success(child) if !success(child) println(stderr, "Interactive-thread subprocess output:\n", output) - else - result = eval(Meta.parse(last(split(chomp(output), '\n')))) - @test result.interactive_tids == [1] - @test result.default_tids == [2, 3] - # A ThreadProc for every default thread, and none for the - # interactive one - @test result.proc_tids == result.default_tids - @test result.exact_tids == result.default_tids - @test isempty(intersect(result.free_tids, result.interactive_tids)) - @test result.free_tids ⊆ result.default_tids - @test result.grid_tids == [first(result.default_tids)] - @test result.worker_first_tid == 3 - @test result.mixed_grid_ok end end end From a94843cc88d2a1ab1839d3b7d4026ab4d73e10fe Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sun, 29 Nov 2026 20:35:15 -0700 Subject: [PATCH 33/59] test: use exact scopes to exercise each Datadeps processor Ten trivial unpinned tasks can legally finish on one eligible thread. Keep the eligibility assertion for those tasks and use explicit scopes to check that every eligible processor can execute a Datadeps task. The multithreaded Julia 1.13.4 suite passed 757 assertions. Written by an AI agent on jpsamaroo's review feedback. --- test/datadeps.jl | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/datadeps.jl b/test/datadeps.jl index a2e81f908..05daeb02a 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1054,12 +1054,12 @@ function test_datadeps(;args_chunks::Bool, for proc in exec_procs @test proc in scope_procs end - for proc in scope_procs - # These few tasks need not reach the processor running the eager - # scheduler's thunk (worker 1's first default-pool thread) - proc == Dagger.first_thread_proc(1) && continue - @test proc in exec_procs - end + # The unpinned tasks may all finish on one eligible processor. Exercise + # each processor in the outer scope with an explicitly placed task. + scoped_procs = fetch.(Dagger.spawn_datadeps() do + [Dagger.@spawn scope=ExactScope(proc) Dagger.task_processor() for proc in scope_procs] + end) + @test scoped_procs == scope_procs # Inner Scope @test_throws Dagger.Sch.SchedulingException Dagger.spawn_datadeps() do From f4274477438d4ab5f5af5bf8f8b80befd22dcf6c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:12:24 -0700 Subject: [PATCH 34/59] Leave MPI allocator tuning to an explicit application call Review finding F4 (should-fix) on PR #815: MPI activation previously changed persistent glibc policy for the whole process. Remove that automatic call and document the existing opt-in helper. The isolated one/two-rank MPI tests still pass allocator helper, allocation and task execution assertions. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/mpi.md | 4 ++++ ext/MPIExt.jl | 2 -- src/memory-spaces.jl | 4 ++-- test/mpi/free_threads.jl | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/src/mpi.md b/docs/src/mpi.md index a28e124e1..7610f095e 100644 --- a/docs/src/mpi.md +++ b/docs/src/mpi.md @@ -199,6 +199,10 @@ with rank information: - `MPIMemorySpace` — a rank-stamped [memory space](data-management.md) (CPU RAM, or device VRAM) used to track where data resides. +MPI activation leaves process allocator settings unchanged. Applications that +want glibc to retain freed tile buffers can explicitly call `Dagger.tune_malloc!()`; +the setting applies to the whole process and persists after MPI deactivation. + You can enumerate the processors of the cluster (useful for building scopes): ```julia diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 0c4bb5ca5..895644610 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2701,8 +2701,6 @@ function initialize_acceleration!(a::MPIAcceleration) a.comm in comms end already && return - # Tiles crossing ranks are libc buffers allocated and freed per region: keep their pages in the heap - Dagger.tune_malloc!() if !MPI.Initialized() MPI.Init(;threadlevel=:multiple) end diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 37e23cd48..9722da625 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -145,8 +145,8 @@ Keep freed memory in the process heap instead of returning it to the system (gli buffer of up to 16 MB comes from the heap, not from its own `mmap`, and the heap's free top is not trimmed. Datadeps slots and received tiles are libc buffers of tens to hundreds of KB that are allocated and freed in every region; with glibc's defaults each one is a fresh `mmap` or a -trimmed heap top, so every use pays page faults (received tiles at ~0.7 GB/s). Called when the -MPI acceleration starts (where tiles cross ranks). Returns whether the settings were applied; +trimmed heap top, so every use pays page faults (received tiles at ~0.7 GB/s). Apply explicitly with `Dagger.tune_malloc!()` if this process should retain freed tile buffers. +MPI activation leaves the allocator policy unchanged. Returns whether the settings were applied; a no-op elsewhere. """ function tune_malloc!() diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index dd22eeec3..f97c766e5 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -115,7 +115,7 @@ if nranks == 1 end end -# The acceleration keeps freed tile memory in the heap (glibc mallopt); it is a no-op elsewhere +# Explicit allocator tuning keeps freed tile memory in the heap (glibc mallopt); it is a no-op elsewhere @testset "tune_malloc!" begin ok = Dagger.tune_malloc!() @test ok isa Bool From 105bdf4347877ef0cfb47c09a7bc90a44b34e8c7 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:12:25 -0700 Subject: [PATCH 35/59] Share the CPU kernel invocation between pinned and migratable tasks Review finding F6 (should-fix) on PR #815: MPI duplicated the CPU fast path for profiling, invokelatest and captured errors. Extract one core helper and call it from both paths. Isolated one/two-rank mixed-pool tests pass task results, exact pinning and one-rank exception propagation/recovery. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 16 +--------------- src/threadproc.jl | 24 +++++++++++++++--------- 2 files changed, 16 insertions(+), 24 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 895644610..a143547c1 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2503,20 +2503,6 @@ function mpi_thread_requested_slow(proc::MPIProcessor, scope) return false end -# The task that runs `execute!` is a pooled, migratable task with its TLS in place, so -# the function can simply be called: Julia runs it on whichever thread is free -function mpi_run_unbound(f, args...; kwargs...) - if Dagger.task_logging_enabled() - Dagger.TimespanLogging.prof_task_put!(Dagger.get_tls().sch_handle.thunk_id.id) - end - try - return @invokelatest f(args...; kwargs...) - catch err - err isa InterruptException && rethrow() - rethrow(CapturedException(err, catch_backtrace())) - end -end - # Start the task of an MPI processor already pinned to the thread of its inner processor. # Without this the task is migratable, and `execute!(::ThreadProc)` then misses its inline # fast path: it creates a second task pinned to the thread, schedules it and waits, which @@ -2534,7 +2520,7 @@ end function mpi_execute_inner(proc::MPIProcessor, f, args...; kwargs...) if proc.innerProc isa ThreadProc && Dagger.in_task() && !mpi_thread_requested(proc, Dagger.get_tls().task_spec.scope) - return mpi_run_unbound(f, args...; kwargs...) + return Dagger.execute_thread_function(f, args...; kwargs...) end return execute!(proc.innerProc, f, args...; kwargs...) end diff --git a/src/threadproc.jl b/src/threadproc.jl index 9095833df..1a712bb43 100644 --- a/src/threadproc.jl +++ b/src/threadproc.jl @@ -56,15 +56,7 @@ function execute!(proc::ThreadProc, @nospecialize(f), @nospecialize(args...); @n # Already pinned to this processor's thread (the normal case when the # scheduler runs us on a pooled, pinned task): run inline instead of # spawning and fetching a second Task. TLS is already ours. - if task_logging_enabled() - TimespanLogging.prof_task_put!(tls.sch_handle.thunk_id.id) - end - try - return @invokelatest f(args...; kwargs...) - catch err - err isa InterruptException && rethrow() - rethrow(CapturedException(err, catch_backtrace())) - end + return execute_thread_function(f, args...; kwargs...) end # FIXME: Use return type of the call to specialize container result = Ref{Any}() @@ -98,3 +90,17 @@ default_enabled(proc::ThreadProc) = true short_name(proc::ThreadProc) = "W: $(proc.owner), TID: $(proc.tid)" # TODO: ThreadGroupProc? + +# Shared by the pinned CPU fast path and accelerations that allow execution +# on whichever default-pool thread is currently running the scheduler task. +function execute_thread_function(@nospecialize(f), @nospecialize(args...); @nospecialize(kwargs...)) + if task_logging_enabled() + TimespanLogging.prof_task_put!(get_tls().sch_handle.thunk_id.id) + end + try + return @invokelatest f(args...; kwargs...) + catch err + err isa InterruptException && rethrow() + rethrow(CapturedException(err, catch_backtrace())) + end +end From 70072de3e272416d118e8a67cdc24133ecf3550e Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:12:25 -0700 Subject: [PATCH 36/59] Report the thread executing an MPI CPU processor query Review finding F3 (blocker) on PR #815: task_processor() returned the scheduler-selected CPU even when the kernel ran on another free thread. Add a processor dispatch hook and derive an MPI CPU processor from the thread executing the query. The two-rank 2-default+1-interactive-thread probe checks 32 unscoped queries per rank and exact-thread scopes; all pass. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/mpi.md | 7 +++++++ ext/MPIExt.jl | 5 +++++ src/task-tls.jl | 5 ++++- test/mpi/free_threads.jl | 7 +++++++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/src/mpi.md b/docs/src/mpi.md index 7610f095e..3143c8ffc 100644 --- a/docs/src/mpi.md +++ b/docs/src/mpi.md @@ -199,6 +199,13 @@ with rank information: - `MPIMemorySpace` — a rank-stamped [memory space](data-management.md) (CPU RAM, or device VRAM) used to track where data resides. +An MPI CPU task whose scope permits every default-pool thread of its rank can +run on any free default-pool thread. A scope that excludes any of those threads +keeps the task on the scheduler's selected thread. `Dagger.task_processor()` +reports the MPI processor for the thread executing that query; a migratable task +can observe a different thread after yielding. Interactive threads remain outside +the CPU processor pool. + MPI activation leaves process allocator settings unchanged. Applications that want glibc to retain freed tile buffers can explicitly call `Dagger.tune_malloc!()`; the setting applies to the whole process and persists after MPI deactivation. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index a143547c1..7668a5097 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2465,6 +2465,11 @@ function mpi_execute_bcast_plan(f, args, proc::MPIProcessor) end # --- Running a task on a free thread of its rank -------------------------------------- + +function Dagger.task_processor(proc::MPIProcessor{ThreadProc}) + inner = ThreadProc(proc.innerProc.owner, Threads.threadid()) + return MPIProcessor(inner, proc.comm, proc.rank) +end # # `execute!(::ThreadProc)` binds the function to the processor's thread, so an MPI task # waits behind anything that occupies that thread without yielding (a long kernel, a diff --git a/src/task-tls.jl b/src/task-tls.jl index 69111ac7a..0ee120eb3 100644 --- a/src/task-tls.jl +++ b/src/task-tls.jl @@ -78,7 +78,10 @@ task_id() = get_tls().sch_handle.thunk_id.id Get the current processor executing the current [`DTask`](@ref). """ -task_processor() = get_tls().processor +task_processor() = task_processor(get_tls().processor) +# Accelerations with migratable CPU tasks can report the thread executing +# this query rather than the processor selected before the task was launched. +task_processor(proc::Processor) = proc @deprecate(thunk_processor(), task_processor()) """ diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index f97c766e5..585701c89 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -3,6 +3,13 @@ hog_busy(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; 1) # does not yield free_quick(x::Int) = x + 1 free_where() = Threads.threadid() +free_reported_where() = (Threads.threadid(), Dagger.task_processor().innerProc.tid) + +@testset "MPI CPU processor reports the executing thread" begin + tasks = [Dagger.@spawn free_reported_where() for _ in 1:32] + @test all(pair -> first(pair) == last(pair), fetch.(tasks)) +end + @testset "Free MPI threads" begin if Threads.nthreads() >= 3 From 784d6133715c772e8e0bdd2815fc49e6308ebf4b Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:12:25 -0700 Subject: [PATCH 37/59] Check MPI thread eligibility with cached local scope membership Review finding F2 (blocker) on PR #815: Every CPU launch and execution scanned a union containing all ranks. Retain the union constructor's deduplication set and exact-member flag, cache canonical local thread scopes, and invalidate those scopes with processor children. Mixed scopes retain the generic fallback, and union hashing agrees with order-independent equality. Credential-free Julia 1.13.4 measurements: 5000 checks, ten warmups, GC before each of five samples, minima over five runs. At 4/64/512 virtual ranks: before 3.837/38.560/414.665 ms and 2.56/40.96/327.68 MB (40k/640k/5.12m allocations); after 1.679/1.698/1.660 ms and zero bytes/allocations throughout. Retaining set metadata grows those scope objects from 652/10252/81932 to 1308/18828/168076 bytes. This deliberately trades retained scope metadata for constant-rank-cost, allocation-free task checks. One/two-rank MPI tests at two default plus one interactive thread pass membership/cache invalidation, exact pinning, busy-thread progress, results and one-rank failure recovery. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 56 +++++++++++++++++++++++++++------------- src/scopes.jl | 15 +++++++++-- test/mpi/free_threads.jl | 23 ++++++++++++++++- 3 files changed, 73 insertions(+), 21 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 7668a5097..cff4e6c16 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -336,12 +336,16 @@ const MPIClusterProcChildren = Dict{MPI.Comm, Set{Processor}}() # processors the current scope admits (see `uniform_mpi_processors`), not just # on the communicator. const MPIUniformProcsCache = Dict{Tuple{MPI.Comm, Dagger.AbstractScope}, Vector{Processor}}() +const MPIThreadScopesCache = Dict{Tuple{MPI.Comm,Int},Vector{Dagger.ExactScope}}() # Drop every cached uniform listing for `comm`, across all scopes. function invalidate_uniform_cache!(comm::MPI.Comm) for key in collect(keys(MPIUniformProcsCache)) key[1] == comm && delete!(MPIUniformProcsCache, key) end + for key in collect(keys(MPIThreadScopesCache)) + key[1] == comm && delete!(MPIThreadScopesCache, key) + end end struct MPIClusterProc <: Processor @@ -2480,30 +2484,46 @@ end # Datadeps and explicit pinning use, or a union of only some threads) did ask for one: # it stays on the thread of the processor the scheduler picked within that scope. +function mpi_thread_scopes(proc::MPIProcessor) + key = (proc.comm, proc.rank) + while true + @lock MPI_PROC_CACHE_LOCK begin + haskey(MPIThreadScopesCache, key) && return MPIThreadScopesCache[key] + end + children = ensure_children!(proc.comm) + scopes = Dagger.ExactScope[] + for inner in children + inner isa ThreadProc || continue + push!(scopes, Dagger.ExactScope(MPIProcessor(inner, proc.comm, proc.rank))) + end + @lock MPI_PROC_CACHE_LOCK begin + # A processor callback may have refreshed children while these + # scopes were built outside the registry lock. Retry that snapshot. + if get(MPIClusterProcChildren, proc.comm, nothing) === children + return get!(MPIThreadScopesCache, key, scopes) + end + end + end +end + # Does `scope` leave out a thread of the rank of `proc`? function mpi_thread_requested(proc::MPIProcessor, scope) (scope === nothing || scope isa Dagger.AnyScope || scope === Dagger.DefaultScope()) && return false - nthreads = count(p -> p isa Dagger.ThreadProc, ensure_children!(proc.comm)) - if scope isa Dagger.UnionScope - # A union of `ExactScope`s (what `scope(mpi_rank=...)` builds) is the common shape: count - # the distinct threads of this rank it names instead of testing every thread against it - named = 0 - for sub in scope.scopes - if sub isa Dagger.ExactScope && sub.processor isa MPIProcessor{Dagger.ThreadProc} - p = sub.processor - (p.rank == proc.rank && p.comm == proc.comm) && (named += 1) - else - return mpi_thread_requested_slow(proc, scope) - end + thread_scopes = mpi_thread_scopes(proc) + # The scheduler has already established that this processor is eligible. + # On a one-thread rank there is no other CPU thread a scope could exclude. + length(thread_scopes) <= 1 && return false + if scope isa Dagger.UnionScope && scope.all_exact + for candidate in thread_scopes + candidate in scope.scope_set || return true end - return named < nthreads + return false end - return mpi_thread_requested_slow(proc, scope) + return mpi_thread_requested_slow(thread_scopes, scope) end -function mpi_thread_requested_slow(proc::MPIProcessor, scope) - for inner in ensure_children!(proc.comm) - inner isa Dagger.ThreadProc || continue - Dagger.proc_in_scope(MPIProcessor(inner, proc.comm, proc.rank), scope) || return true +function mpi_thread_requested_slow(thread_scopes, scope) + for candidate in thread_scopes + Dagger.proc_in_scope(candidate.processor, scope) || return true end return false end diff --git a/src/scopes.jl b/src/scopes.jl index 1cbf7a703..8bfd92b9a 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -32,6 +32,10 @@ DefaultScope() = DEFAULT_SCOPE_INSTANCE "Union of two or more scopes." struct UnionScope <: AbstractScope scopes::Tuple + # Keep the set already built for deduplication. Exact-processor membership + # checks can then avoid scanning a union containing every MPI rank. + scope_set::Set{AbstractScope} + all_exact::Bool function UnionScope(scopes::Tuple) scope_set = Set{AbstractScope}() for scope in scopes @@ -46,13 +50,20 @@ struct UnionScope <: AbstractScope if isempty(scope_set) throw(ArgumentError("Cannot construct UnionScope with no inner scopes")) end - return new((collect(scope_set)...,)) + all_exact = true + for scope in scope_set + all_exact &= scope isa ExactScope + end + return new((collect(scope_set)...,), scope_set, all_exact) end end UnionScope(scopes...) = UnionScope((scopes...,)) UnionScope(scopes::Vector{<:AbstractScope}) = UnionScope((scopes...,)) UnionScope(s::AbstractScope) = UnionScope((s,)) UnionScope() = UnionScope(()) +# Equality ignores member order. Hash the retained contents rather than the +# identity of the mutable set held inside this otherwise immutable scope. +Base.hash(scope::UnionScope, h::UInt) = hash(scope.scope_set, hash(UnionScope, h)) proc_in_scope(proc::Processor, scope::UnionScope) = any(subscope->proc_in_scope(proc, subscope), scope.scopes) @@ -515,4 +526,4 @@ function Base.issubset(scope1::AbstractScope, scope2::AbstractScope) proc in scope2_procs || return false end return true -end \ No newline at end of file +end diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index 585701c89..4876d6050 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -10,9 +10,30 @@ free_reported_where() = (Threads.threadid(), Dagger.task_processor().innerProc.t @test all(pair -> first(pair) == last(pair), fetch.(tasks)) end +@testset "Exact-scope union membership metadata" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + all_threads = Dagger.UnionScope(map(Dagger.ExactScope, cpus)) + @test all_threads.all_exact + @test length(all_threads.scope_set) == length(cpus) + reordered = Dagger.UnionScope(reverse(map(Dagger.ExactScope, cpus))) + @test all_threads == reordered + @test hash(all_threads) == hash(reordered) + @test Dict(all_threads => true)[reordered] + for proc in cpus + @test !MPIExt.mpi_thread_requested(proc, all_threads) + end + mixed = Dagger.UnionScope(Dagger.ExactScope(first(cpus)), Dagger.AnyScope()) + @test !mixed.all_exact + @test !MPIExt.mpi_thread_requested(first(cpus), mixed) + cached = MPIExt.mpi_thread_scopes(first(cpus)) + lock(MPIExt.MPI_PROC_CACHE_LOCK) do + MPIExt.invalidate_uniform_cache!(comm) + end + @test MPIExt.mpi_thread_scopes(first(cpus)) !== cached +end @testset "Free MPI threads" begin - if Threads.nthreads() >= 3 + if Threads.nthreads() >= 2 cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) rank0 = sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid) # Warm up first: the first fetch of a task compiles for a second on slow nodes, which would be measured otherwise From 71ac4c99785a82c463fd91180b7c4b5d35561689 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:12:25 -0700 Subject: [PATCH 38/59] Specify the fixed-thread contract for pooled task launch hooks Review finding F5 (should-fix) on PR #815: A task-aware pinning hook may choose migratable execution or the processor's fixed thread; arbitrary changing non-nothing thread IDs cannot reuse one pinned pool. State that contract in the hook docstring. Existing and new MPI tests exercise alternation between migratable and exact pinned work in mixed Julia pools. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index afd8082a0..dce35f22f 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1783,9 +1783,14 @@ proc_state(proc::Processor) = proc_state(Dagger.get_tls().sch_uid, proc) task_tid_for_processor(::Processor) = nothing task_tid_for_processor(proc::Dagger.ThreadProc) = proc.tid -# The thread the task for `task` should run on at `proc`. An acceleration whose processor wraps -# a `ThreadProc` overrides this so the task starts pinned where `execute!(::ThreadProc)` would -# otherwise have to create a second pinned task, hand the call over and wait for it. +""" + task_tid_for_processor(proc, task) + +Return `nothing` for a migratable task, or the fixed thread assigned to `proc`. +An acceleration wrapping a `ThreadProc` can opt individual tasks into that +processor's pinned launch path. Every non-`nothing` result for a given processor +must name the same thread: pooled tasks are pinned once and reused. +""" task_tid_for_processor(proc::Processor, task) = task_tid_for_processor(proc) stealing_permitted(::Processor) = true From 1eda4da3728d435b5db85f09a19dd858a1d2a890 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:49:02 -0700 Subject: [PATCH 39/59] Preserve equivalent scope identities while caching MPI membership A mutable Set field changed UnionScope ===/objectid and prevented scheduler compatible-set reuse across freshly constructed equivalent regions. Retain only a deterministic immutable content hash and publish the constructor's membership dictionary in a bounded external cache. Check tuple identity on hash collisions and invalidate communicator entries with processor caches. Keep the mixed-scope fallback and exercise one-member unions with two threads. Measured 5000 membership checks after ten warmups and GC, minimum of five: 4/64/512 virtual ranks take 0.877/0.919/0.865 ms, zero bytes and allocations. The original pre-optimization branch took 3.837/38.560/414.665 ms and allocated 2.56/40.96/327.68 MB. Scope retention is 660/10260/81940 bytes (original +8); the shared bounded cache retains 188644 bytes for these three scopes. Profiling also avoided abstract-tuple indexing and escaping immutable Set wrappers. One- and two-rank MPI checks with two default plus one interactive threads cover fresh scope identity, compatible-set reuse, cache invalidation, actual thread placement, busy-thread progress, and failure recovery. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 11 +++++++ ext/MPIExt.jl | 65 ++++++++++++++++++++++++++++++++++++++-- src/scopes.jl | 26 +++++++++------- test/mpi/free_threads.jl | 24 +++++++++++++-- 4 files changed, 110 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4a39fc3b8..3d5bc3de8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1242,3 +1242,14 @@ this section verbatim). Each entry is one bullet starting with `- `. then appear in Distributed's list while exact Dagger scopes naming them fail to schedule. Launch and load Dagger on the workers first, or use `Dagger.addprocs!(ctx, workers)` to extend an existing context. + +111. **Mutable metadata changes immutable scope identity.** Adding a `Set` field + to `UnionScope` makes separately constructed scopes unequal under `===`, + even when their retained tuples and `==` results match. The scheduler + keys compatible-processor entries with `objectid(scope)` and checks `===`, + so that change loses reuse across equivalent regions. Keep retained + membership sets in an external bounded cache and put only deterministic + immutable metadata in the scope. Check fresh constructor identity and + compatible-set identity, not just equality. A hot cache key must also avoid + indexing an abstract `Tuple`: that boxes its immutable elements. Retain a + content hash at construction instead, and measure the lookup allocations. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index cff4e6c16..1ccbfb5e0 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -338,6 +338,52 @@ const MPIClusterProcChildren = Dict{MPI.Comm, Set{Processor}}() const MPIUniformProcsCache = Dict{Tuple{MPI.Comm, Dagger.AbstractScope}, Vector{Processor}}() const MPIThreadScopesCache = Dict{Tuple{MPI.Comm,Int},Vector{Dagger.ExactScope}}() +struct MPIExactScopeMembers + scopes::Tuple + members::Dict{Dagger.AbstractScope,Nothing} +end +mutable struct MPIExactScopeMembersCache + @atomic table::Dict{UInt,MPIExactScopeMembers} +end +const MPI_EXACT_SCOPE_MEMBERS = MPIExactScopeMembersCache(Dict{UInt,MPIExactScopeMembers}()) +const MPI_EXACT_SCOPE_MEMBERS_LOCK = ReentrantLock() + +# The constructor retains an immutable content hash; collisions are checked +# with the original scope identity. Publish the bounded table whole for +# lock-free reads, without changing UnionScope identity or indexing its Tuple. +# Retain the Set's backing Dict: returning a Union{Nothing,Set} boxes its +# immutable wrapper on the hot path, whereas the Dict is already a reference. +mpi_exact_scope_key(scope::Dagger.UnionScope) = scope.membership_hash +function Dagger.record_union_scope_members!(scope::Dagger.UnionScope, members::Set{Dagger.AbstractScope}) + for inner in members + inner isa Dagger.ExactScope || return nothing + end + key = mpi_exact_scope_key(scope) + hit = get((@atomic MPI_EXACT_SCOPE_MEMBERS.table), key, nothing) + hit !== nothing && hit.scopes === scope.scopes && return nothing + lock(MPI_EXACT_SCOPE_MEMBERS_LOCK) do + old = @atomic MPI_EXACT_SCOPE_MEMBERS.table + table = length(old) >= 256 ? Dict{UInt,MPIExactScopeMembers}() : copy(old) + table[key] = MPIExactScopeMembers(scope.scopes, members.dict) + @atomic MPI_EXACT_SCOPE_MEMBERS.table = table + end + return nothing +end +@inline function mpi_exact_scope_members(scope::Dagger.UnionScope) + key = mpi_exact_scope_key(scope) + hit = get((@atomic MPI_EXACT_SCOPE_MEMBERS.table), key, nothing) + hit !== nothing && hit.scopes === scope.scopes && return hit.members + return mpi_exact_scope_members_slow(scope) +end +@noinline function mpi_exact_scope_members_slow(scope::Dagger.UnionScope) + for inner in scope.scopes + inner isa Dagger.ExactScope || return nothing + end + members = Set{Dagger.AbstractScope}(scope.scopes) + Dagger.record_union_scope_members!(scope, members) + return members.dict +end + # Drop every cached uniform listing for `comm`, across all scopes. function invalidate_uniform_cache!(comm::MPI.Comm) for key in collect(keys(MPIUniformProcsCache)) @@ -346,6 +392,20 @@ function invalidate_uniform_cache!(comm::MPI.Comm) for key in collect(keys(MPIThreadScopesCache)) key[1] == comm && delete!(MPIThreadScopesCache, key) end + lock(MPI_EXACT_SCOPE_MEMBERS_LOCK) do + old = @atomic MPI_EXACT_SCOPE_MEMBERS.table + table = copy(old) + for (key, entry) in old + for inner in entry.scopes + proc = inner.processor + if proc isa MPIProcessor && proc.comm == comm + delete!(table, key) + break + end + end + end + @atomic MPI_EXACT_SCOPE_MEMBERS.table = table + end end struct MPIClusterProc <: Processor @@ -2513,9 +2573,10 @@ function mpi_thread_requested(proc::MPIProcessor, scope) # The scheduler has already established that this processor is eligible. # On a one-thread rank there is no other CPU thread a scope could exclude. length(thread_scopes) <= 1 && return false - if scope isa Dagger.UnionScope && scope.all_exact + members = scope isa Dagger.UnionScope ? mpi_exact_scope_members(scope) : nothing + if members !== nothing for candidate in thread_scopes - candidate in scope.scope_set || return true + haskey(members, candidate) || return true end return false end diff --git a/src/scopes.jl b/src/scopes.jl index 8bfd92b9a..e58573b4d 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -29,13 +29,14 @@ const DEFAULT_SCOPE_INSTANCE = TaintScope(AnyScope(), Set{AbstractScopeTaint}([DefaultEnabledTaint()])) DefaultScope() = DEFAULT_SCOPE_INSTANCE +# Accelerations can retain the constructor's temporary deduplication set in an +# external cache without adding mutable identity to the immutable scope itself. +record_union_scope_members!(::AbstractScope, ::Set{AbstractScope}) = nothing + "Union of two or more scopes." struct UnionScope <: AbstractScope scopes::Tuple - # Keep the set already built for deduplication. Exact-processor membership - # checks can then avoid scanning a union containing every MPI rank. - scope_set::Set{AbstractScope} - all_exact::Bool + membership_hash::UInt function UnionScope(scopes::Tuple) scope_set = Set{AbstractScope}() for scope in scopes @@ -50,20 +51,23 @@ struct UnionScope <: AbstractScope if isempty(scope_set) throw(ArgumentError("Cannot construct UnionScope with no inner scopes")) end - all_exact = true - for scope in scope_set - all_exact &= scope isa ExactScope + membership_hash = zero(UInt) + for inner in scope_set + membership_hash ⊻= hash(inner)::UInt end - return new((collect(scope_set)...,), scope_set, all_exact) + result = new((collect(scope_set)...,), membership_hash) + record_union_scope_members!(result, scope_set) + return result end end UnionScope(scopes...) = UnionScope((scopes...,)) UnionScope(scopes::Vector{<:AbstractScope}) = UnionScope((scopes...,)) UnionScope(s::AbstractScope) = UnionScope((s,)) UnionScope() = UnionScope(()) -# Equality ignores member order. Hash the retained contents rather than the -# identity of the mutable set held inside this otherwise immutable scope. -Base.hash(scope::UnionScope, h::UInt) = hash(scope.scope_set, hash(UnionScope, h)) +# Equality ignores member order. Hash the tuple contents commutatively without +# constructing another set. The retained UInt adds no mutable identity to the +# scope: equivalent tuple constructions still share Sch objectid/=== cache keys. +Base.hash(scope::UnionScope, h::UInt) = hash(scope.membership_hash, hash(UnionScope, h)) proc_in_scope(proc::Processor, scope::UnionScope) = any(subscope->proc_in_scope(proc, subscope), scope.scopes) diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index 4876d6050..fd7f4d615 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -13,23 +13,34 @@ end @testset "Exact-scope union membership metadata" begin cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) all_threads = Dagger.UnionScope(map(Dagger.ExactScope, cpus)) - @test all_threads.all_exact - @test length(all_threads.scope_set) == length(cpus) + members = MPIExt.mpi_exact_scope_members(all_threads) + @test members isa Dict{Dagger.AbstractScope,Nothing} + @test length(members) == length(cpus) reordered = Dagger.UnionScope(reverse(map(Dagger.ExactScope, cpus))) @test all_threads == reordered @test hash(all_threads) == hash(reordered) @test Dict(all_threads => true)[reordered] + fresh = Dagger.UnionScope(map(Dagger.ExactScope, cpus)) + @test fresh === all_threads + @test MPIExt.mpi_exact_scope_members(fresh) === members + accel = Dagger.current_acceleration() + procs = unique(Dagger.Processor[Dagger.get_parent(p) for p in cpus]) + a = Dagger.Sch.compatible_processors_cached(accel, all_threads, procs) + b = Dagger.Sch.compatible_processors_cached(accel, fresh, procs) + @test a === b + @test a == Set(cpus) for proc in cpus @test !MPIExt.mpi_thread_requested(proc, all_threads) end mixed = Dagger.UnionScope(Dagger.ExactScope(first(cpus)), Dagger.AnyScope()) - @test !mixed.all_exact + @test MPIExt.mpi_exact_scope_members(mixed) === nothing @test !MPIExt.mpi_thread_requested(first(cpus), mixed) cached = MPIExt.mpi_thread_scopes(first(cpus)) lock(MPIExt.MPI_PROC_CACHE_LOCK) do MPIExt.invalidate_uniform_cache!(comm) end @test MPIExt.mpi_thread_scopes(first(cpus)) !== cached + @test MPIExt.mpi_exact_scope_members(all_threads) !== members end @testset "Free MPI threads" begin @@ -128,6 +139,13 @@ end else fetch(Dagger.@spawn(scope=Dagger.ExactScope(first(filter(p -> p.rank == 0, cpus))), free_where())) end + # A one-member union names a subset on two-thread ranks as well. Exercise + # the union membership cache and pinned pool without requiring three threads. + target = first(sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid)) + subset = Dagger.UnionScope(Dagger.ExactScope(target)) + @test MPIExt.mpi_thread_requested(target, subset) == (nthr > 1) + @test tid_for(target, spec(subset)) == (rank == 0 && nthr > 1 ? target.innerProc.tid : nothing) + @test fetch(Dagger.@spawn(scope=subset, free_where())) == target.innerProc.tid MPI.Barrier(comm) end From 85c40a45b313c571921eb7a9760fe75ee27e90fa Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:51:02 -0700 Subject: [PATCH 40/59] Document the normalized union membership hook contract Specify ownership and immutable retention for acceleration caches. Written by an AI agent on jpsamaroo's review feedback. --- src/scopes.jl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/scopes.jl b/src/scopes.jl index e58573b4d..babb56900 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -29,8 +29,14 @@ const DEFAULT_SCOPE_INSTANCE = TaintScope(AnyScope(), Set{AbstractScopeTaint}([DefaultEnabledTaint()])) DefaultScope() = DEFAULT_SCOPE_INSTANCE -# Accelerations can retain the constructor's temporary deduplication set in an -# external cache without adding mutable identity to the immutable scope itself. +""" + record_union_scope_members!(scope, members) -> nothing + +Acceleration hook called by `UnionScope` after flattening and deduplicating its +members. `members::Set{AbstractScope}` is temporary constructor-owned membership +data; an implementation may retain it or its backing storage without mutating +it. The default does nothing. Implementations return `nothing`. +""" record_union_scope_members!(::AbstractScope, ::Set{AbstractScope}) = nothing "Union of two or more scopes." From da2010688b3c3df802811e89f27df833db199a81 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:51:28 -0700 Subject: [PATCH 41/59] Match taint-scope hashing to its existing content equality The pre-existing TaintScope == compares taint contents while its inherited hash used mutable Set identity. Portable union scopes expose that prerequisite when equivalent scopes are reconstructed. Hash the inner scope and taint contents, with round-trip equality/hash/Dict regressions. After ten warmups and GC, 5000 DefaultScope/ProcessorTypeScope hashes remain zero bytes and allocations (minimum of five samples). Written by an AI agent on jpsamaroo's review feedback. --- src/scopes.jl | 4 ++++ test/scopes.jl | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/scopes.jl b/src/scopes.jl index babb56900..2e73dcf0e 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -20,6 +20,10 @@ Base.:(==)(ts1::TaintScope, ts2::TaintScope) = length(ts1.taints) == length(ts2.taints) && all(collect(ts1.taints) .== collect(ts2.taints)) +# Equality compares taint contents; the backing Set's identity is immaterial. +Base.hash(scope::TaintScope, h::UInt) = + hash(scope.taints, hash(scope.scope, hash(TaintScope, h))) + struct DefaultEnabledTaint <: AbstractScopeTaint end "Default scope that contains the set of `default_enabled` processors." diff --git a/test/scopes.jl b/test/scopes.jl index bc724ffb7..74d2f8769 100644 --- a/test/scopes.jl +++ b/test/scopes.jl @@ -289,3 +289,14 @@ rmprocs([wid1, wid2]) end + +@testset "Equal taint scopes have equal hashes" begin + for original in (Dagger.DefaultScope(), Dagger.ProcessorTypeScope(Dagger.ThreadProc)) + io = IOBuffer(); Dagger.Serialization.serialize(io, original); seekstart(io) + received = Dagger.Serialization.deserialize(io) + @test original == received + @test hash(original) == hash(received) + @test Dict(original => true)[received] + end +end + From a815d4cedf6527da902f911a5270feef2b9d1c36 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:52:11 -0700 Subject: [PATCH 42/59] Rebuild derived union-scope metadata after serialization A serialized cached hash retained sender-side member identities. Reconstruct UnionScope from its normalized member tuple so the receiving process computes its own metadata and registers its membership cache. The previous round-trip probe produced equal fresh scopes with different hashes. Final focused checks pass 57 assertions on one MPI rank and 54/56 on two ranks, including fresh received identity, hash/Dict behavior, portable scope values across ranks, placement, and failure recovery. Membership lookups remain zero bytes/allocations after warmup. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 5 +++++ src/scopes.jl | 9 +++++++++ test/mpi/free_threads.jl | 19 +++++++++++++++++++ test/scopes.jl | 15 +++++++++++++++ 4 files changed, 48 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 3d5bc3de8..5106fdeb1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1253,3 +1253,8 @@ this section verbatim). Each entry is one bullet starting with `- `. compatible-set identity, not just equality. A hot cache key must also avoid indexing an abstract `Tuple`: that boxes its immutable elements. Retain a content hash at construction instead, and measure the lookup allocations. + Derived hashes must be rebuilt after serialization because member + identities can change. Do not serialize cached identity hashes as data. + Specializing a function on a large scope tuple also incurs its full tuple + ABI cost: a three-member fingerprint prototype took 18 s to compile at 1024 + members and its lookup scaled with tuple size despite zero allocations. diff --git a/src/scopes.jl b/src/scopes.jl index 2e73dcf0e..f53825187 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -78,6 +78,15 @@ UnionScope() = UnionScope(()) # constructing another set. The retained UInt adds no mutable identity to the # scope: equivalent tuple constructions still share Sch objectid/=== cache keys. Base.hash(scope::UnionScope, h::UInt) = hash(scope.membership_hash, hash(UnionScope, h)) +# Derived hashes depend on the receiving process's member identities. Send +# normalized members only and rebuild metadata/cache registration on receipt. +function Serialization.serialize(s::AbstractSerializer, scope::UnionScope) + Serialization.serialize_type(s, UnionScope) + Serialization.serialize(s, scope.scopes) +end +Serialization.deserialize(s::AbstractSerializer, ::Type{UnionScope}) = + UnionScope(Serialization.deserialize(s)) + proc_in_scope(proc::Processor, scope::UnionScope) = any(subscope->proc_in_scope(proc, subscope), scope.scopes) diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index fd7f4d615..ddf40a913 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -4,6 +4,7 @@ hog_busy(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; 1) free_quick(x::Int) = x + 1 free_where() = Threads.threadid() free_reported_where() = (Threads.threadid(), Dagger.task_processor().innerProc.tid) +free_scope_value() = Dagger.UnionScope(Dagger.ProcessorTypeScope(Dagger.ThreadProc)) @testset "MPI CPU processor reports the executing thread" begin tasks = [Dagger.@spawn free_reported_where() for _ in 1:32] @@ -43,6 +44,24 @@ end @test MPIExt.mpi_exact_scope_members(all_threads) !== members end +@testset "Serialized MPI scopes retain local identity and hash contracts" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + original = Dagger.UnionScope(Dagger.ExactScope(first(cpus))) + io = IOBuffer(); Dagger.Serialization.serialize(io, original); seekstart(io) + received = Dagger.Serialization.deserialize(io) + fresh = Dagger.UnionScope(received.scopes) + @test received === fresh + @test hash(received) == hash(fresh) + @test Dict(received => true)[fresh] + # The non-owner receives this scope over MPI's serialized value path. + owner = first(filter(p -> p.rank == 0, cpus)) + portable = fetch(Dagger.@spawn(scope=Dagger.ExactScope(owner), return_type=Dagger.UnionScope, free_scope_value())) + @test portable === Dagger.UnionScope(portable.scopes) + @test portable == free_scope_value() + @test hash(portable) == hash(free_scope_value()) + @test Dict(portable => true)[free_scope_value()] +end + @testset "Free MPI threads" begin if Threads.nthreads() >= 2 cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) diff --git a/test/scopes.jl b/test/scopes.jl index 74d2f8769..defd0766e 100644 --- a/test/scopes.jl +++ b/test/scopes.jl @@ -300,3 +300,18 @@ end end end +@testset "Scope serialization rebuilds derived membership metadata" begin + for original in (UnionScope(ExactScope(Dagger.ThreadProc(1, 1))), + UnionScope(Dagger.ProcessorTypeScope(Dagger.ThreadProc))) + io = IOBuffer() + Dagger.Serialization.serialize(io, original) + seekstart(io) + received = Dagger.Serialization.deserialize(io) + fresh = UnionScope(received.scopes) + @test received === fresh + @test hash(received) == hash(fresh) + @test Dict(received => true)[fresh] + @test original == received + @test hash(original) == hash(received) + end +end From 810887105917eafb55ed7efb2ca01c4d7c91d087 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:52:11 -0700 Subject: [PATCH 43/59] Refresh cached scope tuples while retaining equal membership storage An equal membership hash can represent a different tuple order. Preserve the existing membership dictionary when its contents match, and publish the current constructor tuple so task lookups avoid recursively comparing a previous large tuple. Fresh equivalent 512-rank scopes improved from 166.8 ms to 0.89 ms per 5000 checks in a same-process old/new callback control, with zero bytes/allocations in both hot paths. Publishing adds 576 bytes and 4 allocations per constructor at 4/64/512 virtual ranks; 100-constructor samples follow ten warmups and GC, minimum of five. The fresh-scope membership/compatible-cache identity regressions pass. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 1ccbfb5e0..4086560b3 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -358,16 +358,33 @@ function Dagger.record_union_scope_members!(scope::Dagger.UnionScope, members::S for inner in members inner isa Dagger.ExactScope || return nothing end + record_mpi_exact_scope_members!(scope, members) + return nothing +end +function record_mpi_exact_scope_members!(scope::Dagger.UnionScope, members::Set{Dagger.AbstractScope}) key = mpi_exact_scope_key(scope) - hit = get((@atomic MPI_EXACT_SCOPE_MEMBERS.table), key, nothing) - hit !== nothing && hit.scopes === scope.scopes && return nothing - lock(MPI_EXACT_SCOPE_MEMBERS_LOCK) do + return lock(MPI_EXACT_SCOPE_MEMBERS_LOCK) do old = @atomic MPI_EXACT_SCOPE_MEMBERS.table - table = length(old) >= 256 ? Dict{UInt,MPIExactScopeMembers}() : copy(old) - table[key] = MPIExactScopeMembers(scope.scopes, members.dict) + hit = get(old, key, nothing) + backing = members.dict + if hit !== nothing && length(hit.members) == length(members) + same_members = true + for inner in members + if !haskey(hit.members, inner) + same_members = false + break + end + end + same_members && (backing = hit.members) + end + table = hit === nothing && length(old) >= 256 ? Dict{UInt,MPIExactScopeMembers}() : copy(old) + # Refresh the tuple reference for this constructor. Equivalent tuples + # share immutable identity, but comparing distinct large tuple objects + # recursively on every task would restore a rank-count-dependent cost. + table[key] = MPIExactScopeMembers(scope.scopes, backing) @atomic MPI_EXACT_SCOPE_MEMBERS.table = table + return backing end - return nothing end @inline function mpi_exact_scope_members(scope::Dagger.UnionScope) key = mpi_exact_scope_key(scope) @@ -380,8 +397,7 @@ end inner isa Dagger.ExactScope || return nothing end members = Set{Dagger.AbstractScope}(scope.scopes) - Dagger.record_union_scope_members!(scope, members) - return members.dict + return record_mpi_exact_scope_members!(scope, members) end # Drop every cached uniform listing for `comm`, across all scopes. From 4294f76b8c5292173fe80d1e7ebb456bc8936392 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:54:51 -0700 Subject: [PATCH 44/59] Replace migratable pool slots pinned by async payloads Julia can make a reusable task sticky when a payload schedules @async. The setup callback only runs at creation, so later rank-wide MPI work can remain stuck behind that physical thread. Retire such slots by closing their channel before publishing readiness and replace closed slots on reuse. Leave intentionally pinned slots and outstanding async children with their original affinity; never unset sticky on a running task. The new unit controls fail four assertions before the repair and pass all 14 after it; the23 existing lazy-slot assertions still pass. Two ranks x 4default+1interactive pinned to2 CPUs reproduce the independent async-poison probe: subsequent slots are now nonsticky and16quick tasks complete in 0.179/0.190s with another thread occupied, versus1.799s in the independent old-head control. This repairs a preexisting pooled-state weakness exposed by the free-MPI path. After10x1000calls warmup and GC, minimum of five1000call GC-delta runs is 0bytes/0allocations before and after for ordinary unpoisoned dispatch. Retirement deliberately allocates a fresh slot only after async poisoning. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 8 +++++++ src/utils/reuse.jl | 16 +++++++++++++- test/reuse-task-cache.jl | 46 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 5106fdeb1..37ce9fc4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1258,3 +1258,11 @@ this section verbatim). Each entry is one bullet starting with `- `. Specializing a function on a large scope tuple also incurs its full tuple ABI cost: a three-member fingerprint prototype took 18 s to compile at 1024 members and its lookup scaled with tuple size despite zero allocations. + +112. **Async payloads can permanently pin a reusable task.** A cache setup + callback runs only when its slot is created. A later payload that schedules + `@async` makes that Task sticky, so a pool advertised as migratable can + silently accumulate pinned slots. Retire a formerly migratable slot that + becomes sticky; do not unset sticky while its children may still rely on + the affinity. Close its channel before publishing readiness, and replace + closed slots on dispatch, so a new payload cannot be lost during retirement. diff --git a/src/utils/reuse.jl b/src/utils/reuse.jl index 25c309347..6306953bf 100644 --- a/src/utils/reuse.jl +++ b/src/utils/reuse.jl @@ -633,6 +633,7 @@ function initialize_reusable_task_slot!(cache::ReusableTaskCache, idx::Int) end function reusable_task_loop(chan::Channel{Any}, ready::Threads.Atomic{Bool}) r = rand(1:128) + initially_migratable = !current_task().sticky while true f = try take!(chan) @@ -648,6 +649,15 @@ function reusable_task_loop(chan::Channel{Any}, ready::Threads.Atomic{Bool}) catch err @error "[$r] Error in reusable task" exception=(err, catch_backtrace()) end + if initially_migratable && current_task().sticky + # Scheduling @async can pin a formerly migratable slot. Do not + # unset sticky while its children may still need that affinity: + # retire it, and publish the closed channel before releasing the + # slot so the next dispatch creates a fresh migratable task. + close(chan) + Threads.atomic_xchg!(ready, true) + return + end Threads.atomic_xchg!(ready, true) end end @@ -661,7 +671,11 @@ function (cache::ReusableTaskCache)(f, name::String, register=nothing) idx = findfirst(getindex, cache.ready) if idx !== nothing @assert Threads.atomic_xchg!(cache.ready[idx], false) - t = isassigned(cache.tasks, idx) ? cache.tasks[idx] : initialize_reusable_task_slot!(cache, idx) + t = if isassigned(cache.tasks, idx) && isopen(cache.chans[idx]) + cache.tasks[idx] + else + initialize_reusable_task_slot!(cache, idx) + end register === nothing || register(t) put!(cache.chans[idx], f) # N.B. No errormonitor_tracked_set! here: pooled tasks are registered diff --git a/test/reuse-task-cache.jl b/test/reuse-task-cache.jl index 2ffe70e8e..aeac6372a 100644 --- a/test/reuse-task-cache.jl +++ b/test/reuse-task-cache.jl @@ -58,3 +58,49 @@ using Test finalize(empty_cache) @test all(i -> !isassigned(empty_cache.chans, i), 1:empty_cache.N) end + +@testset "Migratable task slots recover after async payloads" begin + cache = Dagger.ReusableTaskCache(1) + Dagger.reusable_task_cache_init!(Dagger.set_task_migratable!, cache) + entered = Channel{Task}(1) + release = Base.Event() + child_done = Base.Event() + poisoned = cache(() -> begin + @async begin + put!(entered, current_task()) + wait(release) + notify(child_done) + end + end, "async payload") + child = take!(entered) + @test timedwait(() -> cache.ready[1][], 10.0; pollint=0.001) === :ok + @test poisoned.sticky + @test !isopen(cache.chans[1]) + @test !istaskdone(child) + tasks = Channel{Tuple{Task,Bool}}(1) + fresh = cache(() -> put!(tasks, (current_task(), current_task().sticky)), "fresh async slot") + @test take!(tasks) === (fresh, false) + @test fresh !== poisoned + @test timedwait(() -> cache.ready[1][], 10.0; pollint=0.001) === :ok + # A clean payload still reuses the replacement slot. + @test cache(() -> put!(tasks, (current_task(), current_task().sticky)), "reused fresh slot") === fresh + @test take!(tasks) === (fresh, false) + notify(release) + wait(child_done) + @test timedwait(() -> cache.ready[1][], 10.0; pollint=0.001) === :ok + finalize(cache) + wait(fresh) + @test !istaskfailed(poisoned) + + # Intentionally pinned slots keep their identity across async payloads. + pinned = Dagger.ReusableTaskCache(1) + Dagger.reusable_task_cache_init!(t -> nothing, pinned) + done = Base.Event() + first = pinned(() -> wait(@async nothing), "pinned async slot") + @test timedwait(() -> pinned.ready[1][], 10.0; pollint=0.001) === :ok + @test pinned(() -> notify(done), "pinned reused slot") === first + wait(done) + @test timedwait(() -> pinned.ready[1][], 10.0; pollint=0.001) === :ok + finalize(pinned) + wait(first) +end From 176a605aa4be0f219255d928136352b480b67c21 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:57:53 -0700 Subject: [PATCH 45/59] Keep owner-elision failure state alive with task and result handles Capture failure-only mode at ordered root submission, independently of later optimization switches. Route typed failures into weakly registered state held by DTask/MPIRef handles, including early relay delivery and serialized refs, instead of retaining every exception in global broadcast slots. Raw failed fetches consume no data-fetch tag. Generate IDs after metadata hooks so a reentrant submission cannot skip registration. Prove host-result/CPU eligibility against registered candidates, option defaults, and function/argument compatibility before binding the owner. Pin the logical processor while preserving the requested scope for free-CPU execution. GPU and custom result metadata keeps the ordinary exchange; failure-only execution uses mpi_execute_inner rather than bypassing that path. The original two-rank switch-off fetch hung; it now throws on both ranks and subsequent uniform work succeeds. Expanded owner-elision coverage passes170/166 assertions, including repeated/raw fetches, early delivery, serialization and weak reclamation. OpenCL metadata fallback passes10 assertions/rank. Before/after 1000-placement GC profiles after10 deep warmups+GC/5samples:92000/3504000B -> 102000/3920000B for the additional proof; a separate follow-up removes candidate copy/sort costs. Full MPI and allocation suites are recorded separately. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 10 ++ docs/src/mpi.md | 19 ++- ext/MPIExt.jl | 293 ++++++++++++++++++++++++++++++---------------- src/dtask.jl | 5 +- src/options.jl | 3 + src/submission.jl | 33 ++++-- test/mpi/elide.jl | 89 +++++++++++++- 7 files changed, 333 insertions(+), 119 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5106fdeb1..692977dfe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1258,3 +1258,13 @@ this section verbatim). Each entry is one bullet starting with `- `. Specializing a function on a large scope tuple also incurs its full tuple ABI cost: a three-member fingerprint prototype took 18 s to compile at 1024 members and its lookup scaled with tuple size despite zero allocations. + +112. **An elided result's failure protocol belongs to its handles.** A live + optimization flag cannot decide whether an existing MPI result checks for + poison: disabling elision after submission otherwise strands nonowners and + desynchronizes later generic fetch tags. Capture the protocol at root + submission, retain its failure state through the DTask and every result + MPIRef, and keep relay registration weak. Failure delivery may precede a + lagging rank's submission; retain only those early messages until ordered + root registration reaches their task id. Generate that id after metadata + hooks finish, so reentrant submission cannot skip a registration gap. diff --git a/docs/src/mpi.md b/docs/src/mpi.md index 6803927f5..a5d3a9164 100644 --- a/docs/src/mpi.md +++ b/docs/src/mpi.md @@ -366,16 +366,25 @@ and tags stay equal on every rank). It is off by default, and every rank must se it to the same value at the same point of the program; changing it waits for the tasks already submitted. -A task is only elided when its scope names a single rank, its return type is -concrete, it has no explicit tag, and this rank owns none of its arguments. -Tasks inside Datadeps regions and inside other tasks are never elided, and -neither are tasks of another communicator or while `check_uniformity!(true)` is -on. +A CPU task is eligible when its result type proves host storage, its owner is +known at submission, it has no explicit tag, and this rank owns none of its +arguments. A rank scope supplies the owner; an unscoped task can use deterministic +placement at submission. Placement uses the scheduler's registered processors, +option defaults, and function/argument compatibility checks. GPU processors and +custom result types retain the normal metadata exchange. A rank-wide CPU scope +still permits execution on a free thread of that rank. + +Elision applies to root-task submissions through the ordinary queue and +`spawn_bulk`. Tasks inside Datadeps regions and inside other tasks are never +elided, and neither are tasks of another communicator or tasks submitted while +`check_uniformity!(true)` is on. The consequence to be aware of: the owner of an elided task reports only failures. A rank that never fetches the task or consumes its result does not wait for it and does not notice that it finished or failed; a rank that does consume it sees the owner's error. +The task and its result handles retain that failure for repeated fetches, including +after elision is disabled. Failure state is released when its last handle dies. ## Collecting and fetching results diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 2fb7992ec..614bd160b 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -847,13 +847,78 @@ to_tag(id::MPIRefID) = id.generic ? id.id : id.tid # tochunk sequence within a thunk), so the resulting MPIRefIDs are uniform. const _MPIREF_TID = LockedObject(Dict{Int,Int}()) +# Only handles and in-flight tasks own failure state. The relay's registry is +# weak, so a failed task's exception dies with its last result/task handle. +mutable struct OwnerElisionState + tid::UInt32 + owner::Int + @atomic error::Any + requested_scope::Any +end +OwnerElisionState(tid, owner, err) = OwnerElisionState(tid, owner, err, nothing) +struct OwnerFailure + error::Any +end +const OWNER_ELISION_STATES = WeakKeyDict{OwnerElisionState,Nothing}() +const OWNER_ELISION_LOCK = ReentrantLock() +const OWNER_ELISION_REGISTERED = Ref{UInt}(0) +# A fast owner can fail before a lagging rank submits the same root task. +# Retain only messages ahead of that rank's root-submission watermark. +const OWNER_ELISION_EARLY = Dict{UInt32,Tuple{Int,Any}}() + +function owner_elision_deliver!(root::Int, tag::UInt32, err) + @lock OWNER_ELISION_LOCK begin + for state in keys(OWNER_ELISION_STATES) + if state.tid == tag + @atomic state.error = err + end + end + UInt(tag) > OWNER_ELISION_REGISTERED[] && (OWNER_ELISION_EARLY[tag] = (root, err)) + end + return +end + +function Serialization.serialize(s::Serialization.AbstractSerializer, state::OwnerElisionState) + Serialization.serialize_cycle_header(s, state) && return + Serialization.serialize(s, state.tid) + Serialization.serialize(s, state.owner) + Serialization.serialize(s, @atomic(state.error)) + Serialization.serialize(s, state.requested_scope) +end +function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnerElisionState}) + tid = Serialization.deserialize(s)::UInt32 + owner = Serialization.deserialize(s)::Int + state = @lock OWNER_ELISION_LOCK begin + found = nothing + for candidate in keys(OWNER_ELISION_STATES) + if candidate.tid == tid + found = candidate + break + end + end + if found === nothing + found = OwnerElisionState(tid, owner, nothing) + OWNER_ELISION_STATES[found] = nothing + end + found + end + Serialization.deserialize_cycle(s, state) + err = Serialization.deserialize(s) + err === nothing || (@atomic state.error = err) + scope = Serialization.deserialize(s) + state.requested_scope === nothing && (state.requested_scope = scope) + return state +end + mutable struct MPIRef comm::MPI.Comm rank::Int size::Int innerRef::Union{DRef, Nothing} id::MPIRefID + owner_elision::Union{OwnerElisionState,Nothing} end +MPIRef(comm, rank, size, innerRef, id) = MPIRef(comm, rank, size, innerRef, id, nothing) Base.hash(ref::MPIRef, h::UInt=UInt(0)) = hash(ref.rank, hash(ref.id, hash(MPIRef, h))) root_worker_id(ref::MPIRef) = myid() @@ -949,16 +1014,16 @@ function take_ref_id!() end #TODO: partitioned scheduling with comm bifurcation -function tochunk_pset(x, space::MPIMemorySpace; device=nothing, force_nonlocal=false, kwargs...) +function tochunk_pset(x, space::MPIMemorySpace; device=nothing, force_nonlocal=false, _owner_elision=nothing, kwargs...) @assert space.comm == MPI.COMM_WORLD "$(space.comm) != $(MPI.COMM_WORLD)" local_rank = MPI.Comm_rank(space.comm) Mid = take_ref_id!() if local_rank != space.rank || force_nonlocal - return MPIRef(space.comm, space.rank, 0, nothing, Mid) + return MPIRef(space.comm, space.rank, 0, nothing, Mid, _owner_elision) else # type= is for Chunk metadata only; MemPool.poolset does not accept it pset_kw = (; (k => v for (k, v) in pairs(kwargs) if k !== :type)...) - return MPIRef(space.comm, space.rank, sizeof(x), poolset(x; device, pset_kw...), Mid) + return MPIRef(space.comm, space.rank, sizeof(x), poolset(x; device, pset_kw...), Mid, _owner_elision) end end @@ -1521,6 +1586,11 @@ function bcast_slot!(state::BcastState, key::Tuple{Int,UInt32}) end function bcast_deliver!(state::BcastState, root::Int, tag::UInt32, value) + if value isa OwnerFailure + owner_elision_deliver!(root, tag, value.error) + note_mpi_progress!() + return + end # `@lock`, not `lock(...) do`: the `do` block is a closure over `state`, # `root`, `tag` and `value`, which boxes them and allocates on a path the # relay runs for every delivered payload. @@ -1783,10 +1853,10 @@ end # tasks `elide_task!` handles (see "Owner elision") the status is instead sent # *only on failure*: ranks never wait for success, and a rank that later needs the # task's data -- an argument move or a fetch -- stops waiting when the failure -# arrives. The failure is the `(:error, ex)` payload of the owner's broadcast on -# the task's tag, which the relay keeps in the task's (root, tag) slot; the data -# the task produced carries that tag in its ref id (`MPIRefID.tid`), so a wait on -# a `MPIRef` can look the failure up. Waits install the ref they are on behalf of +# arrives. A typed failure notification updates a state shared by the local +# task and its result refs. The relay owns only weak state references, so +# exceptions outlive repeated fetches without accumulating in global slots. +# Waits install the ref they are on behalf of # in `POISON_REF`, and every polling wait already goes through # `mpi_deadlock_detect`, which checks it. @@ -1794,26 +1864,16 @@ const POISON_REF = ScopedValue{Union{MPIRef,Nothing}}(nothing) function mpi_check_poison() ref = POISON_REF[]::MPIRef - ref.id.generic && return - state = lock(BCAST_STATES) do states - get(states, ref.comm, nothing) - end + state = ref.owner_elision state === nothing && return - err = nothing - @lock state.cond begin - slot = get(state.slots, (ref.rank, UInt32(ref.id.tid)), nothing) - if slot !== nothing && !isempty(slot.values) - msg = slot.values[1] - msg isa Tuple && first(msg) === :error && (err = msg[2]) - end - end + err = @atomic state.error err === nothing || throw(err) return end # Run `f` (a wait on data of `ref`'s task) so that it ends in that task's error mpi_poisonable(f, ref::MPIRef) = - Dagger.ELIDE_FOREIGN_TASKS[] ? with(f, POISON_REF => ref) : f() + ref.owner_elision === nothing ? f() : with(f, POISON_REF => ref) WeakChunk(c::Chunk{T,H}) where {T,H<:MPIRef} = WeakChunk(c.handle.rank, c.handle.id.id, WeakRef(c), T) @@ -2677,13 +2737,23 @@ end # of chunk arguments), the same one `mpi_execute_inner` looks at. function Dagger.Sch.task_tid_for_processor(proc::MPIProcessor{Dagger.ThreadProc}, task) proc.rank == MPI.Comm_rank(proc.comm) || return nothing - mpi_thread_requested(proc, task.scope) || return nothing + mpi_thread_requested(proc, mpi_execution_scope(task)) || return nothing return Dagger.Sch.task_tid_for_processor(proc.innerProc) end +function mpi_execution_scope(task) + # Owner elision pins the logical processor to keep result metadata equal. + # The user's original scope still decides whether a CPU thread was requested. + if hasproperty(task, :options) + state = task.options._owner_elision + state isa OwnerElisionState && state.owner >= 0 && return state.requested_scope + end + return task.scope +end + function mpi_execute_inner(proc::MPIProcessor, f, args...; kwargs...) if proc.innerProc isa ThreadProc && Dagger.in_task() && - !mpi_thread_requested(proc, Dagger.get_tls().task_spec.scope) + !mpi_thread_requested(proc, mpi_execution_scope(Dagger.get_tls().task_spec)) return Dagger.execute_thread_function(f, args...; kwargs...) end return execute!(proc.innerProc, f, args...; kwargs...) @@ -2748,6 +2818,7 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) end plan = mpi_execute_bcast_plan(f, args, proc) + owner_state = Dagger.in_task() ? Dagger.get_tls().task_spec.options._owner_elision : nothing # Concrete + nothrow: type/space known locally and the call cannot throw, # so non-owners need no status or metadata traffic. Stamp the inferred @@ -2756,10 +2827,10 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) if islocal result = mpi_execute_inner(proc, f, raw_args...; kwargs...) space = mpi_result_space(result, proc) - return tochunk(result, proc, space; type=plan.inferred) + return tochunk(result, proc, space; type=plan.inferred, _owner_elision=owner_state) else space = memory_space(nothing, proc)::MPIMemorySpace - return tochunk(nothing, proc, space; type=plan.inferred) + return tochunk(nothing, proc, space; type=plan.inferred, _owner_elision=owner_state) end end @@ -2772,12 +2843,12 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) if islocal # N.B. A failure reaches the other ranks from `task_failed!`, which # covers every way this task can fail, not only an error in `f` - result = execute!(proc.innerProc, f, raw_args...; kwargs...) + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) space = mpi_result_space(result, proc) - return tochunk(result, proc, space; type=plan.inferred) + return tochunk(result, proc, space; type=plan.inferred, _owner_elision=owner_state) else space = memory_space(nothing, proc)::MPIMemorySpace - return tochunk(nothing, proc, space; type=plan.inferred) + return tochunk(nothing, proc, space; type=plan.inferred, _owner_elision=owner_state) end end if islocal @@ -2791,14 +2862,14 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) @opcounter :execute_bcast_send_yield bcast_meta_yield(proc.comm, proc.rank, tag, :ok) space = mpi_result_space(result, proc) - return tochunk(result, proc, space; type=plan.inferred) + return tochunk(result, proc, space; type=plan.inferred, _owner_elision=owner_state) else msg = bcast_meta_yield(proc.comm, proc.rank, tag) if msg isa Tuple && first(msg) === :error throw(msg[2]) end space = memory_space(nothing, proc)::MPIMemorySpace - return tochunk(nothing, proc, space; type=plan.inferred) + return tochunk(nothing, proc, space; type=plan.inferred, _owner_elision=owner_state) end end @@ -3078,46 +3149,6 @@ function mpi_union_scope_processor(scope::Dagger.UnionScope) return proc end -# The processors of a single-rank union scope in the order the owner's scheduler sees them -# (`select_processors_uniform!`: the canonical order), so that a rank which elides the task -# can stamp its placeholder with the processor the owner will pick: under uniform execution -# that is the candidate at `mod(id - 1, n) + 1` (`select_processors_uniform!`; the owner rank -# is either the whole candidate list or not in it, so no preferred block shortens it). -# `mpi_union_scope_processor` names a fixed member, which gives the right rank but, on a -# non-owner, another thread than the owner's: the placeholder and the real result then -# disagreed on `chunk.processor`. Same content-keyed, lock-free cache as above. -const MPI_UNION_ORDER_CACHE = MPIUnionScopeCache(Dict{UInt,Tuple{Any,Any}}()) -const MPI_UNION_ORDER_CACHE_LOCK = ReentrantLock() -function mpi_union_scope_ordered(accel::MPIAcceleration, scope::Dagger.UnionScope)::Union{Nothing,Vector{Processor}} - key = mpi_union_key(scope) - hit = get((@atomic MPI_UNION_ORDER_CACHE.table), key, nothing) - hit !== nothing && hit[1] === scope && return hit[2]::Union{Nothing,Vector{Processor}} - ordered = nothing - if mpi_union_scope_processor(scope) !== nothing - ordered = Processor[sc.processor for sc in scope.scopes] - unique!(ordered) - # Without a task: the canonical order only, no rotation - Dagger.select_processors_uniform!(ordered, accel) - end - lock(MPI_UNION_ORDER_CACHE_LOCK) do - old = @atomic MPI_UNION_ORDER_CACHE.table - table = length(old) >= 256 ? Dict{UInt,Tuple{Any,Any}}() : copy(old) - table[key] = (scope, ordered) - @atomic MPI_UNION_ORDER_CACHE.table = table - end - return ordered -end - -# The processor the owner's scheduler will run task `uid` on, when its scope names one -# rank; `proc` (the scope's fixed member) otherwise -function mpi_planned_processor(accel::MPIAcceleration, opts::Options, proc::MPIProcessor, uid)::MPIProcessor - scope = mpi_task_scope(opts) - scope isa Dagger.UnionScope || return proc - ordered = mpi_union_scope_ordered(accel, scope) - ordered === nothing && return proc - return ordered[mod(Int(uid) - 1, length(ordered)) + 1]::MPIProcessor -end - # At spawn time the scheduler has not yet filled in the execution or result scope function mpi_task_processor(opts::Options)::Union{Nothing,MPIProcessor} (opts.exec_scope === nothing && opts.result_scope === nothing) || return nothing @@ -3125,22 +3156,44 @@ function mpi_task_processor(opts::Options)::Union{Nothing,MPIProcessor} end # Whether the owner of this task reports only failures (see "Failure-only task -# status"). Decided from the task's own options alone, so every rank agrees; it -# holds for every task `elide_task!` may elide. Uniformity checks are collective -# and so rule it out, as does an explicit tag (Datadeps tasks, whose copies and -# waits do not know about failures that arrive this way). +# status"). Captured in the task's own options at submission, independently of +# later optimization/uniformity switches. Only tasks with a validated placement +# bind an owner and use this protocol. mpi_failure_only(::Nothing) = false -function mpi_failure_only(opts::Options) - Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing || return false - return mpi_failure_only(opts, mpi_scope_processor(opts)) -end +mpi_failure_only(opts::Options) = + opts._owner_elision isa OwnerElisionState && opts._owner_elision.owner >= 0 # With the task's processor already worked out (`elide_task!` needs it for other things too) function mpi_failure_only(opts::Options, proc::Union{Nothing,MPIProcessor}) - Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && opts.tag === nothing || return false + opts._owner_elision isa OwnerElisionState && opts.tag === nothing || return false # Only the world communicator: ids and failure tags of other graphs are not uniform return proc !== nothing && proc.comm == MPI.COMM_WORLD end +function Dagger.prepare_owner_elision!(accel::MPIAcceleration, spec, task) + accel.comm == MPI.COMM_WORLD || return + # Root submissions are rank-uniform and ordered. Other producers use the + # ordinary status protocol; their interleaving cannot define a watermark. + current_task() === Base.roottask && !Dagger.in_task() || return + @lock OWNER_ELISION_LOCK begin + OWNER_ELISION_REGISTERED[] = task.uid + eligible = Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && + spec.options.tag === nothing && 0 < task.uid < MPI.tag_ub() && + mpi_elision_host_type(task.metadata.return_type) + if eligible + queue = Dagger.get_options(:task_queue, Dagger.DefaultTaskQueue()) + eligible = queue isa Union{Dagger.DefaultTaskQueue,Dagger.LazyTaskQueue} + end + early = eligible ? pop!(OWNER_ELISION_EARLY, UInt32(task.uid), nothing) : nothing + if eligible + state = OwnerElisionState(UInt32(task.uid), -1, early === nothing ? nothing : early[2]) + OWNER_ELISION_STATES[state] = nothing + spec.options._owner_elision = state + task.owner_elision = state + end + end + return +end + # Whether `local_rank` takes part in moving `v` to the task's rank, or cannot tell function mpi_arg_participates(v, local_rank::Int) if v isa Dagger.DTask @@ -3168,9 +3221,11 @@ function Dagger.Sch.task_failed!(::MPIAcceleration, thunk, value) proc = mpi_scope_processor(opts) MPI.Comm_rank(proc.comm) == proc.rank || return ex = mpi_wire_exception(value isa Dagger.DTaskFailedException ? value.ex : value) - tag = UInt32(thunk.id) + state = opts._owner_elision::OwnerElisionState + @atomic state.error = ex + tag = state.tid Dagger.Sch.errormonitor_tracked("mpi_task_failed", Threads.@spawn begin - bcast_meta_yield(proc.comm, proc.rank, tag, (:error, ex)) + bcast_meta_yield(proc.comm, proc.rank, tag, OwnerFailure(ex)) end) return end @@ -3178,7 +3233,7 @@ end # A fetch that throws on the owner still has to take the generic id that the # broadcast of a successful fetch takes on every other rank (see `poolget`) function Dagger.fetch_failed_uniform!(::MPIAcceleration) - Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && take_ref_id!() + take_ref_id!() return end @@ -3218,9 +3273,22 @@ end function mpi_preplace!(accel::MPIAcceleration, spec, task) opts = spec.options + state = Dagger.Sch.EAGER_STATE[] + state === nothing && return false + # Match the scheduler's option defaults before proving eligibility. Defaults + # may restrict processors even when the caller supplied only a rank scope. + Dagger.options_merge!(opts, state.sch_options) + fargs = spec.fargs + for arg in fargs + Dagger.ispositional(arg) || return false + end + sig = Dagger.Signature(Any[chunktype(Dagger.value(arg)) for arg in fargs]) + Base.invokelatest(Dagger.populate_defaults!, opts, sig) opts.exec_scope === nothing && opts.result_scope === nothing && opts.proclist === nothing && (opts.single === nothing || opts.single == 0) && opts.restore === nothing && opts.tag === nothing || return false + opts.get_result === true && return false + opts.meta === true && return false (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false scope = if opts.compute_scope === nothing opts.scope @@ -3230,7 +3298,6 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) return false end scope === nothing && (scope = Dagger.DefaultScope()) - fargs = spec.fargs f = Dagger.value(fargs[1]) (f isa Function || f isa Type) || return false pref = nothing @@ -3242,28 +3309,34 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) owner < 0 && return false pref === nothing && (pref = owner) end - state = Dagger.Sch.EAGER_STATE[] - state === nothing && return false + for i in 2:length(fargs) + val = Dagger.value(fargs[i]) + val isa Chunk || continue + scope = Dagger.constrain(scope, val.scope) + scope isa Dagger.InvalidScope && return false + end ctx = Dagger.Sch.eager_context() procs = filter(p -> haskey(state.worker_chans, root_worker_id(p)), Dagger.Sch.procs_to_use(ctx, state.sch_options)) isempty(procs) && return false - # The scheduler's own rule (`schedule_one!`): the compatible processors, re-ordered under uniform - # execution by the canonical key with the owner of the first MPI argument in front, then rotated by the id candidates = Processor[p for p in Dagger.Sch.compatible_processors_cached(accel, scope, procs)] isempty(candidates) && return false Dagger.select_processors_uniform!(candidates, accel, MPIPlacementRequest(Int(task.uid), pref), nothing) proc = first(candidates) proc isa MPIProcessor || return false + proc.innerProc isa ThreadProc || return false # What `can_use_proc` would check of the processor the scheduler picks first Dagger.proc_in_scope(proc, scope) || return false - Dagger.iscompatible_func(proc, opts, typeof(f)) || return false + Base.invokelatest(Dagger.iscompatible_func, proc, opts, typeof(f)) || return false for i in 2:length(fargs) - Dagger.iscompatible_arg(proc, opts, chunktype(Dagger.value(fargs[i]))) || return false + Base.invokelatest(Dagger.iscompatible_arg, proc, opts, chunktype(Dagger.value(fargs[i]))) || return false # The scheduler also constrains the task's scope by that of every chunk argument val = Dagger.value(fargs[i]) val isa Chunk && !Dagger.proc_in_scope(proc, val.scope) && return false end - opts.compute_scope = Dagger.ExactScope(proc) + pinned = Dagger.ExactScope(proc) + opts._owner_elision.requested_scope = scope + opts.scope = pinned + opts.compute_scope = pinned return true end @@ -3286,29 +3359,48 @@ function mpi_chunk_scopes_fit(opts::Options, fargs) end function Dagger.elide_task!(accel::MPIAcceleration, spec, task) - CHECK_UNIFORMITY[] && return false + try + return mpi_elide_task!(accel, spec, task) + finally + state = spec.options._owner_elision + if state isa OwnerElisionState && state.owner < 0 + spec.options._owner_elision = nothing + task.owner_elision = nothing + end + end +end + +# A placeholder may use the predicted processor's host space only when the +# actual result cannot introduce another backend. Custom structs and GPU values +# need the normal metadata exchange, even with a concrete declared return type. +mpi_elision_host_type(T) = isconcretetype(T) && T !== Union{} && + ((isbitstype(T) && parentmodule(T) in (Core, Base)) || + T === String || T === Symbol || T <: Array) + +function mpi_elide_task!(accel::MPIAcceleration, spec, task) # Placement, ids and failure tags here are those of the world communicator only accel.comm == MPI.COMM_WORLD || return false opts = spec.options - # Tasks without a scope are placed here, so that every rank knows the owner. - # N.B. The processor a union scope names is looked up once per task: it is the same - # answer every time, and each lookup is a hash-table probe on every task. + T = task.metadata.return_type + mpi_elision_host_type(T) || return false + # An explicit scope that permits several ranks stays a scheduler decision. + mpi_task_scope(opts) === nothing || mpi_scope_processor(opts) !== nothing || return false + # Use the scheduler's registered candidate set and compatibility predicates + # for every scope, then pin the proven decision. A union's syntactic members + # alone do not account for disabled/custom/incompatible processors. + mpi_preplace!(accel, spec, task) || return false proc = mpi_task_processor(opts) - if proc === nothing && opts.compute_scope === nothing && opts.scope === nothing - mpi_preplace!(accel, spec, task) - proc = mpi_task_processor(opts) - end proc === nothing && return false + proc.innerProc isa ThreadProc || return false # Later submissions use this to decide about their own arguments, and `fetch` # to stay uniform when the task fails. Only failure-only tasks have an owner. mpi_failure_only(opts, proc) || return false + opts._owner_elision.owner = proc.rank task.owner = proc.rank local_rank = MPI.Comm_rank(proc.comm) proc.rank == local_rank && return false (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false opts.restore === nothing || return false - T = task.metadata.return_type - (isconcretetype(T) && T !== Union{}) || return false fargs = spec.fargs f = Dagger.value(fargs[1]) (f isa Function || f isa Type) || return false @@ -3320,14 +3412,13 @@ function Dagger.elide_task!(accel::MPIAcceleration, spec, task) mpi_chunk_scopes_fit(opts, fargs) || return false # The placeholder `execute!` stamps on a non-owner, with the id it would get, on the # processor the owner will run it on - proc = mpi_planned_processor(accel, opts, proc, task.uid) space = memory_space(nothing, proc)::MPIMemorySpace # N.B. `execute!` first takes a ref id for the task's tag when the task has no # tag option (`to_tag()`), so the result chunk is the second id of its task. # The owner builds the real chunk with that id, and every rank must agree on it. stub = with(DATADEPS_THUNK_ID => Int64(task.uid)) do opts.tag === nothing && take_ref_id!() - tochunk(nothing, proc, space; type=T) + tochunk(nothing, proc, space; type=T, _owner_elision=opts._owner_elision) end mpi_cleanup_tid(task.uid) task.stub = stub diff --git a/src/dtask.jl b/src/dtask.jl index 7b44846a9..3b41db3f8 100644 --- a/src/dtask.jl +++ b/src/dtask.jl @@ -83,9 +83,10 @@ mutable struct DTask # not known at spawn time. Unlike `owner` it changes nothing about `fetch`; it only lets an # acceleration decide about the *consumers* of the result (see `note_chunk_placement!`). placed::Int + owner_elision::Any thunk_ref::DRef - DTask(uid, future, metadata) = new(uid, future, metadata, nothing, -1, -1) + DTask(uid, future, metadata) = new(uid, future, metadata, nothing, -1, -1, nothing) end const EagerThunk = DTask @@ -111,7 +112,7 @@ function Base.fetch(t::DTask; raw=false, move_value=!raw, unwrap=!raw, uniform=f value = try fetch(t.future; move_value=false, unwrap=false, uniform) catch - fetch_failed_uniform!(current_acceleration()) + move_value && fetch_failed_uniform!(current_acceleration()) rethrow() end return move_value ? move(OSProc(), value) : value diff --git a/src/options.jl b/src/options.jl index 32fd7a685..8b984798c 100644 --- a/src/options.jl +++ b/src/options.jl @@ -77,6 +77,9 @@ Base.@kwdef mutable struct Options writes::Union{Vector{Int},Nothing} = nothing return_type::Union{Type,Nothing} = nothing + + # Private acceleration state captured at submission, never propagated to children. + _owner_elision = nothing end Options(::Nothing) = Options() function Options(old_options::NamedTuple) diff --git a/src/submission.jl b/src/submission.jl index f1c394a7a..a2dc12140 100644 --- a/src/submission.jl +++ b/src/submission.jl @@ -542,17 +542,27 @@ arg_chunktypes(fargs::Vector) = ntuple(i->chunktype(value(fargs[i+1])), length(fargs)-1) function eager_spawn(spec::DTaskSpec) + # A reused/copied Options must not inherit another task's failure lifetime. + spec.options._owner_elision = nothing # Generate new unlaunched DTask - uid = eager_next_id() future = ThunkFuture() metadata = DTaskMetadata(spec) + # Metadata may invoke user hooks. Finish it before taking the id, so a + # reentrant root submission cannot advance an acceleration's registration + # watermark past a task whose state has not been published yet. + uid = eager_next_id() # Propagate inferred return type to options if isconcretetype(metadata.return_type) spec.options.return_type = metadata.return_type end - return DTask(uid, future, metadata) + task = DTask(uid, future, metadata) + accel = spec.options.acceleration + accel === nothing || prepare_owner_elision!(accel, spec, task) + return task end +prepare_owner_elision!(::Acceleration, spec, task) = nothing + chunktype(t::DTask) = t.metadata.return_type const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) @@ -565,10 +575,10 @@ Switch owner elision on or off for this process (off by default); see changed at run time. Under SPMD every rank must call it with the same value at the same point of the program. -Whether a task reports only failures is decided when it runs, so a change of the flag -first waits until the tasks already submitted have finished (a task submitted under -the old value that ran under the new one would leave the other ranks waiting for a -status that never comes). It therefore must not be called from inside a task. +The result protocol is captured when the task is submitted. Changing the flag +waits until previously submitted tasks finish, and must not be called from +inside a task. Existing task and result handles continue to report failures +after the flag is changed. """ function elide_foreign_tasks!(on::Bool=true) if ELIDE_FOREIGN_TASKS[] != on @@ -603,19 +613,22 @@ elide_task!(::Acceleration, spec, task) = false # made the call sites ~90 % of this function's samples. One dispatch here, onto the # concrete spec type, leaves everything below statically typed. eager_launch!(pair::DTaskPair) = _eager_launch!(pair.spec, pair.task) -function _eager_launch!(spec::DTaskSpec, task::DTask) - +function _try_owner_elision!(spec::DTaskSpec, task::DTask) # Tasks this process only has to account for (never run or source data for) # skip the thunk entirely - if ELIDE_FOREIGN_TASKS[] && !Dagger.in_task() + if task.owner_elision !== nothing && !Dagger.in_task() # The first real submission starts the eager scheduler, which takes a task # id of its own. Elision must not change which process consumes which # ids (they feed the uniform MPI tags), so start it here, at the same # point in the id sequence, whether or not this task is elided. Sch.EAGER_STATE[] === nothing && myid() == 1 && Sch.init_eager() accel = spec.options.acceleration - accel !== nothing && elide_task!(accel, spec, task) && return + accel !== nothing && elide_task!(accel, spec, task) && return true end + return false +end +function _eager_launch!(spec::DTaskSpec, task::DTask) + _try_owner_elision!(spec, task) && return # Assign a name, if specified eager_assign_name!(spec, task) diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 588075eb2..72b22a697 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -9,6 +9,19 @@ elide_blocksum(x::Matrix{Float64}) = sum(x) elide_slow_throws(x::Int) = (sleep(0.5); x > 0 ? error("elide_slow_throws") : x) elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw +elide_filtered_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) +Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, ::Type{typeof(elide_filtered_where)}) = + p.innerProc.tid == last(Dagger.default_pool_tids()) +elide_default_target() = 42 +elide_allow_last(p) = p.innerProc isa Dagger.ThreadProc && p.innerProc.tid == last(Dagger.default_pool_tids()) +Dagger.default_option(::Val{:proclist}, ::Type{typeof(elide_default_target)}) = elide_allow_last + +function elide_orphan_state() + state = MPIExt.OwnerElisionState(UInt32(0), 0, nothing) + @lock MPIExt.OWNER_ELISION_LOCK MPIExt.OWNER_ELISION_STATES[state] = nothing + MPIExt.owner_elision_deliver!(0, UInt32(0), ErrorException("orphan elision failure")) + return WeakRef(state) +end @testset "Owner elision" begin cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) @@ -253,11 +266,85 @@ elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete bad = Dagger.@spawn scope=pinned(0) elide_slow_throws(1) Dagger.elide_foreign_tasks!(false) @test isready(bad) # the owner's task was waited for + @test_throws Exception fetch(bad) # old handles work while the switch stays off + @test_throws Exception fetch(bad) # failure is retained for repeated fetches + Dagger.check_uniformity!(true) + @test fetch(Dagger.@spawn scope=pinned(0) elide_inc(1)) == 2 + Dagger.check_uniformity!(false) Dagger.elide_foreign_tasks!(true) - @test_throws Exception fetch(bad) # and every rank still sees the failure @test_throws Exception fetch(Dagger.@spawn scope=pinned(0) Dagger.elide_foreign_tasks!(false)) end + @testset "scoped placement respects processor eligibility" begin + target = nranks - 1 + tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_filtered_where()) for _ in 1:8] + @test all(w -> first(w) == target, fetch.(tasks)) + stamped = [(p.rank, p.innerProc.tid) for p in (fetch(t; raw=true).processor for t in tasks)] + @test all(==((target, last(Dagger.default_pool_tids()))), stamped) + @test allequal(MPI.Allgather(hash(stamped), comm)) + # A default proclist is applied by the scheduler even when the + # caller did not supply it explicitly. Such tasks use full planning. + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_default_target() + @test t.stub === nothing + @test t.owner < 0 + @test fetch(t) == 42 + end + + @testset "failure lifetime follows handles" begin + target = nranks - 1 + # Earlier failures have warmed the error path. Let the owner submit + # first, so its failure arrives before peers register this task. + if rank != target + deadline = time() + 10 + while (@lock MPIExt.OWNER_ELISION_LOCK isempty(MPIExt.OWNER_ELISION_EARLY)) && time() < deadline + sleep(0.001) + end + @test (@lock MPIExt.OWNER_ELISION_LOCK !isempty(MPIExt.OWNER_ELISION_EARLY)) + end + bad = Dagger.@spawn scope=pinned(target) elide_throws(1) + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + state = bad.owner_elision + @test state isa MPIExt.OwnerElisionState + @test (@atomic state.error) !== nothing + # Serialization must reconnect a ref to the live local state rather + # than create a snapshot which misses a later failure notification. + io = IOBuffer() + MPIExt.Serialization.serialize(io, state) + seekstart(io) + @test MPIExt.Serialization.deserialize(io) === state + # A raw failed fetch consumes no generic fetch id on either rank. + raw = try + fetch(bad; raw=true) + catch + nothing + end + @test (raw === nothing) == (rank == target) + bad = nothing + GC.gc() + if rank != target + @test raw.handle.owner_elision === state + @test_throws Exception MPIExt.mpi_poisonable(raw.handle) do + MPIExt.mpi_check_poison() + end + @test_throws Exception MPIExt.mpi_poisonable(raw.handle) do + MPIExt.mpi_check_poison() + end + end + @test fetch(Dagger.@spawn scope=pinned(target) elide_inc(2)) == 3 + # Typed failures are not retained in the relay's ordinary FIFO. + relay = MPIExt.bcast_state_for(comm) + @test (@lock relay.cond !haskey(relay.slots, (target, state.tid))) + @test (@lock MPIExt.OWNER_ELISION_LOCK isempty(MPIExt.OWNER_ELISION_EARLY)) + orphan = elide_orphan_state() + for _ in 1:10 + GC.gc() + orphan.value === nothing && break + sleep(0.01) + end + @test orphan.value === nothing + end + @testset "later SPMD work is unaffected" begin y = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) fill(2.0, 8) s = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) sum(y) From ab16c901ec1f3459bb9089f6a23f422406c3cb19 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:58:05 -0700 Subject: [PATCH 46/59] Apply owner elision to bulk submissions in dependency order Visit the captured submission mode of each pair before building the remaining bulk payload. This lets later pairs consume earlier placeholders and preserves bulk scheduling for participating ranks. Three bulk-chain assertions pass on each of two ranks as part of the170/166 owner-elision checks. The disabled path borrows the existing batch without allocating a filtered vector. Written by an AI agent on jpsamaroo's review feedback. --- src/submission.jl | 16 ++++++++++++++++ test/mpi/elide.jl | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/submission.jl b/src/submission.jl index a2dc12140..d6a546ff3 100644 --- a/src/submission.jl +++ b/src/submission.jl @@ -676,6 +676,22 @@ function _submission_fargs!(spec::DTaskSpec) end end function eager_launch!(pairs::Vector{DTaskPair}) + for pair in pairs + if pair.task.owner_elision !== nothing + # Examine in submission order: a later task can use the placeholder + # just produced for an earlier task in this same batch. + remaining = DTaskPair[] + sizehint!(remaining, length(pairs)) + for candidate in pairs + _try_owner_elision!(candidate.spec, candidate.task) || push!(remaining, candidate) + end + isempty(remaining) || _eager_launch_batch!(remaining) + return + end + end + _eager_launch_batch!(pairs) +end +function _eager_launch_batch!(pairs::Vector{DTaskPair}) ntasks = length(pairs) # Assign a name, if specified diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 72b22a697..8a5e8ba8e 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -275,6 +275,18 @@ end @test_throws Exception fetch(Dagger.@spawn scope=pinned(0) Dagger.elide_foreign_tasks!(false)) end + @testset "bulk submission keeps owner elision" begin + target = nranks - 1 + tasks = Dagger.spawn_bulk() do + a = Dagger.@spawn scope=pinned(target) elide_inc(1) + b = Dagger.@spawn scope=pinned(target) elide_inc(a) + (a, b) + end + @test fetch.(tasks) == (2, 3) + @test all(t -> (t.stub !== nothing) == (rank != target), tasks) + @test all(t -> t.owner == target, tasks) + end + @testset "scoped placement respects processor eligibility" begin target = nranks - 1 tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_filtered_where()) for _ in 1:8] From 9a6ad55dfed4675acd19c66cbcf69f0d098ba724 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:58:05 -0700 Subject: [PATCH 47/59] Select the first canonical elision candidate without copying and sorting Reuse the scheduler canonical candidate cache and select its preferred-rank rotation directly. Borrow a typed processor scratch vector instead of allocating a worker filter per task. Ten1000-call warmup batches, GC, then five samples: original preplacement92000allocs/3504000B; correctness-proof version102000/3920000B; final17000/704000B. Existing owner/rank/argument-affinity checks compare actual placement and result metadata across ranks. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 614bd160b..cb0235a48 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -3250,12 +3250,6 @@ end # processor list, a processor that rejects the function or an argument) is left to # the scheduler and nothing is elided. -struct MPIPlacementRequest - id::Int - pref::Union{Int,Nothing} -end -Dagger.task_processor_preference(::MPIAcceleration, req::MPIPlacementRequest, state) = req.pref - # Rank that owns `v`, `nothing` for a plain value (the scheduler ignores those when it # looks for the owner), `-1` when it cannot be told at spawn time function mpi_arg_owner(v) @@ -3316,12 +3310,25 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) scope isa Dagger.InvalidScope && return false end ctx = Dagger.Sch.eager_context() - procs = filter(p -> haskey(state.worker_chans, root_worker_id(p)), Dagger.Sch.procs_to_use(ctx, state.sch_options)) + procs = Dagger.@reusable_vector :mpi_elision_procs Processor OSProc() 32 + for candidate in Dagger.Sch.procs_to_use(ctx, state.sch_options) + haskey(state.worker_chans, root_worker_id(candidate)) && push!(procs, candidate) + end isempty(procs) && return false - candidates = Processor[p for p in Dagger.Sch.compatible_processors_cached(accel, scope, procs)] + # The scheduler's own rule (`schedule_one!`): the compatible processors, re-ordered under uniform + # execution by the canonical key with the owner of the first MPI argument in front, then rotated by the id + candidates = Dagger.Sch.compatible_processors_ordered(accel, scope, procs) isempty(candidates) && return false - Dagger.select_processors_uniform!(candidates, accel, MPIPlacementRequest(Int(task.uid), pref), nothing) - proc = first(candidates) + # Only the first candidate is needed. Select the same preferred rank/ring + # offset as place_processors_uniform!, without copying or rotating the cache. + lo, hi = 1, length(candidates) + if pref !== nothing + first_pref, last_pref = Dagger.preferred_processor_range(candidates, accel, pref) + if first_pref <= last_pref + lo, hi = first_pref, last_pref + end + end + proc = candidates[lo + mod(Int(task.uid) - 1, hi - lo + 1)] proc isa MPIProcessor || return false proc.innerProc isa ThreadProc || return false # What `can_use_proc` would check of the processor the scheduler picks first From 33401b54a6d1f8a35bdf071941bf826693e7f7e0 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:04:48 -0700 Subject: [PATCH 48/59] Keep free CPU execution inside extension compatibility constraints A rank-wide scope can still have function or argument compatibility that admits only some CPU threads. The old scope-only decision allowed the selected logical processor to execute on an incompatible physical thread. Check every canonical CPU candidate before choosing the migratable path; otherwise pin to the scheduler's validated processor. Use the same Tf, argument types and options as scheduling, and permit an explicit scope argument for the owner-elision layer's retained requested scope. Real two-rank control expected threadids[3,3] but observed[2,3] before. New compatibility controls pass3 assertions/rank. The combined scopes, serialization and free-thread suites pass on two ranks with4default+1 interactive (pinned to2CPUs) and1default+1interactive. Replace the old scope-only fake launch fixture with real TaskSpecs so it also exercises compatibility metadata. After10x5000 warm queries+GC, minimum of5 samples: scope-only TaskSpec control and full compatibility query both allocate240000bytes/5000calls at4/64/512virtual ranks with2local CPU candidates (48B/call unchanged). The retained canonical scope-only lookup remains covered by the earlier zero-allocation probe; this is the broader task-metadata query, not an end-to-end benchmark. Exact-membership cache remains188644bytes. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 8 ++++++ docs/src/mpi.md | 6 +++-- ext/MPIExt.jl | 24 +++++++++++++++--- test/mpi/free_threads.jl | 54 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 86 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 37ce9fc4e..b76be9385 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1266,3 +1266,11 @@ this section verbatim). Each entry is one bullet starting with `- `. becomes sticky; do not unset sticky while its children may still rely on the affinity. Close its channel before publishing readiness, and replace closed slots on dispatch, so a new payload cannot be lost during retirement. + +113. **Free-thread execution still needs processor compatibility.** A broad + MPI scope does not imply that an extension's `iscompatible_func` or + `iscompatible_arg` accepts every CPU thread. Before making a task + migratable, check those predicates across its rank's CPU candidates with + the scheduler's function/argument types. Otherwise a logically compatible + selected processor can execute on an incompatible physical thread. Test + restrictive hooks while their sole eligible thread is busy. diff --git a/docs/src/mpi.md b/docs/src/mpi.md index 3143c8ffc..4ac853ac1 100644 --- a/docs/src/mpi.md +++ b/docs/src/mpi.md @@ -200,8 +200,10 @@ with rank information: (CPU RAM, or device VRAM) used to track where data resides. An MPI CPU task whose scope permits every default-pool thread of its rank can -run on any free default-pool thread. A scope that excludes any of those threads -keeps the task on the scheduler's selected thread. `Dagger.task_processor()` +run on any free default-pool thread when its function and arguments are also +compatible with every CPU thread. A scope or extension compatibility predicate +that excludes any of those threads keeps the task on the scheduler's selected +thread. `Dagger.task_processor()` reports the MPI processor for the thread executing that query; a migratable task can observe a different thread after yielding. Interactive threads remain outside the CPU processor pool. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 4086560b3..0ef3fff78 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2555,7 +2555,9 @@ end # waits behind anything that occupies that thread without yielding (a long kernel, a # rank-local task), whichever thread the scheduler happened to name. A task whose scope # leaves every thread of its rank open did not ask for a thread: the choice is the -# runtime's and need not be kept, so it runs on whichever thread of its rank is free. +# runtime's and need not be kept, so it runs on whichever eligible thread of its rank is free. +# Custom function/argument compatibility that excludes a CPU thread also pins execution +# to the processor selected by the scheduler. # A task whose scope excludes some thread of its rank (an `ExactScope`, which is what # Datadeps and explicit pinning use, or a union of only some threads) did ask for one: # it stays on the thread of the processor the scheduler picked within that scope. @@ -2605,6 +2607,22 @@ function mpi_thread_requested_slow(thread_scopes, scope) return false end +# A broad scope does not override extension compatibility constraints. A +# custom function/argument predicate may support only some CPU threads, so +# every physical candidate must be eligible before Julia may migrate the task. +function mpi_task_thread_requested(proc::MPIProcessor, task::Dagger.Sch.TaskSpec, scope=task.scope) + mpi_thread_requested(proc, scope) && return true + options = task.options::Dagger.Options + for scope in mpi_thread_scopes(proc) + candidate = scope.processor::MPIProcessor{ThreadProc} + Dagger.iscompatible_func(candidate, options, task.Tf) || return true + for idx in 2:length(task.data) + Dagger.iscompatible_arg(candidate, options, chunktype(task.data[idx])) || return true + end + end + return false +end + # Start the task of an MPI processor already pinned to the thread of its inner processor. # Without this the task is migratable, and `execute!(::ThreadProc)` then misses its inline # fast path: it creates a second task pinned to the thread, schedules it and waits, which @@ -2615,13 +2633,13 @@ end # of chunk arguments), the same one `mpi_execute_inner` looks at. function Dagger.Sch.task_tid_for_processor(proc::MPIProcessor{Dagger.ThreadProc}, task) proc.rank == MPI.Comm_rank(proc.comm) || return nothing - mpi_thread_requested(proc, task.scope) || return nothing + mpi_task_thread_requested(proc, task) || return nothing return Dagger.Sch.task_tid_for_processor(proc.innerProc) end function mpi_execute_inner(proc::MPIProcessor, f, args...; kwargs...) if proc.innerProc isa ThreadProc && Dagger.in_task() && - !mpi_thread_requested(proc, Dagger.get_tls().task_spec.scope) + !mpi_task_thread_requested(proc, Dagger.get_tls().task_spec) return Dagger.execute_thread_function(f, args...; kwargs...) end return execute!(proc.innerProc, f, args...; kwargs...) diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index ddf40a913..66b5e6f0f 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -142,7 +142,14 @@ end mine = first(sort(filter(p -> p.rank == rank, cpus); by=p -> p.innerProc.tid)) others = filter(p -> p.rank != rank, cpus) tid_for = Dagger.Sch.task_tid_for_processor - spec(scope) = (; scope = scope) # the hook only reads `task.scope` + function spec(scope) + task = Dagger.Sch.TaskSpec() + task.scope = scope + task.options = Dagger.Options() + task.Tf = typeof(free_where) + push!(task.data, Dagger.Argument(1, free_where)) + return task + end # (a rank with one thread has none to choose from: its exact scope leaves nothing out) nthr = count(p -> p.rank == rank, cpus) @test tid_for(mine, spec(Dagger.ExactScope(mine))) == (nthr > 1 ? mine.innerProc.tid : nothing) @@ -191,3 +198,48 @@ end A .= 1.0 @test sum(A) == 256 * 256 end + +# Compatibility can constrain physical execution even when scope leaves a +# whole rank open. These hooks intentionally support only its last CPU thread. +free_filtered_where() = Threads.threadid() +struct FreeFilteredArgument end +free_filtered_argument(::FreeFilteredArgument) = Threads.threadid() +Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, + ::Type{typeof(free_filtered_where)}) = + p.innerProc.tid == last(Dagger.default_pool_tids()) +Dagger.iscompatible_arg(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, + ::Type{FreeFilteredArgument}) = + p.innerProc.tid == last(Dagger.default_pool_tids()) + +@testset "Free MPI execution respects compatibility hooks" begin + cpus = filter(p -> p.rank == 0 && p.innerProc isa Dagger.ThreadProc, mpi_procs()) + target = only(filter(p -> p.innerProc.tid == last(Dagger.default_pool_tids()), cpus)) + scope = Dagger.scope(mpi_rank=0) + spec = Dagger.Sch.TaskSpec() + spec.scope = scope + spec.options = Dagger.Options() + spec.Tf = typeof(free_filtered_where) + push!(spec.data, Dagger.Argument(1, free_filtered_where)) + @test MPIExt.mpi_task_thread_requested(target, spec) == (length(cpus) > 1) + spec.Tf = typeof(free_filtered_argument) + spec.data[1].value = free_filtered_argument + push!(spec.data, Dagger.Argument(2, FreeFilteredArgument())) + @test MPIExt.mpi_task_thread_requested(target, spec) == (length(cpus) > 1) + # A busy eligible thread must still execute these tasks itself; another + # free CPU thread may not bypass the function/argument predicate. + foreach(fetch, Dagger.with_options(; scope) do + [Dagger.@spawn(free_filtered_where()), + Dagger.@spawn(free_filtered_argument(FreeFilteredArgument()))] + end) + warm = Dagger.@spawn scope=Dagger.ExactScope(target) hog_busy(0.01) + wait(warm) + blocker = Dagger.@spawn scope=Dagger.ExactScope(target) hog_busy(1.0) + sleep(0.1) + tasks = Dagger.with_options(; scope) do + [Dagger.@spawn(free_filtered_where()), + Dagger.@spawn(free_filtered_argument(FreeFilteredArgument()))] + end + @test fetch.(tasks) == fill(target.innerProc.tid, 2) + wait(blocker) + MPI.Barrier(comm) +end From cd2b81730a7fda17f95abf132d8464cf5ac7bda5 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:16:12 -0700 Subject: [PATCH 49/59] Preserve user options when pinning a proven elision placement Custom compatibility predicates can inspect task options. Rewriting scope and compute_scope after validating a candidate changed those predicates before the scheduler ran them. Keep the proven scope in private elision state and constrain only the effective scheduler scope. Preserve the original requested scope for CPU execution policy. The previous option-scope probe fails; expanded two-rank owner-elision coverage including this predicate passes175/171 assertions. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 16 +++++++++++----- src/acceleration.jl | 4 ++++ src/sch/Sch.jl | 11 +++++++++-- test/mpi/elide.jl | 9 +++++++++ 4 files changed, 33 insertions(+), 7 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index cb0235a48..c2005e51e 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -854,8 +854,9 @@ mutable struct OwnerElisionState owner::Int @atomic error::Any requested_scope::Any + pinned_scope::Any end -OwnerElisionState(tid, owner, err) = OwnerElisionState(tid, owner, err, nothing) +OwnerElisionState(tid, owner, err) = OwnerElisionState(tid, owner, err, nothing, nothing) struct OwnerFailure error::Any end @@ -884,6 +885,7 @@ function Serialization.serialize(s::Serialization.AbstractSerializer, state::Own Serialization.serialize(s, state.owner) Serialization.serialize(s, @atomic(state.error)) Serialization.serialize(s, state.requested_scope) + Serialization.serialize(s, state.pinned_scope) end function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnerElisionState}) tid = Serialization.deserialize(s)::UInt32 @@ -907,6 +909,8 @@ function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{O err === nothing || (@atomic state.error = err) scope = Serialization.deserialize(s) state.requested_scope === nothing && (state.requested_scope = scope) + pinned = Serialization.deserialize(s) + state.pinned_scope === nothing && (state.pinned_scope = pinned) return state end @@ -983,6 +987,7 @@ function schedule_argument_move(::MPIAcceleration, thunk_id::Integer, f::Functio return nothing end + # MPI is the only backend that observes SCHED_MOVE inside moves (to suppress # tag creation); the default acceleration performs the move with no scope. Dagger.sched_move(::MPIAcceleration, to_proc, @nospecialize(value)) = @@ -3162,6 +3167,8 @@ end mpi_failure_only(::Nothing) = false mpi_failure_only(opts::Options) = opts._owner_elision isa OwnerElisionState && opts._owner_elision.owner >= 0 +Dagger.preplaced_scope(::MPIAcceleration, opts::Options) = + mpi_failure_only(opts) ? opts._owner_elision.pinned_scope : nothing # With the task's processor already worked out (`elide_task!` needs it for other things too) function mpi_failure_only(opts::Options, proc::Union{Nothing,MPIProcessor}) opts._owner_elision isa OwnerElisionState && opts.tag === nothing || return false @@ -3218,7 +3225,7 @@ end function Dagger.Sch.task_failed!(::MPIAcceleration, thunk, value) opts = thunk.options mpi_failure_only(opts) || return - proc = mpi_scope_processor(opts) + proc = opts._owner_elision.pinned_scope.processor MPI.Comm_rank(proc.comm) == proc.rank || return ex = mpi_wire_exception(value isa Dagger.DTaskFailedException ? value.ex : value) state = opts._owner_elision::OwnerElisionState @@ -3342,8 +3349,7 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) end pinned = Dagger.ExactScope(proc) opts._owner_elision.requested_scope = scope - opts.scope = pinned - opts.compute_scope = pinned + opts._owner_elision.pinned_scope = pinned return true end @@ -3396,7 +3402,7 @@ function mpi_elide_task!(accel::MPIAcceleration, spec, task) # for every scope, then pin the proven decision. A union's syntactic members # alone do not account for disabled/custom/incompatible processors. mpi_preplace!(accel, spec, task) || return false - proc = mpi_task_processor(opts) + proc = opts._owner_elision.pinned_scope.processor proc === nothing && return false proc.innerProc isa ThreadProc || return false # Later submissions use this to decide about their own arguments, and `fetch` diff --git a/src/acceleration.jl b/src/acceleration.jl index e7bbd0cc8..5e44d67ea 100644 --- a/src/acceleration.jl +++ b/src/acceleration.jl @@ -137,6 +137,10 @@ cleanup_tasks_accel!(accel::Acceleration, tasks) = schedule_argument_move(::Acceleration, ::Integer, f::Function) = Threads.@spawn f() +# A proven placement may narrow the scheduler's effective scope without +# rewriting the user options observed by custom compatibility predicates. +preplaced_scope(::Acceleration, ::Options) = nothing + """ sched_move(accel, to_proc, value) -> Any diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index dce35f22f..a2fcc0124 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1037,6 +1037,7 @@ concurrently across threads. options = task.options Dagger.options_merge!(options, state.sch_options) Dagger.populate_defaults!(options, sig) + accel = something(options.acceleration, current_acceleration()) # Calculate scope. Errors are stored in `scope_ex` and applied in Phase 3. local scope @@ -1069,6 +1070,14 @@ concurrently across threads. end end + if scope_ex === nothing + preplaced = Dagger.preplaced_scope(accel, options) + if preplaced !== nothing + scope = constrain(scope, preplaced) + scope isa InvalidScope && (scope_ex = SchedulingException("Preplaced processor is outside the task scope")) + end + end + if scope_ex !== nothing # scope is invalid — fail the task under state.lock (set_failed! requires it) lock(state.lock) do @@ -1086,8 +1095,6 @@ concurrently across threads. # processors, imposes a deterministic processor order, and (under uniform # execution) makes selection ignore rank-local capacity/occupancy so every # rank picks the same processor for this task. - accel = something(options.acceleration, current_acceleration()) - sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32 if uniform_execution(accel) # Measured costs are rank-local, so under uniform execution the diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 8a5e8ba8e..37dbf9ecb 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -13,6 +13,10 @@ elide_filtered_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, ::Type{typeof(elide_filtered_where)}) = p.innerProc.tid == last(Dagger.default_pool_tids()) elide_default_target() = 42 +elide_option_scope_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) +Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, opts::Dagger.Options, + ::Type{typeof(elide_option_scope_where)}) = + opts.compute_scope isa Dagger.UnionScope && p.innerProc.tid == last(Dagger.default_pool_tids()) elide_allow_last(p) = p.innerProc isa Dagger.ThreadProc && p.innerProc.tid == last(Dagger.default_pool_tids()) Dagger.default_option(::Val{:proclist}, ::Type{typeof(elide_default_target)}) = elide_allow_last @@ -81,6 +85,11 @@ end # member of the scope, so the ranks disagreed on `chunk.processor`) stamped = [(p.rank, p.innerProc.tid) for p in (fetch(t; raw=true).processor for t in tasks)] @test allequal(MPI.Allgather(hash(stamped), comm)) + # Predicates may inspect user options. Proven logical placement + # must not rewrite those options before the scheduler checks them. + option_tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_option_scope_where()) for _ in 1:8] + @test all(w -> first(w) == target, fetch.(option_tasks)) + @test all(t -> fetch(t; raw=true).processor.innerProc.tid == last(Dagger.default_pool_tids()), option_tasks) # a chain across two rank-level scopes, and a failure a = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) elide_inc(1) b = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_add(a, 10) From 76b791548877d5fbca06a3a4011b009150ba3454 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:19:29 -0700 Subject: [PATCH 50/59] Wait for the receiver before sending an elided task argument A source can advance past arguments it does not own while the task owner is still waiting for an earlier one. If that earlier source fails, a later rendezvous send has no receiver and MPI.Cancel need not finish it. Publish failures from every participating rank, propagate task poison through argument moves, and use point-to-point readiness on the independent metadata relay before posting data. Readiness waits share the progress heartbeat and retain only blocked consumers. A weak task-id index avoids per-argument scans and prunes dead metadata once per GC. The two-rank egress failure and three-rank failed-first-argument/8MiB-later-send controls previously hang; both now throw and complete later uniform work. Three-rank owner-elision suite passes226/226/222 assertions, including repeated source permits and1MiB successful transfers. Native no-memory/function arguments retain their existing move context; readiness applies only to data chunks. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 11 +++ ext/MPIExt.jl | 167 +++++++++++++++++++++++++++++++++++++------- src/acceleration.jl | 2 + src/sch/Sch.jl | 5 +- test/mpi/elide.jl | 37 +++++++++- 5 files changed, 193 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 692977dfe..f0e487f69 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1268,3 +1268,14 @@ this section verbatim). Each entry is one bullet starting with `- `. lagging rank's submission; retain only those early messages until ordered root registration reaches their task id. Generate that id after metadata hooks finish, so reentrant submission cannot skip a registration gap. + +113. **An MPI source may reach a later argument before its receiver.** Moves + are ordered within each rank, not across ranks: a spectator of argument 1 + can already post argument 2's rendezvous send while the owner still waits + for argument 1. If argument 1 fails, the owner never receives argument 2; + MPI.Cancel does not guarantee that unmatched send will complete. Failure-only + owner elision therefore waits for receiver readiness before posting each + cross-rank argument. Route readiness through the independent metadata relay, + and make readiness waits poisonable, so no data request depends on a peer + that already abandoned the task. Preserve live request buffers until MPI + completes or cancels their transfer when an active wait throws. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index c2005e51e..f6d89c0c2 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -855,26 +855,108 @@ mutable struct OwnerElisionState @atomic error::Any requested_scope::Any pinned_scope::Any + ready::Int + ready_cond::Union{Threads.Condition,Nothing} end -OwnerElisionState(tid, owner, err) = OwnerElisionState(tid, owner, err, nothing, nothing) +OwnerElisionState(tid, owner, err) = OwnerElisionState(tid, owner, err, nothing, nothing, 0, nothing) struct OwnerFailure error::Any end -const OWNER_ELISION_STATES = WeakKeyDict{OwnerElisionState,Nothing}() +struct OwnerMoveReady end +mutable struct OwnerEarlyState + error::Any + ready::Int +end +const OWNER_ELISION_STATES = Dict{UInt32,WeakRef}() +const OWNER_ELISION_WAITING = Dict{UInt32,OwnerElisionState}() +const OWNER_ELISION_DIRTY = Threads.Atomic{Bool}(false) const OWNER_ELISION_LOCK = ReentrantLock() const OWNER_ELISION_REGISTERED = Ref{UInt}(0) -# A fast owner can fail before a lagging rank submits the same root task. -# Retain only messages ahead of that rank's root-submission watermark. -const OWNER_ELISION_EARLY = Dict{UInt32,Tuple{Int,Any}}() +# A fast owner can notify a rank before its root submits the same task. +const OWNER_ELISION_EARLY = Dict{UInt32,OwnerEarlyState}() +owner_elision_released!(::OwnerElisionState) = (OWNER_ELISION_DIRTY[] = true; nothing) +# Called with OWNER_ELISION_LOCK held. A shared finalizer marks dead weak +# entries; prune once per GC rather than scanning live tasks per argument. +function owner_elision_register!(state::OwnerElisionState) + if Threads.atomic_xchg!(OWNER_ELISION_DIRTY, false) + for (tid, ref) in OWNER_ELISION_STATES + ref.value === nothing && delete!(OWNER_ELISION_STATES, tid) + end + end + finalizer(owner_elision_released!, state) + OWNER_ELISION_STATES[state.tid] = WeakRef(state) + return state +end +function owner_elision_lookup(tid::UInt32) + ref = get(OWNER_ELISION_STATES, tid, nothing) + return ref === nothing ? nothing : ref.value::Union{OwnerElisionState,Nothing} +end function owner_elision_deliver!(root::Int, tag::UInt32, err) @lock OWNER_ELISION_LOCK begin - for state in keys(OWNER_ELISION_STATES) - if state.tid == tag - @atomic state.error = err + state = owner_elision_lookup(tag) + if state !== nothing + @atomic state.error = err + state.ready_cond === nothing || notify(state.ready_cond) + end + if UInt(tag) > OWNER_ELISION_REGISTERED[] + early = get!(()->OwnerEarlyState(nothing, 0), OWNER_ELISION_EARLY, tag) + early.error = err + end + end + return +end +function owner_elision_ready!(tag::UInt32) + @lock OWNER_ELISION_LOCK begin + state = owner_elision_lookup(tag) + if state !== nothing + state.ready += 1 + state.ready_cond === nothing || notify(state.ready_cond) + end + if UInt(tag) > OWNER_ELISION_REGISTERED[] + early = get!(()->OwnerEarlyState(nothing, 0), OWNER_ELISION_EARLY, tag) + early.ready += 1 + end + end + note_mpi_progress!() + return +end +function owner_elision_wait_ready!(state::OwnerElisionState) + timer = DeadlockTimer() + @lock OWNER_ELISION_LOCK begin + try + while true + err = @atomic state.error + err === nothing || throw(err) + if state.ready > 0 + state.ready -= 1 + return + end + timer = mpi_deadlock_detect(timer, MPI.Comm_rank(MPI.COMM_WORLD), state.tid, + "owner-elision argument readiness", state.owner) + if state.ready_cond === nothing + state.ready_cond = Threads.Condition(OWNER_ELISION_LOCK) + end + OWNER_ELISION_WAITING[state.tid] = state + wait(state.ready_cond) end + finally + delete!(OWNER_ELISION_WAITING, state.tid) end - UInt(tag) > OWNER_ELISION_REGISTERED[] && (OWNER_ELISION_EARLY[tag] = (root, err)) + end +end + +# The relay receives readiness independently of task execution, so this tiny +# control send can finish even if its source task has already failed. Data is +# posted only after the destination reaches this argument; later sources then +# observe poison while waiting, without abandoned rendezvous sends. +function owner_elision_request_argument!(comm::MPI.Comm, source::Int, state::OwnerElisionState) + relay = bcast_state_for(comm) + buf = bcast_serialize((MPI.Comm_rank(comm), OwnerMoveReady())) + req = MPI.Isend(buf, relay.bcast_comm; dest=source, tag=state.tid) + with(POISON_REF => nothing, POISON_TASK => nothing) do + __wait_for_request(req, relay.bcast_comm, MPI.Comm_rank(comm), source, state.tid, + "owner-elision argument readiness", "send") end return end @@ -891,18 +973,8 @@ function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{O tid = Serialization.deserialize(s)::UInt32 owner = Serialization.deserialize(s)::Int state = @lock OWNER_ELISION_LOCK begin - found = nothing - for candidate in keys(OWNER_ELISION_STATES) - if candidate.tid == tid - found = candidate - break - end - end - if found === nothing - found = OwnerElisionState(tid, owner, nothing) - OWNER_ELISION_STATES[found] = nothing - end - found + found = owner_elision_lookup(tid) + found === nothing ? owner_elision_register!(OwnerElisionState(tid, owner, nothing)) : found end Serialization.deserialize_cycle(s, state) err = Serialization.deserialize(s) @@ -986,7 +1058,14 @@ function schedule_argument_move(::MPIAcceleration, thunk_id::Integer, f::Functio end return nothing end - +function schedule_argument_move(accel::MPIAcceleration, thunk_id::Integer, f::Function, opts::Options, @nospecialize(value)) + state = opts._owner_elision + if !(state isa OwnerElisionState) || !(value isa Chunk) || value isa Chunk{<:Union{Function,Type}} + return schedule_argument_move(accel, thunk_id, f) + end + with(f, DATADEPS_THUNK_ID => Int64(thunk_id), POISON_TASK => state) + return nothing +end # MPI is the only backend that observes SCHED_MOVE inside moves (to suppress # tag creation); the default acceleration performs the move with no scope. @@ -1465,6 +1544,11 @@ end function mpi_deadlock_detect(timer::DeadlockTimer, rank, tag, kind, srcdest) # A wait on a task's result ends in that task's error when its owner failed POISON_REF[] === nothing || mpi_check_poison() + task_state = POISON_TASK[] + if task_state !== nothing + err = @atomic task_state.error + err === nothing || throw(err) + end timer.detect || return timer progress = MPI_PROGRESS[] if progress != timer.last_progress @@ -1622,6 +1706,11 @@ function bcast_heartbeat!(state::BcastState) cond === nothing || notify(cond) end end + @lock OWNER_ELISION_LOCK begin + for waiting in values(OWNER_ELISION_WAITING) + notify(waiting.ready_cond::Threads.Condition) + end + end return end @@ -1744,6 +1833,10 @@ function bcast_relay_loop(state::BcastState, spin_iters::Int=BCAST_RELAY_SPIN_IT req = MPI.Imrecv!(MPI.Buffer(buf), msg) __wait_for_request(req, comm, rank, src, tag, "bcast_relay", "recv") root, value = Serialization.deserialize(IOBuffer(buf)) + if value isa OwnerMoveReady + owner_elision_ready!(tag) + continue + end for child in bcast_tree_children(rank, Int(root), sz) sreq = MPI.Isend(buf, comm; dest=child, tag=tag) __wait_for_request(sreq, comm, rank, child, tag, "bcast_relay", "send") @@ -1866,6 +1959,7 @@ end # `mpi_deadlock_detect`, which checks it. const POISON_REF = ScopedValue{Union{MPIRef,Nothing}}(nothing) +const POISON_TASK = ScopedValue{Union{OwnerElisionState,Nothing}}(nothing) function mpi_check_poison() ref = POISON_REF[]::MPIRef @@ -2545,6 +2639,14 @@ function move(src::MPIProcessor, dst::MPIProcessor, x::Chunk) # Source processor for egress uses the chunk's owning rank from = src.rank == x.handle.rank ? src : MPIProcessor(src.innerProc, src.comm, x.handle.rank) + state = POISON_TASK[] + if state !== nothing + if local_rank == x.handle.rank + owner_elision_wait_ready!(state) + elseif local_rank == dst.rank + owner_elision_request_argument!(dst.comm, x.handle.rank, state) + end + end if local_rank == x.handle.rank value = move(from, dst, poolget(x.handle; uniform=false)) send_yield(value, dst.comm, dst.rank, tag) @@ -3182,6 +3284,11 @@ function Dagger.prepare_owner_elision!(accel::MPIAcceleration, spec, task) # ordinary status protocol; their interleaving cannot define a watermark. current_task() === Base.roottask && !Dagger.in_task() || return @lock OWNER_ELISION_LOCK begin + if Threads.atomic_xchg!(OWNER_ELISION_DIRTY, false) + for (tid, ref) in OWNER_ELISION_STATES + ref.value === nothing && delete!(OWNER_ELISION_STATES, tid) + end + end OWNER_ELISION_REGISTERED[] = task.uid eligible = Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && spec.options.tag === nothing && 0 < task.uid < MPI.tag_ub() && @@ -3192,8 +3299,13 @@ function Dagger.prepare_owner_elision!(accel::MPIAcceleration, spec, task) end early = eligible ? pop!(OWNER_ELISION_EARLY, UInt32(task.uid), nothing) : nothing if eligible - state = OwnerElisionState(UInt32(task.uid), -1, early === nothing ? nothing : early[2]) - OWNER_ELISION_STATES[state] = nothing + state = owner_elision_lookup(UInt32(task.uid)) + state === nothing && (state = owner_elision_register!(OwnerElisionState(UInt32(task.uid), -1, nothing))) + if early !== nothing + early.error === nothing || (@atomic state.error = early.error) + # An existing deserialized state has already counted these. + state.ready = max(state.ready, early.ready) + end spec.options._owner_elision = state task.owner_elision = state end @@ -3226,13 +3338,16 @@ function Dagger.Sch.task_failed!(::MPIAcceleration, thunk, value) opts = thunk.options mpi_failure_only(opts) || return proc = opts._owner_elision.pinned_scope.processor - MPI.Comm_rank(proc.comm) == proc.rank || return + # An argument's source rank can fail before the owner receives its data. + # Every participating rank must publish such a failure, so the owner's + # pending receive and spectators' result fetches can both terminate. + reporter = MPI.Comm_rank(proc.comm) ex = mpi_wire_exception(value isa Dagger.DTaskFailedException ? value.ex : value) state = opts._owner_elision::OwnerElisionState @atomic state.error = ex tag = state.tid Dagger.Sch.errormonitor_tracked("mpi_task_failed", Threads.@spawn begin - bcast_meta_yield(proc.comm, proc.rank, tag, OwnerFailure(ex)) + bcast_meta_yield(proc.comm, reporter, tag, OwnerFailure(ex)) end) return end diff --git a/src/acceleration.jl b/src/acceleration.jl index 5e44d67ea..049331cc9 100644 --- a/src/acceleration.jl +++ b/src/acceleration.jl @@ -136,6 +136,8 @@ cleanup_tasks_accel!(accel::Acceleration, tasks) = foreach(t -> cleanup_task_accel!(accel, t), tasks) schedule_argument_move(::Acceleration, ::Integer, f::Function) = Threads.@spawn f() +schedule_argument_move(accel::Acceleration, id::Integer, f::Function, ::Options, value) = + schedule_argument_move(accel, id, f) # A proven placement may narrow the scheduler's effective scope without # rewriting the user options observed by custom compatibility predicates. diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index a2fcc0124..ecbcd3184 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2282,6 +2282,7 @@ struct MoveCtx{A<:Dagger.Acceleration,P<:Processor} to_proc::P thunk_id::Int f::Any + options::Options end """ @@ -2299,7 +2300,7 @@ function maybe_async_move!(arg, mctx::MoveCtx) end #=FIXME:REALLOC_TASKS=# return schedule_argument_move(mctx.accel, mctx.thunk_id, - () -> move_one_argument!(arg, mctx)) + () -> move_one_argument!(arg, mctx), mctx.options, Dagger.value(arg)) end function move_one_argument!(arg, mctx::MoveCtx) @@ -2473,7 +2474,7 @@ Executes a single task specified by `task` on `to_proc`. # rank-uniform tags derived from the thunk ID; they must run sequentially # in argument order (FIFO tag matching), with the thunk's TID in scope accel = something(options.acceleration, current_acceleration()) - mctx = MoveCtx(ctx, accel, to_proc, thunk_id, f) + mctx = MoveCtx(ctx, accel, to_proc, thunk_id, f, options) fetch_tasks = nothing for arg in _data t = maybe_async_move!(arg, mctx) diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 37dbf9ecb..5d3159884 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -22,10 +22,16 @@ Dagger.default_option(::Val{:proclist}, ::Type{typeof(elide_default_target)}) = function elide_orphan_state() state = MPIExt.OwnerElisionState(UInt32(0), 0, nothing) - @lock MPIExt.OWNER_ELISION_LOCK MPIExt.OWNER_ELISION_STATES[state] = nothing + @lock MPIExt.OWNER_ELISION_LOCK MPIExt.owner_elision_register!(state) MPIExt.owner_elision_deliver!(0, UInt32(0), ErrorException("orphan elision failure")) return WeakRef(state) end +struct ElideMoveFailure end +Dagger.move(::MPIExt.MPIProcessor, ::MPIExt.MPIProcessor, ::ElideMoveFailure) = + (sleep(0.1); error("expected owner-elision source transfer failure")) +elide_consume(::ElideMoveFailure) = 1 +elide_consume(::ElideMoveFailure, b::Vector{UInt8}) = length(b) +elide_sum_bytes(a::Vector{UInt8}, b::Vector{UInt8}, c::Vector{UInt8}) = Int(sum(a) + sum(b) + sum(c)) @testset "Owner elision" begin cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) @@ -296,6 +302,35 @@ end @test all(t -> t.owner == target, tasks) end + @testset "source argument failure reaches the owner" begin + if nranks > 1 + x = Dagger.tochunk(ElideMoveFailure(), proc_for_rank(0), space_for_rank(0)) + bad = Dagger.@spawn scope=pinned(nranks-1) elide_consume(x) + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + Dagger.check_uniformity!(true) + @test fetch(Dagger.@spawn scope=pinned(nranks-1) elide_inc(8)) == 9 + Dagger.check_uniformity!(false) + end + if nranks >= 3 + # Rank 2 can reach the second argument while the owner still + # waits for the failing first one. Wait for receiver readiness + # before posting this rendezvous payload, so rank 2 can abort. + x = Dagger.tochunk(ElideMoveFailure(), proc_for_rank(0), space_for_rank(0)) + big = Dagger.tochunk(zeros(UInt8, 8*1024*1024), proc_for_rank(2), space_for_rank(2)) + bad = Dagger.@spawn scope=pinned(1) elide_consume(x, big) + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + # Repeated arguments from one source receive distinct permits. + a = Dagger.tochunk(ones(UInt8, 1024*1024), proc_for_rank(0), space_for_rank(0)) + b = Dagger.tochunk(ones(UInt8, 1024*1024), proc_for_rank(2), space_for_rank(2)) + @test fetch(Dagger.@spawn scope=pinned(1) elide_sum_bytes(a, b, b)) == 3*1024*1024 + Dagger.check_uniformity!(true) + @test fetch(Dagger.@spawn scope=pinned(1) elide_inc(8)) == 9 + Dagger.check_uniformity!(false) + end + end + @testset "scoped placement respects processor eligibility" begin target = nranks - 1 tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_filtered_where()) for _ in 1:8] From f7270cf618e3774f72f700a996d1654c0be72e78 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:23:49 -0700 Subject: [PATCH 51/59] Keep MPI request buffers alive until a failed wait completes cleanup A poison or timeout exception must not let Request_free release an in-flight communication buffer. Cancel pending sends and drain their request; matched Imrecv requests finish their existing transfer. Cleanup ignores task poison and sleeps between polls so the paired peer can make progress. Receiver readiness separately prevents later data sends from depending on an owner that abandoned an earlier argument. A real8MiB rendezvous request control notifies the paired peer precisely at cancellation, avoiding JIT/timing assumptions: the old wait passes2/fails2 lifetime assertions; the new wait passes4. Full three-rank owner-elision checks including this control pass230/226/222. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 37 +++++++++++++++++++--------- test/mpi/elide.jl | 62 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 11 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index f6d89c0c2..239f4033e 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1477,19 +1477,34 @@ end function __wait_for_request(req, comm, my_rank, their_rank, tag, fn::String, kind::String) timer = DeadlockTimer() - while true - finish, status = MPI.Test(req, MPI.Status) - if finish - if MPI.Get_error(status) != MPI.SUCCESS - error("$fn failed with error $(MPI.Get_error(status))") + try + while true + finish, status = MPI.Test(req, MPI.Status) + if finish + if MPI.Get_error(status) != MPI.SUCCESS + error("$fn failed with error $(MPI.Get_error(status))") + end + # Every completed request is this rank's proof of life for the + # waits running concurrently with it (see `MPI_PROGRESS`). + note_mpi_progress!() + return end - # Every completed request is this rank's proof of life for the - # waits running concurrently with it (see `MPI_PROGRESS`). - note_mpi_progress!() - return + timer = mpi_deadlock_detect(timer, my_rank, tag, kind, their_rank) + yield() end - timer = mpi_deadlock_detect(timer, my_rank, tag, kind, their_rank) - yield() + catch + # Request_free does not finish the transfer. Its finalizer releases the + # Julia buffer, so retain the request until MPI is done with that buffer. + # An unmatched send can be cancelled; Imrecv has already matched a + # message and must finish receiving it. Cleanup deliberately ignores + # poison and sleeps between polls to let peer tasks make progress. + if !MPI.isnull(req) + kind == "send" && MPI.Cancel!(req) + while !MPI.Test(req) + sleep(0.0001) + end + end + rethrow() end end diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 5d3159884..3036f8f14 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -33,6 +33,23 @@ elide_consume(::ElideMoveFailure) = 1 elide_consume(::ElideMoveFailure, b::Vector{UInt8}) = length(b) elide_sum_bytes(a::Vector{UInt8}, b::Vector{UInt8}, c::Vector{UInt8}) = Int(sum(a) + sum(b) + sum(c)) +# Notify the real MPI peer at cancellation, without timing/JIT assumptions. +# Completion and buffer ownership are still those of an actual rendezvous send. +mutable struct ElideCleanupRequest <: MPI.AbstractRequest + request::MPI.Request + comm::MPI.Comm + signal_tag::UInt32 + signalled::Bool +end +MPI.isnull(req::ElideCleanupRequest) = MPI.isnull(req.request) +MPI.Test(req::ElideCleanupRequest) = MPI.Test(req.request) +MPI.Test(req::ElideCleanupRequest, ::Type{MPI.Status}) = MPI.Test(req.request, MPI.Status) +function MPI.Cancel!(req::ElideCleanupRequest) + req.signalled = true + MPI.send(true, req.comm; dest=1, tag=req.signal_tag) + MPI.Cancel!(req.request) +end + @testset "Owner elision" begin cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) pinned(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) @@ -331,6 +348,51 @@ elide_sum_bytes(a::Vector{UInt8}, b::Vector{UInt8}, c::Vector{UInt8}) = Int(sum( end end + @testset "active request retains its buffer through failure" begin + if nranks > 1 + tag = UInt32(MPI.tag_ub() - 2048) + if rank == 0 + request = MPI.Isend(zeros(UInt8, 8*1024*1024), comm; dest=1, tag) + req = ElideCleanupRequest(request, comm, tag + UInt32(1), false) + @test !MPI.Test(request) + poison = MPIExt.OwnerElisionState(tag, 0, ErrorException("expected active-request poison")) + try + @test_throws ErrorException MPIExt.with(MPIExt.POISON_TASK => poison) do + MPIExt.__wait_for_request(req, comm, 0, 1, tag, "cleanup test", "send") + end + @test MPI.isnull(request) + @test request.buffer === nothing + finally + # The pre-fix control also drains its native request, + # after recording the failed lifetime assertions. + if !req.signalled + MPI.send(true, comm; dest=1, tag=tag+UInt32(1)) + end + while !MPI.Test(request) + sleep(0.001) + end + MPI.send(true, comm; dest=1, tag=tag+UInt32(2)) + end + elseif rank == 1 + MPI.recv(comm; source=0, tag=tag+UInt32(1)) + while true + if MPI.Iprobe(comm; source=0, tag) + MPI.Recv!(zeros(UInt8, 8*1024*1024), comm; source=0, tag) + elseif MPI.Iprobe(comm; source=0, tag=tag+UInt32(2)) + MPI.recv(comm; source=0, tag=tag+UInt32(2)) + break + else + sleep(0.001) + end + end + end + barrier = MPI.Ibarrier(comm) + while !MPI.Test(barrier) + sleep(0.001) + end + end + end + @testset "scoped placement respects processor eligibility" begin target = nranks - 1 tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_filtered_where()) for _ in 1:8] From d1508b604ea80fd5c7fd5ff012cf054ba202f0ef Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:30:28 -0700 Subject: [PATCH 52/59] Exercise GPU owner-elision metadata fallback in every shared backend suite A GPU-scoped task may return a host scalar or Array. Assert that elision is refused and all ranks retain the actual host type/space from the ordinary exchange. The shared OpenCL entrypoint passes12 assertions/rank; the original pre-fix control stamped nonowner host results as VRAM. Written by an AI agent on jpsamaroo's review feedback. --- test/mpi/elide_gpu.jl | 25 +++++++++++++++++++++++++ test/mpi/gpu_suite.jl | 4 ++++ 2 files changed, 29 insertions(+) create mode 100644 test/mpi/elide_gpu.jl diff --git a/test/mpi/elide_gpu.jl b/test/mpi/elide_gpu.jl new file mode 100644 index 000000000..3d328178f --- /dev/null +++ b/test/mpi/elide_gpu.jl @@ -0,0 +1,25 @@ +mpi_elide_gpu_scalar() = 7 +mpi_elide_gpu_host() = ones(Float32, 4) + +function test_owner_elision_gpu(gpu_scope) + old_uniform = Dagger.CHECK_UNIFORMITY[] + old_elision = Dagger.ELIDE_FOREIGN_TASKS[] + Dagger.check_uniformity!(false) + Dagger.elide_foreign_tasks!(true) + try + for (f, T) in ((mpi_elide_gpu_scalar, Int), (mpi_elide_gpu_host, Vector{Float32})) + task = Dagger.@spawn scope=gpu_scope return_type=T f() + @test task.stub === nothing + @test task.owner < 0 + chunk = fetch(task; raw=true) + @test chunk.chunktype === T + @test Dagger.memory_space(chunk).innerSpace isa Dagger.CPURAMMemorySpace + stamp = hash((chunk.chunktype, Dagger.memory_space(chunk))) + @test allequal(MPI.Allgather(stamp, MPI.COMM_WORLD)) + @test fetch(task) == (T === Int ? 7 : ones(Float32, 4)) + end + finally + Dagger.elide_foreign_tasks!(old_elision) + Dagger.check_uniformity!(old_uniform) + end +end diff --git a/test/mpi/gpu_suite.jl b/test/mpi/gpu_suite.jl index 3455a28f4..7ed41df4d 100644 --- a/test/mpi/gpu_suite.jl +++ b/test/mpi/gpu_suite.jl @@ -40,6 +40,7 @@ include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "..", "array", "linalg", "matvec_defs.jl")) +include("elide_gpu.jl") # Broadcast-only mutation helpers (scalar indexing is illegal on GPU arrays) add1!(X) = (X .+= 1; nothing) @@ -91,6 +92,9 @@ function run_mpi_gpu_suite(cfg) cpu_proc_for_rank(r) = first(filter(p->p.rank == r && p.innerProc isa Dagger.ThreadProc, mpi_procs())) gpu_scope(r) = Dagger.ExactScope(gpu_proc_for_rank(r)) cpu_scope(r) = Dagger.ExactScope(cpu_proc_for_rank(r)) + @testset "$(cfg.name) owner elision keeps actual result metadata" begin + test_owner_elision_gpu(gpu_scope(nranks-1)) + end all_gpu_scope() = Dagger.UnionScope([gpu_scope(r) for r in 0:nranks-1]...) # GPU processors are not default-enabled; regions mixing CPU and GPU tasks # must opt in via an outer scope that includes both kinds From c5524643a3e8aee54e69a752b321f671498bdfc2 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:38:44 -0700 Subject: [PATCH 53/59] Inherit the reviewed relay scope and overlap regression repairs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clear creation-time dynamic scope before starting the persistent metadata relay. Port the exact074f2f9a relay test: it validates cleared scope and compares the delayed consumer timestamp strictly inside the destination-local non-yielding interval, avoiding cross-node clock assumptions and planning-window false passes. Focused2rank×2default+1interactive checks pass3 assertions/rank; the independent816 reviewer already validated the exact4default overlap test and its legacy-placement negative control. Written by an AI agent on jpsamaroo's review feedback. --- ext/MPIExt.jl | 1 + test/mpi/relay.jl | 33 +++++++++++++++++++++++++-------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index d7753a936..ca10e8eb3 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1887,6 +1887,7 @@ function start_bcast_relay!(accel_comm::MPI.Comm) # One that stays on the driver's thread shares that thread and must yield to the tasks there. spin_iters = migratable ? 0 : BCAST_RELAY_SPIN_ITERS t = Task(() -> bcast_relay_loop(state, spin_iters)) + Dagger.clear_task_scope!(t) if migratable Dagger.set_task_migratable!(t) else diff --git a/test/mpi/relay.jl b/test/mpi/relay.jl index d57c35299..1a41f8b44 100644 --- a/test/mpi/relay.jl +++ b/test/mpi/relay.jl @@ -2,6 +2,7 @@ # driver's thread stalls behind a driver parked in a blocking call (a long non-yielding computation, # an `MPI` collective), and the ranks that wait for what it forwards wait with it. relay_union_value() = rand() < 2 ? 1 : "never" # non-concrete result type: broadcast to every rank +relay_delayed_union_value(delay::Float64) = (sleep(delay); relay_union_value()) relay_stamp(x) = time() relay_hog(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; nothing) @@ -15,26 +16,42 @@ relay_hog(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; no @test Base.current_task().sticky MPI.Barrier(comm) MPIExt.stop_bcast_relay!(accel.comm) - MPIExt.start_bcast_relay!(accel.comm) + Dagger.with_options(; scope=pin(0)) do + MPIExt.start_bcast_relay!(accel.comm) + end + relay = lock(MPIExt.BCAST_STATES) do states + states[accel.comm].relay + end + @static if VERSION >= v"1.11-" + @test getfield(relay, :scope) === nothing + else + @test getfield(relay, :logstate) === nothing + end MPI.Barrier(comm) # Whatever its placement, it forwards broadcasts w = Dagger.@spawn scope=pin(0) relay_union_value() @test fetch(Dagger.@spawn scope=pin(nranks - 1) relay_stamp(w)) isa Float64 MPI.Barrier(comm) if nranks >= 2 && Threads.nthreads(:default) >= 4 - # The last rank's driver is busy for 1.5 s without yielding. Rank 0 produces a value whose type - # is broadcast, and a task on the last rank consumes it: it can only start once that rank's relay - # has delivered the value, so its start time measures the relay, not the driver. - t0 = time() - x = Dagger.@spawn scope=pin(0) relay_union_value() + # Warm the delayed producer and its consumer before measuring. Its + # metadata must arrive after the destination driver starts its hog, + # rather than slipping through during the planning sleep below. + warm = Dagger.@spawn scope=pin(0) relay_delayed_union_value(0.0) + fetch(Dagger.@spawn scope=pin(nranks - 1) relay_stamp(warm)) + MPI.Barrier(comm) + x = Dagger.@spawn scope=pin(0) relay_delayed_union_value(0.6) s = Dagger.@spawn scope=pin(nranks - 1) relay_stamp(x) + hog_start = hog_end = 0.0 if rank == nranks - 1 sleep(0.2) # let the tasks be planned + hog_start = time() relay_hog(1.5) + hog_end = time() end started = fetch(s) - # The hog still has well over a second to run when the task starts - rank == nranks - 1 || @test started - t0 < 1.0 + # All three timestamps come from the destination. The consumer must + # actually start while its driver is unable to forward the metadata. + rank == nranks - 1 && @test hog_start < started < hog_end MPI.Barrier(comm) end end From 4625151637ac5b9b5398b0b60ebc5c9c36cc3090 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 18:43:02 -0700 Subject: [PATCH 54/59] Keep checkpoint callbacks on every MPI rank Per-task checkpoint hooks run on each normal local thunk result, including metadata-only spectators. Conservatively reject checkpointed tasks after option defaults, so owner elision cannot drop a documented callback. Independent exact-d150 control recorded hits[1,1] with elision off and[0,1] on. Durable on/off all-rank regression now passes as part of240/236/232 three-rank owner-elision checks. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 3 +++ ext/MPIExt.jl | 1 + test/mpi/elide.jl | 16 ++++++++++++++++ 3 files changed, 20 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 50b2f2f0e..cb22e7950 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1268,6 +1268,9 @@ this section verbatim). Each entry is one bullet starting with `- `. lagging rank's submission; retain only those early messages until ordered root registration reaches their task id. Generate that id after metadata hooks finish, so reentrant submission cannot skip a registration gap. + A per-task checkpoint hook makes every rank a participant, even when its + result is only metadata there. Reject checkpointed tasks after option + defaults are applied; elision must preserve each rank's callback. 113. **An MPI source may reach a later argument before its receiver.** Moves are ordered within each rank, not across ranks: a spectator of argument 1 diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index ca10e8eb3..7eff319c6 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -3439,6 +3439,7 @@ function mpi_preplace!(accel::MPIAcceleration, spec, task) opts.exec_scope === nothing && opts.result_scope === nothing && opts.proclist === nothing && (opts.single === nothing || opts.single == 0) && opts.restore === nothing && opts.tag === nothing || return false + opts.checkpoint === nothing || return false opts.get_result === true && return false opts.meta === true && return false (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 3036f8f14..25577d44e 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -8,6 +8,8 @@ elide_len(x::Vector{Int}) = length(x) # concrete, cannot throw elide_blocksum(x::Matrix{Float64}) = sum(x) elide_slow_throws(x::Int) = (sleep(0.5); x > 0 ? error("elide_slow_throws") : x) elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) +const ELIDE_CHECKPOINT_HITS = Threads.Atomic{Int}(0) +elide_checkpoint_hit(node, result) = (Threads.atomic_add!(ELIDE_CHECKPOINT_HITS, 1); nothing) elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw elide_filtered_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, ::Type{typeof(elide_filtered_where)}) = @@ -273,6 +275,20 @@ end @test fetch(v) == 2 end + @testset "checkpoint callbacks still run on every rank" begin + for enabled in (false, true) + Dagger.elide_foreign_tasks!(enabled) + before = ELIDE_CHECKPOINT_HITS[] + t = Dagger.@spawn scope=pinned(nranks-1) checkpoint=elide_checkpoint_hit elide_inc(1) + @test fetch(t) == 2 + @test t.stub === nothing + @test t.owner < 0 + hits = ELIDE_CHECKPOINT_HITS[] - before + @test hits == 1 + @test all(==(1), MPI.Allgather(hits, comm)) + end + end + @testset "tasks that may throw" begin # success: elided like any other, nobody waits for a status ok = Dagger.@spawn scope=pinned(0) elide_throws(0) From 64086864b5d417e46a919ae2818e298a40456a75 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 19:21:23 -0700 Subject: [PATCH 55/59] Keep captured owner-elision protocol ahead of return inference A declared concrete return type may infer as Union{} for an always-throwing kernel. Ordinary metadata then has no consumer on an elided rank and retains the error indefinitely. Honor the submission protocol before inference planning and stamp its declared type. Three-rank owner suite passes 244/240/236 assertions, including repeated failed fetches with no FIFO residue. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 3 +++ ext/MPIExt.jl | 33 ++++++++++++++++++--------------- test/mpi/elide.jl | 12 ++++++++++++ 3 files changed, 33 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cb22e7950..467124b99 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1271,6 +1271,9 @@ this section verbatim). Each entry is one bullet starting with `- `. A per-task checkpoint hook makes every rank a participant, even when its result is only metadata there. Reject checkpointed tasks after option defaults are applied; elision must preserve each rank's callback. + Captured failure-only mode also precedes inference-based broadcast planning: + an explicitly declared result can infer as `Union{}` when it always throws, + but elided ranks still cannot consume an ordinary metadata/error FIFO slot. 113. **An MPI source may reach a later argument before its receiver.** Moves are ordered within each rank, not across ranks: a spectator of argument 1 diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 7eff319c6..ce6c52085 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2960,8 +2960,25 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) return tochunk(result, proc, space; type=typeof(result)) end + opts = Dagger.get_tls().task_spec.options + owner_state = opts._owner_elision + + # Captured elision is a protocol choice made at submission, independent of + # inference here. A declared concrete return type can still infer as Any or + # Union{}; ordinary metadata would have no consumer on an elided rank. + if mpi_failure_only(opts) + if islocal + # task_failed! covers failures in f and in argument movement. + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) + space = mpi_result_space(result, proc) + return tochunk(result, proc, space; type=opts.return_type, _owner_elision=owner_state) + else + space = memory_space(nothing, proc)::MPIMemorySpace + return tochunk(nothing, proc, space; type=opts.return_type, _owner_elision=owner_state) + end + end + plan = mpi_execute_bcast_plan(f, args, proc) - owner_state = Dagger.in_task() ? Dagger.get_tls().task_spec.options._owner_elision : nothing # Concrete + nothrow: type/space known locally and the call cannot throw, # so non-owners need no status or metadata traffic. Stamp the inferred @@ -2980,20 +2997,6 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) # Concrete but may throw: broadcast only status (no T/space on the wire). # Type inference still skips metadata; poison keeps SPMD aligned on error. if !plan.need_type_bcast - if mpi_failure_only(Dagger.in_task() ? Dagger.get_tls().task_spec.options : nothing) - # Status only on failure (see "Failure-only task status"): nobody waits - # for success, so a rank that is not the owner stamps its placeholder at once - if islocal - # N.B. A failure reaches the other ranks from `task_failed!`, which - # covers every way this task can fail, not only an error in `f` - result = mpi_execute_inner(proc, f, raw_args...; kwargs...) - space = mpi_result_space(result, proc) - return tochunk(result, proc, space; type=plan.inferred, _owner_elision=owner_state) - else - space = memory_space(nothing, proc)::MPIMemorySpace - return tochunk(nothing, proc, space; type=plan.inferred, _owner_elision=owner_state) - end - end if islocal result = try mpi_execute_inner(proc, f, raw_args...; kwargs...) diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl index 25577d44e..1644ed846 100644 --- a/test/mpi/elide.jl +++ b/test/mpi/elide.jl @@ -479,6 +479,18 @@ end @test orphan.value === nothing end + @testset "declared return type preserves failure-only protocol" begin + target = nranks - 1 + # Bottom inference must not switch a captured task back to the + # ordinary metadata FIFO: spectator tasks no longer consume it. + bad = Dagger.@spawn scope=pinned(target) return_type=Int error("declared failure") + @test bad.owner_elision isa MPIExt.OwnerElisionState + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + relay = MPIExt.bcast_state_for(comm) + @test (@lock relay.cond !haskey(relay.slots, (target, UInt32(bad.uid)))) + end + @testset "later SPMD work is unaffected" begin y = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) fill(2.0, 8) s = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) sum(y) From 67eb43fccfb13800c93587692d2ca5263e147743 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 00:07:35 -0700 Subject: [PATCH 56/59] Keep stolen Python calls on their GIL-owning thread Port the independently reviewed Python fix from #815 commit c5ccdcc526bf6c1f664fc39b5092ceade99367e6. The work stealer can run a Python callable on a default CPU thread even though Python's GIL is owned by an interactive thread. Route that typed execution through PythonProcessor. Each offload gets a private pinned task and response, preserving captured Python exceptions and distinct concurrent results. Pass only the profiling flag and scalar task ID into that task so cancellation cannot expose recycled Dagger task metadata. Keep the existing branch-specific MPI execution code. Validation: on this branch's immutable source snapshot, Julia 1.13.4 with 2 default + 1 interactive threads, PythonCall 0.9.37 and Python 3.14.6 passes 6 public NumPy assertions, 10 CPU-dispatch/keyword/error/concurrent-result assertions, the matching 3-assertion stolen-dispatch control, and 2 ordinary CPU controls. The controller exits successfully in a credential-free offline sandbox. These checks do not establish full MPI or backend CI parity. The upstream offload allocation measurement is an intentional correctness tradeoff: after ten 1000-call warmups and five GC-separated samples, 1000 calls change from 112000 B / 6000 allocations to 416000 B / 8000 (+304 B / 2 allocations per call). This branch port does not claim a new whole-package allocation or throughput measurement. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 15 +++++++++++++ ext/PythonExt.jl | 50 ++++++++++++++++++++++++++++++++++++++++-- test/extlang/python.jl | 22 +++++++++++++++++++ 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 467124b99..49c758f03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1301,3 +1301,18 @@ this section verbatim). Each entry is one bullet starting with `- `. the scheduler's function/argument types. Otherwise a logically compatible selected processor can execute on an incompatible physical thread. Test restrictive hooks while their sole eligible thread is busy. + +116. **Stolen Python work still needs Python's GIL.** The CPU work stealer's + broad compatibility predicate can select a Python callable even though + direct placement prefers `PythonProcessor`. Registering only default-pool + CPU threads exposes this when the GIL belongs to interactive thread 1. + Delegate typed `ThreadProc`/`Py` execution to the GIL-safe Python executor, + retaining CPU profiling and exception handling. Use a private result per + offloaded call: PythonCall's shared reply channel can mix concurrent or + cancelled callers, and its error printer runs on the receiving thread + without the GIL. Remember the interpreter's actual initialization thread + rather than assuming thread 1. A one-shot task there can return the original + captured exception as a value, without formatting it there. A successful + direct-placement test does not exercise the stealing dispatch. Do not give + the offloaded task pooled Dagger TLS: cancellation can recycle that metadata + while Python is still finishing. Copy only the logging flag and scalar ID. diff --git a/ext/PythonExt.jl b/ext/PythonExt.jl index 9783c9f48..3b3156ad9 100644 --- a/ext/PythonExt.jl +++ b/ext/PythonExt.jl @@ -16,6 +16,11 @@ struct PythonProcessor <: Processor owner::Int end +# PythonCall initializes its interpreter on the importing Julia thread, which +# need not be thread 1. Discover that thread once rather than sharing its +# request/response channel for every task execution. +const PYTHON_GIL_THREAD = Ref{Int}(0) + Dagger.root_worker_id(proc::PythonProcessor) = proc.owner Dagger.get_parent(proc::PythonProcessor) = OSProc(proc.owner) Dagger.default_enabled(::PythonProcessor) = true @@ -38,17 +43,58 @@ function Dagger.execute!(::PythonProcessor, f, args...; kwargs...) # CPython requires that the GIL is held by the calling thread. By default # the GIL is held by the thread that initialized Python (the main thread), # so calling into Python from a Dagger worker thread without the GIL - # segfaults. Mirror PythonCall's own approach (see `Base.propertynames`): + # segfaults. Like PythonCall's own approach (see `Base.propertynames`), # if the current thread holds the GIL, call directly; otherwise hand the # call off to the GIL-holding main thread. if PythonCall.C.PyGILState_Check() == 1 return f(args...; kwargs...) else - return PythonCall.C.on_main_thread(() -> f(args...; kwargs...)) + # PythonCall's shared request/response channels neither associate a + # reply with its caller nor keep exception rendering on the GIL owner. + # A private task gives each invocation its own result, including when + # its waiter is cancelled. Return exceptions as values so fetch does + # not render a Python exception on the waiting CPU thread. + # The old Python helper did not run with Dagger TLS. Keep that + # behavior: a cancelled caller can recycle its pooled task metadata + # while this Python invocation is still finishing. + logging = Dagger.task_logging_enabled() + task_id = logging ? (Dagger.task_id()::Int) : 0 + task = Task() do + try + PythonCall.C.PyGILState_Check() == 1 || error("Python's interpreter thread no longer holds the GIL") + if logging + Dagger.TimespanLogging.prof_task_put!(task_id) + end + Some(f(args...; kwargs...)) + catch err + CapturedException(err, catch_backtrace()) + end + end + Dagger.set_task_tid!(task, PYTHON_GIL_THREAD[]) + schedule(task) + response = fetch(task) + if response isa CapturedException + response.ex isa InterruptException && throw(response.ex) + throw(response) + end + return something(response) end end +# CPU work stealing can select Python work through ThreadProc's broad +# compatibility predicate. Keep the CPU execution's profiling/error handling, +# but invoke Python through the same GIL-safe path as its own processor. +function Dagger.execute!(proc::ThreadProc, f::Py, args...; kwargs...) + return Dagger.execute_thread_function(Dagger.execute!, PythonProcessor(proc.owner), + f, args...; kwargs...) +end + function __init__() + PYTHON_GIL_THREAD[] = if PythonCall.C.PyGILState_Check() == 1 + Threads.threadid() + else + PythonCall.C.on_main_thread(Threads.threadid)::Int + end Dagger.add_processor_callback!(:pythonproc) do return PythonProcessor(myid()) end diff --git a/test/extlang/python.jl b/test/extlang/python.jl index 64e6d62c2..9257b93b2 100644 --- a/test/extlang/python.jl +++ b/test/extlang/python.jl @@ -27,3 +27,25 @@ Dagger.cancel!(;halt_sch=true) @test result isa Py @test pyconvert(Array, result) == [9, 12, 15] end + +@testset "Python execution from CPU work stealing" begin + # The scheduler may steal Python work onto a CPU processor even though + # direct Python placement prefers PythonProcessor. Exercise that dispatch + # from a real Dagger task, with its normal TLS and profiling state. + function execute_python_on_cpu(f, args...; kwargs...) + Dagger.execute!(Dagger.task_processor(), f, args...; kwargs...) + end + cpu_procs = [p for p in Dagger.get_processors(Dagger.OSProc()) if p isa Dagger.ThreadProc] + builtins = pyimport("builtins") + for proc in cpu_procs + result = fetch(Dagger.@spawn scope=Dagger.ExactScope(proc) execute_python_on_cpu(builtins.sum, [1, 2, 3])) + @test result isa Py + @test pyconvert(Int, result) == 6 + result = fetch(Dagger.@spawn scope=Dagger.ExactScope(proc) execute_python_on_cpu(builtins.sorted, [1, 3, 2]; reverse=true)) + @test pyconvert(String, pyrepr(result)) == "[3, 2, 1]" + @test_throws Dagger.DTaskFailedException fetch(Dagger.@spawn scope=Dagger.ExactScope(proc) execute_python_on_cpu(builtins.int, "invalid integer")) + end + tasks = [Dagger.@spawn scope=Dagger.ExactScope(cpu_procs[mod1(i, length(cpu_procs))]) execute_python_on_cpu(builtins.sum, [i, i + 1]) for i in 1:24] + @test pyconvert.(Int, fetch.(tasks)) == [2i + 1 for i in 1:24] + @test_throws Dagger.DTaskFailedException fetch(Dagger.@spawn builtins.int("invalid integer")) +end From 2c53299285fc640f42a602762b508c58038e0312 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 11:33:50 -0700 Subject: [PATCH 57/59] Tolerate absent execution options in failure notifications The acceleration failure hook runs during dependency failure propagation, including for thunks without execution options. Reading acceleration from nothing aborts the eager scheduler before downstream futures are filled, masking the original failure. Return when there is no options metadata and keep normal acceleration notifications unchanged. Add a source-to-dependent failure regression with a real scheduler state and future, including positive acceleration dispatch and duplicate-finish suppression. Current OpenCL jobs on both owner-elision branches expose the missing-options exception; this repair does not claim to fix the original GPU failure hidden by it. Native validation is pending the resource grant. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 8 ++++++ src/sch/util.jl | 6 +++- test/scheduler.jl | 2 ++ test/task-failure-hook.jl | 59 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 test/task-failure-hook.jl diff --git a/AGENTS.md b/AGENTS.md index 49c758f03..71b9cb5cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1316,3 +1316,11 @@ this section verbatim). Each entry is one bullet starting with `- `. direct-placement test does not exercise the stealing dispatch. Do not give the offloaded task pooled Dagger TLS: cancellation can recycle that metadata while Python is still finishing. Copy only the logging flag and scalar ID. + +117. **Failure notifications must tolerate absent execution options.** A + `Thunk`'s options are optional, and dependency failure propagation visits + thunks without scheduling them first. A newly added acceleration hook must + check for missing options before selecting an acceleration; throwing there + aborts the scheduler before downstream futures receive the original error. + Exercise the complete failure/future path, as well as a positive accelerated + notification and duplicate-completion suppression. diff --git a/src/sch/util.jl b/src/sch/util.jl index e63c65f1e..b83cffeab 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -128,7 +128,11 @@ processes cannot see this failure on their own override it for the tasks they need to tell; it must not block. Does nothing by default. """ function task_failed!(thunk, value) - accel = thunk.options.acceleration + opts = thunk.options + # Failure propagation can visit a thunk whose optional execution metadata + # is absent. It has no acceleration to notify; still finish its futures. + opts === nothing && return + accel = opts.acceleration accel === nothing || task_failed!(accel, thunk, value) return end diff --git a/test/scheduler.jl b/test/scheduler.jl index d7c663980..a579d6774 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -1,6 +1,8 @@ import Dagger: Chunk, Options import Dagger.Sch: SchedulerOptions, SchedulerHaltedException, ComputeState, ThunkID, sch_handle +include("task-failure-hook.jl") + @everywhere begin using Dagger import Dagger: sch_handle, exec!, halt!, get_dag_ids, add_thunk! diff --git a/test/task-failure-hook.jl b/test/task-failure-hook.jl new file mode 100644 index 000000000..8d30a82f0 --- /dev/null +++ b/test/task-failure-hook.jl @@ -0,0 +1,59 @@ +module TaskFailureHookTests +using Test, Distributed, Dagger + +struct RecordingAcceleration <: Dagger.Acceleration + failures::Vector{Any} +end +function Dagger.Sch.task_failed!(accel::RecordingAcceleration, thunk, value) + push!(accel.failures, (thunk, value)) + return +end + +@testset "Failure notifications tolerate absent execution options" begin + chan = RemoteChannel(()->Channel{Dagger.Sch.AnyTaskResult}(1)) + state = Dagger.Sch.start_state(Dict(), identity, chan, + Dagger.Context([myid()]), + Dagger.Sch.SchedulerOptions()) + try + failures = Any[] + accel = RecordingAcceleration(failures) + source = Dagger.Thunk(identity; options=Dagger.Options(; acceleration=accel)) + # ThunkSpec and the failure-propagation traversal both permit missing + # options. The notification hook must not prevent a downstream future + # from receiving the upstream's original exception. + dependent = Dagger.Thunk(Dagger.ThunkSpec(; id=Dagger.next_id())) + future = Dagger.ThunkFuture() + @test dependent.options === nothing + @test Dagger.futures_push!(dependent, future) + @test Dagger.deps_push!(source, dependent) + @atomic dependent.pending_deps = 1 + original = ErrorException("upstream failure survives notification") + lock(state.lock) do + Dagger.Sch.set_failed!(state, source; ex=original) + end + @test isready(future) + if isready(future) + failure = try + fetch(future; raw=true) + catch err + err + end + @test failure isa Dagger.DTaskFailedException + @test failure.ex === original + end + @test (@atomic dependent.finished) + @test (@atomic dependent.errored) + @test length(failures) == 1 + @test failures[1] == (source, original) + # A duplicate completion must not notify the acceleration twice. + @test !Dagger.Sch.store_result!(state, source, original; error=true) + @test length(failures) == 1 + + ordinary = Dagger.Thunk(identity) + @test Dagger.Sch.task_failed!(ordinary, original) === nothing + @test length(failures) == 1 + finally + close(chan) + end +end +end From 860e95389e54334e2b028d8089f8c7db83c0daca Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 11:38:48 -0700 Subject: [PATCH 58/59] Use the selected Distributed provider in failure-hook tests ComputeState's channel field belongs to the transport Dagger selected. A stdlib RemoteChannel cannot initialize it in DistributedNext runs, so bind the fixture to Dagger's provider before constructing channels. Production logic is unchanged. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 4 +++- test/task-failure-hook.jl | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 71b9cb5cb..e06f9d00e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1323,4 +1323,6 @@ this section verbatim). Each entry is one bullet starting with `- `. check for missing options before selecting an acceleration; throwing there aborts the scheduler before downstream futures receive the original error. Exercise the complete failure/future path, as well as a positive accelerated - notification and duplicate-completion suppression. + notification and duplicate-completion suppression. Build test channels with + Dagger's selected Distributed provider so their concrete transport types + match the scheduler under both Distributed and DistributedNext. diff --git a/test/task-failure-hook.jl b/test/task-failure-hook.jl index 8d30a82f0..57490572a 100644 --- a/test/task-failure-hook.jl +++ b/test/task-failure-hook.jl @@ -1,5 +1,7 @@ module TaskFailureHookTests -using Test, Distributed, Dagger +using Test, Dagger +const Distributed = parentmodule(Dagger.myid) +using .Distributed struct RecordingAcceleration <: Dagger.Acceleration failures::Vector{Any} From 7c6670b930641aee823fe306c68519f0104f2282 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 14:00:29 -0700 Subject: [PATCH 59/59] Assert MPI free-thread progress before result delivery Port the independently reviewed two-file test repair from #815. Record kernel overlap and physical thread placement while other CPUs remain occupied, release and fetch every busy task before reporting assertions, and retain explicit-scope and compatibility checks. Only the lesson number is adapted to this branch; the registered test is byte-identical to #815. Production code and existing branch fixes are unchanged. The shared #815 source passes 96 and 114 focused assertions on Julia 1.10.14 at two ranks with two and three default threads. A private forced- pinning control gives only the five intended failures with zero errors and full cleanup. No native test or whole-CI pass is claimed for this port. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 13 +++++ test/mpi/free_threads.jl | 117 +++++++++++++++++++++++++++++---------- 2 files changed, 100 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e06f9d00e..035547fdf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1326,3 +1326,16 @@ this section verbatim). Each entry is one bullet starting with `- `. notification and duplicate-completion suppression. Build test channels with Dagger's selected Distributed provider so their concrete transport types match the scheduler under both Distributed and DistributedNext. + +118. **Assert free-thread progress inside the kernel, before result delivery.** + Timing `fetch` in an MPI scheduling test includes result metadata and + broadcast progress after the kernel has run. Keep an explicitly pinned + thread occupied behind a rank-local atomic gate and record whether a + broad-scope kernel runs before release. Waiters must sleep, release the + gate in `finally`, and give the non-yielding busy kernel a bounded escape + deadline. Record wait statuses while occupied, then report assertions only + after release. In the forced-bound control, reporting an assertion before + `finally` deferred release past the busy kernel's watchdog. Fetch every + busy task before resetting shared test state. An + exact-scope negative control must run only after release. This distinguishes + execution progress from delivery latency without relaxing a speed bound. diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl index 66b5e6f0f..3716f0804 100644 --- a/test/mpi/free_threads.jl +++ b/test/mpi/free_threads.jl @@ -6,6 +6,79 @@ free_where() = Threads.threadid() free_reported_where() = (Threads.threadid(), Dagger.task_processor().innerProc.tid) free_scope_value() = Dagger.UnionScope(Dagger.ProcessorTypeScope(Dagger.ThreadProc)) +# Rank-local state is read inside the kernel, before MPI result delivery. A +# deadline only rescues a broken test; successful execution must beat release, +# not a wall-clock performance threshold. +const FREE_GATE_ENTERED = Threads.Atomic{Int}(0) +const FREE_GATE_ACTIVE = Threads.Atomic{Int}(0) +const FREE_GATE_RELEASE = Threads.Atomic{Bool}(true) +const FREE_GATE_COMPLETED = Threads.Atomic{Int}(0) +const FREE_GATE_WAIT_SECONDS = 30.0 + +function free_gated_hog() + start = time_ns() + Threads.atomic_add!(FREE_GATE_ACTIVE, 1) + Threads.atomic_add!(FREE_GATE_ENTERED, 1) + try + while !FREE_GATE_RELEASE[] && time_ns() - start < UInt64(90_000_000_000) + # Deliberately non-yielding: this is the occupied CPU thread. + end + return FREE_GATE_RELEASE[] + finally + Threads.atomic_sub!(FREE_GATE_ACTIVE, 1) + end +end + +function free_gated_quick(x::Int, busy::Int) + ran_while_busy = FREE_GATE_ACTIVE[] == busy && !FREE_GATE_RELEASE[] + tid = Threads.threadid() + Threads.atomic_add!(FREE_GATE_COMPLETED, 1) + return (x + 1, ran_while_busy, tid) +end + +function free_progress_case(scope, rank0, count::Int; expect_progress=true) + busy = length(rank0) - 1 + # Compile the exact kernels with an open gate before occupying any CPU. + FREE_GATE_RELEASE[] = true + foreach(fetch, [Dagger.@spawn(scope=Dagger.ExactScope(p), free_gated_hog()) for p in rank0]) + foreach(fetch, [Dagger.@spawn(scope=scope, free_gated_quick(i, busy)) for i in 1:count]) + FREE_GATE_ENTERED[] = 0 + FREE_GATE_ACTIVE[] = 0 + FREE_GATE_COMPLETED[] = 0 + FREE_GATE_RELEASE[] = false + hogs = Dagger.DTask[] + tasks = Dagger.DTask[] + entered_status = :not_checked + completed_status = :not_checked + local hog_results + try + for p in rank0[2:end] + push!(hogs, Dagger.@spawn(scope=Dagger.ExactScope(p), free_gated_hog())) + end + if rank == 0 + entered_status = timedwait(() -> FREE_GATE_ENTERED[] == busy, + FREE_GATE_WAIT_SECONDS; pollint=0.001) + end + for i in 1:count + push!(tasks, Dagger.@spawn(scope=scope, free_gated_quick(i, busy))) + end + if rank == 0 && expect_progress + completed_status = timedwait(() -> FREE_GATE_COMPLETED[] == count, + FREE_GATE_WAIT_SECONDS; pollint=0.001) + end + finally + # Even a failed progress assertion must release the occupied threads. + # Peers may already be fetching; that delivery latency is not asserted. + FREE_GATE_RELEASE[] = true + hog_results = fetch.(hogs) + end + # Failure reporting may compile and block; do it after releasing every CPU. + rank == 0 && @test entered_status === :ok + rank == 0 && expect_progress && @test completed_status === :ok + @test all(hog_results) + return fetch.(tasks) +end + @testset "MPI CPU processor reports the executing thread" begin tasks = [Dagger.@spawn free_reported_where() for _ in 1:32] @test all(pair -> first(pair) == last(pair), fetch.(tasks)) @@ -66,30 +139,19 @@ end if Threads.nthreads() >= 2 cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) rank0 = sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid) - # Warm up first: the first fetch of a task compiles for a second on slow nodes, which would be measured otherwise - foreach(fetch, Dagger.with_options(; scope=Dagger.scope(mpi_rank=0)) do - [Dagger.@spawn(free_quick(i)) for i in 1:16] - end) - foreach(fetch, [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(0.01)) for p in rank0]) - MPI.Barrier(comm) - # Occupy every thread of rank 0 but the first with a pinned (so bound) task that never yields - hogs = [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(2.5)) for p in rank0[2:end]] - sleep(0.3) - MPI.Barrier(comm) - t0 = time() - # Scope = the whole rank, 16 tasks: the scheduler names every thread in turn, busy ones included - tasks = Dagger.with_options(; scope=Dagger.scope(mpi_rank=0)) do - [Dagger.@spawn(free_quick(i)) for i in 1:16] - end - vals = fetch.(tasks) - elapsed = time() - t0 - @test vals == [i + 1 for i in 1:16] - # Before tasks ran on free threads, the tasks the scheduler places on a busy thread wait for the hogs (measured: 3.3 s of 4 s) - rank == 0 && @test elapsed < 1.5 # the hogs still have a second to run + # Whole-rank work must run while the other threads remain occupied. + res = free_progress_case(Dagger.scope(mpi_rank=0), rank0, 16) + @test first.(res) == [i + 1 for i in 1:16] + @test all(r -> r[2], res) + @test all(r -> r[3] == first(rank0).innerProc.tid, res) + # Negative control: exact placement on the occupied thread cannot run + # before release, even though another thread is free. + bound = free_progress_case(Dagger.ExactScope(last(rank0)), rank0, 1; + expect_progress=false) + @test only(bound) == (2, false, last(rank0).innerProc.tid) # An explicit thread is still a promise where = fetch(Dagger.@spawn scope=Dagger.ExactScope(last(rank0)) free_where()) @test where == last(rank0).innerProc.tid - foreach(wait, hogs) end MPI.Barrier(comm) end @@ -120,15 +182,10 @@ end @test all(in(subset_tids), fetch.(tasks)) foreach(wait, hogs) all_threads = Dagger.UnionScope(map(Dagger.ExactScope, rank0)) - MPI.Barrier(comm) - hogs = [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(2.5)) for p in rank0[2:end]] - sleep(0.3) - MPI.Barrier(comm) - t0 = time() - vals = fetch.([Dagger.@spawn(scope=all_threads, free_quick(i)) for i in 1:8]) - @test vals == [i + 1 for i in 1:8] - rank == 0 && @test time() - t0 < 1.5 # the hogs still have a second to run - foreach(wait, hogs) + res = free_progress_case(all_threads, rank0, 8) + @test first.(res) == [i + 1 for i in 1:8] + @test all(r -> r[2], res) + @test all(r -> r[3] == first(rank0).innerProc.tid, res) end MPI.Barrier(comm) end