From c0c8f63c7c072c0d9e4227535aeab9846181fb20 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 21 Nov 2026 14:58:12 +0100 Subject: [PATCH 01/28] 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/28] 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/28] 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/28] 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/28] 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 bac8442add08d6d3de7df2217fdd2af31cf0dbee Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 21:30:01 +0100 Subject: [PATCH 06/28] sched: place on the less loaded of two random threads when one process has many candidates With every candidate a thread of one process, a candidate's cost is its reserved pressure alone (same-worker transfers are free, the signature's time estimate is the same for all), yet estimate_task_costs! read every counter, filled a cost vector and rotated/selected the order: O(threads) work that phase timers on our cluster put at 9 + 5 + 3.5 us at 4 threads and 26 + 10 + 14 us at 64 threads, of a ~110 / ~155 us task. For more than TWO_CHOICES_MIN (8) candidates of one worker and no per-candidate cost dict, the scheduler now samples two candidates, takes the one with less pressure, and keeps the rest in rotation order as capacity fallbacks. Idle runners steal what is queued behind a busy one, so the first choice only has to be good, not optimal. Multi-worker candidate sets, datadeps (one candidate) and callers that want the costs are untouched. Laptop, 16 threads, plain @spawn: 36 -> 16 us per task. Balance probe (sleeping tasks, equal and irregular, 5 rounds, both placements in one process): makespan ratios within noise of the full ranking. Measurements on our cluster follow. --- src/sch/util.jl | 64 +++++++++++++++++++++++++++++++++++++++++++++ test/runtests.jl | 1 + test/two-choices.jl | 44 +++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 test/two-choices.jl diff --git a/src/sch/util.jl b/src/sch/util.jl index d916f3316..1ec587bb9 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -817,6 +817,62 @@ function order_candidates!(P::Vector{Int}, cost_vec::Vector{Float64}, all_equal: return end +# With many candidates that are all threads of one process, the cost of a candidate is its +# reserved pressure and nothing else (same-worker transfers are free, `est_time_util` is the +# same for every candidate), so ranking all of them reads every counter, shuffles and sorts: +# O(threads) work per task that grew to ~50 us at 64 threads on our cluster. The scheduler only +# needs a good first choice, because idle runners steal what is queued behind a busy one. +# Choose the less loaded of two random candidates instead ("power of two choices": the +# maximum load stays within O(log log n) of the mean), and keep the rest in rotation order as +# fallbacks for the capacity checks. +const TWO_CHOICES_MIN = 8 # candidates + +# The pid shared by every candidate, or -1 +function single_worker_pid(procs, ::Type{P}) where {P} + pid = Dagger.root_worker_id(@inbounds(procs[1])::P) + for idx in 2:length(procs) + Dagger.root_worker_id(@inbounds(procs[idx])::P) == pid || return -1 + end + return pid +end + +function place_two_choices!(sorted_procs, state, procs, np::Int, pid::Int) + i1 = rand(1:np) + i2 = rand(1:np-1) + i2 >= i1 && (i2 += 1) + p1 = @inbounds procs[i1] + p2 = @inbounds procs[i2] + # One acquisition for both counters. N.B. Explicit lock/unlock, and the result returned + # from the `try`, so nothing is captured and reassigned (which would box it). + lock(state.worker_time_pressure) + c1, c2 = try + wtp = Dagger.payload(state.worker_time_pressure) + proc_map = get(wtp, pid, nothing) + if proc_map === nothing + (UInt64(0), UInt64(0)) + else + r1 = get(proc_map, p1, nothing) + r2 = get(proc_map, p2, nothing) + (r1 === nothing ? UInt64(0) : r1[], r2 === nothing ? UInt64(0) : r2[]) + end + finally + unlock(state.worker_time_pressure) + end + first_idx, second_idx = c2 < c1 ? (i2, i1) : (i1, i2) + @inbounds sorted_procs[1] = procs[first_idx] + @inbounds sorted_procs[2] = procs[second_idx] + pos = 3 + off = rand(1:np) + for k in 1:np + j = off + k + j > np && (j -= np) + (j == first_idx || j == second_idx) && continue + @inbounds sorted_procs[pos] = procs[j] + pos += 1 + end + return +end + """ estimate_task_costs!(sorted_procs, costs, state, procs, task; sig=nothing) @@ -844,6 +900,14 @@ candidate lookups cost about 130 us for 16 threads and grew with the thread coun return end + if costs === nothing && np > TWO_CHOICES_MIN + pid = single_worker_pid(procs, candidate_type(procs)) + if pid >= 0 + place_two_choices!(sorted_procs, state, procs, np, pid) + return + end + end + # Find all Chunks chunks = @reusable_vector :estimate_task_costs_chunks Union{Chunk,Nothing} nothing 32 for input in task.inputs diff --git a/test/runtests.jl b/test/runtests.jl index 35aa76788..6ecfe6b3d 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -22,6 +22,7 @@ tests = [ ("Scheduler", "scheduler.jl"), ("Processors", "processors.jl"), ("Uniform Placement", "uniform-placement.jl"), + ("Two-choices Placement", "two-choices.jl"), ("Processor Grids", "procgrid.jl"), ("Memory Spaces", "memory-spaces.jl"), ("Logging", "logging.jl"), diff --git a/test/two-choices.jl b/test/two-choices.jl new file mode 100644 index 000000000..108cbcc1e --- /dev/null +++ b/test/two-choices.jl @@ -0,0 +1,44 @@ +using Dagger, Test, Distributed +import Dagger: ThreadProc, Processor, LockedObject + +@testset "Two-choices placement" begin + pid = myid() + nproc = 16 + procs = Processor[ThreadProc(pid, t) for t in 1:nproc] + busy = procs[5] + pressure = Dict{Processor,Threads.Atomic{UInt64}}(p => Threads.Atomic{UInt64}(UInt64(p === busy ? 10^9 : 0)) for p in procs) + state = (; worker_time_pressure=LockedObject(Dict{Int,Dict{Processor,Threads.Atomic{UInt64}}}(pid => pressure))) + sorted = Vector{Processor}(undef, nproc) + firsts = Set{Processor}() + for _ in 1:3000 + Dagger.Sch.place_two_choices!(sorted, state, procs, nproc, pid) + # a permutation of the candidates + @test length(unique(sorted)) == nproc + @test Set(sorted) == Set(procs) + # the loaded processor never wins a comparison, so it is never first + @test sorted[1] !== busy + push!(firsts, sorted[1]) + end + # every other processor is a possible first choice (the choice is random, not fixed) + @test length(firsts) == nproc - 1 + + # a processor with less pressure than its competitor is placed ahead of it + for p in procs; pressure[p][] = UInt64(0); end + pressure[procs[1]][] = UInt64(7) + for _ in 1:500 + Dagger.Sch.place_two_choices!(sorted, state, procs, nproc, pid) + @test findfirst(==(procs[1]), sorted) >= 2 # worse than every other processor it is compared with + end + + # no table for this worker yet: still a valid order + empty_state = (; worker_time_pressure=LockedObject(Dict{Int,Dict{Processor,Threads.Atomic{UInt64}}}())) + Dagger.Sch.place_two_choices!(sorted, empty_state, procs, nproc, pid) + @test Set(sorted) == Set(procs) + + # candidates of two workers use the full ranking path + @test Dagger.Sch.single_worker_pid(procs, Processor) == pid + if nprocs() > 1 + mixed = Processor[ThreadProc(pid, 1), ThreadProc(first(workers()), 1)] + @test Dagger.Sch.single_worker_pid(mixed, Processor) == -1 + end +end From 2c32c8c4f0703608a0ba15353b16d786e7ef9281 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Thu, 26 Nov 2026 21:30:39 +0100 Subject: [PATCH 07/28] Sch: lightweight placement for tasks that run on a thread of this process schedule_one! ranks candidate processors across workers, re-checks every candidate against the scope, and takes capacity locks, for tasks whose candidates are all CPU threads of this process (has_capacity always says yes, same-worker transfers cost nothing, a ThreadProc accepts every function and argument type). Such a task now takes the compatible set of its scope from the cached entry (the set the general path used), picks the less loaded of two random threads (all of them when there are 8 or fewer) from pressure counters resolved once per scheduler, and reserves the counter. Falls back to the general path for proclist/single/time_util/ alloc_util/occupancy, for scopes the scheduler would have to build or constrain (compute/result scope, chunk scope restrictions), for any acceleration but DistributedAcceleration (MPI), for a compatible set with a non-local or non-ThreadProc member (workers, GPUs), and when a thread refuses the function or an argument type. test/local-fastpath.jl covers the fast and the fallback cases and that the pressure is released. --- src/sch/Sch.jl | 206 ++++++++++++++++++++++------------------- src/sch/fastpath.jl | 197 +++++++++++++++++++++++++++++++++++++++ test/local-fastpath.jl | 107 +++++++++++++++++++++ test/runtests.jl | 1 + 4 files changed, 416 insertions(+), 95 deletions(-) create mode 100644 src/sch/fastpath.jl create mode 100644 test/local-fastpath.jl diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 9dc42cbf3..623e3cbd3 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -36,6 +36,7 @@ import ScopedValues: ScopedValue, @with, with include("util.jl") +include("fastpath.jl") include("fault-handler.jl") include("dynamic.jl") @@ -107,6 +108,8 @@ mutable struct CompatEntry const procs::Vector{Processor} const compat::Set{Processor} @atomic ordered::Union{Nothing,Vector{Processor}} + # The local fast path's view of this set (`missing` until first asked; see fastpath.jl) + @atomic fast::Any end const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},CompatEntry}(256)) # Drop all cached compatible-processor sets. Called whenever the processor @@ -158,7 +161,7 @@ function compat_entry(accel, scope, procs::Vector{<:Processor}) # happens not to have this (accel, scope) pair cached already -- see the # sibling fix in generic `compatible_processors`, which had the same defect # with `Set(gen)`. - entry = CompatEntry(scope, Vector{Processor}(procs), compat, nothing) + entry = CompatEntry(scope, Vector{Processor}(procs), compat, nothing, missing) return @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin # N.B. `get!` would keep a *stale* entry for this key (one whose `procs` no longer # matches, because the processor list changed without a cache flush) and hand it @@ -1013,115 +1016,128 @@ concurrently across threads. Dagger.options_merge!(options, state.sch_options) Dagger.populate_defaults!(options, sig) - # Calculate scope. Errors are stored in `scope_ex` and applied in Phase 3. - local scope - local scope_ex = nothing - if options.exec_scope !== nothing - # Bypass scope calculation if it's been done for us already - scope = options.exec_scope - else - scope = constrain(@something(options.compute_scope, options.scope, DefaultScope()), - @something(options.result_scope, AnyScope())) - if scope isa InvalidScope - scope_ex = SchedulingException("compute_scope and result_scope are not compatible: $(scope.x), $(scope.y)") - else - for arg in task.inputs - scope_ex === nothing || break - value = unwrap_weak_checked(Dagger.value(arg)) - # After collect_task_inputs!, Thunk inputs are resolved to Chunks. - @assert !istask(value) - chunk = if value isa Chunk - value - else - nothing - end - chunk isa Chunk || continue - scope = constrain(scope, chunk.scope) - if scope isa InvalidScope - scope_ex = SchedulingException("Current scope and argument Chunk scope are not compatible: $(scope.x), $(scope.y)") - end - end - end - end - - if scope_ex !== nothing - # scope is invalid — fail the task under state.lock (set_failed! requires it) - lock(state.lock) do - set_failed!(state, task; ex=scope_ex) - # Release the `running_count` credit `task` received when it - # entered `ready_out` (see comment at the other `set_failed!` - # call sites in this function for why this is necessary). - Threads.atomic_sub!(state.running_count, 1) - @logfinish ctx LogSchedule LogScheduleId(state.uid, task.id) (;thunk_id=task.id) - end - return - end - # `accel` drives uniform (e.g. MPI) scheduling: it filters compatible # processors, imposes a deterministic processor order, and (under uniform # execution) makes selection ignore rank-local capacity/occupancy so every # rank picks the same processor for this task. accel = something(options.acceleration, current_acceleration()) - sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32 - if uniform_execution(accel) - # Measured costs are rank-local, so under uniform execution the - # candidates are ordered by a deterministic, acceleration-dispatched key - # instead and the cost estimate would be discarded unread. Start from - # the cached canonical order of the candidate set and apply only the - # per-task part (owner preference and rotation). - ordered = compatible_processors_ordered(accel, scope, procs_filt) - resize!(sorted_procs, length(ordered)) - copyto!(sorted_procs, ordered) - Dagger.place_processors_uniform!(sorted_procs, accel, task, state) - else - input_procs = @reusable_vector :schedule_one!_input_procs Processor OSProc() 32 - compat = compatible_processors_cached(accel, scope, procs_filt) - # N.B. `compat` is a `Set`: its elements are already unique - append!(input_procs, compat) - resize!(sorted_procs, length(input_procs)) - estimate_task_costs!(sorted_procs, nothing, state, input_procs, task; sig) - empty!(input_procs) - end - - # Select the best available processor and reserve time pressure optimistically. - # These operations use their own fine-grained locks — no state.lock needed. + # Lightweight placement for a task that certainly runs on a thread of this process + # (fastpath.jl); anything it does not handle takes the general path below. scheduled = false local best_loc, best_spec - for proc in sorted_procs - gproc = get_parent(proc) - can_use, scope = can_use_proc(state, task, gproc, proc, options, scope) - if can_use - has_cap, est_time_util, est_alloc_util, est_occupancy = - has_capacity(state, proc, root_worker_id(gproc), options.time_util, options.alloc_util, options.occupancy, sig) - # Under uniform execution capacity is rank-local; every rank must - # take the first usable processor in the deterministic order. - if has_cap || scheduling_ignore_capacity(accel) - # Optimistic reservation: capture-the-ref, atomic_add! - counter_ref = lock(state.worker_time_pressure) do wtp - proc_map = get!(wtp, root_worker_id(gproc)) do - Dict{Processor,Threads.Atomic{UInt64}}() + fast_cand = local_fast_candidates(state, task, options, procs, accel) + if fast_cand !== nothing + placed = local_fast_place!(state, task, options, sig, fast_cand[1], fast_cand[2]) + if placed !== nothing + best_loc, best_spec = placed + scheduled = true + end + end + + if !scheduled + # Calculate scope. Errors are stored in `scope_ex` and applied in Phase 3. + local scope + local scope_ex = nothing + if options.exec_scope !== nothing + # Bypass scope calculation if it's been done for us already + scope = options.exec_scope + else + scope = constrain(@something(options.compute_scope, options.scope, DefaultScope()), + @something(options.result_scope, AnyScope())) + if scope isa InvalidScope + scope_ex = SchedulingException("compute_scope and result_scope are not compatible: $(scope.x), $(scope.y)") + else + for arg in task.inputs + scope_ex === nothing || break + value = unwrap_weak_checked(Dagger.value(arg)) + # After collect_task_inputs!, Thunk inputs are resolved to Chunks. + @assert !istask(value) + chunk = if value isa Chunk + value + else + nothing end - get!(proc_map, proc) do - Threads.Atomic{UInt64}(UInt64(0)) + chunk isa Chunk || continue + scope = constrain(scope, chunk.scope) + if scope isa InvalidScope + scope_ex = SchedulingException("Current scope and argument Chunk scope are not compatible: $(scope.x), $(scope.y)") end end - Threads.atomic_add!(counter_ref, est_time_util) - lock(state.running_pressure_refs) do rpr - rpr[task.id] = (counter_ref, est_time_util) + end + end + + if scope_ex !== nothing + # scope is invalid — fail the task under state.lock (set_failed! requires it) + lock(state.lock) do + set_failed!(state, task; ex=scope_ex) + # Release the `running_count` credit `task` received when it + # entered `ready_out` (see comment at the other `set_failed!` + # call sites in this function for why this is necessary). + Threads.atomic_sub!(state.running_count, 1) + @logfinish ctx LogSchedule LogScheduleId(state.uid, task.id) (;thunk_id=task.id) + end + return + end + + sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32 + if uniform_execution(accel) + # Measured costs are rank-local, so under uniform execution the + # candidates are ordered by a deterministic, acceleration-dispatched key + # instead and the cost estimate would be discarded unread. Start from + # the cached canonical order of the candidate set and apply only the + # per-task part (owner preference and rotation). + ordered = compatible_processors_ordered(accel, scope, procs_filt) + resize!(sorted_procs, length(ordered)) + copyto!(sorted_procs, ordered) + Dagger.place_processors_uniform!(sorted_procs, accel, task, state) + else + input_procs = @reusable_vector :schedule_one!_input_procs Processor OSProc() 32 + compat = compatible_processors_cached(accel, scope, procs_filt) + # N.B. `compat` is a `Set`: its elements are already unique + append!(input_procs, compat) + resize!(sorted_procs, length(input_procs)) + estimate_task_costs!(sorted_procs, nothing, state, input_procs, task; sig) + empty!(input_procs) + end + + # Select the best available processor and reserve time pressure optimistically. + # These operations use their own fine-grained locks — no state.lock needed. + for proc in sorted_procs + gproc = get_parent(proc) + can_use, scope = can_use_proc(state, task, gproc, proc, options, scope) + if can_use + has_cap, est_time_util, est_alloc_util, est_occupancy = + has_capacity(state, proc, root_worker_id(gproc), options.time_util, options.alloc_util, options.occupancy, sig) + # Under uniform execution capacity is rank-local; every rank must + # take the first usable processor in the deterministic order. + if has_cap || scheduling_ignore_capacity(accel) + # Optimistic reservation: capture-the-ref, atomic_add! + counter_ref = lock(state.worker_time_pressure) do wtp + proc_map = get!(wtp, root_worker_id(gproc)) do + Dict{Processor,Threads.Atomic{UInt64}}() + end + get!(proc_map, proc) do + Threads.Atomic{UInt64}(UInt64(0)) + end + end + Threads.atomic_add!(counter_ref, est_time_util) + lock(state.running_pressure_refs) do rpr + rpr[task.id] = (counter_ref, est_time_util) + end + @dagdebug task :schedule "Scheduling to $gproc -> $proc (pressure: $(counter_ref[]))" + # Uniform execution overlaps communicating tasks on a processor + # (rank-local shares); avoid serializing them into wait cycles. + est_occupancy = scheduling_task_occupancy(accel, est_occupancy) + best_loc = ScheduleTaskLocation(gproc, proc) + best_spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, est_occupancy) + scheduled = true + break end - @dagdebug task :schedule "Scheduling to $gproc -> $proc (pressure: $(counter_ref[]))" - # Uniform execution overlaps communicating tasks on a processor - # (rank-local shares); avoid serializing them into wait cycles. - est_occupancy = scheduling_task_occupancy(accel, est_occupancy) - best_loc = ScheduleTaskLocation(gproc, proc) - best_spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, est_occupancy) - scheduled = true - break end end + empty!(sorted_procs) end - empty!(sorted_procs) # Phase 3 — brief state.lock hold: fire or fail the task. # `restore_ready` only becomes non-empty if a task completes synchronously diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl new file mode 100644 index 000000000..2265a4e9f --- /dev/null +++ b/src/sch/fastpath.jl @@ -0,0 +1,197 @@ +# Lightweight local placement. +# +# `schedule_one!` is written for the general case: candidate processors of several workers, every +# kind of processor, per-candidate capacity checks, user scopes. A task whose compatible +# processors are all CPU threads of *this* process needs none of it: nothing to rank across +# workers, no data to transfer, `has_capacity` always says yes, and every candidate accepts the +# function and its arguments. For those tasks this path takes the processors the general path +# would have used (the cached compatible set of the task's scope) and does only what still +# matters: pick the less loaded of two random candidates (all candidates when there are few), +# reserve its pressure counter, and hand the spec to phase 3. +# +# A task takes the general path whenever one of these does not hold: an option the fast path +# does not model (`proclist`, `single`, `time_util`, `alloc_util`, `occupancy`), a compute or +# result scope that is not the scope the scheduler would build itself, a chunk argument with a +# scope restriction, an acceleration other than `DistributedAcceleration` (MPI plans uniformly), +# a compatible set with any processor that is not a local `ThreadProc` (workers, GPUs, ...), or a +# function or argument type that a thread refuses. + +# Pressure counters of one scheduler's processors, aligned with `LocalFast.procs` +struct FastCounters + uid::UInt64 + refs::Vector{Threads.Atomic{UInt64}} +end + +# The compatible set of one (accel, scope) entry, when it qualifies for the fast path +mutable struct LocalFast + const procs::Vector{Processor} # all `ThreadProc`s of this process, in the compatible set's order + const gproc::OSProc + const pid::Int + @atomic counters::Union{Nothing,FastCounters} +end + +function build_local_fast(entry, accel) + accel isa Dagger.DistributedAcceleration || return nothing + compat = entry.compat + isempty(compat) && return nothing + me = myid() + procs = Vector{Processor}() + for p in compat + (p isa Dagger.ThreadProc && p.owner == me) || return nothing + push!(procs, p) + end + return LocalFast(procs, OSProc(me), me, nothing) +end + +# `entry.fast` is `missing` until first asked +function local_fast_of(entry, accel) + fast = @atomic entry.fast + if fast === missing + fast = build_local_fast(entry, accel) + @atomic entry.fast = fast + end + return fast::Union{Nothing,LocalFast} +end + +# What the scheduler builds for a task without any scope of its own; computed once +const UNSCOPED_SCOPE = Ref{Union{Nothing,Dagger.AbstractScope}}(nothing) +function unscoped_scope() + scope = UNSCOPED_SCOPE[] + if scope === nothing + scope = constrain(DefaultScope(), AnyScope()) + UNSCOPED_SCOPE[] = scope + end + return scope::Dagger.AbstractScope +end + +""" + local_fast_candidates(state, task, options, procs, accel) -> Union{Nothing,Tuple{LocalFast,AbstractScope}} + +The fast path's candidate set and the scope the task is scheduled under, or `nothing` when the +task must take the general path (see the file header). Reads only; reserves nothing. +""" +function local_fast_candidates(state, task, options, procs, accel)::Union{Nothing,Tuple{LocalFast,Dagger.AbstractScope}} + (options.proclist === nothing && options.single === nothing && options.time_util === nothing && + options.alloc_util === nothing && options.occupancy === nothing) || return nothing + accel isa Dagger.DistributedAcceleration || return nothing + haskey(state.worker_chans, myid()) || return nothing + exec = options.exec_scope + if exec !== nothing + # The scope was fixed by the caller (Datadeps): it is used as is + fast = local_fast_of(compat_entry(accel, exec, procs), accel) + fast === nothing && return nothing + return (fast, exec) + end + if options.compute_scope === nothing && options.scope === nothing && options.result_scope === nothing + for arg in task.inputs + value = unwrap_weak_checked(Dagger.value(arg)) + # A chunk with a scope restriction narrows the candidates + value isa Chunk && !(value.scope isa AnyScope) && return nothing + end + scope = unscoped_scope() + fast = local_fast_of(compat_entry(accel, scope, procs), accel) + fast === nothing && return nothing + return (fast, scope) + end + return nothing +end + +function build_fast_counters!(state, fast::LocalFast) + refs = Vector{Threads.Atomic{UInt64}}(undef, length(fast.procs)) + lock(state.worker_time_pressure) + try + wtp = Dagger.payload(state.worker_time_pressure) + proc_map = get!(wtp, fast.pid) do + Dict{Processor,Threads.Atomic{UInt64}}() + end + for idx in eachindex(fast.procs) + refs[idx] = get!(proc_map, fast.procs[idx]) do + Threads.Atomic{UInt64}(UInt64(0)) + end + end + finally + unlock(state.worker_time_pressure) + end + counters = FastCounters(state.uid, refs) + @atomic fast.counters = counters + return counters +end + +@inline function locked_get(lo::LockedObject, key, default) + lock(lo) + try + return get(Dagger.payload(lo), key, default) + finally + unlock(lo) + end +end + +# The index of the candidate to run on: what the general path's ranking would put first. The +# counters are read without a lock (they are atomics). +function pick_fast_candidate(refs::Vector{Threads.Atomic{UInt64}}) + np = length(refs) + np == 1 && return 1 + if np > TWO_CHOICES_MIN + i1 = rand(1:np) + i2 = rand(1:np-1) + i2 >= i1 && (i2 += 1) + return @inbounds(refs[i2][]) < @inbounds(refs[i1][]) ? i2 : i1 + end + # Few candidates: the least loaded, a tie broken uniformly at random + best = typemax(UInt64) + idx = 1 + nties = 0 + for i in 1:np + c = @inbounds(refs[i][]) + if c < best + best = c + idx = i + nties = 1 + elseif c == best + nties += 1 + rand(1:nties) == 1 && (idx = i) + end + end + return idx +end + +""" + local_fast_place!(state, task, options, sig, fast, scope) -> Union{Nothing,Tuple{ScheduleTaskLocation,ScheduleTaskSpec}} + +Chooses a processor of `fast` for `task` and reserves its pressure counter. `nothing` (with +nothing reserved) when a thread would refuse the function or an argument: the general path then +decides. +""" +function local_fast_place!(state, task, options, sig, fast::LocalFast, scope) + procs = fast.procs + proc1 = @inbounds procs[1]::Dagger.ThreadProc + # Compatibility depends on the processor's type only, so one thread speaks for all + inputs = task.inputs + Dagger.iscompatible_func(proc1, options, chunktype(task.f)) || return nothing + for idx in 2:length(inputs) + value = unwrap_weak_checked(Dagger.value(@inbounds inputs[idx])) + value isa Thunk && return nothing + Dagger.iscompatible_arg(proc1, options, chunktype(value)) || return nothing + end + + est_time_util = round(UInt64, locked_get(state.signature_time_cost, sig, UInt64(1000^3)))::UInt64 + est_alloc_util = locked_get(state.signature_alloc_cost, sig, UInt64(0))::UInt64 + + counters = @atomic fast.counters + if counters === nothing || counters.uid != state.uid + counters = build_fast_counters!(state, fast) + end + refs = counters.refs + idx = pick_fast_candidate(refs) + counter_ref = @inbounds refs[idx] + Threads.atomic_add!(counter_ref, est_time_util) + lock(state.running_pressure_refs) + try + Dagger.payload(state.running_pressure_refs)[task.id] = (counter_ref, est_time_util) + finally + unlock(state.running_pressure_refs) + end + loc = ScheduleTaskLocation(fast.gproc, @inbounds(procs[idx])) + spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, typemax(UInt32)) + return (loc, spec) +end diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl new file mode 100644 index 000000000..f889ddbc9 --- /dev/null +++ b/test/local-fastpath.jl @@ -0,0 +1,107 @@ +using Dagger, Test, Distributed, LinearAlgebra, Random +import Dagger: ThreadProc, Processor +import Dagger.Sch: COMPAT_PROCS_CACHE + +# With workers, unscoped tasks may run anywhere (and take the general path), so the code the tasks +# run exists everywhere; what the fast path decides is checked where it can be seen, on one process. +@everywhere begin + using Dagger + struct NoThreadFn end + (::NoThreadFn)(x) = x + Dagger.iscompatible_func(::Dagger.ThreadProc, opts, ::Type{NoThreadFn}) = false + FP_TINY(x) = x + 1 + fp_proc() = (sleep(0.002); Dagger.task_processor()) +end + +# The fast path's view of every cached compatible set that qualified +fast_entries() = count(e -> e.fast isa Dagger.Sch.LocalFast, values(Dagger.payload(COMPAT_PROCS_CACHE).cache)) + +# Total reserved pressure of the eager scheduler; zero once everything has finished. Every counter is +# checked on its own: a release without a matching reservation wraps a counter around to a huge value, +# which a plain sum could cancel against another counter. +function reserved_pressure() + state = Dagger.Sch.EAGER_STATE[] + total = UInt64(0) + lock(state.worker_time_pressure) do wtp + for pm in values(wtp), c in values(pm) + c[] == 0 || (total = max(total, c[])) + end + end + return total +end + +@testset "Local fast path" begin + begin + @testset "tasks complete and release their pressure" begin + Dagger.Sch.invalidate_compat_procs_cache!() + ts = [Dagger.@spawn FP_TINY(i) for i in 1:500] + @test sum(fetch.(ts)) == sum(2:501) + Dagger.@spawn(FP_TINY(0)) |> fetch # one more so the last completions have been handled + # unscoped tasks on a plain process qualify (with workers they may run anywhere) + nprocs() == 1 && @test fast_entries() >= 1 + sleep(0.2) + @test reserved_pressure() == 0 + end + + @testset "placement spreads over the threads" begin + nt = Threads.nthreads() + if nt > 1 && nprocs() == 1 + ps = Set{Processor}(fetch.([Dagger.@spawn fp_proc() for _ in 1:20 * nt])) + @test length(ps) >= min(nt, 4) + @test all(p -> p isa ThreadProc && p.owner == myid(), ps) + end + end + + @testset "options the fast path does not model take the general path" begin + @test fetch(Dagger.@spawn proclist=[ThreadProc] FP_TINY(1)) == 2 + @test fetch(Dagger.@spawn single=1 FP_TINY(1)) == 2 + @test fetch(Dagger.@spawn occupancy=Dict(ThreadProc=>0.5) FP_TINY(3)) == 4 + @test fetch(Dagger.@spawn time_util=Dict(ThreadProc=>1_000_000) FP_TINY(4)) == 5 + @test fetch(Dagger.@spawn alloc_util=Dict(ThreadProc=>UInt64(1024)) FP_TINY(5)) == 6 + # a scope is honoured + p = fetch(Dagger.@spawn scope=Dagger.scope(worker=myid(), thread=1) fp_proc()) + @test p == ThreadProc(myid(), 1) + # so is a scope on a chunk argument + ch = Dagger.tochunk(5, ThreadProc(myid(), 1), Dagger.ExactScope(ThreadProc(myid(), 1))) + @test fetch(Dagger.@spawn FP_TINY(ch)) == 6 + end + + @testset "scopes naming some threads are honoured" begin + nt = Threads.nthreads() + rng = MersenneTwister(7) + for _ in 1:80 + k = rand(rng, 1:min(nt, 4)) + tids = sort!(randperm(rng, nt)[1:k]) + sc = rand(rng, Bool) ? Dagger.scope(worker=myid(), threads=tids) : + Dagger.UnionScope(map(t -> Dagger.ExactScope(ThreadProc(myid(), t)), tids)) + ts = [Dagger.with_options(scope=sc) do; Dagger.@spawn fp_proc(); end for _ in 1:4] + @test all(p -> p isa ThreadProc && p.owner == myid() && p.tid in tids, fetch.(ts)) + end + # many small tasks pinned to a thread subset, some of them consuming earlier results + sc = Dagger.scope(worker=myid(), threads=1:min(nt, 2)) + first_ts = [Dagger.with_options(scope=sc) do; Dagger.@spawn fp_proc(); end for _ in 1:50] + second_ts = [Dagger.with_options(scope=sc) do; Dagger.@spawn identity(t); end for t in first_ts] + @test all(p -> p.tid in 1:min(nt, 2), fetch.(second_ts)) + sleep(0.2) + @test reserved_pressure() == 0 + end + + @testset "a thread that refuses the function is respected" begin + t = Dagger.@spawn NoThreadFn()(1) + @test_throws Exception fetch(t) + end + + @testset "Datadeps" begin + A = [zeros(8) for _ in 1:12] + Dagger.spawn_datadeps() do + for a in A + Dagger.@spawn fill!(Dagger.InOut(a), 3.0) + end + for a in A + Dagger.@spawn rmul!(Dagger.InOut(a), 2.0) + end + end + @test all(a -> all(==(6.0), a), A) + end + end +end diff --git a/test/runtests.jl b/test/runtests.jl index 6ecfe6b3d..56a787055 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -23,6 +23,7 @@ tests = [ ("Processors", "processors.jl"), ("Uniform Placement", "uniform-placement.jl"), ("Two-choices Placement", "two-choices.jl"), + ("Local Fast Path", "local-fastpath.jl"), ("Processor Grids", "procgrid.jl"), ("Memory Spaces", "memory-spaces.jl"), ("Logging", "logging.jl"), From b40b4b2b06a805d40d9e3ee365847ef39f53a7d5 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 25 Oct 2026 11:47:43 +0100 Subject: [PATCH 08/28] Sch: read the fast path's compatible sets from a lock-free snapshot The compatible-set cache is one frequency-ordered cache behind one lock and a hit updates the frequency under it, so every placing thread took that lock for every task: the candidate lookup of a fast-path task measured 3.9 us at 16 threads and 11.7 us at 64 (flat Datadeps Cholesky: 9.7 / 28.6 us). The fast path now keeps the same CompatEntry objects in a dictionary that is replaced, not mutated, when an entry is added (bounded to 2048 keys, emptied with the cache when the processor hierarchy changes), so a lookup takes no lock. --- src/sch/Sch.jl | 4 +++- src/sch/fastpath.jl | 42 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 623e3cbd3..f44ae4c4d 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -36,7 +36,6 @@ import ScopedValues: ScopedValue, @with, with include("util.jl") -include("fastpath.jl") include("fault-handler.jl") include("dynamic.jl") @@ -122,6 +121,7 @@ const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},Co # sessions): `__init__`'s per-thread callback registrations trigger it. function invalidate_compat_procs_cache!() @safe_lock_spin1 COMPAT_PROCS_CACHE cache empty!(cache) + invalidate_fast_index!() return end # Cache key of a scope. `objectid` of a union scope hashes every member (one `ExactScope` per @@ -196,6 +196,8 @@ function compatible_processors_ordered(accel, scope, procs::Vector{<:Processor}) return ordered end +include("fastpath.jl") + # N.B. `mutable` (with no field ever assigned) so the 23-field struct has a # stable heap identity and is passed by pointer; as an immutable struct it was # stored inline in closures and re-boxed (~200B) on every dynamic call. diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl index 2265a4e9f..6c2b7d85c 100644 --- a/src/sch/fastpath.jl +++ b/src/sch/fastpath.jl @@ -43,6 +43,44 @@ function build_local_fast(entry, accel) return LocalFast(procs, OSProc(me), me, nothing) end +# The compatible-set cache (`COMPAT_PROCS_CACHE`) is one frequency-ordered cache behind one lock, and +# a hit updates the frequency under that lock: every placing thread takes it for every task (4 us at +# 16 threads, 12-29 us at 64). The fast path reads its entries from a snapshot instead: an immutable- +# by-convention dictionary that is replaced (copy, then store) when an entry is added, so a lookup +# takes no lock. It holds the same `CompatEntry`s the cache does, so processor-hierarchy changes +# (`invalidate_compat_procs_cache!`) empty it too. Bounded: once full, new keys go through the cache. +mutable struct FastIndex + @atomic dict::Dict{Tuple{UInt,UInt},CompatEntry} +end +const FAST_INDEX = FastIndex(Dict{Tuple{UInt,UInt},CompatEntry}()) +const FAST_INDEX_LOCK = ReentrantLock() +const FAST_INDEX_MAX = 2048 + +function invalidate_fast_index!() + lock(FAST_INDEX_LOCK) do + @atomic FAST_INDEX.dict = Dict{Tuple{UInt,UInt},CompatEntry}() + end + return +end + +function fast_compat_entry(accel, scope, procs::Vector{<:Processor}) + key = (objectid(accel), scope_key(scope)) + entry = get(@atomic(FAST_INDEX.dict), key, nothing) + if entry !== nothing && entry.scope === scope && entry.procs == procs + return entry::CompatEntry + end + entry = compat_entry(accel, scope, procs) + lock(FAST_INDEX_LOCK) do + dict = @atomic FAST_INDEX.dict + if haskey(dict, key) || length(dict) < FAST_INDEX_MAX + dict = copy(dict) + dict[key] = entry + @atomic FAST_INDEX.dict = dict + end + end + return entry +end + # `entry.fast` is `missing` until first asked function local_fast_of(entry, accel) fast = @atomic entry.fast @@ -78,7 +116,7 @@ function local_fast_candidates(state, task, options, procs, accel)::Union{Nothin exec = options.exec_scope if exec !== nothing # The scope was fixed by the caller (Datadeps): it is used as is - fast = local_fast_of(compat_entry(accel, exec, procs), accel) + fast = local_fast_of(fast_compat_entry(accel, exec, procs), accel) fast === nothing && return nothing return (fast, exec) end @@ -89,7 +127,7 @@ function local_fast_candidates(state, task, options, procs, accel)::Union{Nothin value isa Chunk && !(value.scope isa AnyScope) && return nothing end scope = unscoped_scope() - fast = local_fast_of(compat_entry(accel, scope, procs), accel) + fast = local_fast_of(fast_compat_entry(accel, scope, procs), accel) fast === nothing && return nothing return (fast, scope) end From 0aab580b96229ae75107de319f3b211e561af390 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Mon, 26 Oct 2026 13:37:03 +0100 Subject: [PATCH 09/28] sched: uniform placement reads the compatible set from the lock-free snapshot compatible_processors_ordered went through the frequency cache behind one lock (every placing thread, every task: 12-29 us per task at 64 threads on our cluster, per the fast path's measurements); it now uses the snapshot of the local fast path (same entries, same canonical order, a miss falls through to compat_entry). Laptop, 4 threads, plain @spawn under MPI with one rank: 15.32 -> 14.2 us per task. Local suites: thunk, processors, uniform-placement (5780), two-choices (9506), local-fastpath, options, task-queues; MPI 2 ranks x 2 threads suite. --- src/sch/Sch.jl | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index f44ae4c4d..97ae0b8a9 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -185,7 +185,10 @@ placement sorts a given candidate set once, not once per task. The returned vector is shared: callers must not mutate it. """ function compatible_processors_ordered(accel, scope, procs::Vector{<:Processor}) - entry = compat_entry(accel, scope, procs) + # The lock-free snapshot of the local fast path (see fastpath.jl) instead of the cache behind one lock: + # every placing thread of every task took that lock, 12-29 us per task at 64 threads on our cluster. + # Same entries, same canonical order; a miss falls through to `compat_entry`. + entry = fast_compat_entry(accel, scope, procs) ordered = @atomic :acquire entry.ordered if ordered === nothing # Two threads may both get here and sort the same set; the result is From 3be72dc54805230c7847adced3956d41fef1e564 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 27 Nov 2026 12:22:12 +0100 Subject: [PATCH 10/28] test: local fast path decisions Each decision of the fast path is now asserted directly: which compatible sets qualify (this process's threads only, the distributed acceleration only), that the path places tasks (its counters get built), that a scope restriction on a chunk argument and unscoped tasks with workers are not decided by it, that pick_fast_candidate takes the less loaded of two threads above TWO_CHOICES_MIN and the least loaded at or below it, that estimate_task_costs! switches to two choices only above the limit, and that the lock-free snapshot is bounded and emptied with the compatible-set cache. --- test/local-fastpath.jl | 132 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index f889ddbc9..07537bc7c 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -10,6 +10,8 @@ import Dagger.Sch: COMPAT_PROCS_CACHE (::NoThreadFn)(x) = x Dagger.iscompatible_func(::Dagger.ThreadProc, opts, ::Type{NoThreadFn}) = false FP_TINY(x) = x + 1 + struct NoThreadArg end + Dagger.iscompatible_arg(::Dagger.ThreadProc, opts, ::Type{NoThreadArg}) = false fp_proc() = (sleep(0.002); Dagger.task_processor()) end @@ -86,6 +88,11 @@ end @test reserved_pressure() == 0 end + @testset "a thread that refuses an argument type is respected" begin + t = Dagger.@spawn FP_TINY(NoThreadArg()) + @test_throws Exception fetch(t) + end + @testset "a thread that refuses the function is respected" begin t = Dagger.@spawn NoThreadFn()(1) @test_throws Exception fetch(t) @@ -105,3 +112,128 @@ end end end end + +@everywhere begin + FP_PROCARG(x) = (sleep(0.002); Dagger.task_processor()) +end + +# Pressure counters aligned like `LocalFast.refs` +struct FPOtherAccel <: Dagger.Acceleration end +fp_refs(v) =[Threads.Atomic{UInt64}(UInt64(x)) for x in v] +fast_values() = collect(values(@atomic Dagger.Sch.FAST_INDEX.dict)) + +@testset "Local fast path: decisions" begin + LocalFast = Dagger.Sch.LocalFast + me = myid() + accel = Dagger.DistributedAcceleration() + + @testset "only a compatible set made of this process's threads qualifies" begin + local_set = Processor[ThreadProc(me, 1), ThreadProc(me, 2)] + @test Dagger.Sch.build_local_fast((; compat=local_set), accel) isa LocalFast + @test Dagger.Sch.build_local_fast((; compat=Processor[]), accel) === nothing + # a thread of another worker + @test Dagger.Sch.build_local_fast((; compat=Processor[ThreadProc(me, 1), ThreadProc(me + 1, 1)]), accel) === nothing + # a processor that is not a thread + @test Dagger.Sch.build_local_fast((; compat=Processor[ThreadProc(me, 1), FakeProc()]), accel) === nothing + # only the distributed acceleration is handled + @test Dagger.Sch.build_local_fast((; compat=local_set), FPOtherAccel()) === nothing + end + + @testset "the fast path places tasks" begin + if nprocs() == 1 + Dagger.Sch.invalidate_compat_procs_cache!() + @test !any(e -> e.fast isa LocalFast && (@atomic e.fast.counters) !== nothing, fast_values()) + fetch.([Dagger.@spawn FP_TINY(i) for i in 1:50]) + @test any(e -> e.fast isa LocalFast && (@atomic e.fast.counters) !== nothing, fast_values()) + end + end + + @testset "options the fast path does not model are not decided by it" begin + if nprocs() == 1 + for (name, f) in (("proclist", () -> Dagger.@spawn proclist=[ThreadProc] FP_TINY(1)), + ("single", () -> Dagger.@spawn single=1 FP_TINY(1)), + ("occupancy", () -> Dagger.@spawn occupancy=Dict(ThreadProc=>0.5) FP_TINY(1)), + ("time_util", () -> Dagger.@spawn time_util=Dict(ThreadProc=>1_000_000) FP_TINY(1)), + ("alloc_util", () -> Dagger.@spawn alloc_util=Dict(ThreadProc=>UInt64(1024)) FP_TINY(1))) + Dagger.Sch.invalidate_compat_procs_cache!() + @test fetch(f()) == 2 + @test !any(e -> e.fast isa LocalFast && (@atomic e.fast.counters) !== nothing, fast_values()) + end + end + end + + @testset "a scope restriction on a chunk argument is honoured" begin + nt = Threads.nthreads() + if nt > 1 + tp = ThreadProc(me, nt) + ch = Dagger.tochunk(5, tp, Dagger.ExactScope(tp)) + ps = fetch.([Dagger.@spawn FP_PROCARG(ch) for _ in 1:40]) + @test all(==(tp), ps) + end + end + + @testset "with workers, unscoped tasks also run on other workers" begin + if nprocs() > 1 + owners = Set(p.owner for p in fetch.([Dagger.@spawn fp_proc() for _ in 1:120])) + @test length(owners) > 1 + end + end + + @testset "pick_fast_candidate chooses the less loaded thread" begin + pick = Dagger.Sch.pick_fast_candidate + @test pick(fp_refs([5])) == 1 + # up to TWO_CHOICES_MIN candidates: always the least loaded + refs8 = fp_refs([5, 9, 0, 7, 3, 8, 6, 4]) + @test length(refs8) == Dagger.Sch.TWO_CHOICES_MIN + @test all(_ -> pick(refs8) == 3, 1:300) + # ties are broken at random + @test length(Set(pick(fp_refs(zeros(Int, 8))) for _ in 1:400)) == 8 + # more candidates: two random ones are compared. The most loaded never wins, the least + # loaded wins when it is drawn, and it is not always the one picked + refs9 = fp_refs([5, 9, 0, 7, 3, 8, 6, 4, 2]) + picks = [pick(refs9) for _ in 1:3000] + @test 2 ∉ picks + @test 3 in picks + @test any(!=(3), picks) + end + + @testset "candidate ranking switches to two choices above TWO_CHOICES_MIN" begin + # One heavily loaded thread among n. The full ranking selects the PLACEMENT_SELECT cheapest + # exactly, so the loaded one is never among the first places; two choices compares only two + # random candidates, so the loaded one is the second place whenever it is drawn + busy_early(n) = begin + procs = Processor[ThreadProc(me, t) for t in 1:n] + pressure = Dict{Processor,Threads.Atomic{UInt64}}(p => Threads.Atomic{UInt64}(UInt64(p === procs[1] ? 10^9 : 0)) for p in procs) + state = (; worker_time_pressure=Dagger.LockedObject(Dict{Int,Dict{Processor,Threads.Atomic{UInt64}}}(me => pressure)), + signature_time_cost=Dagger.LockedObject(Dict{Any,Any}()), + worker_transfer_rate=Dagger.LockedObject(Dict{Any,Any}())) + task = (; inputs=Any[], f=identity) + sorted = Vector{Processor}(undef, n) + early = 0 + for _ in 1:300 + Dagger.Sch.estimate_task_costs!(sorted, nothing, state, procs, task; sig=:sig) + early += findfirst(==(procs[1]), sorted) <= Dagger.Sch.PLACEMENT_SELECT + @test sorted[1] !== procs[1] + end + early + end + @test busy_early(Dagger.Sch.TWO_CHOICES_MIN) == 0 + @test busy_early(Dagger.Sch.TWO_CHOICES_MIN + 1) > 0 + end + + @testset "the lock-free snapshot is bounded and follows invalidation" begin + procs = Processor[ThreadProc(me, 1)] + Dagger.Sch.invalidate_compat_procs_cache!() + @test isempty(@atomic Dagger.Sch.FAST_INDEX.dict) + fetch(Dagger.@spawn FP_TINY(1)) + nprocs() == 1 && @test !isempty(@atomic Dagger.Sch.FAST_INDEX.dict) + Dagger.Sch.invalidate_compat_procs_cache!() + @test isempty(@atomic Dagger.Sch.FAST_INDEX.dict) + scopes = [Dagger.ExactScope(ThreadProc(me, t)) for t in 1:(Dagger.Sch.FAST_INDEX_MAX + 50)] + entries = [Dagger.Sch.fast_compat_entry(accel, sc, procs) for sc in scopes] + # beyond the bound an entry is still returned, it is just not kept in the snapshot + @test all(i -> entries[i].scope === scopes[i], eachindex(scopes)) + @test length(@atomic Dagger.Sch.FAST_INDEX.dict) <= Dagger.Sch.FAST_INDEX_MAX + Dagger.Sch.invalidate_compat_procs_cache!() + end +end From 0443836cd140c2033b1586ed98d5ec57158046e4 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:54:52 -0700 Subject: [PATCH 11/28] Use the selected Distributed transport in placement tests Review finding 4 on PR #814 (blocker): New placement tests fail with DistributedNext in CI Requested: Use the test harness's selected Distributed transport in both new placement tests. Import the module already bound by runtests.jl. The original two-choices test reproduced the Distributed binding error locally. With the relative imports and DistributedNext selected, Two-choices Placement passed 9,503 assertions and Local Fast Path passed 729. Written by an AI agent on jpsamaroo's review feedback. --- test/local-fastpath.jl | 3 ++- test/two-choices.jl | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index 07537bc7c..4af4e8703 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -1,4 +1,5 @@ -using Dagger, Test, Distributed, LinearAlgebra, Random +using Dagger, Test, LinearAlgebra, Random +using .Distributed import Dagger: ThreadProc, Processor import Dagger.Sch: COMPAT_PROCS_CACHE diff --git a/test/two-choices.jl b/test/two-choices.jl index 108cbcc1e..299b0bfca 100644 --- a/test/two-choices.jl +++ b/test/two-choices.jl @@ -1,4 +1,5 @@ -using Dagger, Test, Distributed +using Dagger, Test +using .Distributed import Dagger: ThreadProc, Processor, LockedObject @testset "Two-choices placement" begin From 6fb2012e9248e3282680e8cf9eb9a7378e3b70e1 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:56:45 -0700 Subject: [PATCH 12/28] Check the selected thread's compatibility before reserving it Review finding 1 on PR #814 (blocker): The fast path can choose a thread rejected by a compatibility hook Requested: Check compatibility with the chosen processor before reserving it, and use the general scheduler if that candidate is rejected. Check both function and argument compatibility against the actual choice. An incompatible candidate leaves pressure and reservations untouched. The two targeted refusal cases and their accounting assertions pass. Julia 1.12.6 with DistributedNext passes Two-choices Placement 9,503/9,503 and Local Fast Path 733/733 on the combined fixes. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/fastpath.jl | 23 +++++++++++------------ test/local-fastpath.jl | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl index 6c2b7d85c..dcc344df0 100644 --- a/src/sch/fastpath.jl +++ b/src/sch/fastpath.jl @@ -201,26 +201,25 @@ nothing reserved) when a thread would refuse the function or an argument: the ge decides. """ function local_fast_place!(state, task, options, sig, fast::LocalFast, scope) - procs = fast.procs - proc1 = @inbounds procs[1]::Dagger.ThreadProc - # Compatibility depends on the processor's type only, so one thread speaks for all + counters = @atomic fast.counters + if counters === nothing || counters.uid != state.uid + counters = build_fast_counters!(state, fast) + end + refs = counters.refs + idx = pick_fast_candidate(refs) + proc = @inbounds fast.procs[idx]::Dagger.ThreadProc + # Compatibility hooks can inspect the processor instance, including its tid. inputs = task.inputs - Dagger.iscompatible_func(proc1, options, chunktype(task.f)) || return nothing + Dagger.iscompatible_func(proc, options, chunktype(task.f)) || return nothing for idx in 2:length(inputs) value = unwrap_weak_checked(Dagger.value(@inbounds inputs[idx])) value isa Thunk && return nothing - Dagger.iscompatible_arg(proc1, options, chunktype(value)) || return nothing + Dagger.iscompatible_arg(proc, options, chunktype(value)) || return nothing end est_time_util = round(UInt64, locked_get(state.signature_time_cost, sig, UInt64(1000^3)))::UInt64 est_alloc_util = locked_get(state.signature_alloc_cost, sig, UInt64(0))::UInt64 - counters = @atomic fast.counters - if counters === nothing || counters.uid != state.uid - counters = build_fast_counters!(state, fast) - end - refs = counters.refs - idx = pick_fast_candidate(refs) counter_ref = @inbounds refs[idx] Threads.atomic_add!(counter_ref, est_time_util) lock(state.running_pressure_refs) @@ -229,7 +228,7 @@ function local_fast_place!(state, task, options, sig, fast::LocalFast, scope) finally unlock(state.running_pressure_refs) end - loc = ScheduleTaskLocation(fast.gproc, @inbounds(procs[idx])) + loc = ScheduleTaskLocation(fast.gproc, proc) spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, typemax(UInt32)) return (loc, spec) end diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index 4af4e8703..c3a8a3338 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -13,6 +13,11 @@ import Dagger.Sch: COMPAT_PROCS_CACHE FP_TINY(x) = x + 1 struct NoThreadArg end Dagger.iscompatible_arg(::Dagger.ThreadProc, opts, ::Type{NoThreadArg}) = false + struct FirstThreadFn end + (::FirstThreadFn)() = Dagger.task_processor() + Dagger.iscompatible_func(proc::ThreadProc, opts, ::Type{FirstThreadFn}) = proc.tid == 1 + struct FirstThreadArg end + Dagger.iscompatible_arg(proc::ThreadProc, opts, ::Type{FirstThreadArg}) = proc.tid == 1 fp_proc() = (sleep(0.002); Dagger.task_processor()) end @@ -149,6 +154,28 @@ fast_values() = collect(values(@atomic Dagger.Sch.FAST_INDEX.dict)) end end + @testset "compatibility is checked on the selected thread" begin + # Force the chooser to select the second thread, which refuses these + # inputs. The fast path should leave pressure untouched and fall back. + procs = Processor[ThreadProc(me, 1), ThreadProc(me, 2)] + refs = fp_refs([1, 0]) + uid = UInt64(1) + fast = LocalFast(procs, Dagger.OSProc(me), me, Dagger.Sch.FastCounters(uid, refs)) + reservations = Dict{Int,Tuple{Threads.Atomic{UInt64},UInt64}}() + state = (; uid, + signature_time_cost=Dagger.LockedObject(Dict{Any,UInt64}()), + signature_alloc_cost=Dagger.LockedObject(Dict{Any,UInt64}()), + running_pressure_refs=Dagger.LockedObject(reservations)) + opts = Dagger.Options() + scope = Dagger.DefaultScope() + @test Dagger.Sch.local_fast_place!(state, Dagger.Thunk(FirstThreadFn(); options=opts), + opts, :func, fast, scope) === nothing + @test Dagger.Sch.local_fast_place!(state, Dagger.Thunk(FP_PROCARG, nothing => FirstThreadArg(); options=opts), + opts, :arg, fast, scope) === nothing + @test [r[] for r in refs] == [1, 0] + @test isempty(reservations) + end + @testset "options the fast path does not model are not decided by it" begin if nprocs() == 1 for (name, f) in (("proclist", () -> Dagger.@spawn proclist=[ThreadProc] FP_TINY(1)), From 39de00d587387f25d2119f0ecc8c7c80ef6053ac Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:56:45 -0700 Subject: [PATCH 13/28] Use the locked worker snapshot for local placement Review finding 2 on PR #814 (blocker): Local placement can race updates to the worker channel table Requested: Use the initialized-worker processor snapshot from phase 1 in the fast candidate lookup and remove the unlocked worker channel lookup. The general scheduler already consumes the registered worker snapshot created under the state lock. Reuse it for the local candidate cache so phase 2 never reads the mutable worker-channel dictionary. Two-choices Placement passed 9,503/9,503 and Local Fast Path 733/733 with DistributedNext. Minimum among six warm samples for 250 spawns during A/B for the combined fix was 41,343 to 40,202 allocations and 1,323,392 to 1,285,104 bytes on Julia 1.12.6 with two threads. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 2 +- src/sch/fastpath.jl | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 97ae0b8a9..cdcd24576 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1031,7 +1031,7 @@ concurrently across threads. # (fastpath.jl); anything it does not handle takes the general path below. scheduled = false local best_loc, best_spec - fast_cand = local_fast_candidates(state, task, options, procs, accel) + fast_cand = local_fast_candidates(task, options, procs_filt, accel) if fast_cand !== nothing placed = local_fast_place!(state, task, options, sig, fast_cand[1], fast_cand[2]) if placed !== nothing diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl index dcc344df0..3f3bab4e8 100644 --- a/src/sch/fastpath.jl +++ b/src/sch/fastpath.jl @@ -103,16 +103,16 @@ function unscoped_scope() end """ - local_fast_candidates(state, task, options, procs, accel) -> Union{Nothing,Tuple{LocalFast,AbstractScope}} + local_fast_candidates(task, options, procs, accel) -> Union{Nothing,Tuple{LocalFast,AbstractScope}} The fast path's candidate set and the scope the task is scheduled under, or `nothing` when the -task must take the general path (see the file header). Reads only; reserves nothing. +task must take the general path (see the file header). The caller has already filtered `procs` +to workers registered with the scheduler. This function reserves nothing. """ -function local_fast_candidates(state, task, options, procs, accel)::Union{Nothing,Tuple{LocalFast,Dagger.AbstractScope}} +function local_fast_candidates(task, options, procs, accel)::Union{Nothing,Tuple{LocalFast,Dagger.AbstractScope}} (options.proclist === nothing && options.single === nothing && options.time_util === nothing && options.alloc_util === nothing && options.occupancy === nothing) || return nothing accel isa Dagger.DistributedAcceleration || return nothing - haskey(state.worker_chans, myid()) || return nothing exec = options.exec_scope if exec !== nothing # The scope was fixed by the caller (Datadeps): it is used as is From d8fd8dd5f3fef5510c392ca3ca1c75e98263581d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:49:10 -0700 Subject: [PATCH 14/28] 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 1f4cc72e2..bdc55f693 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2199,6 +2199,9 @@ 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) +# 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. @@ -2285,9 +2288,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" @@ -2305,17 +2310,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 @@ -2326,6 +2321,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 @@ -2338,7 +2334,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 24b106df602938211f32977ee9ce2e3647736cd4 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:49:11 -0700 Subject: [PATCH 15/28] 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 69f383cbe..01367badc 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -865,8 +865,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 663ead247b7f90ab8ffa3678bd9696b018ef05d8 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:51:41 -0700 Subject: [PATCH 16/28] Reject compatible-set publications that cross invalidation Review finding F2 (should-fix) on PR #814: The fast index can republish stale processor sets after invalidation. Associate each compatible entry with the processor hierarchy generation. Retry computations invalidated before either cache publication, and check the generation on fast cache hits. Invalidation increments the token while clearing the main cache. Also strengthen the refused-argument regression so the kernel itself would accept the argument and only a scheduling refusal satisfies the assertion. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 62 ++++++++++++++++++++++-------------------- src/sch/fastpath.jl | 29 ++++++++++++-------- test/local-fastpath.jl | 41 +++++++++++++++++++++++++++- 3 files changed, 89 insertions(+), 43 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index bdc55f693..30e065fed 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -103,6 +103,7 @@ completion handler (via `schedule_dependents!`) so there is no central ready que # filled without the cache lock, so it is atomic: the release store publishes the # fully built vector to a thread that reads it with an acquire load. mutable struct CompatEntry + const generation::UInt const scope::Any const procs::Vector{Processor} const compat::Set{Processor} @@ -110,6 +111,7 @@ mutable struct CompatEntry # The local fast path's view of this set (`missing` until first asked; see fastpath.jl) @atomic fast::Any end +const COMPAT_PROCS_GENERATION = Threads.Atomic{UInt}(0) const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},CompatEntry}(256)) # Drop all cached compatible-processor sets. Called whenever the processor # hierarchy changes (add/delete_processor_callback!) — a callback change alters @@ -120,7 +122,10 @@ const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},Co # precompile workload (both cache-key objectids are content-stable across # sessions): `__init__`'s per-thread callback registrations trigger it. function invalidate_compat_procs_cache!() - @safe_lock_spin1 COMPAT_PROCS_CACHE cache empty!(cache) + @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin + Threads.atomic_add!(COMPAT_PROCS_GENERATION, UInt(1)) + empty!(cache) + end invalidate_fast_index!() return end @@ -142,36 +147,33 @@ function scope_key(scope::Dagger.UnionScope) end function compat_entry(accel, scope, procs::Vector{<:Processor}) 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 - cache.freq[key] += 1 - entry - else - nothing - end - end - cached !== nothing && return cached::CompatEntry - compat = Dagger.compatible_processors(accel, scope, procs) - # N.B. `Vector{Processor}`, not `copy(procs)`: the cache's value type is - # `CompatEntry`, whose `procs` field is a `Vector{Processor}`, and `copy` - # preserves the caller's concrete element type (`Vector{OSProc}` from a - # `Context`'s procs, `Vector{MPIProcessor{...}}` under MPI), which fails - # the field conversion. Only on a *miss*, so it stays hidden until some run - # happens not to have this (accel, scope) pair cached already -- see the - # sibling fix in generic `compatible_processors`, which had the same defect - # with `Set(gen)`. - entry = CompatEntry(scope, Vector{Processor}(procs), compat, nothing, missing) - return @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin - # N.B. `get!` would keep a *stale* entry for this key (one whose `procs` no longer - # matches, because the processor list changed without a cache flush) and hand it - # back, so every later call would miss again and recompute the set - if haskey(cache.cache, key) - cache.cache[key] = entry - else - get!(()->entry, cache, key) + while true + generation, cached = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin + generation = COMPAT_PROCS_GENERATION[] + entry = get(cache.cache, key, nothing) + if entry !== nothing && entry.scope === scope && entry.procs == procs + cache.freq[key] += 1 + (generation, entry) + else + (generation, nothing) + end end - end::CompatEntry + cached !== nothing && return cached::CompatEntry + compat = Dagger.compatible_processors(accel, scope, procs) + entry = CompatEntry(generation, scope, Vector{Processor}(procs), compat, nothing, missing) + published = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin + # Invalidation may have run while compatible_processors computed. + # Never put its pre-invalidation answer back into either cache. + if generation != COMPAT_PROCS_GENERATION[] + nothing + elseif haskey(cache.cache, key) + cache.cache[key] = entry + else + get!(()->entry, cache, key) + end + end + published !== nothing && return published::CompatEntry + end end compatible_processors_cached(accel, scope, procs::Vector{<:Processor}) = compat_entry(accel, scope, procs).compat diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl index 3f3bab4e8..fa53c344b 100644 --- a/src/sch/fastpath.jl +++ b/src/sch/fastpath.jl @@ -65,20 +65,25 @@ end function fast_compat_entry(accel, scope, procs::Vector{<:Processor}) key = (objectid(accel), scope_key(scope)) - entry = get(@atomic(FAST_INDEX.dict), key, nothing) - if entry !== nothing && entry.scope === scope && entry.procs == procs - return entry::CompatEntry - end - entry = compat_entry(accel, scope, procs) - lock(FAST_INDEX_LOCK) do - dict = @atomic FAST_INDEX.dict - if haskey(dict, key) || length(dict) < FAST_INDEX_MAX - dict = copy(dict) - dict[key] = entry - @atomic FAST_INDEX.dict = dict + while true + entry = get(@atomic(FAST_INDEX.dict), key, nothing) + if entry !== nothing && entry.generation == COMPAT_PROCS_GENERATION[] && + entry.scope === scope && entry.procs == procs + return entry::CompatEntry + end + entry = compat_entry(accel, scope, procs) + published = lock(FAST_INDEX_LOCK) do + entry.generation == COMPAT_PROCS_GENERATION[] || return false + dict = @atomic FAST_INDEX.dict + if haskey(dict, key) || length(dict) < FAST_INDEX_MAX + dict = copy(dict) + dict[key] = entry + @atomic FAST_INDEX.dict = dict + end + return true end + published && return entry end - return entry end # `entry.fast` is `missing` until first asked diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index c3a8a3338..f8ee235f4 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -12,6 +12,7 @@ import Dagger.Sch: COMPAT_PROCS_CACHE Dagger.iscompatible_func(::Dagger.ThreadProc, opts, ::Type{NoThreadFn}) = false FP_TINY(x) = x + 1 struct NoThreadArg end + FP_TINY(::NoThreadArg) = :kernel_would_accept_this_argument Dagger.iscompatible_arg(::Dagger.ThreadProc, opts, ::Type{NoThreadArg}) = false struct FirstThreadFn end (::FirstThreadFn)() = Dagger.task_processor() @@ -21,6 +22,44 @@ import Dagger.Sch: COMPAT_PROCS_CACHE fp_proc() = (sleep(0.002); Dagger.task_processor()) end +# A compatible-set computation paused across a simulated hierarchy change. +mutable struct PausedCompatScope <: Dagger.AbstractScope + current::Vector{Processor} + entered::Base.Event + release::Base.Event + pause::Bool +end +function Dagger.compatible_processors(::Dagger.DistributedAcceleration, scope::PausedCompatScope, + ::Vector{<:Processor}) + result = Set{Processor}(scope.current) + if scope.pause + scope.pause = false + notify(scope.entered) + wait(scope.release) + end + return result +end + +@testset "In-flight compatible sets cannot survive invalidation" begin + accel = Dagger.DistributedAcceleration() + old_proc = ThreadProc(myid(), 1) + new_proc = ThreadProc(myid(), 2) + scope = PausedCompatScope(Processor[old_proc], Base.Event(), Base.Event(), true) + procs = Processor[Dagger.OSProc(myid())] + Dagger.Sch.invalidate_compat_procs_cache!() + lookup = Threads.@spawn Dagger.Sch.fast_compat_entry(accel, scope, procs) + @test timedwait(() -> scope.entered.set, 30) == :ok + scope.current = Processor[new_proc] + Dagger.Sch.invalidate_compat_procs_cache!() + notify(scope.release) + @test timedwait(() -> istaskdone(lookup), 30) == :ok + if istaskdone(lookup) + @test fetch(lookup).compat == Set{Processor}([new_proc]) + @test Dagger.Sch.fast_compat_entry(accel, scope, procs).compat == Set{Processor}([new_proc]) + end + Dagger.Sch.invalidate_compat_procs_cache!() +end + # The fast path's view of every cached compatible set that qualified fast_entries() = count(e -> e.fast isa Dagger.Sch.LocalFast, values(Dagger.payload(COMPAT_PROCS_CACHE).cache)) @@ -96,7 +135,7 @@ end @testset "a thread that refuses an argument type is respected" begin t = Dagger.@spawn FP_TINY(NoThreadArg()) - @test_throws Exception fetch(t) + @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason="No processors available" fetch(t) end @testset "a thread that refuses the function is respected" begin From 926574f86bfbf7420bb1a563cf2ef5a6028e62b0 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:52:50 -0700 Subject: [PATCH 17/28] Publish fast compatible entries in fixed atomic slots Review finding F3 (should-fix) on PR #814: A cache miss can copy the whole index once per placement. Replace the copy-on-write dictionary with 2048 stable direct-mapped slots. Hits check the full key, scope, processor list and generation; collisions replace one slot. Add a forced scope-collision regression and preserve bounded/invalidation coverage. Store local CPU candidates in a concrete ThreadProc vector while constructing those entries. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/fastpath.jl | 48 ++++++++++++++++++++++-------------------- test/local-fastpath.jl | 16 +++++++++----- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl index fa53c344b..cbb70ae40 100644 --- a/src/sch/fastpath.jl +++ b/src/sch/fastpath.jl @@ -24,7 +24,7 @@ end # The compatible set of one (accel, scope) entry, when it qualifies for the fast path mutable struct LocalFast - const procs::Vector{Processor} # all `ThreadProc`s of this process, in the compatible set's order + const procs::Vector{Dagger.ThreadProc} # all `ThreadProc`s of this process, in the compatible set's order const gproc::OSProc const pid::Int @atomic counters::Union{Nothing,FastCounters} @@ -35,7 +35,7 @@ function build_local_fast(entry, accel) compat = entry.compat isempty(compat) && return nothing me = myid() - procs = Vector{Processor}() + procs = Vector{Dagger.ThreadProc}() for p in compat (p isa Dagger.ThreadProc && p.owner == me) || return nothing push!(procs, p) @@ -43,43 +43,45 @@ function build_local_fast(entry, accel) return LocalFast(procs, OSProc(me), me, nothing) end -# The compatible-set cache (`COMPAT_PROCS_CACHE`) is one frequency-ordered cache behind one lock, and -# a hit updates the frequency under that lock: every placing thread takes it for every task (4 us at -# 16 threads, 12-29 us at 64). The fast path reads its entries from a snapshot instead: an immutable- -# by-convention dictionary that is replaced (copy, then store) when an entry is added, so a lookup -# takes no lock. It holds the same `CompatEntry`s the cache does, so processor-hierarchy changes -# (`invalidate_compat_procs_cache!`) empty it too. Bounded: once full, new keys go through the cache. -mutable struct FastIndex - @atomic dict::Dict{Tuple{UInt,UInt},CompatEntry} +# Stable direct-mapped slots avoid copying the whole cache on each miss. +# Entries are immutable and published atomically; a collision costs a miss. +struct FastIndexEntry + key::Tuple{UInt,UInt} + entry::CompatEntry +end +mutable struct FastIndexSlot + @atomic value::Union{Nothing,FastIndexEntry} end -const FAST_INDEX = FastIndex(Dict{Tuple{UInt,UInt},CompatEntry}()) -const FAST_INDEX_LOCK = ReentrantLock() const FAST_INDEX_MAX = 2048 +const FAST_INDEX = [FastIndexSlot(nothing) for _ in 1:FAST_INDEX_MAX] +const FAST_INDEX_LOCK = ReentrantLock() +fast_index_slot(key::Tuple{UInt,UInt}) = FAST_INDEX[Int(hash(key) & UInt(FAST_INDEX_MAX - 1)) + 1] function invalidate_fast_index!() lock(FAST_INDEX_LOCK) do - @atomic FAST_INDEX.dict = Dict{Tuple{UInt,UInt},CompatEntry}() + for slot in FAST_INDEX + @atomic :release slot.value = nothing + end end return end function fast_compat_entry(accel, scope, procs::Vector{<:Processor}) key = (objectid(accel), scope_key(scope)) + slot = fast_index_slot(key) while true - entry = get(@atomic(FAST_INDEX.dict), key, nothing) - if entry !== nothing && entry.generation == COMPAT_PROCS_GENERATION[] && - entry.scope === scope && entry.procs == procs - return entry::CompatEntry + cached = @atomic :acquire slot.value + if cached !== nothing && cached.key == key + entry = cached.entry + if entry.generation == COMPAT_PROCS_GENERATION[] && + entry.scope === scope && entry.procs == procs + return entry + end end entry = compat_entry(accel, scope, procs) published = lock(FAST_INDEX_LOCK) do entry.generation == COMPAT_PROCS_GENERATION[] || return false - dict = @atomic FAST_INDEX.dict - if haskey(dict, key) || length(dict) < FAST_INDEX_MAX - dict = copy(dict) - dict[key] = entry - @atomic FAST_INDEX.dict = dict - end + @atomic :release slot.value = FastIndexEntry(key, entry) return true end published && return entry diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index f8ee235f4..0f7a64d71 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -291,16 +291,22 @@ fast_values() = collect(values(@atomic Dagger.Sch.FAST_INDEX.dict)) @testset "the lock-free snapshot is bounded and follows invalidation" begin procs = Processor[ThreadProc(me, 1)] Dagger.Sch.invalidate_compat_procs_cache!() - @test isempty(@atomic Dagger.Sch.FAST_INDEX.dict) + @test all(slot -> (@atomic slot.value) === nothing, Dagger.Sch.FAST_INDEX) fetch(Dagger.@spawn FP_TINY(1)) - nprocs() == 1 && @test !isempty(@atomic Dagger.Sch.FAST_INDEX.dict) + nprocs() == 1 && @test !all(slot -> (@atomic slot.value) === nothing, Dagger.Sch.FAST_INDEX) Dagger.Sch.invalidate_compat_procs_cache!() - @test isempty(@atomic Dagger.Sch.FAST_INDEX.dict) + @test all(slot -> (@atomic slot.value) === nothing, Dagger.Sch.FAST_INDEX) scopes = [Dagger.ExactScope(ThreadProc(me, t)) for t in 1:(Dagger.Sch.FAST_INDEX_MAX + 50)] entries = [Dagger.Sch.fast_compat_entry(accel, sc, procs) for sc in scopes] - # beyond the bound an entry is still returned, it is just not kept in the snapshot + # More keys than slots replace collisions but still return exact entries. @test all(i -> entries[i].scope === scopes[i], eachindex(scopes)) - @test length(@atomic Dagger.Sch.FAST_INDEX.dict) <= Dagger.Sch.FAST_INDEX_MAX + @test length(Dagger.Sch.FAST_INDEX) == Dagger.Sch.FAST_INDEX_MAX + # Force a collision with a different scope under the requested key. + scope = first(scopes) + key = (objectid(accel), Dagger.Sch.scope_key(scope)) + slot = Dagger.Sch.fast_index_slot(key) + @atomic :release slot.value = Dagger.Sch.FastIndexEntry(key, last(entries)) + @test Dagger.Sch.fast_compat_entry(accel, scope, procs).scope === scope Dagger.Sch.invalidate_compat_procs_cache!() end end From 54697bcbd41ac74aad451abc4c635408e9458400 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:53:09 -0700 Subject: [PATCH 18/28] 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 01367badc..c85c394c6 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 3c371a94a294a11a0da7deaa784d1a63402638fe Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:58:48 -0700 Subject: [PATCH 19/28] Explain approximate local and partial candidate placement Review finding F14 (should-fix) on PR #814: The scheduler manual omits approximate candidate selection. Document the four-candidate general ranking, local pressure ranking, two-choice sampling and transfer-rate policy difference, with the conditions that select the general path. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/scheduler-internals.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/src/scheduler-internals.md b/docs/src/scheduler-internals.md index 52108a1ff..b7c79a09c 100644 --- a/docs/src/scheduler-internals.md +++ b/docs/src/scheduler-internals.md @@ -81,7 +81,16 @@ 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 + +For eligible tasks whose candidate processors are all CPU threads of this +process, a short placement path compares estimated queued compute pressure. +It checks the selected processor's function and argument compatibility before +reserving pressure. With many candidates it samples two processors rather than +scanning every candidate. This local path approximates the general cost policy: +it does not rank threads by their individual measured transfer rates. Tasks +with explicit resource overrides, restricted input scopes, remote or device +candidates, or uniform execution use the general path. After these operations have been performed for each task, the tasks will be fired off to their appropriate worker for handling. From 7cf1c1a4db047eede1ca5f0bd1a4b38eb5b95edd Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:01:10 -0700 Subject: [PATCH 20/28] Keep device candidates on the general placement cost path Independent review on PR #814: The two-choice shortcut also accepted GPUs or mixed processor types sharing one worker, discarding their distinct transfer and memory-space costs. Require a homogeneous ThreadProc candidate set before compute-pressure-only ranking. Add same-worker virtual device and mixed-candidate eligibility regressions. Update the remaining test snapshot helper to read the new atomic slots. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/util.jl | 7 ++++++- test/local-fastpath.jl | 9 ++++++++- test/two-choices.jl | 11 +++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/sch/util.jl b/src/sch/util.jl index c85c394c6..a745753fe 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -831,6 +831,11 @@ function single_worker_pid(procs, ::Type{P}) where {P} return pid end +# Compute-only ranking is valid for same-worker CPU threads. Other processor +# kinds may have distinct memory spaces and transfer costs even on one worker. +two_choices_pid(procs) = candidate_type(procs) === Dagger.ThreadProc ? + single_worker_pid(procs, Dagger.ThreadProc) : -1 + function place_two_choices!(sorted_procs, state, procs, np::Int, pid::Int) i1 = rand(1:np) i2 = rand(1:np-1) @@ -897,7 +902,7 @@ candidate lookups cost about 130 us for 16 threads and grew with the thread coun end if costs === nothing && np > TWO_CHOICES_MIN - pid = single_worker_pid(procs, candidate_type(procs)) + pid = two_choices_pid(procs) if pid >= 0 place_two_choices!(sorted_procs, state, procs, np, pid) return diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index 0f7a64d71..81240d13d 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -165,7 +165,14 @@ end # Pressure counters aligned like `LocalFast.refs` struct FPOtherAccel <: Dagger.Acceleration end fp_refs(v) =[Threads.Atomic{UInt64}(UInt64(x)) for x in v] -fast_values() = collect(values(@atomic Dagger.Sch.FAST_INDEX.dict)) +function fast_values() + entries = Dagger.Sch.CompatEntry[] + for slot in Dagger.Sch.FAST_INDEX + cached = @atomic slot.value + cached === nothing || push!(entries, cached.entry) + end + return entries +end @testset "Local fast path: decisions" begin LocalFast = Dagger.Sch.LocalFast diff --git a/test/two-choices.jl b/test/two-choices.jl index 299b0bfca..85313fec6 100644 --- a/test/two-choices.jl +++ b/test/two-choices.jl @@ -2,6 +2,12 @@ using Dagger, Test using .Distributed import Dagger: ThreadProc, Processor, LockedObject +struct NonThreadCandidate <: Processor + owner::Int + index::Int +end +Dagger.get_parent(proc::NonThreadCandidate) = Dagger.OSProc(proc.owner) + @testset "Two-choices placement" begin pid = myid() nproc = 16 @@ -36,6 +42,11 @@ import Dagger: ThreadProc, Processor, LockedObject Dagger.Sch.place_two_choices!(sorted, empty_state, procs, nproc, pid) @test Set(sorted) == Set(procs) + @test Dagger.Sch.two_choices_pid(procs) == pid + devices = Processor[NonThreadCandidate(pid, i) for i in 1:16] + @test Dagger.Sch.two_choices_pid(devices) == -1 + @test Dagger.Sch.two_choices_pid(Processor[procs[1:8]..., devices[1:8]...]) == -1 + # candidates of two workers use the full ranking path @test Dagger.Sch.single_worker_pid(procs, Processor) == pid if nprocs() > 1 From c2878dca6a4d59c04df0082f3efff7de97e953b6 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:04:40 -0700 Subject: [PATCH 21/28] Verify stale-generation fast entries are rejected on lookup Independent review of PR #814 requested direct coverage of fast cache generation checks as well as the blocked-computation invalidation regression. Seed an otherwise matching slot with an old generation and verify lookup rejects it. Written by an AI agent on jpsamaroo's review feedback. --- test/local-fastpath.jl | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index 81240d13d..28e8398f0 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -314,6 +314,11 @@ end slot = Dagger.Sch.fast_index_slot(key) @atomic :release slot.value = Dagger.Sch.FastIndexEntry(key, last(entries)) @test Dagger.Sch.fast_compat_entry(accel, scope, procs).scope === scope + current = Dagger.Sch.fast_compat_entry(accel, scope, procs) + stale = Dagger.Sch.CompatEntry(current.generation - UInt(1), current.scope, + current.procs, current.compat, nothing, missing) + @atomic :release slot.value = Dagger.Sch.FastIndexEntry(key, stale) + @test Dagger.Sch.fast_compat_entry(accel, scope, procs) !== stale Dagger.Sch.invalidate_compat_procs_cache!() end end From bcba49d2010abe003ea9eea885ffbdc65c8c240b Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:05:17 -0700 Subject: [PATCH 22/28] 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 30e065fed..d8a7722d4 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2201,9 +2201,9 @@ 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) -# 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. @@ -2319,11 +2319,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 e30e017a00c29249a2ba67d04f9b6436bab78b10 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:09:23 -0700 Subject: [PATCH 23/28] Match scheduling refusal without freezing diagnostic details The strengthened argument-refusal test on PR #814 correctly observed SchedulingException, but compared its full reason against only a prefix. Use the test helper's prefix assertion so task IDs and scope diagnostics remain visible. The failing run otherwise passed725 placement assertions, including the invalidation race and cache collision regressions. Validation: local fast-path suite726 passes; two-choices suite9507 passes. The isolated1024-miss fast-index profile after10warmups and GC, minimum3 runs, falls from11079 allocations /53450128 bytes to4609 allocations /204816 bytes (all samples identical). Written by an AI agent on jpsamaroo's review feedback. --- test/local-fastpath.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/local-fastpath.jl b/test/local-fastpath.jl index 28e8398f0..f577f2d11 100644 --- a/test/local-fastpath.jl +++ b/test/local-fastpath.jl @@ -135,7 +135,7 @@ end @testset "a thread that refuses an argument type is respected" begin t = Dagger.@spawn FP_TINY(NoThreadArg()) - @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason="No processors available" fetch(t) + @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason < "No processors available" fetch(t) end @testset "a thread that refuses the function is respected" begin From f48c01dfcc6e87fe35814af1f4b914f05c0d2bfd Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:14:46 -0700 Subject: [PATCH 24/28] Share task estimates and pressure reservation across placement paths Review finding F11 (should-fix) on PR #814: Fast and general placement duplicate cost and reservation bookkeeping. Use has_capacity with absent resource overrides for the fast path, specializing away the branches it never needs. Both paths now reserve through reserve_pressure!, which captures the exact counter and estimate used by completion. Keep the fast path's cached counter lookup. Existing placement tests verify pressure is fully released on both normal and fallback paths. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 5 +---- src/sch/fastpath.jl | 24 +++++------------------- src/sch/util.jl | 13 +++++++++++++ 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index d8a7722d4..c24062eee 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1170,10 +1170,7 @@ concurrently across threads. Threads.Atomic{UInt64}(UInt64(0)) end end - Threads.atomic_add!(counter_ref, est_time_util) - lock(state.running_pressure_refs) do rpr - rpr[task.id] = (counter_ref, est_time_util) - end + reserve_pressure!(state, task.id, counter_ref, est_time_util) @dagdebug task :schedule "Scheduling to $gproc -> $proc (pressure: $(counter_ref[]))" # Uniform execution overlaps communicating tasks on a processor # (rank-local shares); avoid serializing them into wait cycles. diff --git a/src/sch/fastpath.jl b/src/sch/fastpath.jl index cbb70ae40..8952291a0 100644 --- a/src/sch/fastpath.jl +++ b/src/sch/fastpath.jl @@ -162,15 +162,6 @@ function build_fast_counters!(state, fast::LocalFast) return counters end -@inline function locked_get(lo::LockedObject, key, default) - lock(lo) - try - return get(Dagger.payload(lo), key, default) - finally - unlock(lo) - end -end - # The index of the candidate to run on: what the general path's ranking would put first. The # counters are read without a lock (they are atomics). function pick_fast_candidate(refs::Vector{Threads.Atomic{UInt64}}) @@ -224,18 +215,13 @@ function local_fast_place!(state, task, options, sig, fast::LocalFast, scope) Dagger.iscompatible_arg(proc, options, chunktype(value)) || return nothing end - est_time_util = round(UInt64, locked_get(state.signature_time_cost, sig, UInt64(1000^3)))::UInt64 - est_alloc_util = locked_get(state.signature_alloc_cost, sig, UInt64(0))::UInt64 + has_cap, est_time_util, est_alloc_util, est_occupancy = + has_capacity(state, proc, fast.pid, nothing, nothing, nothing, sig) + has_cap || return nothing counter_ref = @inbounds refs[idx] - Threads.atomic_add!(counter_ref, est_time_util) - lock(state.running_pressure_refs) - try - Dagger.payload(state.running_pressure_refs)[task.id] = (counter_ref, est_time_util) - finally - unlock(state.running_pressure_refs) - end + reserve_pressure!(state, task.id, counter_ref, est_time_util) loc = ScheduleTaskLocation(fast.gproc, proc) - spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, typemax(UInt32)) + spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, est_occupancy) return (loc, spec) end diff --git a/src/sch/util.jl b/src/sch/util.jl index a745753fe..4f74fc486 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -615,6 +615,19 @@ function has_capacity(state, p, gp, time_util, alloc_util, occupancy, sig) return true, est_time_util, est_alloc_util, est_occupancy end +# Both placement paths reserve through this operation so completion always +# releases the exact counter and estimate that placement credited. +function reserve_pressure!(state, task_id::Int, counter_ref::Threads.Atomic{UInt64}, est::UInt64) + Threads.atomic_add!(counter_ref, est) + lock(state.running_pressure_refs) + try + Dagger.payload(state.running_pressure_refs)[task_id] = (counter_ref, est) + finally + unlock(state.running_pressure_refs) + end + return counter_ref +end + "Like `sum`, but replaces `nothing` entries with the average of non-`nothing` entries." function impute_sum(xs) total = 0 From 5c8fb519542259547ef1ee86c86f34d0fda20d89 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:17:17 -0700 Subject: [PATCH 25/28] 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. 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 4de82ffa3318acdcb0e8ce6e80c44cbafa8f2bfe Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:18:31 -0700 Subject: [PATCH 26/28] Record the generation boundary for multi-layer cache invalidation Review finding F2 on PR #814: Clearing both caches does not prevent in-flight computations from republishing old compatible processor sets. Document the generation and deterministic paused-computation test pattern. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index ad8c5740e..2873ce446 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1217,3 +1217,12 @@ this section verbatim). Each entry is one bullet starting with `- `. the protocol alone is not enough for them. Test with a remote reader *and* a remote writer, in both orders: in one process every slot is the argument itself, so none of this is visible. + +110. **Cache invalidation must also reject in-flight publications.** Clearing + compatible-processor caches does not stop a computation that read the old + processor hierarchy from storing its answer afterwards. Carry a hierarchy + generation through computation and check it before publishing into every + cache layer; a second fast cache can otherwise restore what the first + cache correctly invalidated. Check the generation on fast hits too. A + deterministic test pauses the compatible-set computation with Events, + invalidates, then releases it and checks that the computation retries. From 4cfc21b2ee1f0a652f1912299dbe00c9bcafa78c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:19:14 -0700 Subject: [PATCH 27/28] Preserve safe scope diagnostics on the local-placement fallback The full scheduler check exposed a merge-resolution mistake in PR #814: the new fallback rendered the scope directly, bypassing master's safe metadata formatter and allowing a user show method to throw. Use scheduling_scope_name and report the initialized processor count exactly as master does. The existing diagnostic regression checks a large captured function, a throwing callable/scope show method, and short ExactScope metadata. Written by an AI agent on jpsamaroo's review feedback. --- src/sch/Sch.jl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index c24062eee..2195eea48 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1184,7 +1184,8 @@ concurrently across threads. end if !scheduled no_proc_diag = string(" for task ", task.id, " (", scheduling_function_name(task.f), "): ", length(sorted_procs), - " compatible candidate(s), scope=", scope, ", proclist=", options.proclist) + " candidate processor(s) after scope ", scheduling_scope_name(scope), + ", ", length(procs_filt), " processor(s) known to this scheduler") end empty!(sorted_procs) end From 27d7c625c5312e4f655edcb5c41dacd502cda2ab Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:21:58 -0700 Subject: [PATCH 28/28] Describe two-choice ranking on remote CPU workers too Complete the scheduler policy documentation for PR #814: the general path can sample two same-worker CPU threads even when the worker is remote. Explain that cross-worker and device candidates retain the transfer-aware path. Validation: the shared estimates/reservation profile over 10,000 warmed iterations allocates 0 objects / 0 bytes both before and after (10 warmup groups, GC, minimum of three identical runs). The final focused diagnostic and scope-sharing checks pass 9 and 4 assertions respectively. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/scheduler-internals.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/src/scheduler-internals.md b/docs/src/scheduler-internals.md index b7c79a09c..e9adb9ae9 100644 --- a/docs/src/scheduler-internals.md +++ b/docs/src/scheduler-internals.md @@ -92,6 +92,10 @@ it does not rank threads by their individual measured transfer rates. Tasks with explicit resource overrides, restricted input scopes, remote or device candidates, or uniform execution use the general path. +The general path also uses two-choice pressure ranking for a large candidate +set consisting entirely of CPU threads on one worker, including a remote +worker. Cross-worker and non-CPU candidates keep the transfer-aware cost path. + After these operations have been performed for each task, the tasks will be fired off to their appropriate worker for handling.