From 8741fa9a99431472a6e9bc349fcde24ea8c8e813 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:32:44 -0700 Subject: [PATCH 01/13] 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 02/13] 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 03/13] 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 04/13] 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 05/13] 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 06/13] 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 07/13] 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 08/13] 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 09/13] 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 10/13] 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 9b1b398ceffedc8d8f87d994d4f47e63cd30d00c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:12:44 -0700 Subject: [PATCH 11/13] Preserve processor compatibility when stealing queued tasks Review finding (blocker) on PR #841: CPU runners can steal correctly placed Python tasks, bypass PythonExt's ThreadProc exclusion and invoke CPython without its GIL. Registering only default-pool threads exposes this because the protected main-thread runner is no longer a candidate. Check function and argument compatibility before removing a task from another processor's queue. Enter the latest method world for those hooks, since runners may predate a loaded extension. Retain the scope/acceleration and capacity gates before entering that dynamic path. Add a bounded subprocess regression covering callable and argument restrictions after CPU runners have warmed up. Validation: the old queue-stealing path intermittently executes the restricted callable on a CPU; real PythonCall replay segfaults in PyTuple_New. The corrected path passes the restricted-callable probe, the processor suite (32 parent assertions, including the child checks), and eight real Python calls with an interactive thread. Deep-warmed Base.gc_num deltas (10 warmups, GC.gc, minimum of five runs) for a pinned 100-task submission batch: 17,338 allocations /630,224 bytes before, 17,655 /648,384 after. The added checks are required for correctness; existing allocation bounds are unchanged. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 11 +++++++++++ src/sch/Sch.jl | 16 +++++++++++++++- test/processors.jl | 28 ++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 4a39fc3b8..7e7db6e83 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. **Work stealing must repeat function and argument compatibility checks.** + A processor being inside a task's scope says nothing about whether it can + execute that function. CPU runners used to steal Python tasks from their + correctly selected PythonProcessor queue, bypassing PythonExt's CPU + exclusion and invoking CPython without its GIL. Excluding interactive + threads made this much more likely by removing the protected main-thread + runner. Check function and argument types before removing a queued task, + and enter the latest world for those hooks: a runner may predate the + extension. Test a restricted callable and a restricted argument separately; + a scope-only test cannot detect this violation. diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 8fce00ca0..8a205ded5 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1790,6 +1790,16 @@ stealing_permitted(proc::Dagger.ThreadProc) = proc.owner != 1 || proc.tid != 1 proc_has_occupancy(proc_occupancy, task_occupancy) = UInt64(task_occupancy) + UInt64(proc_occupancy) <= typemax(UInt32) +function steal_compatible(proc, task::TaskSpec) + opts = task.options::Options + Dagger.iscompatible_func(proc, opts, task.Tf) || return false + for idx in 2:length(task.data) + Targ = chunktype(Dagger.value(task.data[idx])) + Dagger.iscompatible_arg(proc, opts, Targ) || return false + end + return true +end + function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, return_queue::RemoteChannel, start_event::Base.Event) to_proc = istate.proc proc_run_task = @task begin @@ -1888,8 +1898,12 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re task, occupancy = first(queue) scope = task.scope::Dagger.AbstractScope accel = something((task.options::Options).acceleration, Dagger.DistributedAcceleration()) + # A task can be in scope yet require another processor + # type (e.g. PythonProcessor holds the GIL). Runners + # also predate late-loaded extension hooks. if Dagger.proc_in_scope(to_proc, scope) && Dagger.accel_matches_proc(accel, to_proc) && - typemax(UInt32) - proc_occupancy_cached >= occupancy + typemax(UInt32) - proc_occupancy_cached >= occupancy && + (@invokelatest steal_compatible(to_proc, task)) # Compatible, steal this task return popfirst!(queue) end diff --git a/test/processors.jl b/test/processors.jl index d2ecbaa23..f2364bb14 100644 --- a/test/processors.jl +++ b/test/processors.jl @@ -123,6 +123,18 @@ end # default pool is threads 2 and 3. script = """ using Dagger, Test + struct LateCallable end + (::LateCallable)(x) = :thread + struct RestrictedArgument end + read_restricted_arg(x) = :thread + struct LateProcessor <: Dagger.Processor end + Dagger.root_worker_id(::LateProcessor) = 1 + Dagger.get_parent(::LateProcessor) = Dagger.OSProc(1) + Dagger.default_enabled(::LateProcessor) = true + Dagger.iscompatible_func(::LateProcessor, opts, ::Type{LateCallable}) = true + Dagger.iscompatible_func(::LateProcessor, opts, ::Type{typeof(read_restricted_arg)}) = true + Dagger.iscompatible_arg(::LateProcessor, opts, x) = true + Dagger.execute!(::LateProcessor, f, args...) = :special const Distributed = parentmodule(Dagger.myid) using .Distributed worker = only(addprocs(1; exeflags=`--project=\$(Base.active_project()) -t 2,2`)) @@ -160,6 +172,22 @@ end @test worker_first_tid == 3 @test mixed_grid_ok end + # The CPU runners above predate this compatibility override, as + # happens when PythonCall loads after ordinary Dagger tasks ran. + @eval Dagger.iscompatible_func(::Dagger.ThreadProc, opts, ::Type{LateCallable}) = false + @eval Dagger.iscompatible_arg(::Dagger.ThreadProc, opts, ::Type{RestrictedArgument}) = false + Dagger.add_processor_callback!(()->LateProcessor(), :late_processor) + try + @testset "Stealing preserves late compatibility hooks" begin + for _ in 1:64 + parent = Dagger.@spawn sleep(0.005) + @test fetch(Dagger.spawn(LateCallable(), parent)) == :special + @test fetch(Dagger.spawn(read_restricted_arg, RestrictedArgument())) == :special + end + end + finally + Dagger.delete_processor_callback!(:late_processor) + end """ # Resolve packages and preferences (the transport) like this process load_path = join(Base.load_path(), Sys.iswindows() ? ';' : ':') From ea4ccca07ebd11f87abfd9094812a70ed1d39983 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:14:54 -0700 Subject: [PATCH 12/13] Describe default thread IDs for multiple interactive threads Review finding (nit) on PR #841: the helper docstring used the single interactive-thread range for every -t N,M startup configuration. State the general M+1:M+N range and then identify the usual M=1 case. Checked against the existing mixed-pool processor regression, whose worker starts with two interactive threads and picks Julia thread 3. Written by an AI agent on jpsamaroo's review feedback. --- src/threadproc.jl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/threadproc.jl b/src/threadproc.jl index 9095833df..6b47cb849 100644 --- a/src/threadproc.jl +++ b/src/threadproc.jl @@ -18,8 +18,9 @@ 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 +with `julia -t N,M` before that), and numbers them first. With `M` interactive +threads, the default pool is `M+1:M+N`; the usual single interactive thread puts +it at `2:N+1`. Thread 1 is then interactive. `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 From 4d346dfe0855db59ec98ccc6ae737c8861c2c124 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 00:08:30 -0700 Subject: [PATCH 13/13] 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. This branch predates execute_thread_function. Its typed ThreadProc/Py method therefore preserves the existing inline CPU profiling, latest-world call, and captured-exception wrapper locally, without adding a generic CPU helper. 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 | 59 ++++++++++++++++++++++++++++++++++++++++-- test/extlang/python.jl | 22 ++++++++++++++++ 3 files changed, 94 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7e7db6e83..9bffe4d01 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1253,3 +1253,18 @@ this section verbatim). Each entry is one bullet starting with `- `. and enter the latest world for those hooks: a runner may predate the extension. Test a restricted callable and a restricted argument separately; a scope-only test cannot detect this violation. + +113. **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..4745a30f0 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,67 @@ 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...) + # Match this branch's inline CPU wrapper without changing its generic path. + if Dagger.task_logging_enabled() + Dagger.TimespanLogging.prof_task_put!(Dagger.get_tls().sch_handle.thunk_id.id) + end + try + return Base.invokelatest(Dagger.execute!, PythonProcessor(proc.owner), + f, args...; kwargs...) + catch err + err isa InterruptException && rethrow() + rethrow(CapturedException(err, catch_backtrace())) end 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