From a9d3a0ced93e21358d730686d8314bcc4db0b778 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 28 Nov 2026 18:10:59 +0100 Subject: [PATCH 1/3] Datadeps: free copies of identity-less arguments, give each its own slot Since #792, aliased_object! returned early for NoAliasing, so the copy made for another memory space never entered the object cache and region teardown (which frees the cache's non-original entries) no longer freed it. And an identity-less aliasing that is not NoAliasing itself, such as the empty CombinedAliasing of a struct whose fields are all NoAliasing, still shared one cache key, so a distinct argument could get another one's slot. Add aliasing_has_identity (false for NoAliasing, wrappers of it, and empty CombinedAliasing; dispatchable for user aliasing types). Such values bypass the keyed lookup, and a copy made for another space is recorded under a fresh CopyKey, so teardown frees it while originals stay untouched. Fixes #822. --- src/datadeps/aliasing.jl | 71 +++++++++++++++++++++++++++++++++++++--- test/datadeps.jl | 54 ++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 5 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index cfce21de5..85d967e6c 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -495,7 +495,8 @@ function resolve_pending!(cache::AliasedObjectCacheStore) end for (i, value_ainfo) in enumerate(batch_ainfos(cache.accel, values, dep_mods)) key, value = entries[i] - cache.derived[value_ainfo] = key + # Copies under a `CopyKey` are never looked up by aliasing. + key isa CopyKey || (cache.derived[value_ainfo] = key) # Keep `value_ainfo` around: this is the one point where the buffer's own # aliasing is computed on every rank, and the free loop needs it later. ainfos_dict = get!(Dict{AbstractAliasing,AbstractAliasing}, cache.value_ainfos, memory_space(value)) @@ -585,6 +586,42 @@ function set_key_stored!(cache::AliasedObjectCacheStore, space::MemorySpace, ain return end +""" + CopyKey(id) + +Cache key of a copy made for a value whose aliasing has no identity (see +`aliasing_has_identity`). Never looked up by aliasing, only walked by teardown. +""" +struct CopyKey <: AbstractAliasing + id::Int +end +memory_spans(::CopyKey) = MemorySpan{CPURAMMemorySpace}[] + +""" + aliasing_has_identity(ainfo) -> Bool + +Whether `ainfo` distinguishes the object it describes from every other object. +`false` for aliasings that compare equal for all values (`NoAliasing`, an empty +`CombinedAliasing`); the object cache cannot key such values by their aliasing. +""" +aliasing_has_identity(::AbstractAliasing) = true +aliasing_has_identity(::NoAliasing) = false +aliasing_has_identity(ca::CombinedAliasing) = any(aliasing_has_identity, ca.sub_ainfos) +aliasing_has_identity(w::AliasingWrapper) = aliasing_has_identity(w.inner) + +# Records `value` as a Datadeps-allocated copy under a fresh key. It is not an +# original (so it is freed) and not in `derived` (nothing can look it up). +function set_copy_stored!(cache::AliasedObjectCacheStore, space::MemorySpace, value::Chunk) + @check_uniform(value) + key = CopyKey(length(cache.keys) + 1) + push!(cache.keys, key) + push!(get!(Set{AbstractAliasing}, cache.stored, space), key) + values_dict = get!(Dict{AbstractAliasing,Chunk}, cache.values, space) + values_dict[key] = value + push!(cache.pending, key => value) + return +end + struct AliasedObjectCache accel::Acceleration space::MemorySpace @@ -625,6 +662,15 @@ function set_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, return end +function set_copy_stored!(cache::AliasedObjectCache, value::Chunk) + wid = root_worker_id(cache.chunk) + if wid != myid() + return remotecall_fetch(set_copy_stored!, wid, cache, value) + end + set_copy_stored!(unwrap(cache.chunk)::AliasedObjectCacheStore, cache.space, value) + return +end + function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, space::MemorySpace, ainfo::AbstractAliasing, value::Chunk) wid = root_worker_id(cache.chunk) if wid != myid() @@ -635,10 +681,12 @@ function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCac end function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.accel, x, identity)) - # `NoAliasing` has no identity: every such value would share one cache key, - # so the second distinct argument would be handed the first one's slot. - # There is no aliasing to preserve, so each value gets its own copy. - (ainfo isa NoAliasing || (ainfo isa AliasingWrapper && ainfo.inner isa NoAliasing)) && return f(x)::Chunk + # An aliasing without identity (`NoAliasing`, an empty `CombinedAliasing`, + # ...) is equal for every value that has it, so it cannot be the cache key: + # the second distinct argument would be handed the first one's slot. There is + # no aliasing to preserve, so each value gets its own copy, which is recorded + # under a fresh key so that region teardown still frees it. + aliasing_has_identity(ainfo) || return aliased_object_unkeyed!(f, cache, x) x_space = memory_space(x) if !is_key_present(cache, x_space, ainfo) # Preserve the object's memory-space/processor pairing when inserting @@ -662,6 +710,19 @@ function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.a end end +function aliased_object_unkeyed!(f, cache::AliasedObjectCache, x) + x_space = memory_space(x) + y = f(x) + @assert y isa Chunk "Didn't get a Chunk from functor" + # Only a copy made for another space is ours to free. `y === x` is the + # already-in-place case, and anything in `x`'s own space is user data. + if y !== x && x_space != cache.space + @assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)" + set_copy_stored!(cache, y) + end + return y +end + # N.B. Declared `mutable` (despite no field ever being rebound) purely for # identity: an immutable struct this large is re-boxed on every dynamic call # that passes it, and planning threads it through hundreds of such calls per diff --git a/test/datadeps.jl b/test/datadeps.jl index a7d020350..5cd56f076 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1312,3 +1312,57 @@ end end end end + +# Values whose aliasing carries no identity must get a slot of their own per +# value, and the copies made for another worker must be freed at region end. +@everywhere begin +import Dagger +struct IdlessBuf; part::Int; v::Vector{Float64}; end +Dagger.aliasing(::IdlessBuf) = Dagger.NoAliasing() +Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, to::IdlessBuf, from::IdlessBuf) = (copyto!(to.v, from.v); nothing) +struct IdlessOuter; x::IdlessBuf; end +Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, to::IdlessOuter, from::IdlessOuter) = (copyto!(to.x.v, from.x.v); nothing) +idless_check!(out::Vector{Float64}, x::IdlessBuf, expect::Int) = (out[1] = x.part == expect ? 0.0 : 1.0; out[2] = x.part; nothing) +idless_check!(out::Vector{Float64}, x::IdlessOuter, expect::Int) = idless_check!(out, x.x, expect) +end +function count_free_tasks(logs) + n = 0 + for wl in keys(logs) + _logs = logs[wl] + for idx in 1:length(_logs[:core]) + core_log = _logs[:core][idx] + if core_log.category == :add_thunk && core_log.kind == :start && + _logs[:taskfuncnames][idx] == "unsafe_free!" + n += 1 + end + end + end + return n +end +@testset "Identity-less aliasing: own slot per value, copies freed" begin + @test !Dagger.aliasing_has_identity(Dagger.NoAliasing()) + @test !Dagger.aliasing_has_identity(Dagger.AliasingWrapper(Dagger.NoAliasing())) + @test !Dagger.aliasing_has_identity(Dagger.aliasing(IdlessOuter(IdlessBuf(1, zeros(1))))) + @test Dagger.aliasing_has_identity(Dagger.aliasing(zeros(2))) + if nprocs() >= 2 + w = workers()[1] + for mk in (IdlessBuf, p -> IdlessOuter(IdlessBuf(p, fill(Float64(p), 4)))) + mkv = mk === IdlessBuf ? (p -> IdlessBuf(p, fill(Float64(p), 4))) : mk + P = 3 + # Built on the driver so every value has to cross to the worker. + vals = [Dagger.@spawn(scope=Dagger.scope(worker=1), mkv(i)) for i in 1:P] + outs = [zeros(2) for _ in 1:P] + logs = with_logs() do + Dagger.spawn_datadeps() do + for i in 1:P + Dagger.@spawn scope=Dagger.scope(worker=w) idless_check!(Dagger.InOut(outs[i]), vals[i], i) + end + end + end + @test all(o -> o[1] == 0.0, outs) + @test [Int(o[2]) for o in outs] == collect(1:P) + # One free per distinct argument copy, plus one per `outs` copy. + @test count_free_tasks(logs) == 2P + end + end +end From 6e0e28564324722188501762620b54d08d86306f Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 21:13:54 -0700 Subject: [PATCH 2/3] Datadeps: free each identity-less copy only after every task that used its slot Review finding 1 on PR #833 (blocker): Copies of NoAliasing arguments are freed at region end without waiting for the tasks reading them (use-after-free) Requested: Make the region-end free of each CopyKey copy wait for every task that used that slot, by porting PR #834's per-slot user list (UnkeyedSlot / add_unkeyed_user! / free_unkeyed_copies!, branch jps/review/pr792 commit af59cd78) or an equivalent wait attached to the CopyKey free. Keep it rank-uniform under MPI. The region-end free loops take a buffer's syncdeps from dependency tracking, which orders nothing on bare NoAliasing (get_write_deps! returns at once). So the unsafe_free! of a CopyKey copy waited for nothing and ran while the copy's readers were still running. This ports #834's per-slot user list onto this PR's CopyKey design, rather than adding a second free loop: - generate_slot! attributes each CopyKey copy made while building a slot to that slot (a leaf argument's slot, or a wrapper slot's children), by scanning the cache keys appended during the call. - add_reader!, which every task touching a slot passes through (writers and copy tasks included), records the task as a user of such a slot. - Both planners' existing free loops add the slot's users to a CopyKey copy's syncdeps (push_copy_users_syncdeps!). The hierarchical planner's shared-owner syncdep, the free-once check and the sorted order still apply. A CopyKey copy with no recorded slot is an error, not a free with no syncdeps. CopyKey ids, slots and users are all recorded in planning order, which is the same on every rank, so the free syncdeps are rank-uniform. The bookkeeping (UnkeyedSlots) is created lazily, on a region's first CopyKey copy. DataDepsState holds its (always local) cache store directly, so generate_slot! checks it without a MemPool lookup. The common path pays a length read and a short isa scan per slot, and a `nothing` check per reader. One region over plain Vectors (8 InOut and 7 two-In tasks; -t1, 15 warmup regions, minimum of 12, 3 fresh processes, Julia 1.12.6): 4600-4602 allocations / 175,440-175,632 bytes with this commit, 4695-4697 / 178,224-178,416 on the PR head. No increase. Verified: - The next commit's test fails in all 6 slow-read rounds (both planners) without this commit, and passes 12/12 with it. - --test datadeps (1555 pass, 2 broken) and --test allocations (25/25) pass, Julia 1.13.1, 3 workers. - The 2-rank MPI CPU suite (test/mpi/cpu.jl, including test/mpi/noaliasing_args.jl) passes: 1143 and 1146 per rank. - A 2-rank MPI probe with uniformity checks on (a NoAliasing isbits Vector built on rank 0, read by two slow tasks on rank 1, both planners, 3 rounds each) sees every copy allocated throughout its reads and freed after the region. Written by an AI agent on jpsamaroo's review feedback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- src/datadeps/aliasing.jl | 119 ++++++++++++++++++++++++++++++++--- src/datadeps/hierarchical.jl | 3 + src/datadeps/queue.jl | 3 + 3 files changed, 116 insertions(+), 9 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 85d967e6c..37b1ff9ed 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -590,7 +590,8 @@ end CopyKey(id) Cache key of a copy made for a value whose aliasing has no identity (see -`aliasing_has_identity`). Never looked up by aliasing, only walked by teardown. +`aliasing_has_identity`). Never looked up by aliasing, only walked by teardown, +whose free of it waits for every task that used its slot (see `UnkeyedSlots`). """ struct CopyKey <: AbstractAliasing id::Int @@ -723,12 +724,43 @@ function aliased_object_unkeyed!(f, cache::AliasedObjectCache, x) return y end -# N.B. Declared `mutable` (despite no field ever being rebound) purely for -# identity: an immutable struct this large is re-boxed on every dynamic call -# that passes it, and planning threads it through hundreds of such calls per -# task. A mutable struct has a stable heap identity and is passed by pointer -# instead, so those boxes disappear. It is never used as a `Dict` key, so the -# resulting identity-based `hash`/`==` are not observed. +""" + UnkeyedSlots + +The slots holding copies recorded under a `CopyKey` (see +`aliased_object_unkeyed!`), and every task that used each of them. + +The region-end free loop finds the tasks a buffer's free must wait for through +dependency tracking, and dependency tracking orders nothing on an aliasing without +identity (`get_write_deps!` returns at once for `NoAliasing`). On its own, the +free of such a copy would therefore wait for nothing and race the tasks reading +it. But a `CopyKey` copy is private to the slot whose creation made it (the slot +itself for a leaf argument, or one of a wrapper slot's children), so the tasks +that may touch it are exactly the tasks that used that slot. `generate_slot!` +attributes each copy to its slot, `add_reader!` (which every task touching a +slot passes through, writers and copies included) records the slot's users, and +the free loops add those users to the copy's free syncdeps +(`push_copy_users_syncdeps!`). + +Everything here is filled in planning order, which is rank-uniform, so under +uniform (MPI) execution every rank derives the same syncdeps. +""" +struct UnkeyedSlots + # Slot, as stored in `DataDepsState.remote_args` => index into `users` + slot_index::IdDict{Any,Int} + # `CopyKey` id => index into `users` of the slot holding that copy + copy_slot::Dict{Int,Int} + # Per slot, in creation order, the tasks that used it + users::Vector{Vector{DTask}} +end +UnkeyedSlots() = UnkeyedSlots(IdDict{Any,Int}(), Dict{Int,Int}(), Vector{DTask}[]) + +# N.B. Declared `mutable` purely for identity (only `unkeyed_slots` is ever +# rebound, once, lazily): an immutable struct this large is re-boxed on every +# dynamic call that passes it, and planning threads it through hundreds of such +# calls per task. A mutable struct has a stable heap identity and is passed by +# pointer instead, so those boxes disappear. It is never used as a `Dict` key, so +# the resulting identity-based `hash`/`==` are not observed. mutable struct DataDepsState # The mapping of original raw argument to its Chunk # N.B. Values are Chunks, or raw remote handles (e.g. ChunkView under MPI) @@ -788,6 +820,15 @@ mutable struct DataDepsState # The mapping of, for a given memory space, the backing Chunks that an ainfo references # Used by slot generation to replace the backing Chunks during move ainfo_backing_chunk::Chunk{AliasedObjectCacheStore} + # The store `ainfo_backing_chunk` holds. That chunk is created here, by the + # planner, so it is always local; holding the store directly lets slot + # generation check it without a MemPool lookup per slot. + ainfo_backing::AliasedObjectCacheStore + + # Slots holding `CopyKey` copies, and the tasks using them; see + # `UnkeyedSlots`. `nothing` until a region makes such a copy, so that + # regions without any pay nothing for it. + unkeyed_slots::Union{UnkeyedSlots,Nothing} # Cache of argument's supports_inplace_move query result supports_inplace_cache::IdDict{Any,Bool} @@ -831,8 +872,9 @@ mutable struct DataDepsState arg_current = Dict{ArgumentWrapper,Set{MemorySpace}}() arg_overlaps = Dict{ArgumentWrapper,Set{ArgumentWrapper}}() accel = current_acceleration() + ainfo_backing = AliasedObjectCacheStore(accel) ainfo_backing_chunk = _with_default_acceleration() do - tochunk(AliasedObjectCacheStore(accel)) + tochunk(ainfo_backing) end supports_inplace_cache = IdDict{Any,Bool}() @@ -844,7 +886,7 @@ mutable struct DataDepsState ainfos_owner = Dict{AliasingWrapper,Union{Pair{DTask,Int},Pair{CopyBatchOwner,Int},Nothing}}() ainfos_readers = Dict{AliasingWrapper,Vector{Pair{DTask,Int}}}() - return new(arg_to_chunk, sparse_arg_wrap, arg_origin, remote_args, remote_arg_to_original, remote_arg_w, ainfo_arg, arg_history, arg_owner, arg_current, arg_overlaps, ainfo_backing_chunk, + return new(arg_to_chunk, sparse_arg_wrap, arg_origin, remote_args, remote_arg_to_original, remote_arg_w, ainfo_arg, arg_history, arg_owner, arg_current, arg_overlaps, ainfo_backing_chunk, ainfo_backing, nothing, supports_inplace_cache, ainfo_cache, ainfos_lookup, ainfos_overlaps, ainfos_owner, ainfos_readers, TaskArgInfo[], DataDepsTaskDependency[], Any[]) end @@ -1410,6 +1452,57 @@ function add_writer!(state::DataDepsState, arg_w::ArgumentWrapper, dest_space::M end function add_reader!(state::DataDepsState, arg_w::ArgumentWrapper, dest_space::MemorySpace, ainfo::AbstractAliasing, task, write_num) push!(state.ainfos_readers[ainfo], task=>write_num) + # Every task touching a slot comes through here, writers and copies + # included (`add_writer!` records them as readers too). + unkeyed = state.unkeyed_slots + unkeyed === nothing || add_unkeyed_user!(unkeyed, state, arg_w, dest_space, task) + return +end + +# Attribute the `CopyKey` copy `key`, made while generating `slot`, to that slot. +function add_unkeyed_copy!(state::DataDepsState, slot, key::CopyKey) + unkeyed = state.unkeyed_slots + if unkeyed === nothing + unkeyed = state.unkeyed_slots = UnkeyedSlots() + end + idx = get(unkeyed.slot_index, slot, 0) + if idx == 0 + push!(unkeyed.users, DTask[]) + idx = unkeyed.slot_index[slot] = length(unkeyed.users) + end + unkeyed.copy_slot[key.id] = idx + return +end +function add_unkeyed_user!(unkeyed::UnkeyedSlots, state::DataDepsState, arg_w::ArgumentWrapper, space::MemorySpace, task::DTask) + space_args = get(state.remote_args, space, nothing) + space_args === nothing && return + slot = get(space_args, arg_w.arg, nothing) + slot === nothing && return + idx = get(unkeyed.slot_index, slot, 0) + idx == 0 && return + users = unkeyed.users[idx] + # A task reaches here once per dependency on the slot; record it once. + (isempty(users) || last(users) !== task) && push!(users, task) + return +end + +""" + push_copy_users_syncdeps!(state, key::CopyKey, syncdeps) + +Add to `syncdeps` every task that used the slot holding the `CopyKey` copy +`key`, so that the copy's region-end free waits for them (see `UnkeyedSlots`). +""" +function push_copy_users_syncdeps!(state::DataDepsState, key::CopyKey, syncdeps) + unkeyed = state.unkeyed_slots + idx = unkeyed === nothing ? 0 : get(unkeyed.copy_slot, key.id, 0) + # Every `CopyKey` copy is made inside `generate_slot!`, which attributes it + # to its slot. Carrying on without one would free the copy with nothing to + # wait for -- the use-after-free this exists to prevent. + idx == 0 && error("No slot recorded for Datadeps copy $key; cannot determine free syncdeps") + for user in unkeyed.users[idx] + push!(syncdeps, ThunkSyncdep(user)) + end + return end # Make a copy of each piece of data on each worker @@ -1493,6 +1586,8 @@ function generate_slot!(state::DataDepsState, dest_space, data) tid = something(DATADEPS_CURRENT_TASK[], (;uid=0)).uid timing = HIER_TIMING[] t0 = timing ? time_ns() : UInt64(0) + cache_keys = state.ainfo_backing.keys + n_keys = length(cache_keys) data_chunk = if slot_is_already_in_place(data, orig_space, dest_space) # Nothing to move: the slot for data already in `dest_space` is the data # itself. Going through `move_rewrap` here would allocate a second Chunk @@ -1514,6 +1609,12 @@ function generate_slot!(state::DataDepsState, dest_space, data) end timing && hier_log!(LogHierSlot, 0x01, LogHierSlotId(:total), time_ns() - t0) logging && @logfinish ctx LogMove LogMoveId(0, ArgPosition(), to_proc, id) data_chunk + # Any `CopyKey` copies made just now belong to this slot alone (see + # `UnkeyedSlots`). Keys are appended in creation order on every rank. + for i in (n_keys + 1):length(cache_keys) + key = cache_keys[i] + key isa CopyKey && add_unkeyed_copy!(state, data_chunk, key) + end @assert memory_space(data_chunk) == dest_space "space mismatch! $dest_space (dest) != $(memory_space(data_chunk)) (actual) ($(typeof(data)) (data) vs. $(typeof(data_chunk)) (chunk)), spaces ($orig_space -> $dest_space)" dest_space_args[data] = data_chunk state.remote_arg_to_original[data_chunk] = data diff --git a/src/datadeps/hierarchical.jl b/src/datadeps/hierarchical.jl index b195a879e..b54459b83 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -1959,6 +1959,9 @@ function _hierarchical_copy_from_and_free!(partition_states::Vector{DataDepsStat buf_ainfo = stored_value_ainfo(obj_cache, remote_space, ainfo) gather_free_syncdeps!(state, remote_space, buf_ainfo, remote_arg, write_num, chunk_to_ainfos, free_syncdeps) + # Dependency tracking orders nothing on an identity-less copy, + # so wait for every task that used its slot instead. + ainfo isa CopyKey && push_copy_users_syncdeps!(state, ainfo, free_syncdeps) if registry !== nothing orig = get(state.remote_arg_to_original, remote_arg, nothing) if orig !== nothing diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index e22866428..5530540be 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -238,6 +238,9 @@ function distribute_tasks!(queue::DataDepsTaskQueue) free_syncdeps = Set{ThunkSyncdep}() buf_ainfo = stored_value_ainfo(obj_cache, remote_space, ainfo) gather_free_syncdeps!(state, remote_space, buf_ainfo, remote_arg, write_num, chunk_to_ainfos, free_syncdeps) + # Dependency tracking orders nothing on an identity-less copy, so + # wait for every task that used its slot instead. + ainfo isa CopyKey && push_copy_users_syncdeps!(state, ainfo, free_syncdeps) # `tag` keeps the free task rank-uniform under MPI/uniform execution. Dagger.@spawn scope=free_scope syncdeps=free_syncdeps tag=datadeps_task_tag() Dagger.unsafe_free!(remote_arg) end From 0324e6cff93b3a0c5f3aa2d63f47105c5b3bad81 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 21:13:54 -0700 Subject: [PATCH 3/3] test: check that an identity-less copy is not freed under a slow reader Review finding 2 on PR #833 (should-fix): The new free test cannot detect an early free: it counts free tasks for payloads whose free does nothing Requested: As reported: make the free test detect an early free, using a payload whose free is observable (Libc-backed isbits array) read by a deliberately slow task on another worker; it must fail without the F1 fix. The existing free test counts unsafe_free! tasks for plain-struct payloads, whose free is a no-op, and its tasks read without waiting. So it passes while the free runs under the reader. The new testset's payload has an observable free: a Vector of an isbits struct declared NoAliasing. It is built on the driver and read (In) by two tasks on another worker. Each task checks Dagger.is_libc_allocated before and after a 0.5 s sleep. Datadeps' copy on the worker is Libc-backed, so an early unsafe_free! makes is_libc_allocated false. After the region, the test checks that every copy was freed. It runs under both planners, 3 rounds each. Verified (Julia 1.12.6, 3 workers, only this testset): with the previous commit's src changes reverted locally (not committed), the reader assertion fails in all 6 rounds (6 passed, 6 failed). With them, 12/12 pass. It also passes in the full --test datadeps run. Written by an AI agent on jpsamaroo's review feedback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- test/datadeps.jl | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/test/datadeps.jl b/test/datadeps.jl index 5cd56f076..aba557305 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1366,3 +1366,50 @@ end end end end + +# The payloads above have a do-nothing `unsafe_free!`, so counting free tasks +# cannot tell whether a free waited for the tasks reading the copy. An isbits +# `Vector` declared `NoAliasing` gets a Libc-backed copy on another worker, which +# `unsafe_free!` really frees, so a slow reader sees an early free. +@everywhere begin +struct IdlessTile; a::Float64; b::Int; end +Dagger.aliasing(::Vector{IdlessTile}) = Dagger.NoAliasing() +idless_tiles(n::Int) = [IdlessTile(i, i) for i in 1:n] +# Slots the readers were given, to check after the region that they were freed. +const IDLESS_SEEN = Vector{Any}() +const IDLESS_SEEN_LOCK = ReentrantLock() +# Whether the slot was still allocated after a deliberately slow read. +function idless_slow_read(x::Vector{IdlessTile}) + @lock IDLESS_SEEN_LOCK push!(IDLESS_SEEN, x) + Dagger.is_libc_allocated(x) || return false + sleep(0.5) + return Dagger.is_libc_allocated(x) +end +function idless_seen_freed() + @lock IDLESS_SEEN_LOCK begin + freed = !isempty(IDLESS_SEEN) && !any(Dagger.is_libc_allocated, IDLESS_SEEN) + empty!(IDLESS_SEEN) + return freed + end +end +end +@testset "Identity-less copies are freed after their readers, hierarchical=$hierarchical" for hierarchical in (false, true) + if nprocs() >= 2 + w = workers()[1] + dst = Dagger.scope(worker=w) + for rep in 1:3 + # Built on the driver so the value has to cross to the worker. + v = Dagger.@spawn scope=Dagger.scope(worker=1) idless_tiles(8) + readers = Vector{Dagger.DTask}(undef, 2) + Dagger.spawn_datadeps(; hierarchical) do + for i in 1:2 + readers[i] = Dagger.@spawn scope=dst idless_slow_read(Dagger.In(v)) + end + end + # Each reader's copy was still allocated when it finished... + @test all(fetch, readers) + # ...and freed once the region ended. + @test fetch(Dagger.@spawn scope=dst idless_seen_freed()) + end + end +end