From c0c8f63c7c072c0d9e4227535aeab9846181fb20 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 21 Nov 2026 14:58:12 +0100 Subject: [PATCH 01/12] Datadeps: give every processor of a space the same union scope object The scope Datadeps hands each task depends on the processor only through its memory space, but get! built one UnionScope per processor, equal in content. The scheduler's compatible-set lookup then ended every hit in a member-by- member comparison of 64 scopes: 22 us per task at 64 threads on our cluster (flat Datadeps Cholesky 8192/256; 1.3 us on a laptop, the cluster's cores are ~7x slower per primitive). The first processor's scope is now shared with the others (share_equal_scope), so the comparison is a pointer test. --- src/datadeps/queue.jl | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index e22866428..08692bfc8 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -264,6 +264,17 @@ function written_positions(task_arg_ws, deps_vec) return something(writes, Int[]) end +# Every processor of a memory space gets an equal union scope (the scope does not depend on `our_proc` +# beyond its space), but `get!` builds one object per processor. The scheduler's compatible-set lookup +# then compares up to 64 member-by-member equal scopes (22 us at 64 threads on our cluster) where one shared +# object is a pointer comparison. Return the cached scope equal to `scope` if there is one. +function share_equal_scope(cache, scope) + for existing in values(cache.cache) + existing === scope && return existing + end + return scope +end + function distribute_task!(queue::DataDepsTaskQueue, state::DataDepsState, all_procs, all_scope, spec::DTaskSpec{typed}, task::DTask, fargs, proc_to_scope_lfu, write_num::Int; ownership=nothing) where typed @specialize spec fargs @@ -307,7 +318,7 @@ function distribute_task!(queue::DataDepsTaskQueue, state::DataDepsState, all_pr # `all_procs`, both of which are fixed for this cache's lifetime. our_scope = get!(proc_to_scope_lfu, our_proc) do our_procs = filter(proc->proc in all_procs, collect(processors(our_space))) - return constrain(UnionScope(map(ExactScope, our_procs)...), DefaultScope()) + return share_equal_scope(proc_to_scope_lfu, constrain(UnionScope(map(ExactScope, our_procs)...), DefaultScope())) end else # Use the provided scope and constrain it to the available processors From af84a493d4bfe30bc1f47bc427946c8c0aa14b90 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 21 Nov 2026 14:58:12 +0100 Subject: [PATCH 02/12] Sch: key the compatible-processor cache of a large union scope by a cheap content key objectid of a UnionScope hashes every member; Datadeps hands each task a union of one ExactScope per thread, so the cache lookup cost O(threads) per task (measured on our cluster, flat Datadeps Cholesky 8192/256: 11.4 us at 16 threads, 39.9 us at 64 threads, of ~190 us per schedule_one!). A union of more than 8 scopes is keyed by its length and its first and last member, which stays a function of the contents: the equal union a later Datadeps region builds finds the earlier region's entry. (A key by address looks cheaper but pollutes the frequency-ordered cache with 64 never-hit entries per region; once it is full the new keys are evicted at once and every task misses: 98 us per task at 64 threads, measured.) The hit test still compares the scope (===), and a collision of two different unions only replaces the entry. Everything else keeps objectid. --- src/sch/Sch.jl | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 50763132c..4820e3591 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -121,8 +121,24 @@ function invalidate_compat_procs_cache!() @safe_lock_spin1 COMPAT_PROCS_CACHE cache empty!(cache) return end +# Cache key of a scope. `objectid` of a union scope hashes every member (one `ExactScope` per +# thread for the scopes Datadeps hands out), O(threads) work per task: 40 us at 64 threads. +# A large union is keyed by its length and its first and last member instead: still a function of +# the *contents*, so the equal union a later Datadeps region builds finds the entry of the earlier +# one (a key by address does not: every region would add 64 never-hit entries, and once the +# frequency-ordered cache is full the new, frequency-1 keys are evicted at once, so every task of +# the region misses). The hit test `entry.scope === scope` compares the members, and a collision +# of two different unions only replaces the entry. A small union, or any other scope, keeps `objectid`. +const SCOPE_KEY_UNION_MIN = 8 +scope_key(scope) = objectid(scope) +function scope_key(scope::Dagger.UnionScope) + scopes = scope.scopes + n = length(scopes) + n > SCOPE_KEY_UNION_MIN || return objectid(scope) + return hash(n, hash(objectid(@inbounds(scopes[1])), UInt(objectid(@inbounds(scopes[n]))))) +end function compat_entry(accel, scope, procs::Vector{<:Processor}) - key = (objectid(accel), objectid(scope)) + key = (objectid(accel), scope_key(scope)) cached = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin entry = get(cache.cache, key, nothing) if entry !== nothing && entry.scope === scope && entry.procs == procs From c32b04df59e8fd7a38b59971c1d364ab3912e988 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 21 Nov 2026 14:58:12 +0100 Subject: [PATCH 03/12] perf: rank only the cheapest placement candidates instead of sorting all of them estimate_task_costs! shuffled (randperm!) and sorted every candidate processor for every unscoped task, although the scheduler takes the first usable one: O(T log T) per task, 12 -> 24-58 us per task at 8 -> 32-64 threads on our cluster (Opteron). The scheduler-facing path (costs === nothing) now rotates the candidates by a random offset and selects the 4 cheapest into the front; ties stay random, the tail keeps rotation order. The path that returns costs keeps the full sort. The ordering is a plain function with concrete argument types. Fan-out of 64 tiny unscoped tasks at 64 threads, spawn only, 6 interleaved rounds in one allocation: median 11.3 -> 10.7 ms (about 6 % faster, better in 6 of 6 rounds). --- src/sch/util.jl | 43 ++++++++++++++++++++++++++++++++++++++++--- test/scheduler.jl | 22 ++++++++++++++++++++++ 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/sch/util.jl b/src/sch/util.jl index 58804e56f..d916f3316 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -784,6 +784,39 @@ function fill_costs!(cost_vec, procs, wtr, pressures, tx_costs, est_time_util, h return all_equal end +# How many of the cheapest candidates `order_candidates!` ranks exactly. +const PLACEMENT_SELECT = 4 + +# The scheduler tries candidates in order and nearly always takes the first, so a +# full shuffle plus a full sort (O(np log np) per task, growing with the thread +# count) is more than it needs. Rotate by a random offset (fair for equal costs) +# and select only the cheapest few into the front; the tail keeps rotation order, +# and the first minimum in rotation order wins ties, so ties stay random. +# N.B. A plain function: inside the `@reusable` block `best`/`bc` were captured +# and reassigned, i.e. boxed, and every comparison became a dynamic dispatch. +function order_candidates!(P::Vector{Int}, cost_vec::Vector{Float64}, all_equal::Bool) + np = length(P) + off = rand(1:np) + @inbounds for idx in 1:np + k = off + idx + P[idx] = k > np ? k - np : k + end + all_equal && return + @inbounds for j in 1:min(np - 1, PLACEMENT_SELECT) + best = j + bc = cost_vec[P[j]] + for k in (j+1):np + ck = cost_vec[P[k]] + if ck < bc + best = k + bc = ck + end + end + P[j], P[best] = P[best], P[j] + end + return +end + """ estimate_task_costs!(sorted_procs, costs, state, procs, task; sig=nothing) @@ -880,9 +913,13 @@ candidate lookups cost about 130 us for 16 threads and grew with the thread coun # but-fair order that sorting would leave us with anyway. @reusable :estimate_task_costs_P Vector{Int} 0 4 np P begin resize!(P, np) - copyto!(P, 1:np) - randperm!(P) - all_equal || sort!(P, by=i->@inbounds(cost_vec[i])) + if costs === nothing + order_candidates!(P, cost_vec, all_equal) + else + copyto!(P, 1:np) + randperm!(P) + all_equal || sort!(P, by=i->@inbounds(cost_vec[i])) + end for idx in 1:np @inbounds sorted_procs[idx] = procs[P[idx]] end diff --git a/test/scheduler.jl b/test/scheduler.jl index 23292605d..98df009f2 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -869,3 +869,25 @@ end nowhere = Dagger.ExactScope(Dagger.ThreadProc(1, typemax(Int) - 1)) @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason="No processors available, try widening scope" fetch(Dagger.@spawn scope=nowhere identity(1)) end + +@testset "Candidate ordering" begin + order! = Dagger.Sch.order_candidates! + for np in (2, 5, 64), all_equal in (true, false) + cost = Float64.(rand(1:3, np)) + # With unequal costs a cheapest candidate must come first and the next few must be ranked; + # with equal costs (or among tied minima) every candidate must get a chance to be first. + firsts = Set{Int}() + for _ in 1:4000 + P = zeros(Int, np) + order!(P, cost, all_equal) + @test sort(P) == 1:np + if !all_equal + @test cost[P[1]] == minimum(cost) + np > 5 && @test issorted(cost[P[1:Dagger.Sch.PLACEMENT_SELECT]]) + end + push!(firsts, P[1]) + end + @test length(firsts) == (all_equal ? np : count(==(minimum(cost)), cost)) + end + @inferred order!(zeros(Int, 8), rand(8), false) +end From 808790ce6dc6c0cf825e7f97829054cb367d239e Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 21 Nov 2026 14:58:12 +0100 Subject: [PATCH 04/12] Sched: wake only the runners that can take the enqueued task After every do_tasks, every other processor's doorbell was rung "to make it steal". Each woken runner then scanned the queues of all T processors, locking each one: T wake-ups and ~T^2 lock operations per enqueued task. For a task whose scope is an ExactScope nobody else can take it at all (proc_in_scope is proc == scope.processor), and for an unscoped task one thief is enough. * ExactScope tasks only: no kick. * Otherwise wake at most one runner per enqueued task, chosen among the runners that are parked (ProcessorInternalState.parked, set before the runner looks for work and cleared when it takes a task: one that is not parked looks at the queues again by itself, so skipping it cannot lose a wake-up) and that could take a task (scope, acceleration, free occupancy: the same test the steal scan applies). The starting point rotates so the same runners are not always the thieves. The MPI rule (stealing_permitted) stays. One process, no MPI, our cluster (Opteron 6272), tasks/s with 50 us bodies, before -> after, 8 / 16 / 32 / 64 threads (single runs, bench shm_scaling.jl): unscoped 6.6k / 4.9k / 5.7k / 3.3k -> 6.0k / 5.1k / 6.0k / 5.6k (64 threads +69 %) pinned 7.0k / 7.2k / 8.3k / 5.5k -> 7.5k / 8.0k / 8.8k / 7.2k (64 threads +32 %) With 500 us bodies at 64 threads: unscoped 3.7k -> 4.2k, pinned 5.8k -> 7.5k. Within noise at 8 and 16 threads, as expected: the wasted work grows with T^2. The throughput no longer falls between 32 and 64 threads but stays at ~6-8k tasks/s: what remains is the serial per-task cost of the submitting thread (~125-165 us here). Tests: thunk, scheduler, processors, uniform-placement, scopes, options, task-queues, task-affinity, mutation pass (-p 2 -t 2). --- src/sch/Sch.jl | 61 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 4820e3591..f020391fa 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1651,6 +1651,9 @@ mutable struct ProcessorInternalState # Free-list of reset `TaskSpec`s (with their `data` vectors and `Argument` # cells) for reuse by `fire_tasks!`. Guarded by `queue`'s lock. spec_pool::Vector{TaskSpec} + # True from the moment the runner starts looking for work until it takes a task: `do_tasks` wakes + # only runners that are parked, because one that is not will look at the queues again by itself + parked::Threads.Atomic{Bool} end struct ProcessorState state::ProcessorInternalState @@ -1778,6 +1781,10 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re # runner creation ctx = istate.ctx + # From here until a task is taken, this runner is looking for work: a task enqueued + # from now on is seen by the dequeue/steal attempt below or wakes the doorbell + istate.parked[] = true + # Wait for new tasks if !work_to_do @dagdebug nothing :processor "Waiting for tasks" @@ -1881,6 +1888,7 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re end @label execute + istate.parked[] = false task, task_occupancy = task_and_occupancy thunk_id = task.thunk_id time_util = task.est_time_util @@ -2112,6 +2120,9 @@ end Executes a batch of tasks on `to_proc`, returning their results through `return_queue`. """ +# Rotates where `do_tasks` starts looking for a runner to wake, so that the same runners are not always the thieves +const KICK_CURSOR = Threads.Atomic{Int}(0) + function do_tasks(to_proc, return_queue, tasks) @dagdebug nothing :processor "Enqueuing task batch" batch_size=length(tasks) @@ -2132,7 +2143,8 @@ function do_tasks(to_proc, return_queue, tasks) Set{Int}(), Dict{Int,Dagger.CancelToken}(), Ref(false), - TaskSpec[]) + TaskSpec[], + Threads.Atomic{Bool}(false)) start_event = Base.Event() runner = start_processor_runner!(istate, uid, return_queue, start_event) @static if VERSION < v"1.9" @@ -2193,17 +2205,54 @@ function do_tasks(to_proc, return_queue, tasks) # Kick other processors to make them steal # TODO: Alternatively, automatically balance work instead of blindly enqueueing - for other_state in states_snapshot!(STATES_CACHE_TLV[], proc_states(uid)) - other_istate = other_state.state - if other_istate.proc === to_proc - continue + # + # A task whose scope is an `ExactScope` can run on that one processor only (`proc_in_scope` is + # `proc == scope.processor`), so nobody can steal it and a kick would be wasted. Every kick wakes + # a runner that then scans the queues of all the others, so with T threads each enqueued task + # cost O(T) wake-ups and O(T^2) queue probes: pinned tasks went from ~8000 to ~5500 tasks/s + # between 32 and 64 threads. + all_pinned = true + for task in tasks + if !((task.scope::Dagger.AbstractScope) isa Dagger.ExactScope) + all_pinned = false + break end + end + all_pinned && return nothing + # Wake the runners that could take one of these tasks, at most one per task. Waking every + # processor made each enqueued task cost T wake-ups, each followed by a scan that locks the + # queues of all T processors: O(T^2) lock operations per task, which collapsed the throughput + # of unscoped tasks at 32 threads and more. A runner that is not parked will look at the + # queues again by itself (see `ProcessorInternalState.parked`), and one that cannot take any + # of the tasks (scope, acceleration, free occupancy) would only go back to sleep. + states_vec = states_snapshot!(STATES_CACHE_TLV[], proc_states(uid)) + nstates = length(states_vec) + nkick = 0 + maxkick = length(tasks) + start_idx = nstates <= 1 ? 1 : mod1(Threads.atomic_add!(KICK_CURSOR, 1), nstates) + for state_offset in 0:(nstates-1) + state_idx = start_idx + state_offset + state_idx > nstates && (state_idx -= nstates) + other_istate = (@inbounds states_vec[state_idx]).state + other_istate.proc === to_proc && continue # A kick only makes the runner try to steal (see `start_processor_runner!`); # one that may not steal wakes up to do nothing. Under MPI that is every # processor of every rank, so each enqueued task would otherwise wake # `ranks x threads` runners on every rank. stealing_permitted(other_istate.proc) || continue - notify(other_istate.reschedule) + other_istate.parked[] || continue + free = typemax(UInt32) - other_istate.proc_occupancy[] + for task in tasks + scope = task.scope::Dagger.AbstractScope + accel = something((task.options::Options).acceleration, Dagger.DistributedAcceleration()) + if Dagger.proc_in_scope(other_istate.proc, scope) && Dagger.accel_matches_proc(accel, other_istate.proc) && + free >= task.est_occupancy + notify(other_istate.reschedule) + nkick += 1 + break + end + end + nkick >= maxkick && break end @dagdebug nothing :processor "Kicked processors" end From 54991c9d275b22f0841bd1af7503ddc1a7a8207b Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 21 Nov 2026 16:15:15 +0100 Subject: [PATCH 05/12] Sched: do not read a TaskSpec after handing it to the queue The previous commit's do_tasks enqueued a batch and then read each spec again (scope for the all-pinned check, options.acceleration and est_occupancy for the wake-up decision). From the moment a spec is in the queue another runner may take it, run it and recycle it (reset_task_spec! sets scope and options to nothing, thunk_id to 0), so on few threads with short tasks the scope assertion threw a TypeError, the wake-up decision used stale values, and FireTaskSpec reported the failure under first_task.thunk_id, read after the recycle: id 0, or the id of whatever task had reused the spec, which failed an innocent bystander. The decision data (scope, acceleration, occupancy) is now captured in reusable vectors inside the enqueue loop, while do_tasks still owns the spec, and the all-pinned check and the kick loop use those; FireTaskSpec reads first_thunk_id before do_tasks. Skipped (pre-cancelled / already running) tasks no longer count towards maxkick. Regression test: AFTER_ENQUEUE_HOOK (one load and compare per batch) lets the test sleep right after the enqueue; with 2+ threads the batch counter FIRE_FAILURES must not move. The test fails on the previous commit plus the hook and passes with the fix. --- src/sch/Sch.jl | 49 ++++++++++++++++++++++++++++++++++++----------- test/scheduler.jl | 33 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 11 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index f020391fa..9dc42cbf3 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1534,6 +1534,9 @@ end empty!(to_send) end +# Number of batches whose `do_tasks` threw (reported to the scheduler as a failure of the batch's first task). Read by tests. +const FIRE_FAILURES = Threads.Atomic{Int}(0) + struct FireTaskSpec init_proc::Processor return_chan::RemoteChannel @@ -1547,6 +1550,9 @@ function (ets::FireTaskSpec)() ctx_vars = first_task.ctx_vars::NamedTuple ctx = Dagger.log_context(ctx_vars.log_sink, ctx_vars.profile) uid = first_task.sch_uid + # Read before `do_tasks` hands the specs over: afterwards the first one may already be recycled + # (its `thunk_id` reset to 0, or reused by another task), and a failure must be reported under the id it belongs to. + first_thunk_id = first_task.thunk_id proc = ets.init_proc chan = ets.return_chan @@ -1561,10 +1567,10 @@ function (ets::FireTaskSpec)() end catch err bt = catch_backtrace() - # FIXME: Catch the correct task ID - thunk_id = first_task.thunk_id + # FIXME: Catch the correct task ID (this is the first of the batch, not necessarily the one that failed) + Threads.atomic_add!(FIRE_FAILURES, 1) if isopen(chan) - put!(chan, TaskResult(pid, proc, thunk_id, CapturedException(err, bt), nothing)) + put!(chan, TaskResult(pid, proc, first_thunk_id, CapturedException(err, bt), nothing)) end finally @logfinish ctx LogFire LogFireId(uid, pid) nothing @@ -2123,6 +2129,10 @@ Executes a batch of tasks on `to_proc`, returning their results through # Rotates where `do_tasks` starts looking for a runner to wake, so that the same runners are not always the thieves const KICK_CURSOR = Threads.Atomic{Int}(0) +# Test hook: called by `do_tasks` right after it enqueued a batch, i.e. from the moment on at which another runner may take, run and +# recycle the specs. Tests set it to a sleep to make that window wide; `nothing` (the default) costs one load and compare per batch. +const AFTER_ENQUEUE_HOOK = Ref{Any}(nothing) + function do_tasks(to_proc, return_queue, tasks) @dagdebug nothing :processor "Enqueuing task batch" batch_size=length(tasks) @@ -2164,6 +2174,14 @@ function do_tasks(to_proc, return_queue, tasks) istate.ctx = ctx end states = proc_states(uid) + # What the wake-up decision below needs is read here, while `do_tasks` still owns each spec. The + # moment a spec is in the queue another runner may take it, run it and recycle it + # (`reset_task_spec!` sets `scope` and `options` to `nothing`), so reading `tasks` again after the + # enqueue loop saw `nothing` and stale occupancies (a `TypeError` in the `scope` assertion, on + # few threads with many short tasks). + kick_scopes = @reusable_vector :do_tasks_kick_scopes Dagger.AbstractScope nothing 32 + kick_accels = @reusable_vector :do_tasks_kick_accels Dagger.Acceleration nothing 32 + kick_occupancies = @reusable_vector :do_tasks_kick_occupancies UInt32 UInt32(0) 32 lock(istate.queue) do queue for task in tasks thunk_id = task.thunk_id @@ -2196,12 +2214,17 @@ function do_tasks(to_proc, return_queue, tasks) end end should_launch || continue + push!(kick_scopes, task.scope::Dagger.AbstractScope) + push!(kick_accels, something((task.options::Options).acceleration, Dagger.DistributedAcceleration())) + push!(kick_occupancies, occupancy) push!(queue, task => occupancy) @logfinish ctx LogEnqueue LogEnqueueId(uid, to_proc, thunk_id) nothing @dagdebug thunk_id :processor "Enqueued task" end end notify(istate.reschedule) + hook = AFTER_ENQUEUE_HOOK[] + hook === nothing || hook() # Kick other processors to make them steal # TODO: Alternatively, automatically balance work instead of blindly enqueueing @@ -2212,13 +2235,16 @@ function do_tasks(to_proc, return_queue, tasks) # cost O(T) wake-ups and O(T^2) queue probes: pinned tasks went from ~8000 to ~5500 tasks/s # between 32 and 64 threads. all_pinned = true - for task in tasks - if !((task.scope::Dagger.AbstractScope) isa Dagger.ExactScope) + for scope in kick_scopes + if !(scope isa Dagger.ExactScope) all_pinned = false break end end - all_pinned && return nothing + if all_pinned + empty!(kick_scopes); empty!(kick_accels); empty!(kick_occupancies) + return nothing + end # Wake the runners that could take one of these tasks, at most one per task. Waking every # processor made each enqueued task cost T wake-ups, each followed by a scan that locks the # queues of all T processors: O(T^2) lock operations per task, which collapsed the throughput @@ -2228,7 +2254,7 @@ function do_tasks(to_proc, return_queue, tasks) states_vec = states_snapshot!(STATES_CACHE_TLV[], proc_states(uid)) nstates = length(states_vec) nkick = 0 - maxkick = length(tasks) + maxkick = length(kick_scopes) start_idx = nstates <= 1 ? 1 : mod1(Threads.atomic_add!(KICK_CURSOR, 1), nstates) for state_offset in 0:(nstates-1) state_idx = start_idx + state_offset @@ -2242,11 +2268,11 @@ function do_tasks(to_proc, return_queue, tasks) stealing_permitted(other_istate.proc) || continue other_istate.parked[] || continue free = typemax(UInt32) - other_istate.proc_occupancy[] - for task in tasks - scope = task.scope::Dagger.AbstractScope - accel = something((task.options::Options).acceleration, Dagger.DistributedAcceleration()) + for idx in eachindex(kick_scopes) + scope = @inbounds kick_scopes[idx] + accel = @inbounds kick_accels[idx] if Dagger.proc_in_scope(other_istate.proc, scope) && Dagger.accel_matches_proc(accel, other_istate.proc) && - free >= task.est_occupancy + free >= @inbounds(kick_occupancies[idx]) notify(other_istate.reschedule) nkick += 1 break @@ -2254,6 +2280,7 @@ function do_tasks(to_proc, return_queue, tasks) end nkick >= maxkick && break end + empty!(kick_scopes); empty!(kick_accels); empty!(kick_occupancies) @dagdebug nothing :processor "Kicked processors" end diff --git a/test/scheduler.jl b/test/scheduler.jl index 98df009f2..0b50cc146 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -891,3 +891,36 @@ end end @inferred order!(zeros(Int, 8), rand(8), false) end + +@testset "Batch enqueue does not read a recycled spec" begin + # `do_tasks` used to read each `TaskSpec` again after enqueueing it, to decide whom to wake. A runner can run and + # recycle a short task before that (`scope` and `options` become `nothing`), which threw a TypeError in the scope + # assertion. The window is tiny on a fast machine, so the test widens it through the hook that `do_tasks` calls right + # after the enqueue; a runner on another thread then recycles the spec while `do_tasks` still sleeps. + nthr = Threads.nthreads() + tiny(i) = i + 1 + scopes = [Dagger.ExactScope(Dagger.ThreadProc(1, t)) for t in 1:nthr] + function run_many(n) + ts = DTask[] + for i in 1:n + t = i % 3 == 0 ? Dagger.@spawn(tiny(i)) : Dagger.@spawn(scope=scopes[mod1(i, nthr)], tiny(i)) + push!(ts, t) + end + return all(i -> fetch(ts[i]) == i + 1, eachindex(ts)) + end + failures0 = Dagger.Sch.FIRE_FAILURES[] + @test run_many(2000) # without the hook: smoke test + if nthr >= 2 + Dagger.Sch.AFTER_ENQUEUE_HOOK[] = () -> Libc.systemsleep(0.002) + try + @test run_many(300) + finally + Dagger.Sch.AFTER_ENQUEUE_HOOK[] = nothing + end + # The error is reported under the id of a recycled spec, so it does not always fail a task the test waits for; + # count the batches that threw instead. + @test Dagger.Sch.FIRE_FAILURES[] == failures0 + else + @test_skip run_many(300) # one thread: nothing else can run while do_tasks sleeps + end +end From b13399ae38c7985a7d322096abdbdc76b6351ab6 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:55:13 -0700 Subject: [PATCH 06/12] Attach the batch enqueue docstring to do_tasks Review finding 4 on PR #806 (should-fix): The enqueue docstring now describes a counter Requested: Attach the existing enqueue docstring to do_tasks again. Keep the existing documentation next to the function it documents. An isolated Julia Docs.meta probe on the exact declaration confirmed the binding moved from KICK_CURSOR back to do_tasks. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 9dc42cbf3..e41b72e6e 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2120,12 +2120,6 @@ function (dts::DoTaskSpec)() return end -""" - do_tasks(to_proc, return_queue, tasks) - -Executes a batch of tasks on `to_proc`, returning their results through -`return_queue`. -""" # Rotates where `do_tasks` starts looking for a runner to wake, so that the same runners are not always the thieves const KICK_CURSOR = Threads.Atomic{Int}(0) @@ -2133,6 +2127,12 @@ const KICK_CURSOR = Threads.Atomic{Int}(0) # recycle the specs. Tests set it to a sleep to make that window wide; `nothing` (the default) costs one load and compare per batch. const AFTER_ENQUEUE_HOOK = Ref{Any}(nothing) +""" + do_tasks(to_proc, return_queue, tasks) + +Executes a batch of tasks on `to_proc`, returning their results through +`return_queue`. +""" function do_tasks(to_proc, return_queue, tasks) @dagdebug nothing :processor "Enqueuing task batch" batch_size=length(tasks) From 266c33bba5bcbe315aa5533147975ab5cd07ff4c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:49:10 -0700 Subject: [PATCH 07/12] Bound mixed-scope wakeup filtering and read occupancy under its lock Review finding F3 (should-fix) on PR #806: Mixed-scope batches can scan every runner and task combination. Skip pinned task metadata and use broad wakeups if the runner/task cross product exceeds 64 eligibility checks. Read runner occupancy under its queue lock on the selective path. This retains selective wakeups for small batches while bounding filtering work by the batch plus runner counts. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 22e316317..fbf81a7f0 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2172,6 +2172,9 @@ end # Rotates where `do_tasks` starts looking for a runner to wake, so that the same runners are not always the thieves const KICK_CURSOR = Threads.Atomic{Int}(0) +# Bound eligibility probes per batch. Larger cross-products use the ordinary +# broad wakeup, so a batch cannot spend runners × tasks time filtering wakeups. +const MAX_KICK_SCOPE_CHECKS = 64 # Test hook: called by `do_tasks` right after it enqueued a batch, i.e. from the moment on at which another runner may take, run and # recycle the specs. Tests set it to a sleep to make that window wide; `nothing` (the default) costs one load and compare per batch. @@ -2264,9 +2267,11 @@ function do_tasks(to_proc, return_queue, tasks) end end should_launch || continue - push!(kick_scopes, task.scope::Dagger.AbstractScope) - push!(kick_accels, something((task.options::Options).acceleration, Dagger.DistributedAcceleration())) - push!(kick_occupancies, occupancy) + if !(task.scope isa Dagger.ExactScope) + push!(kick_scopes, task.scope::Dagger.AbstractScope) + push!(kick_accels, something((task.options::Options).acceleration, Dagger.DistributedAcceleration())) + push!(kick_occupancies, occupancy) + end push!(queue, task => occupancy) @logfinish ctx LogEnqueue LogEnqueueId(uid, to_proc, thunk_id) nothing @dagdebug thunk_id :processor "Enqueued task" @@ -2284,17 +2289,7 @@ function do_tasks(to_proc, return_queue, tasks) # a runner that then scans the queues of all the others, so with T threads each enqueued task # cost O(T) wake-ups and O(T^2) queue probes: pinned tasks went from ~8000 to ~5500 tasks/s # between 32 and 64 threads. - all_pinned = true - for scope in kick_scopes - if !(scope isa Dagger.ExactScope) - all_pinned = false - break - end - end - if all_pinned - empty!(kick_scopes); empty!(kick_accels); empty!(kick_occupancies) - return nothing - end + isempty(kick_scopes) && return nothing # Wake the runners that could take one of these tasks, at most one per task. Waking every # processor made each enqueued task cost T wake-ups, each followed by a scan that locks the # queues of all T processors: O(T^2) lock operations per task, which collapsed the throughput @@ -2305,6 +2300,7 @@ function do_tasks(to_proc, return_queue, tasks) nstates = length(states_vec) nkick = 0 maxkick = length(kick_scopes) + broad_kick = nstates > div(MAX_KICK_SCOPE_CHECKS, maxkick) start_idx = nstates <= 1 ? 1 : mod1(Threads.atomic_add!(KICK_CURSOR, 1), nstates) for state_offset in 0:(nstates-1) state_idx = start_idx + state_offset @@ -2317,7 +2313,13 @@ function do_tasks(to_proc, return_queue, tasks) # `ranks x threads` runners on every rank. stealing_permitted(other_istate.proc) || continue other_istate.parked[] || continue - free = typemax(UInt32) - other_istate.proc_occupancy[] + if broad_kick + notify(other_istate.reschedule) + continue + end + free = lock(other_istate.queue) do _ + typemax(UInt32) - other_istate.proc_occupancy[] + end for idx in eachindex(kick_scopes) scope = @inbounds kick_scopes[idx] accel = @inbounds kick_accels[idx] From 47a5406413272a0de7bd9b10d93770cbc857611d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:49:11 -0700 Subject: [PATCH 08/12] Describe the scheduler's partial candidate ranking accurately Review finding F1 (should-fix) on PR #806: Placement beyond the fourth candidate no longer follows cost order. State which candidates are cost-ranked and which retain rotation order; the existing partial-ranking tests cover the implemented ordering. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/util.jl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/sch/util.jl b/src/sch/util.jl index 9b5491194..882531853 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -809,8 +809,9 @@ end """ estimate_task_costs!(sorted_procs, costs, state, procs, task; sig=nothing) -Fill `sorted_procs` with `procs` ordered by estimated cost of running `task` (cheapest -first; equally costly processors in random order). `costs` is an optional +Fill `sorted_procs` with `procs`, selecting the cheapest four candidates first. +The remaining candidates retain a random rotation order, so a fallback beyond +those four need not choose the next cheapest processor. `costs` is an optional `Dict{Processor,Float64}` that receives the estimate of each processor; the scheduler passes `nothing`, because a dictionary keyed by an abstractly typed, isbits processor allocates a box for every insertion and is looked up again by the sort. From 5e40a17b69cd84097fb18e18da120021518c14a4 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:53:09 -0700 Subject: [PATCH 09/12] Give every tied cheapest candidate equal selection weight Review finding F6 (should-fix) on PR #814, shared with PR #806: Rotating candidates skews choices among tied minima. Use reservoir sampling within each selection pass. A minimum no longer wins in proportion to the distance from the previous minimum. The regression places two minima behind unequal gaps and checks their first-choice counts. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/util.jl | 10 ++++++++-- test/scheduler.jl | 11 +++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/sch/util.jl b/src/sch/util.jl index 882531853..61e1d36c1 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -779,8 +779,9 @@ const PLACEMENT_SELECT = 4 # The scheduler tries candidates in order and nearly always takes the first, so a # full shuffle plus a full sort (O(np log np) per task, growing with the thread # count) is more than it needs. Rotate by a random offset (fair for equal costs) -# and select only the cheapest few into the front; the tail keeps rotation order, -# and the first minimum in rotation order wins ties, so ties stay random. +# and select only the cheapest few into the front; the tail keeps rotation order. +# Reservoir sampling gives each tied minimum equal probability even when the +# minima are separated by different numbers of higher-cost candidates. # N.B. A plain function: inside the `@reusable` block `best`/`bc` were captured # and reassigned, i.e. boxed, and every comparison became a dynamic dispatch. function order_candidates!(P::Vector{Int}, cost_vec::Vector{Float64}, all_equal::Bool) @@ -794,11 +795,16 @@ function order_candidates!(P::Vector{Int}, cost_vec::Vector{Float64}, all_equal: @inbounds for j in 1:min(np - 1, PLACEMENT_SELECT) best = j bc = cost_vec[P[j]] + ties = 1 for k in (j+1):np ck = cost_vec[P[k]] if ck < bc best = k bc = ck + ties = 1 + elseif ck == bc + ties += 1 + rand(1:ties) == 1 && (best = k) end end P[j], P[best] = P[best], P[j] diff --git a/test/scheduler.jl b/test/scheduler.jl index cb4eedc3b..a5b82340b 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -930,6 +930,17 @@ end end @test length(firsts) == (all_equal ? np : count(==(minimum(cost)), cost)) end + # Rotation alone weights a tied minimum by the gap preceding it. These + # minima have unequal gaps, but must still receive equal first-choice weight. + cost = [0.0, 1, 0, 1, 1, 1, 1, 1] + firsts = zeros(Int, length(cost)) + P = zeros(Int, length(cost)) + for _ in 1:2000 + order!(P, cost, false) + firsts[P[1]] += 1 + end + @test 800 <= firsts[1] <= 1200 + @test 800 <= firsts[3] <= 1200 @inferred order!(zeros(Int, 8), rand(8), false) end From 2f032737790b1d286ff600c7dc9658adc99b2d80 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:05:17 -0700 Subject: [PATCH 10/12] Keep wakeup filtering selective for small large-pool batches Follow-up on the bounded wakeup scan in PR #806: A fixed 64-probe cap would wake every runner for a single task on a pool larger than64, restoring the scalability cliff this PR removes. Bound filtering by eight times the combined runner and task counts instead. Singleton batches retain a linear selective scan; large cross-products still fall back to broad waking. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index fbf81a7f0..11692df34 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2172,9 +2172,9 @@ end # Rotates where `do_tasks` starts looking for a runner to wake, so that the same runners are not always the thieves const KICK_CURSOR = Threads.Atomic{Int}(0) -# Bound eligibility probes per batch. Larger cross-products use the ordinary -# broad wakeup, so a batch cannot spend runners × tasks time filtering wakeups. -const MAX_KICK_SCOPE_CHECKS = 64 +# Bound probes by a constant multiple of runners + tasks. This preserves +# selective waking for small batches even on very large thread pools. +const MAX_KICK_SCOPE_CHECKS = 8 # Test hook: called by `do_tasks` right after it enqueued a batch, i.e. from the moment on at which another runner may take, run and # recycle the specs. Tests set it to a sleep to make that window wide; `nothing` (the default) costs one load and compare per batch. @@ -2296,11 +2296,13 @@ function do_tasks(to_proc, return_queue, tasks) # of unscoped tasks at 32 threads and more. A runner that is not parked will look at the # queues again by itself (see `ProcessorInternalState.parked`), and one that cannot take any # of the tasks (scope, acceleration, free occupancy) would only go back to sleep. + # If exact eligibility would exceed a linear probe budget, wake broadly and + # leave compatibility checks to stealing instead. states_vec = states_snapshot!(STATES_CACHE_TLV[], proc_states(uid)) nstates = length(states_vec) nkick = 0 maxkick = length(kick_scopes) - broad_kick = nstates > div(MAX_KICK_SCOPE_CHECKS, maxkick) + broad_kick = nstates > div(MAX_KICK_SCOPE_CHECKS * (nstates + maxkick), maxkick) start_idx = nstates <= 1 ? 1 : mod1(Threads.atomic_add!(KICK_CURSOR, 1), nstates) for state_offset in 0:(nstates-1) state_idx = start_idx + state_offset From add5f7cf0fed691364b9a70683464329d7d2284c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:17:17 -0700 Subject: [PATCH 11/12] Bound best-effort scope sharing across unrelated spaces Independent review of PR #814 found that the shared #806 scope optimization scans every cached scope on each new worker/device processor miss. Stop after16 entries. Scope sharing remains an optional identity reuse optimization; missing a later match does not alter eligible processors. A counted1024-entry cache regression verifies a bounded miss and immediate reuse of an early match. Validation: the counted miss reproduces 1,024 visits before versus 17 fetched entries (16 comparisons) afterwards. Both scope-sharing variants allocate 0 bytes across 1,000 warmed calls (minimum of three runs). Written by an AI agent on jpsamaroo's review feedback. --- src/datadeps/queue.jl | 7 ++++++- test/scheduler.jl | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index 991b6e1fb..b76744c0b 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -270,10 +270,15 @@ end # Every processor of a memory space gets an equal union scope (the scope does not depend on `our_proc` # beyond its space), but `get!` builds one object per processor. The scheduler's compatible-set lookup # then compares up to 64 member-by-member equal scopes (22 us at 64 threads on our cluster) where one shared -# object is a pointer comparison. Return the cached scope equal to `scope` if there is one. +# object is a pointer comparison. Sharing is best-effort: bound the scan so a +# new space never searches every unrelated worker/device scope in the cache. +const SCOPE_SHARE_SCAN_LIMIT = 16 function share_equal_scope(cache, scope) + checked = 0 for existing in values(cache.cache) + checked >= SCOPE_SHARE_SCAN_LIMIT && break existing === scope && return existing + checked += 1 end return scope end diff --git a/test/scheduler.jl b/test/scheduler.jl index a5b82340b..04ff2aad2 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -976,3 +976,25 @@ end @test_skip run_many(300) # one thread: nothing else can run while do_tasks sleeps end end + +struct CountedScopeValues + data::Vector{Int} + visited::Base.RefValue{Int} +end +Base.values(values::CountedScopeValues) = values +function Base.iterate(values::CountedScopeValues, idx::Int=1) + idx > length(values.data) && return nothing + values.visited[] += 1 + return values.data[idx], idx + 1 +end +@testset "Scope sharing has a bounded search on unrelated spaces" begin + values = CountedScopeValues(collect(1:1024), Ref(0)) + cache = (; cache=values) + @test Dagger.share_equal_scope(cache, -1) == -1 + # Iteration may obtain the next element before checking the bound. + @test values.visited[] <= Dagger.SCOPE_SHARE_SCAN_LIMIT + 1 + values.data[1] = -1 + values.visited[] = 0 + @test Dagger.share_equal_scope(cache, -1) == -1 + @test values.visited[] == 1 +end From 645782fd8c8941d73836794ff881dd26bbe2a29b Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:32:08 -0700 Subject: [PATCH 12/12] Document partial candidate ordering in the scheduler manual Independent review of PR #806 found that only the internal cost estimator docstring had been updated. The scheduler manual still promised the globally least costly eligible processor. Describe the four-best prefix and rotated fallback order where users read the scheduling policy. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/scheduler-internals.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/src/scheduler-internals.md b/docs/src/scheduler-internals.md index 52108a1ff..61c26b2d5 100644 --- a/docs/src/scheduler-internals.md +++ b/docs/src/scheduler-internals.md @@ -81,7 +81,7 @@ Once one or more tasks are ready to be scheduled, the scheduler will begin assig - Selecting candidate processors based on the task's combined scope - Calculating the cost to move needed data to each candidate processor - Adding a "wait time" cost proportional to the estimated run time for all the tasks currently executing on each candidate processor -- Selecting the least costly candidate processor as the executor for this task +- Trying the four least costly candidates first; further candidates retain a random rotation order and need not be the next cheapest eligible processor After these operations have been performed for each task, the tasks will be fired off to their appropriate worker for handling.