From 3a11aec6bc371efc77a04d408e9836cca34f483d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:40:45 -0700 Subject: [PATCH 1/4] datadeps: never record the user's own object as a freeable cached copy Datadeps frees only slots it allocated itself; user data, including an argument serving as its own slot, is never freed by it. The aliased-object cache stored whatever a slot's copy function returned as a Datadeps copy, and the region-end free loop (flat and hierarchical) `unsafe_free!`s every such entry. Two paths hand back the user's own object instead of a copy: - The in-place slot of `generate_slot!` (`Returns(data)`), when another argument with the same aliasing was registered first in another memory space. `transpose(X)` of a device array `X` does exactly that: it has `X`'s aliasing but defaults to the host space. A host task reading `In(transpose(X))` followed by a device task writing `InOut(X)` freed `X` at region end (reproduced with CUDA: "Attempt to use a freed reference"). - A `move` that is the identity between two memory spaces of one process, which is the default `move` for a user-defined processor. `libc_backed` passes an already Libc-backed `Array` through unchanged, so Datadeps `Libc.free`d such an argument. Record a slot whose payload is the argument's own (`slot_holds_value`) as an original, which the free loops already skip. `y === x` is rank-uniform; payloads are compared only when both are local, and never under uniform execution, as in #834's guard for unkeyed copies. The check runs only when a slot is created by `f`; a cross-worker copy returns after comparing the slot's owner with `myid()`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- ext/MPIExt.jl | 4 +-- src/datadeps/aliasing.jl | 67 ++++++++++++++++++++++++++++++++++------ 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 0d2d640ab..8cbb75ca7 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2250,8 +2250,8 @@ end # The aliased-object cache is a per-rank replicated store; every rank updates # its own copy at the same logical point during SPMD planning, so no # cross-rank communication is required here. -function set_stored!(accel::MPIAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing) - set_stored!(unwrap(cache.chunk)::AliasedObjectCacheStore, cache.space, value, ainfo) +function set_stored!(accel::MPIAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing, original::Bool=false) + set_stored!(unwrap(cache.chunk)::AliasedObjectCacheStore, cache.space, value, ainfo, original) return end function set_key_stored!(accel::MPIAcceleration, cache::AliasedObjectCache, space::MemorySpace, ainfo::AbstractAliasing, value::Chunk) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index cfce21de5..d9080d54a 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -434,8 +434,10 @@ struct AliasedObjectCacheStore # The `(space, key)` pairs identifying the user's original data, as opposed # to Datadeps-allocated copies. A `key` ainfo is recorded here at the space # where it is first registered (its source space, see `set_key_stored!`), - # which is exactly where its value is the user's own object. Every *other* - # space holding that key is a copy we allocated and may free. + # which is exactly where its value is the user's own object -- and at any + # other space whose slot turned out to be the user's object as well (see + # `slot_holds_value`). Every other space holding that key is a copy we + # allocated and may free. originals::Set{Tuple{MemorySpace,AbstractAliasing}} # Copies whose own (destination-side) ainfo has not been computed yet, as # `key => copy`. See `resolve_pending!`. @@ -516,8 +518,9 @@ end is_original(cache, space, ainfo) -> Bool Whether `cache.values[space][ainfo]` holds the user's original data (which must -never be freed) rather than a Datadeps-allocated copy. True only at the `key` -ainfo's source space (recorded by `set_key_stored!`). +never be freed) rather than a Datadeps-allocated copy. True at the `key` ainfo's +source space (recorded by `set_key_stored!`), and at any other space whose slot +is the user's own object (recorded by `set_stored!`; see `slot_holds_value`). """ is_original(cache::AliasedObjectCacheStore, space::MemorySpace, ainfo::AbstractAliasing) = (space, ainfo) in cache.originals @@ -538,11 +541,19 @@ function get_stored(cache::AliasedObjectCacheStore, space::MemorySpace, ainfo::A @assert key !== nothing "Cache does not have derived ainfo $ainfo" return cache.values[space][key] end -function set_stored!(cache::AliasedObjectCacheStore, dest_space::MemorySpace, value::Chunk, ainfo::AbstractAliasing) +# `original` marks `value` as the user's own object rather than a copy (see +# `slot_holds_value`): it is then never freed, and needs no destination-side +# ainfo of its own, since its memory is the key's. +function set_stored!(cache::AliasedObjectCacheStore, dest_space::MemorySpace, value::Chunk, ainfo::AbstractAliasing, original::Bool=false) @assert !is_stored(cache, dest_space, ainfo) "Cache already has derived ainfo $ainfo" @check_uniform(value) + @check_uniform(original) key = cache.derived[ainfo] - push!(cache.pending, key => value) + if original + push!(cache.originals, (dest_space, key)) + else + push!(cache.pending, key => value) + end push!(get!(Set{AbstractAliasing}, cache.stored, dest_space), key) values_dict = get!(Dict{AbstractAliasing,Chunk}, cache.values, dest_space) values_dict[key] = value @@ -615,13 +626,13 @@ function get_stored(cache::AliasedObjectCache, ainfo::AbstractAliasing) return get_stored(cache_raw, cache.space, ainfo) end -function set_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing) +function set_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing, original::Bool=false) wid = root_worker_id(cache.chunk) if wid != myid() - return remotecall_fetch(set_stored!, wid, accel, cache, value, ainfo) + return remotecall_fetch(set_stored!, wid, accel, cache, value, ainfo, original) end cache_raw = unwrap(cache.chunk)::AliasedObjectCacheStore - set_stored!(cache_raw, cache.space, value, ainfo) + set_stored!(cache_raw, cache.space, value, ainfo, original) return end @@ -657,11 +668,47 @@ function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.a # the space assertion above already implies it, and asking for `y`'s ainfo # here would cost a collective per slot (see `resolve_pending!`). @assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)" - set_stored!(cache.accel, cache, y, ainfo) + # Usually `y` is a copy, which the region-end free loop releases. But it + # can be the user's own object: `f` may hand back `x` itself (the + # in-place slot of `generate_slot!`, when another argument with the same + # aliasing was registered first in another space), or `move` may be the + # identity between two spaces of one process. Datadeps frees only what + # it allocated, so record such a slot as an original instead. + set_stored!(cache.accel, cache, y, ainfo, slot_holds_value(cache.accel, x, y)) return y end end +""" + slot_holds_value(accel, x, y::Chunk) -> Bool + +Whether the slot `y` made for `x` holds `x`'s own payload rather than a copy of +it. `move` between two memory spaces normally copies, and `libc_backed` copies +any `Array` it did not allocate -- but it returns an already Libc-backed `Array` +unchanged, so a `move` that is the identity between two spaces of one process +(the default `move` for a user-defined processor, say) would hand back the +user's own object. And a slot that is `x` itself (`y === x`) is the user's +object by construction. Datadeps frees only what it allocated, so such a slot +must not be recorded for freeing. + +`y === x` is decided identically on every rank, as both are the same uniform +`Chunk`. Beyond that, only values in one process can be the same object, so this +compares payloads only when both are local. Under uniform (MPI) execution that +comparison is skipped (`false`): whether a slot is freed must agree across ranks, +and no rank holds both payloads; there, two spaces of one process are a host and +a device, between which `move` always copies. +""" +function slot_holds_value(accel, x, y::Chunk) + y === x && return true + uniform_execution(accel) && return false + root_worker_id(y) == myid() || return false + if x isa Chunk + root_worker_id(x) == myid() || return false + return unwrap(y) === unwrap(x) + end + return unwrap(y) === x +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 From 7d63395f99dd9a9b11c84d9eac96741b60ce28fd Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:40:45 -0700 Subject: [PATCH 2/4] test: Datadeps never frees the user's own object Each case makes a slot that is the user's object, in a space other than the one where its aliasing was first registered, and fails on master: - unit: an aliased-object cache whose copy function hands back the argument's payload, and an in-place slot whose key was registered first in another space, must both be recorded as originals; - end to end, CPU: a user-defined processor and memory space relying on the default (identity) `move`, with a Libc-backed argument that Datadeps used to `Libc.free`; - end to end, GPU (every backend in GPU_SCOPES): a host task reading `transpose(X)` and a device task writing `X` in one region used to free `X`. Built-in processors and spaces only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- test/datadeps.jl | 82 ++++++++++++++++++++++++++++++++++++++++++++++++ test/gpu.jl | 18 +++++++++++ 2 files changed, 100 insertions(+) diff --git a/test/datadeps.jl b/test/datadeps.jl index a7d020350..d825c4fa5 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1312,3 +1312,85 @@ end end end end + +# A memory space and processor defined outside Dagger, as the processor docs +# invite. It relies on the default `move`, which is the identity, so a slot made +# in this space for an argument from host memory is the argument itself. +@everywhere begin + struct IdentityMoveSpace <: Dagger.MemorySpace + owner::Int + end + struct IdentityMoveProc <: Dagger.Processor + owner::Int + end + Dagger.get_parent(proc::IdentityMoveProc) = Dagger.OSProc(proc.owner) + Dagger.root_worker_id(space::IdentityMoveSpace) = space.owner + Dagger.memory_spaces(proc::IdentityMoveProc) = Set([IdentityMoveSpace(proc.owner)]) + Dagger.processors(space::IdentityMoveSpace) = Set([IdentityMoveProc(space.owner)]) + Dagger.iscompatible_func(::IdentityMoveProc, opts, f) = true + Dagger.iscompatible_arg(::IdentityMoveProc, opts, x) = true + Dagger.default_enabled(::IdentityMoveProc) = true + Dagger.execute!(::IdentityMoveProc, f, args...) = f(args...) +end + +@testset "Datadeps never frees the user's own object" begin + # Datadeps frees only slots it allocated itself. Each case below makes a + # slot that is the user's object (or holds its payload), in a space other + # than the one its aliasing was first registered in, and checks that the + # cache records it as an original -- which the region-end free loop skips -- + # rather than as a Datadeps-allocated copy. + accel = Dagger.current_acceleration() + here = Dagger.CPURAMMemorySpace(myid()) + there = IdentityMoveSpace(myid()) + proc = IdentityMoveProc(myid()) + new_cache(space) = (backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)); + (Dagger.AliasedObjectCache(accel, space, backing), Dagger.unwrap(backing))) + + @testset "a move that hands back the argument's payload" begin + x = rand(4) + key = Dagger.aliasing(accel, x, identity) + cache, store = new_cache(there) + y = Dagger.aliased_object!(_->Dagger.tochunk(x, proc, there), cache, x) + @test Dagger.unwrap(y) === x + @test Dagger.is_original(store, there, key) + + # A real copy is still Datadeps' to free + cache, store = new_cache(there) + Dagger.aliased_object!(_->Dagger.tochunk(copy(x), proc, there), cache, x) + @test !Dagger.is_original(store, there, key) + end + + @testset "a slot that is the argument itself" begin + # Two arguments with the same aliasing, labelled in different spaces of + # one process (as `transpose(X)`, which defaults to the host space, and + # a device array `X` are). The second one's in-place slot is itself. + x = rand(4) + x_there = Dagger.tochunk(x, proc, there) + x_here = Dagger.tochunk(x) + key = Dagger.aliasing(accel, x_here, identity) + backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)) + store = Dagger.unwrap(backing) + Dagger.aliased_object!(Returns(x_there), Dagger.AliasedObjectCache(accel, there, backing), x_there) + y = Dagger.aliased_object!(Returns(x_here), Dagger.AliasedObjectCache(accel, here, backing), x_here) + @test y === x_here + @test Dagger.is_original(store, here, key) + end + + @testset "end to end, with a user-defined processor" begin + # A Libc-backed array is the one host array `unsafe_free!` releases, and + # `libc_backed` passes it through `move_rewrap` unchanged. + Dagger.add_processor_callback!(()->IdentityMoveProc(myid()), :identity_move_proc) + try + A = Dagger.alloc_libc_array(Float64, 4) + fill!(A, 1.0) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=Dagger.ExactScope(proc) (x->(x[1] = 2.0; nothing))(InOut(A)) + end + @test Dagger.is_libc_allocated(A) + @test A == [2.0, 1.0, 1.0, 1.0] + Dagger.unsafe_free!(A) + finally + Dagger.delete_processor_callback!(:identity_move_proc) + end + end +end diff --git a/test/gpu.jl b/test/gpu.jl index 4f19c1d55..8c691f096 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -91,6 +91,24 @@ end end end +@testset "Datadeps never frees a device argument ($name)" for (name, scope) in GPU_SCOPES + # Datadeps frees only slots it allocated itself. `transpose(X)` has `X`'s + # aliasing but defaults to the host memory space, so a host task reading it + # registers `X`'s memory there first. The device task's slot for `X` is then + # `X` itself, which used to be recorded as a copy, and freed at region end. + proc = only(Dagger.compatible_processors(scope)) + host = Dagger.scope(worker=1, thread=1) + X = Dagger.move(Dagger.ThreadProc(1, 1), proc, ones(Float32, 4, 4)) + Dagger.with_options(; scope=Dagger.UnionScope(host, scope)) do + Dagger.spawn_datadeps() do + Dagger.@spawn scope=host size(In(transpose(X))) + Dagger.@spawn scope=scope addarray!(InOut(X)) + end + end + Dagger.gpu_synchronize(proc) + @test Dagger.with_context(()->Array(X), proc) == fill(2f0, 4, 4) +end + function generate_thunks() as = [Dagger.spawn(x->x+1, 1) for i in 1:10] Dagger.spawn((xs...)->[sum(xs)], as...) From 9fca15bb48e88b0afadefc899579a326f37fb07a Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:41:26 -0700 Subject: [PATCH 3/4] AGENTS.md: a wrapper's space and aliasing can disagree with its parent's Record why the aliased-object cache can meet one memory under one key in two spaces of one process (`transpose(X)` of a device array is a host-space argument with `X`'s aliasing), which is what let Datadeps free a user's device array, and the related slot mix-up it causes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- AGENTS.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 61b1c43b8..0622554b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1023,3 +1023,19 @@ lesson. and MPI paths. When diagnosing MPI uniformity errors, check for an earlier task failure that left ranks on different operations. Compare the actual Julia versions behind rolling CI labels such as `pre`. + +100. **A wrapper lives in the host memory space unless something says + otherwise, and may share its parent's aliasing.** `memory_space` has + methods for device arrays, not for `Transpose`, `Adjoint` or a `SubArray` + of one, so `transpose(X)` of a `CuArray` is a host-space argument whose + `aliasing` is exactly `X`'s. Datadeps' aliased-object cache keys slots by + aliasing and records a key's original in the space where it is *first* + seen, so a region using both `transpose(X)` and `X` registers `X`'s memory + as a host original, and the device slot for `X` -- `X` itself -- was + recorded as a Datadeps copy and freed at region end. The same key sharing + also hands one argument the other's slot, which is still open: a task + asking for `InOut(A)` on another worker, after one reading + `In(transpose(A))`, receives a `Transpose`, and its write lands + transposed in `A`. Never assume one object has one key in one space, and + never assume a slot `f` returns is not the user's own object; check + `slot_holds_value` before recording it for freeing. From c529b3e3373c9fe101188389eebd06286cded72e Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:07:17 -0700 Subject: [PATCH 4/4] datadeps: give the real reason slot_holds_value skips MPI Review finding 1 on PR #839 (should-fix): The new docstring's reason for skipping the payload check under MPI is wrong: GPU moves can return their input, and the owning rank does hold both. Requested: as reported -- say the check is skipped under MPI because only the owning rank could compare the payloads, so ranks would disagree, not because MPI moves always copy or no rank holds both values. The docstring claimed no rank holds both payloads and that host/device moves always copy. Both are false: the owning rank holds both, and the CUDA/ROC moves return a device array already on the target device unchanged (ext/CUDAExt.jl:624-627, ext/ROCExt.jl:699-702). The skip itself is unchanged and still required for rank-uniformity; the text now says it leaves identity moves under MPI undetected rather than impossible. Docstring only. 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 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index d9080d54a..6c36d8c42 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -695,8 +695,10 @@ must not be recorded for freeing. `Chunk`. Beyond that, only values in one process can be the same object, so this compares payloads only when both are local. Under uniform (MPI) execution that comparison is skipped (`false`): whether a slot is freed must agree across ranks, -and no rank holds both payloads; there, two spaces of one process are a host and -a device, between which `move` always copies. +and only the rank that owns both payloads could compare them, so the others would +answer differently. This is a uniformity requirement, not a claim that MPI is +safe: a GPU `move` can return its input (a device array already on the target +device), so an identity move under MPI is not ruled out, only left undetected. """ function slot_holds_value(accel, x, y::Chunk) y === x && return true