From f4e0f29ba877a3684d9cb2b576ab402aaac6e21c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 11:47:24 -0700 Subject: [PATCH 01/27] test: run the NoAliasing slot tests everywhere, including across spaces PR #792 fixed core Datadeps slot logic (`aliased_object!`), which every acceleration shares, but its only test lived in the MPI suite -- whose own header says acceleration-independent Datadeps behavior belongs in test/datadeps.jl. That left the threads and Distributed configurations, which most users run, untested. The test also created every value on the rank of the task that read it, so it only exercised the in-place path, where the slot is the value itself. The path where #792's bypass actually makes a new slot -- a value copied into another memory space -- ran in no test at all. Move the body into test/noaliasing_defs.jl (as stencil_defs.jl and sparse_defs.jl do) and call it from both entry points, with both planners, in place and across memory spaces (several distinct values landing in one destination space). The across-spaces cases fail with #792's guard removed: every task reads the first value. Also replace the MPI test's header, which cited a private reference, with a description of the scenario. Co-Authored-By: Claude Opus 5.5 --- test/datadeps.jl | 28 +++++++++++++++++ test/mpi/noaliasing_args.jl | 41 ++++++++++++------------ test/noaliasing_defs.jl | 62 +++++++++++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 19 deletions(-) create mode 100644 test/noaliasing_defs.jl diff --git a/test/datadeps.jl b/test/datadeps.jl index a7d020350..8d724681e 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1160,6 +1160,34 @@ include(joinpath(@__DIR__, "array", "sparse_defs.jl")) end end +include("noaliasing_defs.jl") + +# The same bodies run under MPI from test/mpi/noaliasing_args.jl. +@testset "NoAliasing Arguments" begin + on(w) = Dagger.scope(worker=w) + @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val,), hierarchical in (false, true) + @testset "in place" begin + test_noaliasing_args(; mk, hierarchical, src_scope=_->on(1), dst_scope=_->on(1)) + end + if nprocs() >= 3 + w1, w2 = workers()[1], workers()[2] + @testset "in place, on a worker" begin + test_noaliasing_args(; mk, hierarchical, src_scope=_->on(w1), dst_scope=_->on(w1)) + end + # Every value lands in the same destination space, each needing a + # slot of its own there. + @testset "across memory spaces" begin + test_noaliasing_args(; mk, hierarchical, src_scope=_->on(w1), dst_scope=_->on(w2)) + end + @testset "across memory spaces, mixed" begin + test_noaliasing_args(; mk, hierarchical, nvals=6, + src_scope=i->on(isodd(i) ? 1 : w1), + dst_scope=i->on(isodd(i) ? w2 : 1)) + end + end + end +end + # Custom scheduler tests struct DummyErrorScheduler <: Dagger.DataDepsScheduler end diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index df7077903..148786ddd 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -1,23 +1,26 @@ -# Datadeps arguments whose aliasing is `NoAliasing` share one aliasing identity; each must still reach its own task -# (app entry 45: with several in flight, writer i received the value of another partition). -struct NoAliasVal; part::Int; v::Vector{Float64}; end -Dagger.aliasing(::NoAliasVal) = Dagger.NoAliasing() -mk_noalias(part::Int) = NoAliasVal(part, fill(Float64(part), 10 + part)) -check_noalias!(buf::Vector{Float64}, x::NoAliasVal, expect::Int) = (buf[1] = x.part == expect ? 0.0 : 1.0; buf[2] = x.part; nothing) +# Datadeps arguments whose aliasing describes no memory must each reach their +# task with their own value, both on the rank that created them and on another +# rank. The bodies are shared with test/datadeps.jl; see test/noaliasing_defs.jl. -@testset "NoAliasing arguments of one Datadeps region keep their own value" begin - nr = MPI.Comm_size(comm) - P = 2 * nr - owner_of(i) = (i - 1) ÷ 2 - procs_by_rank = Dict(r => first(filter(p -> p.rank == r, mpi_procs())) for r in 0:nr-1) - bufs = [Dagger.tochunk(zeros(2), procs_by_rank[owner_of(i)], Dagger.memory_space(procs_by_rank[owner_of(i)])) for i in 1:P] - vals = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=owner_of(i)), mk_noalias(i)) for i in 1:P] - Dagger.spawn_datadeps() do - for i in 1:P - Dagger.@spawn scope=Dagger.scope(mpi_rank=owner_of(i)) check_noalias!(Dagger.InOut(bufs[i]), vals[i], i) +include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) + +@testset "NoAliasing Arguments" begin + # Two values per rank, so that distinct values meet in one memory space. + owner(i) = (i - 1) % nranks + on(r) = Dagger.scope(mpi_rank=r) + nvals = 2 * nranks + @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val,), hierarchical in (false, true) + @testset "in place" begin + test_noaliasing_args(; mk, hierarchical, nvals, + src_scope=i->on(owner(i)), + dst_scope=i->on(owner(i))) + end + if nranks > 1 + @testset "across ranks" begin + test_noaliasing_args(; mk, hierarchical, nvals, + src_scope=i->on(owner(i)), + dst_scope=i->on((owner(i) + 1) % nranks)) + end end end - seen = [fetch(Dagger.@spawn(scope=Dagger.scope(mpi_rank=owner_of(i)), copy(bufs[i]))) for i in 1:P] - @test all(s -> s[1] == 0.0, seen) - @test [Int(s[2]) for s in seen] == collect(1:P) end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl new file mode 100644 index 000000000..301f778d2 --- /dev/null +++ b/test/noaliasing_defs.jl @@ -0,0 +1,62 @@ +# Shared test bodies for Datadeps arguments whose aliasing describes no memory. +# +# Datadeps normally shares one slot per memory space between arguments whose +# aliasing compares equal, which is how overlapping views end up backed by one +# copy. An argument whose aliasing describes no memory has nothing to share, and +# its aliasing carries no identity either: every `NoAliasing()` compares equal, +# as does every empty `CombinedAliasing` (a struct whose fields all report +# `NoAliasing`). Keyed on that, a second distinct argument used in the same +# space was silently handed the first one's value. +# +# The slot logic is core Datadeps code, shared by every acceleration, so these +# bodies run from each entry point: +# +# threads / Distributed -> test/datadeps.jl +# MPI -> test/mpi/noaliasing_args.jl (from test/mpi/cpu.jl) +# +# `src_scope(i)` places the task that creates value `i`, and `dst_scope(i)` the +# task that reads it. Equal scopes exercise the in-place path, where the slot is +# the value itself; different memory spaces exercise the path that copies the +# value into a slot of its own. + +@everywhere begin + # Declared `NoAliasing` although it holds a `Vector`: the user's way of + # saying it shares no memory with anything else. `type_may_alias` still + # answers `true` (it inspects field types), so these values do reach + # Datadeps' slot machinery. + struct NoAliasVal + v::Vector{Float64} + end + Dagger.aliasing(::NoAliasVal) = Dagger.NoAliasing() + + # Aliasing is computed from the fields, which all report `NoAliasing`, so + # the result is an empty `CombinedAliasing`. + struct NoAliasWrap + x::NoAliasVal + end + + # Datadeps fills a cross-space slot with `move!`. + Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, + to::NoAliasVal, from::NoAliasVal) = (copyto!(to.v, from.v); nothing) + Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, + to::NoAliasWrap, from::NoAliasWrap) = + Dagger.move!(dep_mod, to_space, from_space, to.x, from.x) + + # Each value is distinguishable by both content and length. + noalias_val(i::Int) = NoAliasVal(fill(Float64(i), 10 + i)) + noalias_wrap(i::Int) = NoAliasWrap(noalias_val(i)) + noalias_id(x::NoAliasVal) = (Int(x.v[1]), length(x.v)) + noalias_id(x::NoAliasWrap) = noalias_id(x.x) +end + +# Every task of one region must read its own argument's value. +function test_noaliasing_args(; mk, src_scope, dst_scope, nvals::Int=4, hierarchical=nothing) + vals = [Dagger.@spawn scope=src_scope(i) mk(i) for i in 1:nvals] + ids = Vector{Dagger.DTask}(undef, nvals) + Dagger.spawn_datadeps(; hierarchical) do + for i in 1:nvals + ids[i] = Dagger.@spawn scope=dst_scope(i) noalias_id(In(vals[i])) + end + end + @test [fetch(ids[i]) for i in 1:nvals] == [(i, 10 + i) for i in 1:nvals] +end From a0365a5e5318ad4c418a5ef60b57615e7da95fc6 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 11:49:23 -0700 Subject: [PATCH 02/27] datadeps: decide slot sharing with a dispatchable `describes_memory` #792 bypassed the aliased-object cache for bare `NoAliasing` only, by a hard-coded `isa` check. An empty `CombinedAliasing` -- what any struct whose fields all report `NoAliasing` gets, e.g. one wrapping a value declared `NoAliasing` -- has no identity either: every empty one compares equal, so distinct arguments still collided on one cache key and a task silently received another argument's value. The new wrapped-value tests fail this way on master, in place and across spaces, with both planners. Name the property instead: `describes_memory(ainfo)` is `false` for `NoAliasing` and for a `CombinedAliasing` made only of such parts, and the bypass keys on it. Being a generic function, a third-party `AbstractAliasing` that describes no memory can opt in too. `UnknownAliasing` deliberately stays on the cache path. It means "may alias any memory", the opposite of describing none: two arguments with unknown aliasing may be one object reached through different wrappers, and giving each a private copy would split it. Distinct objects with unknown aliasing do still share a key; fixing that needs a real identity (or refusing such arguments), not this bypass. Dagger's own `aliasing` methods throw rather than return it, so only user methods can produce it. The four dependency helpers that skip `NoAliasing` keep testing bare `NoAliasing`: an empty `CombinedAliasing` is tracked today, which keeps successive uses of one such argument ordered, and this change is not meant to alter dependency tracking. Co-Authored-By: Claude Opus 5.5 --- src/datadeps/aliasing.jl | 13 +++++++++---- src/memory-spaces.jl | 29 +++++++++++++++++++++++++++++ test/datadeps.jl | 2 +- test/mpi/noaliasing_args.jl | 2 +- 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index cfce21de5..c55d82c9b 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -635,10 +635,11 @@ 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 + # Aliasing that describes no memory 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. See `describes_memory`. + describes_memory(ainfo)::Bool || return f(x)::Chunk x_space = memory_space(x) if !is_key_present(cache, x_space, ainfo) # Preserve the object's memory-space/processor pairing when inserting @@ -1132,6 +1133,10 @@ function get_read_deps!(state::DataDepsState, dest_space::MemorySpace, ainfo::Ab end function _get_write_deps!(state::DataDepsState, dest_space::MemorySpace, ainfo::AbstractAliasing, write_num, syncdeps) + # N.B. Deliberately bare `NoAliasing`, here and in the helpers below, not + # `!describes_memory`: an empty `CombinedAliasing` (e.g. a struct holding a + # `NoAliasing` value) is still tracked, so successive uses of one such + # argument stay ordered through its own ainfo, as they always have been. ainfo.inner isa NoAliasing && return for other_ainfo in state.ainfos_overlaps[ainfo] other_task_write_num = state.ainfos_owner[other_ainfo] diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bfc5afb8f..4b960c698 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -541,6 +541,35 @@ Base.:(==)(ca1::CombinedAliasing, ca2::CombinedAliasing) = Base.hash(ca1::CombinedAliasing, h::UInt) = hash(ca1.sub_ainfos, hash(CombinedAliasing, h)) +""" + describes_memory(ainfo::AbstractAliasing) -> Bool + +Whether `ainfo` refers to any memory at all. `false` means a value with this +aliasing shares no memory with any other value: `NoAliasing`, and a +`CombinedAliasing` made only of such parts -- including an empty one, which is +what a struct whose fields all report `NoAliasing` gets. + +Datadeps shares one slot per memory space between arguments whose aliasing +compares equal (see `aliased_object!`). Aliasing that describes no memory cannot +be used that way: it carries no identity (every `NoAliasing()` compares equal), +so sharing would hand one argument another argument's value, and there is no +shared memory to preserve. Such arguments get a slot of their own instead. A +custom `AbstractAliasing` that likewise describes no memory should add a method +returning `false`. + +`UnknownAliasing` returns `true`: it means "may alias any memory", not "aliases +none". Two arguments with unknown aliasing may be one object reached through +different wrappers, which separate copies would silently split. (Dagger's own +`aliasing` methods throw rather than return it.) + +This only decides slot sharing. Dependency tracking skips bare `NoAliasing` +alone, and is unaffected. +""" +describes_memory(::AbstractAliasing) = true +describes_memory(::NoAliasing) = false +describes_memory(ca::CombinedAliasing) = any(describes_memory, ca.sub_ainfos) +describes_memory(x::AliasingWrapper) = describes_memory(x.inner) + struct ObjectAliasing{S<:MemorySpace} <: AbstractAliasing ptr::RemotePtr{Cvoid,S} sz::UInt diff --git a/test/datadeps.jl b/test/datadeps.jl index 8d724681e..5bbd50e85 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1165,7 +1165,7 @@ include("noaliasing_defs.jl") # The same bodies run under MPI from test/mpi/noaliasing_args.jl. @testset "NoAliasing Arguments" begin on(w) = Dagger.scope(worker=w) - @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val,), hierarchical in (false, true) + @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val, noalias_wrap), hierarchical in (false, true) @testset "in place" begin test_noaliasing_args(; mk, hierarchical, src_scope=_->on(1), dst_scope=_->on(1)) end diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 148786ddd..852384f29 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -9,7 +9,7 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) owner(i) = (i - 1) % nranks on(r) = Dagger.scope(mpi_rank=r) nvals = 2 * nranks - @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val,), hierarchical in (false, true) + @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val, noalias_wrap), hierarchical in (false, true) @testset "in place" begin test_noaliasing_args(; mk, hierarchical, nvals, src_scope=i->on(owner(i)), From 51ea20528f4c15c84eabdb894a18b75b10aa589d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 11:51:52 -0700 Subject: [PATCH 03/27] datadeps: an unkeyed argument in place is its own slot; check copies' space #792's bypass returned `f(x)` unconditionally. That skipped two things the cached path guarantees: - An object already in the cache's space is its own slot. The cached path registers it as the original and returns it without calling `f`. The bypass called `f` anyway, which inside `move_rewrap` is a same-space transfer -- and for an isbits `Array`, a `libc_backed` copy. A copy in the argument's own space would silently lose writes, since an argument is assumed current where it lives and is never copied back there. The top-level in-place path happens to pass `Returns(data)`, but a wrapper's children reach this point through `move_rewrap` too. - The assertion that a new slot landed in `cache.space`, which catches a backend's move putting a copy in the wrong space. Move the bypass into `unkeyed_object!`, which returns the object itself in its own space and otherwise asserts the copy's space, as the cached path does. The check is a field comparison and allocates nothing. Also correct the comment on `generate_slot!`'s in-place branch, which said the cache always records the object; it no longer does for these arguments. Co-Authored-By: Claude Opus 5.5 --- src/datadeps/aliasing.jl | 37 +++++++++++++++++++++++++++++++------ test/datadeps.jl | 19 +++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index c55d82c9b..2ad9fdd73 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -635,11 +635,7 @@ function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCac end function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.accel, x, identity)) - # Aliasing that describes no memory 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. See `describes_memory`. - describes_memory(ainfo)::Bool || return f(x)::Chunk + describes_memory(ainfo)::Bool || return unkeyed_object!(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 @@ -663,6 +659,33 @@ function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.a end end +""" + unkeyed_object!(f, cache, x) -> Chunk + +The slot in `cache.space` for `x`, an argument whose aliasing describes no +memory (see `describes_memory`), made without consulting the cache. + +Such aliasing has no identity to key the cache on -- every `NoAliasing()` +compares equal -- so a cached slot would be handed to whichever such argument +asked next; and there is no shared memory to preserve. Each argument therefore +gets the slot the cache would give it if its key were unique: + +- In its own space, the slot is `x` itself, the user's original data, which is + never freed. It must not be a copy: an argument is assumed current where it + lives, so writes to a copy there would never be copied back. +- Elsewhere, `f` makes a private copy. +""" +function unkeyed_object!(f, cache::AliasedObjectCache, x) + x_space = memory_space(x) + if x_space == cache.space + return x isa Chunk ? x : tochunk(x, first(processors(x_space))) + end + y = f(x) + @assert y isa Chunk "Didn't get a Chunk from functor" + @assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)" + 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 @@ -1443,7 +1466,9 @@ function generate_slot!(state::DataDepsState, dest_space, data) # (and DRef) over the very same memory, which costs a MemPool round-trip # per argument per region and buys nothing. Still route through # `aliased_object!` so the cache records this object as the (never-freed) - # original for its aliasing key, exactly as the general path does. + # original for its aliasing key, as the general path does -- unless its + # aliasing describes no memory, in which case nothing is recorded and the + # object is simply its own slot (see `unkeyed_object!`). aliased_object!(Returns(data), aliased_object_cache, data)::Chunk else moved = with(DATADEPS_THUNK_ID=>tid) do diff --git a/test/datadeps.jl b/test/datadeps.jl index 5bbd50e85..486ac8aef 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1186,6 +1186,25 @@ include("noaliasing_defs.jl") end end end + + @testset "unkeyed slot construction" begin + accel = Dagger.current_acceleration() + backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)) + x = Dagger.tochunk(noalias_val(1)) + space = Dagger.memory_space(x) + # In its own space the value is its own slot, never a copy: a copy + # there would not be copied back after a write. + cache = Dagger.AliasedObjectCache(accel, space, backing) + @test Dagger.aliased_object!(_->error("copied an in-place value"), cache, x) === x + # Elsewhere, a copy made in the wrong space is caught, as on the + # cached path. + if nprocs() >= 2 + other = Dagger.CPURAMMemorySpace(workers()[1]) + other_cache = Dagger.AliasedObjectCache(accel, other, backing) + @test_throws AssertionError Dagger.aliased_object!( + _->Dagger.tochunk(noalias_val(2)), other_cache, x) + end + end end # Custom scheduler tests From af59cd7808b741d3172a3c13e277da522f866767 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 11:59:18 -0700 Subject: [PATCH 04/27] datadeps: free unkeyed copies at region end, after all their users Since #792, a copy made for an argument whose aliasing describes no memory bypasses the aliased-object cache, and the region-end free loop only walks the cache, so such copies were never `unsafe_free!`d (#822). That only matters where `unsafe_free!` does anything: Libc-backed copies of isbits `Array`s and GPU arrays declared `NoAliasing`, which then waited for finalizers that GC pressure does not account for. Simply putting them back in a free loop would not be enough. Their aliasing describes no memory, so `get_write_deps!` returns no tasks for them: the free would race the very tasks reading the copy. (This is what happened to such copies before #792, when they were cached under the shared `NoAliasing` key.) Datadeps orders nothing on such aliasing, so the free has to wait for every task that used the slot. So: - `unkeyed_object!` records each copy in the cache store (`unkeyed`), in creation order, which is rank-uniform. - `generate_slot!` attributes the copies made while building a slot to that slot (a leaf, or a wrapper's children), only when there are any. - `add_reader!`, which every task touching a slot passes through (writers included), records the task as a user of such a slot. - `free_unkeyed_copies!`, called by both planners after their cache free loop, frees each copy with all of its slot's users as syncdeps (plus, in the hierarchical planner, the same shared-chunk owner syncdep the cached frees get, now factored into `push_shared_owner_syncdep!`). The common path pays one extra empty `Vector` per region (in the cache store), two `length` reads per slot and one `nothing` check per recorded reader. The per-slot bookkeeping is allocated lazily, only in regions that make an unkeyed copy. The new test reads a cross-space `Vector` of an isbits type declared `NoAliasing` from two slow tasks. Without the tracking, the copy is still allocated after the region (fails on master); with the free but without the user syncdeps, the readers see it freed under them. Closes #822. Co-Authored-By: Claude Opus 5.5 --- src/datadeps/aliasing.jl | 129 +++++++++++++++++++++++++++++++++-- src/datadeps/hierarchical.jl | 29 +++++--- src/datadeps/queue.jl | 3 + test/datadeps.jl | 8 +++ test/mpi/noaliasing_args.jl | 5 ++ test/noaliasing_defs.jl | 44 ++++++++++++ 6 files changed, 205 insertions(+), 13 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 2ad9fdd73..3855f1913 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -440,6 +440,11 @@ struct AliasedObjectCacheStore # Copies whose own (destination-side) ainfo has not been computed yet, as # `key => copy`. See `resolve_pending!`. pending::Vector{Pair{AbstractAliasing,Chunk}} + # Private copies made for arguments whose aliasing describes no memory (see + # `unkeyed_object!`). They never enter `values`, so the free loop over it + # cannot see them; `free_unkeyed_copies!` frees them instead. In creation + # order, which is rank-uniform. + unkeyed::Vector{Chunk} end AliasedObjectCacheStore(accel::Acceleration) = AliasedObjectCacheStore(accel, @@ -449,7 +454,8 @@ AliasedObjectCacheStore(accel::Acceleration) = Dict{MemorySpace,Dict{AbstractAliasing,Chunk}}(), Dict{MemorySpace,Dict{AbstractAliasing,AbstractAliasing}}(), Set{Tuple{MemorySpace,AbstractAliasing}}(), - Vector{Pair{AbstractAliasing,Chunk}}()) + Vector{Pair{AbstractAliasing,Chunk}}(), + Vector{Chunk}()) """ resolve_pending!(cache) -> Bool @@ -634,6 +640,17 @@ function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCac set_key_stored!(cache_raw, space, ainfo, value) end +function add_unkeyed_copy!(cache::AliasedObjectCache, value::Chunk) + wid = root_worker_id(cache.chunk) + if wid != myid() + return remotecall_fetch(add_unkeyed_copy!, wid, cache, value) + end + @check_uniform(value) + cache_raw = unwrap(cache.chunk)::AliasedObjectCacheStore + push!(cache_raw.unkeyed, value) + return +end + function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.accel, x, identity)) describes_memory(ainfo)::Bool || return unkeyed_object!(f, cache, x) x_space = memory_space(x) @@ -673,7 +690,10 @@ gets the slot the cache would give it if its key were unique: - In its own space, the slot is `x` itself, the user's original data, which is never freed. It must not be a copy: an argument is assumed current where it lives, so writes to a copy there would never be copied back. -- Elsewhere, `f` makes a private copy. +- Elsewhere, `f` makes a private copy. Nothing else can reach it, but the + cache's region-end free loop cannot see it either, so it is recorded with + `add_unkeyed_copy!` and freed by `free_unkeyed_copies!` once every task that + used its slot is done (see `UnkeyedSlot`). """ function unkeyed_object!(f, cache::AliasedObjectCache, x) x_space = memory_space(x) @@ -683,9 +703,36 @@ function unkeyed_object!(f, cache::AliasedObjectCache, x) y = f(x) @assert y isa Chunk "Didn't get a Chunk from functor" @assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)" + add_unkeyed_copy!(cache, y) return y end +""" + UnkeyedSlot + +A slot whose creation made unkeyed copies (see `unkeyed_object!`): the slot +itself for a leaf argument, or some of a wrapper slot's children. The copies are +private to this slot, so the tasks that may touch them are exactly the tasks that +use the slot -- and all of them, because Datadeps orders nothing on aliasing that +describes no memory. `add_reader!` records each one in `users`, and +`free_unkeyed_copies!` frees the copies after all of them. +""" +struct UnkeyedSlot + # The slot, as stored in `DataDepsState.remote_args` + slot::Any + space::MemorySpace + # Indices into the cache store's `unkeyed` + copies::UnitRange{Int} + users::Vector{DTask} +end +struct UnkeyedSlots + # Slot => index into `slots` + index::IdDict{Any,Int} + # In creation order, which is rank-uniform + slots::Vector{UnkeyedSlot} +end +UnkeyedSlots() = UnkeyedSlots(IdDict{Any,Int}(), UnkeyedSlot[]) + # 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 @@ -751,6 +798,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 unkeyed copies, and the tasks using them; see + # `UnkeyedSlot`. `nothing` until a region makes one, 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} @@ -794,8 +850,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}() @@ -807,7 +864,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 @@ -1377,6 +1434,64 @@ 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 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 + +function add_unkeyed_slot!(state::DataDepsState, space::MemorySpace, slot, copies::UnitRange{Int}) + unkeyed = state.unkeyed_slots + if unkeyed === nothing + unkeyed = state.unkeyed_slots = UnkeyedSlots() + end + push!(unkeyed.slots, UnkeyedSlot(slot, space, copies, DTask[])) + unkeyed.index[slot] = length(unkeyed.slots) + 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.index, slot, 0) + idx == 0 && return + push!(unkeyed.slots[idx].users, task) + return +end + +""" + free_unkeyed_copies!(state[, owner_syncdep!]) + +Launch an `unsafe_free!` for every unkeyed copy in `state` (see +`unkeyed_object!`), once every task that used its slot has finished. + +The object cache's free loop cannot cover these: they are not in the cache, and +even if they were, their aliasing describes no memory, so `get_write_deps!` +would find no tasks to wait for and the free would race the slot's users. +`owner_syncdep!(syncdeps, slot)`, if given, may add further syncdeps (the +hierarchical planner's cross-partition owner). Slots are visited in creation +order, so under uniform (MPI) execution every rank launches the same frees in +the same order. +""" +function free_unkeyed_copies!(state::DataDepsState, owner_syncdep! = nothing) + unkeyed = state.unkeyed_slots + unkeyed === nothing && return + copies = state.ainfo_backing.unkeyed + for entry in unkeyed.slots + free_scope = ExactScope(first(processors(entry.space))) + for i in entry.copies + free_syncdeps = Set{ThunkSyncdep}() + for user in entry.users + push!(free_syncdeps, ThunkSyncdep(user)) + end + owner_syncdep! === nothing || owner_syncdep!(free_syncdeps, entry.slot) + # `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!(copies[i]) + end + end + return end # Make a copy of each piece of data on each worker @@ -1460,6 +1575,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) + unkeyed = state.ainfo_backing.unkeyed + n_unkeyed = length(unkeyed) 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 @@ -1483,6 +1600,10 @@ 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 unkeyed copies made just now belong to this slot alone. + if length(unkeyed) > n_unkeyed + add_unkeyed_slot!(state, dest_space, data_chunk, (n_unkeyed + 1):length(unkeyed)) + 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..50bc54055 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -1959,17 +1959,28 @@ 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) - if registry !== nothing - orig = get(state.remote_arg_to_original, remote_arg, nothing) - if orig !== nothing - entry = get(registry.entries, orig, nothing) - if entry !== nothing && entry.owner_task !== nothing - push!(free_syncdeps, ThunkSyncdep(entry.owner_task)) - end - end - end + registry === nothing || + push_shared_owner_syncdep!(free_syncdeps, registry, state, remote_arg) Dagger.@spawn scope=free_scope syncdeps=free_syncdeps tag=datadeps_task_tag() Dagger.unsafe_free!(remote_arg) end end + # Copies made outside the cache, for arguments whose aliasing describes + # no memory; they need the same final-owner syncdep. + if registry === nothing + free_unkeyed_copies!(state) + else + free_unkeyed_copies!(state, (syncdeps, slot) -> + push_shared_owner_syncdep!(syncdeps, registry, state, slot)) + end + end +end +# For a slot of a shared chunk, sync on the chunk's final global writer (see above). +function push_shared_owner_syncdep!(free_syncdeps, registry, state::DataDepsState, remote_arg) + orig = get(state.remote_arg_to_original, remote_arg, nothing) + orig === nothing && return + entry = get(registry.entries, orig, nothing) + if entry !== nothing && entry.owner_task !== nothing + push!(free_syncdeps, ThunkSyncdep(entry.owner_task)) end + return end diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index e22866428..1328b0e67 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -242,6 +242,9 @@ function distribute_tasks!(queue::DataDepsTaskQueue) Dagger.@spawn scope=free_scope syncdeps=free_syncdeps tag=datadeps_task_tag() Dagger.unsafe_free!(remote_arg) end end + # Copies made outside the cache, for arguments whose aliasing describes no + # memory. + free_unkeyed_copies!(state) end map_or_ntuple(f, xs::Vector) = map(f, 1:length(xs)) # N.B. Accept any `Tuple` (typed specs produce heterogeneous tuples of diff --git a/test/datadeps.jl b/test/datadeps.jl index 486ac8aef..41a24e6f3 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1187,6 +1187,14 @@ include("noaliasing_defs.jl") end end + if nprocs() >= 3 + @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) + w1, w2 = workers()[1], workers()[2] + test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + end + end + @testset "unkeyed slot construction" begin accel = Dagger.current_acceleration() backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)) diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 852384f29..ac3c0abf5 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -23,4 +23,9 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) end end end + if nranks > 1 + @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(0), dst_scope=on(1)) + end + end end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 301f778d2..6aed263f4 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -60,3 +60,47 @@ function test_noaliasing_args(; mk, src_scope, dst_scope, nvals::Int=4, hierarch end @test [fetch(ids[i]) for i in 1:nvals] == [(i, 10 + i) for i in 1:nvals] end + +# An isbits `Array` declared `NoAliasing`. Unlike the values above, Datadeps can +# free its copies eagerly (they are Libc-backed), so this checks that a copy made +# outside the aliased-object cache is still freed at region end -- and not +# before every task reading it has finished. +@everywhere begin + struct NoAliasTile + a::Float64 + b::Int + end + Dagger.aliasing(::Vector{NoAliasTile}) = Dagger.NoAliasing() + noalias_tiles(n::Int) = [NoAliasTile(i, i) for i in 1:n] + + # Readers hold on to the slot they were given, after checking that it was + # not freed while they ran. + const NOALIAS_SEEN = Vector{Any}() + const NOALIAS_SEEN_LOCK = ReentrantLock() + function noalias_keep!(x) + sleep(0.25) + @lock NOALIAS_SEEN_LOCK push!(NOALIAS_SEEN, x) + return Dagger.is_libc_allocated(x) + end + function noalias_seen_freed() + @lock NOALIAS_SEEN_LOCK begin + freed = !isempty(NOALIAS_SEEN) && !any(Dagger.is_libc_allocated, NOALIAS_SEEN) + empty!(NOALIAS_SEEN) + return freed + end + end +end + +function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, hierarchical=nothing) + v = Dagger.@spawn scope=src_scope noalias_tiles(8) + kept = Vector{Dagger.DTask}(undef, nreaders) + Dagger.spawn_datadeps(; hierarchical) do + for i in 1:nreaders + kept[i] = Dagger.@spawn scope=dst_scope noalias_keep!(In(v)) + end + end + # Each reader got a freeable copy, which was still allocated while it ran... + @test all(i->fetch(kept[i]), 1:nreaders) + # ...and freed once the region ended. + @test fetch(Dagger.@spawn scope=dst_scope noalias_seen_freed()) +end From 749afd307e857f32e373ffea2bdce88982edba0d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 12:17:38 -0700 Subject: [PATCH 05/27] AGENTS.md: Datadeps orders nothing on NoAliasing slots Record why `free_unkeyed_copies!` tracks a slot's users itself, and the related, still-open gap it exposed: a consumer of a cross-space `NoAliasing` argument is not ordered after its own copy-to, which only shows up with multithreaded workers. Numbered 100 because lesson 99 (on `type_may_alias`) is pending on another branch. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 61b1c43b8..33f1dbba1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1023,3 +1023,18 @@ 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. **Datadeps orders nothing on `NoAliasing`, not even a slot against its own + copies.** The dependency helpers (`_get_write_deps!` and friends) return + early for a `NoAliasing` ainfo, so `get_write_deps!` yields no tasks for + such a slot. Anything that must wait for a slot's users therefore has to + track them itself: a region-end free keyed on the slot's ainfo races the + tasks still reading it (what happened to cached `NoAliasing` copies before + PR #792), which is why `free_unkeyed_copies!` waits on every task recorded + in `add_reader!`. The same gap means a consumer does not wait for its own + copy-to: an isbits `Vector` declared `NoAliasing`, created on one worker + and summed on another, gave a wrong sum 10 times out of 10 with 4-thread + workers -- and 0 out of 10 with 1-thread workers, where the copy and the + consumer happen to run in submission order. Test such ordering with + multithreaded workers, and test frees with slow readers that check the + buffer is still allocated. From 04abcce1860e83bd4503453c1354dcd514808161 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 13:40:48 -0700 Subject: [PATCH 06/27] datadeps: pass arguments whose aliasing describes no memory by value Such an argument is read-only and passed by value: its slot in another memory space is `move`'s copy of it (or the argument itself, in its own space), and nothing is ever copied into it or back out of it. Datadeps did not hold to that on the cross-space path: - `move_rewrap` let an isbits payload (e.g. a `Vector` of an isbits type declared `NoAliasing`) take the uninitialized-slot path, and `compute_remainder_for_arg!` then scheduled a full copy-to to fill it. The reader is not ordered after that copy -- nothing orders tasks on aliasing that describes no memory -- so it could read the buffer before it was filled. Summing such a `Vector` on another worker gave a wrong sum in 10 of 10 regions with 4-thread workers (0 of 10 now). - Types that do take `move`'s path still got that full copy-to, scheduled into an already-filled slot: a write into data that must not be written. The tests' `NoAliasVal` only worked because they defined a `move!` for it. Now `move_rewrap` (generic and MPI) never gives such an argument an uninitialized slot, and `compute_remainder_for_arg!` never schedules a copy for it in either direction. With no copies there is nothing written to record in `arg_history`/`arg_owner`. The aliasing `move_rewrap` now checks is the query `aliased_object!` was going to make anyway, passed through rather than repeated; `compute_remainder_for_arg!` checks the aliasing it already computes, after its same-space fast path. The tests' `move!` methods for these types now raise, so any copy into one fails the region. A new test sums a cross-space `Vector` of isbits values declared `NoAliasing`. These fail on master and on this PR's previous head: the copy is attempted. Co-Authored-By: Claude Opus 5.5 --- ext/MPIExt.jl | 12 +++++++++--- src/datadeps/aliasing.jl | 13 ++++++++++--- src/datadeps/remainders.jl | 9 ++++++++- test/datadeps.jl | 5 +++++ test/mpi/noaliasing_args.jl | 3 +++ test/noaliasing_defs.jl | 36 ++++++++++++++++++++++++++++-------- 6 files changed, 63 insertions(+), 15 deletions(-) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 0d2d640ab..06400bbb9 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2139,14 +2139,20 @@ function move_rewrap(accel::MPIAcceleration, cache::AliasedObjectCache, from_pro # N.B. The predicate depends only on the two spaces and the destination # type, all rank-uniform, so every rank takes the same branch and the # collectives below stay matched. + # + # An argument whose aliasing describes no memory is passed by value: its + # slot must be the transferred copy, never an uninitialized buffer (see + # the generic `move_rewrap`). The aliasing is the same (collective) query + # `aliased_object!` would make, just made first. + ainfo = aliasing(cache.accel, w, identity) T_dest = move_type(mpi_inner_proc(as_mpi_proc(from_proc, from_space)), mpi_inner_proc(as_mpi_proc(to_proc, to_space)), T) - if Dagger.slot_may_be_uninit(from_space, to_space, T_dest) - return aliased_object!(cache, w) do w + if Dagger.slot_may_be_uninit(from_space, to_space, T_dest) && Dagger.describes_memory(ainfo)::Bool + return aliased_object!(cache, w; ainfo) do w return mpi_endpoint_alloc(accel, to_proc, to_space, T_dest, w) end end - return aliased_object!(cache, w) do w + return aliased_object!(cache, w; ainfo) do w return Dagger.libc_backed(mpi_endpoint_transfer(accel, from_proc, to_proc, from_space, to_space, w)) end end diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 3855f1913..d6b933702 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1725,13 +1725,20 @@ function move_rewrap(accel, cache::AliasedObjectCache, from_proc::Processor, to_ # establishes the contents, and for a wrapper (a view, say) it copies # only the wrapper's own spans rather than the whole backing array. # See `slot_may_be_uninit` for why this is safe. + # + # Not so for an argument whose aliasing describes no memory: it is + # read-only and passed by value, so no copy-to ever fills its slot (see + # `compute_remainder_for_arg!`), and the slot must be `move`'s copy. + # `aliased_object!` needs the aliasing anyway; computing it here costs + # nothing extra. + ainfo = aliasing(cache.accel, data, identity) T_dest = move_type(from_proc, to_proc, typeof(data)) - if slot_may_be_uninit(from_space, to_space, T_dest) - return aliased_object!(cache, data) do data + if slot_may_be_uninit(from_space, to_space, T_dest) && describes_memory(ainfo)::Bool + return aliased_object!(cache, data; ainfo) do data return remotecall_endpoint_alloc(accel, to_proc, to_space, T_dest, alloc_header(data)) end end - return aliased_object!(cache, data) do data + return aliased_object!(cache, data; ainfo) do data return remotecall_endpoint_transfer(accel, from_proc, to_proc, from_space, to_space, data) do accel, from_proc, to_proc, from_space, to_space, data return tochunk(libc_backed(move(from_proc, to_proc, data)), to_proc, to_space) end diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 509da2f8e..7c8c5b23d 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -110,6 +110,13 @@ function compute_remainder_for_arg!(state::DataDepsState, all_local && return NoAliasing(), 0 end + target_ainfo = aliasing!(state, target_space, arg_w) + + # An argument whose aliasing describes no memory is read-only and passed by + # value: its slot in `target_space` is already `move`'s copy of it (see + # `move_rewrap`), so nothing is ever copied into it -- nor back to its origin. + describes_memory(target_ainfo)::Bool || return NoAliasing(), 0 + # Whole-object containers (e.g. `DSparseArray`) reallocate their entire # storage on every write, so they can never be *partially* current in a # memory space -- the whole object is current in exactly one space: the most @@ -128,7 +135,7 @@ function compute_remainder_for_arg!(state::DataDepsState, # of a whole-object container (the same container written through one argument # and read through a different, overlapping one); supporting that would require # sourcing the copy from `history[end].space` instead of `arg_owner`. - if aliases_as_whole(aliasing!(state, target_space, arg_w)) + if aliases_as_whole(target_ainfo) history = state.arg_history[arg_w] @assert isempty(history) || history[end].space == owner_space "whole-object container reached through a different overlapping argument than its owner; cross-argument aliasing of whole-object containers is unsupported" return owner_space == target_space ? (NoAliasing(), 0) : (FullCopy(), 0) diff --git a/test/datadeps.jl b/test/datadeps.jl index 41a24e6f3..8a0ebf3ac 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1188,6 +1188,11 @@ include("noaliasing_defs.jl") end if nprocs() >= 3 + @testset "passed by value across memory spaces, hierarchical=$hierarchical" for hierarchical in (false, true) + w1, w2 = workers()[1], workers()[2] + test_noaliasing_by_value(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) + test_noaliasing_by_value(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + end @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) w1, w2 = workers()[1], workers()[2] test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index ac3c0abf5..9d4ae1b96 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -24,6 +24,9 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) end end if nranks > 1 + @testset "passed by value across ranks, hierarchical=$hierarchical" for hierarchical in (false, true) + test_noaliasing_by_value(; hierarchical, src_scope=on(0), dst_scope=on(1)) + end @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) test_noaliasing_copy_freed(; hierarchical, src_scope=on(0), dst_scope=on(1)) end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 6aed263f4..9a5a1eff1 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -35,12 +35,14 @@ x::NoAliasVal end - # Datadeps fills a cross-space slot with `move!`. + # Such an argument is read-only and passed by value: its slot in another + # space is `move`'s copy, and nothing is ever copied into it afterwards. + # Fail loudly if Datadeps tries. + noalias_no_copy(T) = error("Datadeps copied into a `$T` argument, whose aliasing describes no memory") Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, - to::NoAliasVal, from::NoAliasVal) = (copyto!(to.v, from.v); nothing) + to::NoAliasVal, from::NoAliasVal) = noalias_no_copy(NoAliasVal) Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, - to::NoAliasWrap, from::NoAliasWrap) = - Dagger.move!(dep_mod, to_space, from_space, to.x, from.x) + to::NoAliasWrap, from::NoAliasWrap) = noalias_no_copy(NoAliasWrap) # Each value is distinguishable by both content and length. noalias_val(i::Int) = NoAliasVal(fill(Float64(i), 10 + i)) @@ -61,17 +63,23 @@ function test_noaliasing_args(; mk, src_scope, dst_scope, nvals::Int=4, hierarch @test [fetch(ids[i]) for i in 1:nvals] == [(i, 10 + i) for i in 1:nvals] end -# An isbits `Array` declared `NoAliasing`. Unlike the values above, Datadeps can -# free its copies eagerly (they are Libc-backed), so this checks that a copy made -# outside the aliased-object cache is still freed at region end -- and not -# before every task reading it has finished. +# An isbits `Array` declared `NoAliasing`. Unlike the values above, Datadeps +# could leave such a slot uninitialized, for a later copy task to fill: the +# reader would not wait for that copy, since nothing orders tasks on aliasing +# that describes no memory. And Datadeps can free its copies eagerly (they are +# Libc-backed), so these also check that a copy made outside the aliased-object +# cache is freed at region end -- and not before every task reading it is done. @everywhere begin struct NoAliasTile a::Float64 b::Int end Dagger.aliasing(::Vector{NoAliasTile}) = Dagger.NoAliasing() + Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, + to::Vector{NoAliasTile}, from::Vector{NoAliasTile}) = + noalias_no_copy(Vector{NoAliasTile}) noalias_tiles(n::Int) = [NoAliasTile(i, i) for i in 1:n] + noalias_sum(x::Vector{NoAliasTile}) = sum(t->t.b, x) # Readers hold on to the slot they were given, after checking that it was # not freed while they ran. @@ -104,3 +112,15 @@ function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, hie # ...and freed once the region ended. @test fetch(Dagger.@spawn scope=dst_scope noalias_seen_freed()) end + +# The slot a reader in another space gets is a complete copy from the start. +function test_noaliasing_by_value(; src_scope, dst_scope, n::Int=1_000_000, nregions::Int=3, hierarchical=nothing) + for _ in 1:nregions + v = Dagger.@spawn scope=src_scope noalias_tiles(n) + total = nothing + Dagger.spawn_datadeps(; hierarchical) do + total = Dagger.@spawn scope=dst_scope noalias_sum(In(v)) + end + @test fetch(total) == sum(1:n) + end +end From 96ff204057b337b6f2bd925727e6274c931cf1c5 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 13:51:41 -0700 Subject: [PATCH 07/27] datadeps: never record an argument's own payload as an unkeyed copy Datadeps frees only slots it allocated itself; user data, including an argument serving as its own slot, is never freed by it. `unkeyed_object!` recorded whatever `f` returned for freeing. `move` between two spaces normally copies, and `libc_backed` copies any `Array` it did not allocate, but it returns an already Libc-backed `Array` unchanged: if `move` were ever the identity between two memory spaces of one process, the "copy" would be the user's own object and `free_unkeyed_copies!` would free it. Record the slot only if `slot_holds_value` says its payload is not the argument's own. Only same-process values can be identical, so it compares only when both are local; under uniform (MPI) execution it is always `false`, since the decision must agree across ranks and two spaces of one rank are a host and a device, between which `move` always copies. This runs only when an unkeyed copy is made, never on the common path. Also restate why an argument in its own space is its own slot: it is read-only and passed by value, and the value is already there. The cached path (`aliased_object!` storing `f`'s result in `values`, then the region-end free loop) has the same theoretical hole; it is left for a separate change. Co-Authored-By: Claude Opus 5.5 --- src/datadeps/aliasing.jl | 44 ++++++++++++++++++++++++++++++++-------- test/datadeps.jl | 10 +++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index d6b933702..14b085ef4 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -687,13 +687,15 @@ compares equal -- so a cached slot would be handed to whichever such argument asked next; and there is no shared memory to preserve. Each argument therefore gets the slot the cache would give it if its key were unique: -- In its own space, the slot is `x` itself, the user's original data, which is - never freed. It must not be a copy: an argument is assumed current where it - lives, so writes to a copy there would never be copied back. -- Elsewhere, `f` makes a private copy. Nothing else can reach it, but the - cache's region-end free loop cannot see it either, so it is recorded with - `add_unkeyed_copy!` and freed by `free_unkeyed_copies!` once every task that - used its slot is done (see `UnkeyedSlot`). +- In its own space, the slot is `x` itself. Such an argument is read-only and + passed by value, and here the value is already present, so there is nothing + to copy. Being the user's own data, it is never freed. +- Elsewhere, `f` makes a by-value copy (`move`'s, never an uninitialized buffer; + see `move_rewrap`). Nothing else can reach it, but the cache's region-end free + loop cannot see it either, so it is recorded with `add_unkeyed_copy!` and freed + by `free_unkeyed_copies!` once every task that used its slot is done (see + `UnkeyedSlot`) -- unless `f` handed back `x`'s own payload after all (see + `slot_holds_value`), which Datadeps did not allocate and must never free. """ function unkeyed_object!(f, cache::AliasedObjectCache, x) x_space = memory_space(x) @@ -703,10 +705,36 @@ function unkeyed_object!(f, cache::AliasedObjectCache, x) y = f(x) @assert y isa Chunk "Didn't get a Chunk from functor" @assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)" - add_unkeyed_copy!(cache, y) + slot_holds_value(cache.accel, x, y) || add_unkeyed_copy!(cache, y) return y 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 +would hand back the user's own object. Datadeps frees only what it allocated, so +such a slot must not be recorded for freeing. + +Only values in one process can be the same object, so this compares payloads +only when both are local. Under uniform (MPI) execution it is always `false`: +whether a copy is recorded 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) + 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 + """ UnkeyedSlot diff --git a/test/datadeps.jl b/test/datadeps.jl index 8a0ebf3ac..94bcf3dba 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1216,6 +1216,16 @@ include("noaliasing_defs.jl") other_cache = Dagger.AliasedObjectCache(accel, other, backing) @test_throws AssertionError Dagger.aliased_object!( _->Dagger.tochunk(noalias_val(2)), other_cache, x) + + # A copy is recorded for freeing at region end; the argument's own + # payload, should a move ever hand it back, never is. + store = Dagger.unwrap(backing) + proc = first(Dagger.processors(other)) + y = Dagger.aliased_object!(_->Dagger.tochunk(Dagger.unwrap(x), proc, other), other_cache, x) + @test Dagger.unwrap(y) === Dagger.unwrap(x) + @test isempty(store.unkeyed) + y = Dagger.aliased_object!(_->Dagger.tochunk(noalias_val(1), proc, other), other_cache, x) + @test store.unkeyed == [y] end end end From f47ab013b446fa15f2554cd8d7543d8e69085fb1 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 13:51:54 -0700 Subject: [PATCH 08/27] AGENTS.md: NoAliasing arguments are passed by value Lesson 100 described the copy-to race as an open gap; it is fixed now. Restate it around the rule the fix follows (the slot is complete when it is created, and nothing is copied into or out of it), and record why write access to such arguments is not rejected: aliasing is per dependency, and `Deps(X, InOut(:field))` on an isbits field is a documented usage whose aliasing is `NoAliasing`. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 33f1dbba1..e8121ff04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1024,17 +1024,24 @@ lesson. task failure that left ranks on different operations. Compare the actual Julia versions behind rolling CI labels such as `pre`. -100. **Datadeps orders nothing on `NoAliasing`, not even a slot against its own - copies.** The dependency helpers (`_get_write_deps!` and friends) return - early for a `NoAliasing` ainfo, so `get_write_deps!` yields no tasks for - such a slot. Anything that must wait for a slot's users therefore has to - track them itself: a region-end free keyed on the slot's ainfo races the - tasks still reading it (what happened to cached `NoAliasing` copies before - PR #792), which is why `free_unkeyed_copies!` waits on every task recorded - in `add_reader!`. The same gap means a consumer does not wait for its own - copy-to: an isbits `Vector` declared `NoAliasing`, created on one worker - and summed on another, gave a wrong sum 10 times out of 10 with 4-thread - workers -- and 0 out of 10 with 1-thread workers, where the copy and the - consumer happen to run in submission order. Test such ordering with - multithreaded workers, and test frees with slow readers that check the - buffer is still allocated. +100. **Datadeps orders nothing on `NoAliasing`, so such arguments must be + passed by value.** The dependency helpers (`_get_write_deps!` and friends) + return early for a `NoAliasing` ainfo, so no task ever waits on such a slot + through dependency tracking. Two consequences. First, the slot must be + complete when it is created: `move_rewrap` gives it `move`'s copy (never + the uninitialized-slot path), and `compute_remainder_for_arg!` schedules no + copy into or out of it. Otherwise the reader is not ordered after the copy + that fills its slot: an isbits `Vector` declared `NoAliasing`, created on + one worker and summed on another, gave a wrong sum 10 times out of 10 with + 4-thread workers -- and 0 out of 10 with 1-thread workers, where the copy + and the reader happen to run in submission order. Second, anything that + must wait for a slot's users has to track them itself: a region-end free + keyed on the slot's ainfo races the tasks still reading it (what happened + to cached `NoAliasing` copies before PR #792), which is why + `free_unkeyed_copies!` waits on every task recorded in `add_reader!`. Test + ordering with multithreaded workers, frees with slow readers that check the + buffer is still allocated, and "nothing is copied in" with a `move!` that + raises. Beware that aliasing is per *dependency*: `Deps(X, InOut(:field))` + on an isbits field of a mutable `X` has `NoAliasing` aliasing, so rejecting + writes to `NoAliasing` would break that documented usage (which works only + within one memory space; a remote write to the field is already lost). From 629a36f8296330814f575e2b825f22884021c278 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 14:26:35 -0700 Subject: [PATCH 09/27] test: MPI's by-value NoAliasing copies are not Libc-backed Since NoAliasing arguments are passed by value, an isbits `Vector` declared `NoAliasing` no longer gets an uninitialized (Libc-allocated) slot under MPI either, but `move`'s transferred copy. MPI's slot transfer returns a `Chunk`, which `libc_backed` passes through unchanged, so that copy is an ordinary GC-managed array with nothing to free eagerly, and the free test's "freeable while read" precondition does not hold there. Check only that nothing is left allocated under MPI. Co-Authored-By: Claude Opus 5.5 --- test/mpi/noaliasing_args.jl | 4 +++- test/noaliasing_defs.jl | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 9d4ae1b96..68fd4d0b3 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -28,7 +28,9 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) test_noaliasing_by_value(; hierarchical, src_scope=on(0), dst_scope=on(1)) end @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) - test_noaliasing_copy_freed(; hierarchical, src_scope=on(0), dst_scope=on(1)) + # MPI's slot transfer returns a `Chunk`, which `libc_backed` leaves + # as it is, so its copies are not Libc-backed. + test_noaliasing_copy_freed(; hierarchical, freeable=false, src_scope=on(0), dst_scope=on(1)) end end end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 9a5a1eff1..59a16e41e 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -99,7 +99,11 @@ end end end -function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, hierarchical=nothing) +# +# `freeable=false` is for transports whose copies are ordinary GC-managed +# arrays, which there is nothing to free eagerly; it then only checks that +# nothing is left allocated. +function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, freeable::Bool=true, hierarchical=nothing) v = Dagger.@spawn scope=src_scope noalias_tiles(8) kept = Vector{Dagger.DTask}(undef, nreaders) Dagger.spawn_datadeps(; hierarchical) do @@ -108,7 +112,7 @@ function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, hie end end # Each reader got a freeable copy, which was still allocated while it ran... - @test all(i->fetch(kept[i]), 1:nreaders) + freeable && @test all(i->fetch(kept[i]), 1:nreaders) # ...and freed once the region ended. @test fetch(Dagger.@spawn scope=dst_scope noalias_seen_freed()) end From 3825255c3626e9af867a86f476380cb3b84d4bb9 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:21:07 -0700 Subject: [PATCH 10/27] datadeps: an isbits field dependency aliases the field's own memory `Deps(X, InOut(:value))` on an isbits field of a mutable `X` is a documented usage, but its aliasing was that of the isbits *value*: `NoAliasing`. So nothing ordered it against other uses of the field, and a write from another memory space was never copied back -- `X.value` stayed 0 on master (for a plain struct the copy-to even threw, for want of a `move!`). The field is memory inside `X`, and its dependency now says so. - `field_aliasing`: for an isbits field of a mutable struct (stored inline), an `ObjectAliasing` of `sizeof` the field at its `fieldoffset`. It overlaps `X` as a whole, and is a whole-object unit, so a cross-space use takes a full copy of just that field, and the write comes back the same way. Any other field keeps aliasing what it refers to: writes into that object are tracked, rebinding the field is not. An isbits field of an immutable struct stays `NoAliasing`; it cannot be written. - `move_field!`: copies one field, for every struct, from the generic `move!` fallback (a `dep_mod::Symbol` method would be ambiguous with every `move!` that specializes the values, `Chunk`s included). The existing `RefValue` method now forwards to it. - MPI copies a non-identity `dep_mod` as packed memory spans; the generic `read_remainder!`/`write_remainder!` now copy a span lying inside a mutable object's own storage directly, instead of failing to find "the object holding" it (`find_object_holding_ptr` has no method for an arbitrary struct). The new shared test (test/field_deps_defs.jl) writes two fields of one struct and a `Ref{Int}` in place, from another worker/rank, and with the reader elsewhere. Every cross-space case errors on master; the MPI case also errors without the span change. docs/src/datadeps.md now says what a field dependency covers. Co-Authored-By: Claude Opus 5.5 --- docs/src/datadeps.md | 12 +++++++++ src/datadeps/remainders.jl | 15 +++++++++++ src/memory-spaces.jl | 53 +++++++++++++++++++++++++++++++++----- test/datadeps.jl | 15 +++++++++++ test/field_deps_defs.jl | 42 ++++++++++++++++++++++++++++++ test/mpi/cpu.jl | 9 +++++++ 6 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 test/field_deps_defs.jl diff --git a/docs/src/datadeps.md b/docs/src/datadeps.md index 2d9e27c4f..788b67a94 100644 --- a/docs/src/datadeps.md +++ b/docs/src/datadeps.md @@ -201,6 +201,18 @@ for writing memory-efficient, generic algorithms in Julia). - `Diagonal`/`Bidiagonal`/`Tridiagonal`/`SymTridiagonal` (via `Deps`, e.g. to read from the diagonal of `X`: `Dagger.@spawn sum(Deps(X, In(Diagonal)))`) - `Symbol` for field access (via `Deps`, e.g. to write to `X.value`: `Dagger.@spawn setindex!(Deps(X, InOut(:value)), :value, 42)` +A field dependency covers different memory depending on the field: + +- An isbits field of a mutable struct (an `Int`, a `Float64`, an isbits struct, + ...) is stored inside the struct, so the dependency covers exactly that field. + It may be written from any memory space: Datadeps copies just that field to + where the task runs, and back afterwards. +- Any other field refers to another object (an array, say), and the dependency + covers that object. Writing *into* it (e.g. `X.v .= 0`) is tracked; replacing + the field with a different object is not. +- A field of an immutable struct cannot be written. An isbits one describes no + memory, so it may only be read (`In`). + ## In-place data movement rules Datadeps uses a specialized 5-argument function, `Dagger.move!(dep_mod, from_space::Dagger.MemorySpace, to_space::Dagger.MemorySpace, from, to)`, for managing in-place data movement. This function is an in-place variant of the more general `move` function (see [Data movement rules](@ref)) and is exclusively used within the Datadeps system. The `dep_mod` argument is usually just `identity`, but it can also be an access modifier function like `UpperTriangular`, which limits what portion of the data should be read from and written to. diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 7c8c5b23d..ed92a49c8 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -652,7 +652,18 @@ function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from::Den copies_typed = unsafe_wrap(Vector{eltype(from)}, Ptr{eltype(from)}(pointer(copies, copies_offset)), n) copyto!(copies_typed, 1, from_vec, Int(from_offset_n), Int(n)) end +# Whether `[ptr, ptr+n)` lies in the inline storage of the mutable object `x`, +# as an isbits field of it does (see `field_aliasing`). +function span_is_inline(x, ptr::UInt64, n::UInt64) + ismutable(x) || return false + base = UInt64(pointer_from_objref(x)) + return base <= ptr && ptr + n <= base + UInt64(sizeof(typeof(x))) +end function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from, from_ptr::UInt64, n::UInt64) + if span_is_inline(from, from_ptr, n) + GC.@preserve from unsafe_copyto!(pointer(copies, copies_offset), Ptr{UInt8}(from_ptr), n) + return + end real_from = find_object_holding_ptr(from, from_ptr) return read_remainder!(copies, copies_offset, real_from, from_ptr, n) end @@ -678,6 +689,10 @@ function write_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, to::Dens copyto!(to_vec, Int(to_offset_n), copies_typed, 1, Int(n)) end function write_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, to, to_ptr::UInt64, n::UInt64) + if span_is_inline(to, to_ptr, n) + GC.@preserve to unsafe_copyto!(Ptr{UInt8}(to_ptr), pointer(copies, copies_offset), n) + return + end real_to = find_object_holding_ptr(to, to_ptr) return write_remainder!(copies, copies_offset, real_to, to_ptr, n) end diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 4b960c698..4b710e860 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -172,8 +172,15 @@ function unwrap(handle::DRef) @assert root_worker_id(handle) == myid() "DRef $handle is not owned by this process: $(root_worker_id(handle)) != $(myid())" return MemPool.poolget(handle) end -move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::T, from::F) where {T,F} = +function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::T, from::F) where {T,F} + # A field dependency (`Deps(x, InOut(:field))`) of any struct. Handled here + # rather than by a `dep_mod::Symbol` method, which would be ambiguous with + # every `move!` that specializes the values instead (`Chunk`s, arrays, ...). + if dep_mod isa Symbol && T === F + return move_field!(to_space, from_space, to, from, dep_mod) + end throw(ArgumentError("No `move!` implementation defined for $F -> $T")) +end function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Chunk, from::Chunk) to_w = root_worker_id(to_space) remotecall_wait(to_w, dep_mod, to_space, from_space, to, from) do dep_mod, to_space, from_space, to, from @@ -200,16 +207,27 @@ function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Base to[] = from[] return end -function move!(dep_mod::Symbol, to_space::MemorySpace, from_space::MemorySpace, to::Base.RefValue{T}, from::Base.RefValue{T}) where {T} - to_f = getfield(to, dep_mod) - from_f = getfield(from, dep_mod) +move!(dep_mod::Symbol, to_space::MemorySpace, from_space::MemorySpace, to::Base.RefValue{T}, from::Base.RefValue{T}) where {T} = + move_field!(to_space, from_space, to, from, dep_mod) + +""" + move_field!(to_space, from_space, to, from, field::Symbol) + +Copy one field of `from` into `to`, for a field dependency (see +`field_aliasing`). +""" +function move_field!(to_space::MemorySpace, from_space::MemorySpace, to::T, from::T, field::Symbol) where T + to_f = getfield(to, field) + from_f = getfield(from, field) if to_f isa AbstractArray && from_f isa AbstractArray && axes(to_f) == axes(from_f) # Update the field's storage in place: aliasing spans computed when the # destination slot was created point into that storage, and rebinding # the field would silently disconnect them move!(to_space, from_space, to_f, from_f) + elseif ismutabletype(T) + setfield!(to, field, from_f) else - setfield!(to, dep_mod, from_f) + throw(ArgumentError("Cannot copy field `$field` of an immutable `$T`")) end return end @@ -594,10 +612,33 @@ end aliasing(accel::Acceleration, x, T) = aliasing_unwrapped(x, T) function aliasing(x, dep_mod) if dep_mod isa Symbol - return aliasing(getfield(x, dep_mod)) + return field_aliasing(x, dep_mod) end return aliasing(dep_mod(x)) end + +""" + field_aliasing(x, field::Symbol) -> AbstractAliasing + +The aliasing of a `Deps(x, In(:field))`-style dependency on one field of `x`. + +- An isbits field of a mutable struct is stored inline, inside `x`'s own memory: + its aliasing is that memory, `sizeof` the field at its `fieldoffset`. It + therefore overlaps `x` as a whole, and is copied on its own (see `move_field!`). +- Any other field -- a reference field, or any field of an immutable struct -- + aliases whatever it refers to, so writing *through* it (e.g. into an array it + holds) is tracked, but rebinding the field itself is not. For an isbits field + of an immutable struct that is `NoAliasing`: there is nothing to write. +""" +function field_aliasing(x::T, field::Symbol) where T + idx = Base.fieldindex(T, field) + FT = fieldtype(T, idx) + if ismutabletype(T) && isbitstype(FT) + addr = UInt(pointer_from_objref(x)) + UInt(fieldoffset(T, idx)) + return ObjectAliasing(RemotePtr{Cvoid}(addr, CPURAMMemorySpace(myid())), sizeof(FT)) + end + return aliasing(getfield(x, field)) +end function aliasing(x::T) where T if isbits(x) return NoAliasing() diff --git a/test/datadeps.jl b/test/datadeps.jl index 94bcf3dba..ddbba421a 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1160,6 +1160,21 @@ include(joinpath(@__DIR__, "array", "sparse_defs.jl")) end end +include("field_deps_defs.jl") + +# The same body runs under MPI from test/mpi/cpu.jl. +@testset "Isbits Field Dependencies" begin + on(w) = Dagger.scope(worker=w) + @testset "hierarchical=$hierarchical" for hierarchical in (false, true) + @testset "in place" test_isbits_field_writes(; hierarchical, scope=on(1)) + if nprocs() >= 3 + w1, w2 = workers()[1], workers()[2] + @testset "on another worker" test_isbits_field_writes(; hierarchical, scope=on(w1)) + @testset "read on a third worker" test_isbits_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) + end + end +end + include("noaliasing_defs.jl") # The same bodies run under MPI from test/mpi/noaliasing_args.jl. diff --git a/test/field_deps_defs.jl b/test/field_deps_defs.jl new file mode 100644 index 000000000..ea80d4703 --- /dev/null +++ b/test/field_deps_defs.jl @@ -0,0 +1,42 @@ +# Shared test bodies for Datadeps field dependencies (`Deps(x, InOut(:field))`). +# +# An isbits field of a mutable struct is memory inside the struct, so its +# dependency must describe that memory. It used to come out as `NoAliasing` +# (the aliasing of the isbits *value*), so a write from another memory space +# was never copied back, and nothing ordered it against other uses of the field. +# +# Run from test/datadeps.jl (threads / Distributed) and test/mpi/cpu.jl (MPI). +# `writeback_visible` must be false on MPI ranks that do not own the origin, +# whose replica of a bare Julia object is never written back to. + +@everywhere begin + mutable struct FieldBox + value::Int + other::Float64 + v::Vector{Float64} + end + field_set_value!(X::FieldBox, x::Int) = (X.value = x; nothing) + field_set_other!(X::FieldBox, x::Float64) = (X.other = x; nothing) + field_get_value(X::FieldBox) = X.value + field_set_ref!(R::Base.RefValue{Int}, x::Int) = (R[] = x; nothing) +end + +function test_isbits_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) + X = FieldBox(0, 0.0, zeros(4)) + R = Ref(0) + seen = nothing + Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), 42) + # A different field of the same object: copied back on its own. + Dagger.@spawn scope=scope field_set_other!(Deps(X, Out(:other)), 1.5) + Dagger.@spawn scope=scope field_set_ref!(Deps(R, InOut(:x)), 42) + # Ordered after the write to the same field. + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + end + @test fetch(seen) == 42 + if writeback_visible + @test X.value == 42 + @test X.other == 1.5 + @test R[] == 42 + end +end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index ba97dfd08..35016e1f8 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -44,6 +44,7 @@ const MPIExt = Base.get_extension(Dagger, :MPIExt) include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) +include(joinpath(@__DIR__, "..", "field_deps_defs.jl")) Dagger.accelerate!(:mpi) Dagger.check_uniformity!(true) @@ -607,6 +608,14 @@ end end end +@testset "Isbits field dependencies, hierarchical=$hierarchical" for hierarchical in (false, true) + # Shared with test/datadeps.jl; see test/field_deps_defs.jl + r1 = min(1, nranks-1) + test_isbits_field_writes(; hierarchical, scope=rank_scope(0), writeback_visible = rank == 0) + test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), writeback_visible = rank == 0) + test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(nranks-1), writeback_visible = rank == 0) +end + @testset "Field aliasing" begin # Symbol dep_mods narrow the dependency (and cross-rank move!) to one # field of a wrapped object (mirrors test/datadeps.jl "Field aliasing") From 9f8aea24b0d5e3fc314ebbf1b4d12b4a4b76aeb8 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:26:06 -0700 Subject: [PATCH 11/27] datadeps: reject write access to dependencies that describe no memory An argument (or a field dependency) whose aliasing describes no memory is read-only and passed by value: Datadeps never copies anything into or out of its slots, so a task writing one would have its write silently lost. Raise an `ArgumentError` at planning instead, as Datadeps already does for write access to bare sparse arguments. This was held back until field dependencies had real aliasing: before the previous commit, the documented `Deps(X, InOut(:value))` on an isbits field of a mutable struct came out as `NoAliasing` and would have been rejected. Now only what truly has no writable memory is: a value declared `NoAliasing` (or a struct of nothing else), and an isbits field of an immutable struct. `String`, `Symbol` and `Type` arguments are not affected either way: `type_may_alias` is `false` for them, so they never reach dependency tracking, and a write dependency on one is ignored as before. The check sits where planning already computes the dependency's aliasing (`_populate_arg_deps!`, shared by both planners) and reuses that result: one `describes_memory` call per written dependency, nothing for reads, and the message is built out of line. The aliasing is rank-uniform under MPI, so every rank throws together. The new tests fail without the check. Co-Authored-By: Claude Opus 5.5 --- src/datadeps/aliasing.jl | 22 +++++++++++++++++++++- test/datadeps.jl | 6 ++++++ test/mpi/noaliasing_args.jl | 6 ++++++ test/noaliasing_defs.jl | 27 +++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 14b085ef4..04a2855f9 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1063,11 +1063,31 @@ function _populate_arg_deps!(state::DataDepsState, infos::Vector{TaskArgInfo}, for dep in raw_deps dep_full = DataDepsTaskDependency(arg_chunk, dep) push!(deps_vec, dep_full) - populate_argument_info!(state, dep_full.arg_w, origin_space) + ainfo = populate_argument_info!(state, dep_full.arg_w, origin_space) + # N.B. The aliasing is the one planning just computed; checking it costs + # one call per written argument and nothing for a read. + if dep_full.writedep && !(describes_memory(ainfo)::Bool) + throw_unwritable(arg_chunk, dep_full.arg_w.dep_mod) + end end push!(infos, TaskArgInfo(arg_chunk, pos, may_alias, inplace_move, dep_start, length(deps_vec))) return end +# An argument whose aliasing describes no memory is read-only and passed by +# value (see `move_rewrap` and `compute_remainder_for_arg!`): Datadeps never +# copies a write to it anywhere, so a write would be silently lost. The aliasing +# is rank-uniform under MPI, so every rank throws together. +@noinline function throw_unwritable(arg, dep_mod) + T = arg isa Chunk ? chunktype(arg) : typeof(arg) + target = dep_mod === identity ? "a `$T` argument" : "a `$T` argument (through `$dep_mod`)" + throw(ArgumentError(""" + Datadeps cannot take write access (`Out`/`InOut`) to $target whose aliasing describes no memory. + + Such an argument (e.g. one whose `aliasing` returns `NoAliasing()`) is read-only + and passed by value: tasks in other memory spaces get a copy, and nothing is + ever copied back, so a write would be lost. Pass it as `In`, or give its type an + `aliasing` method that describes the memory it holds.""")) +end function populate_argument_info!(state::DataDepsState, arg_w::ArgumentWrapper, origin_space::MemorySpace) # Initialize ownership and history if !haskey(state.arg_owner, arg_w) diff --git a/test/datadeps.jl b/test/datadeps.jl index ddbba421a..da203a3c8 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1181,6 +1181,12 @@ include("noaliasing_defs.jl") @testset "NoAliasing Arguments" begin on(w) = Dagger.scope(worker=w) @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val, noalias_wrap), hierarchical in (false, true) + @testset "write access is rejected" begin + test_noaliasing_write_rejected(; mk, hierarchical, scope=on(1)) + end + mk === noalias_val && @testset "write access to an immutable isbits field is rejected" begin + test_immutable_field_write_rejected(; hierarchical, scope=on(1)) + end @testset "in place" begin test_noaliasing_args(; mk, hierarchical, src_scope=_->on(1), dst_scope=_->on(1)) end diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 68fd4d0b3..6a9ba3a18 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -10,6 +10,12 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) on(r) = Dagger.scope(mpi_rank=r) nvals = 2 * nranks @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val, noalias_wrap), hierarchical in (false, true) + @testset "write access is rejected" begin + test_noaliasing_write_rejected(; mk, hierarchical, scope=on(0)) + end + mk === noalias_val && @testset "write access to an immutable isbits field is rejected" begin + test_immutable_field_write_rejected(; hierarchical, scope=on(0)) + end @testset "in place" begin test_noaliasing_args(; mk, hierarchical, nvals, src_scope=i->on(owner(i)), diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 59a16e41e..d33ecba36 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -128,3 +128,30 @@ function test_noaliasing_by_value(; src_scope, dst_scope, n::Int=1_000_000, nreg @test fetch(total) == sum(1:n) end end + +# Such an argument is read-only, so asking to write it is an error rather than +# a write that would silently be lost. +function test_noaliasing_write_rejected(; mk, scope, hierarchical=nothing) + x = Dagger.@spawn scope=scope mk(1) + for dep in (Out, InOut) + @test_throws ArgumentError Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope noalias_id(dep(x)) + end + end +end + +# The same holds for an isbits field of an immutable struct, which describes no +# memory and cannot be written at all. +@everywhere begin + struct NoAliasImmutableBox + value::Int + v::Vector{Float64} + end + noalias_touch(x) = nothing +end +function test_immutable_field_write_rejected(; scope, hierarchical=nothing) + B = NoAliasImmutableBox(0, zeros(2)) + @test_throws ArgumentError Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope noalias_touch(Deps(B, InOut(:value))) + end +end From df6208258abd28e3dea72fa412532a654a906c9c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 16:29:11 -0700 Subject: [PATCH 12/27] AGENTS.md: a field dependency's memory is the field's Update lesson 100 now that isbits field dependencies of mutable structs have real aliasing: "describes no memory" has to be true of the dependency, and getting that wrong for fields is what lost remote field writes and made write rejection look unsafe. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e8121ff04..6346e8618 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1041,7 +1041,10 @@ lesson. `free_unkeyed_copies!` waits on every task recorded in `add_reader!`. Test ordering with multithreaded workers, frees with slow readers that check the buffer is still allocated, and "nothing is copied in" with a `move!` that - raises. Beware that aliasing is per *dependency*: `Deps(X, InOut(:field))` - on an isbits field of a mutable `X` has `NoAliasing` aliasing, so rejecting - writes to `NoAliasing` would break that documented usage (which works only - within one memory space; a remote write to the field is already lost). + raises. Beware that aliasing is per *dependency*, and "no memory" must + mean the dependency truly has none: an isbits field of a mutable `X` + (`Deps(X, InOut(:field))`) is memory inside `X`, so `field_aliasing` gives + it an `ObjectAliasing` at the field's offset. While it came out as the + isbits value's `NoAliasing`, a write to it from another memory space was + silently lost, and rejecting writes to `NoAliasing` would have broken that + documented usage outright. From f6ed74006e841eafb2c4887e52b54724112147b3 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:05:16 -0700 Subject: [PATCH 13/27] Keep field aliasing divisible alongside its parent Review finding F2 (should-fix) on PR #834: mixing a field dependency with its whole parent reached the indivisible-container owner assertion. Wrap inline field spans in FieldAliasing rather than returning the bare ObjectAliasing marker reserved for whole-object containers. Exercise both field/parent access orders across workers in the shared Distributed/MPI body, on both planners. Validation: the isolated cross-worker probe asserts on df620825; the fix passes 8/8 assertions across both planners. Deep-warmed Base.gc_num deltas (minimum of five runs after ten warmups and GC.gc) for 1,000 field alias queries remain 1,000 allocations / 32,000 bytes before and after. A one-element CombinedAliasing alternative cost 4,000 / 112,000, avoided by the immutable FieldAliasing wrapper. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 10 ++++++++++ ext/MPIExt.jl | 2 ++ src/memory-spaces.jl | 12 +++++++++++- test/field_deps_defs.jl | 29 +++++++++++++++++++++++++++++ 4 files changed, 52 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 6346e8618..40caad49c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1048,3 +1048,13 @@ lesson. isbits value's `NoAliasing`, a write to it from another memory space was silently lost, and rejecting writes to `NoAliasing` would have broken that documented usage outright. + +101. **A field span must not look like an indivisible container.** Bare + `ObjectAliasing` is the dispatch signal for containers whose storage must + be copied as a whole. An inline field also has an object-relative pointer, + but is only part of its parent: returning bare `ObjectAliasing` for it + makes a field/parent dependency combination hit the whole-container owner + assertion. `FieldAliasing` preserves the span while keeping it divisible. + An immutable wrapper costs no extra descriptor allocation; wrapping it in + a one-element `CombinedAliasing` vector added three allocations (80 bytes) + per field query in the isolated warmed probe. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 06400bbb9..561178e70 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1924,6 +1924,8 @@ mpi_remap_ainfo(a::Dagger.ContiguousAliasing, owner::Int) = Dagger.ContiguousAliasing(mpi_remap_span(a.span, owner)) mpi_remap_ainfo(a::Dagger.ObjectAliasing, owner::Int) = Dagger.ObjectAliasing(mpi_remap_ptr(a.ptr, owner), a.sz) +mpi_remap_ainfo(a::Dagger.FieldAliasing, owner::Int) = + Dagger.FieldAliasing(mpi_remap_ainfo(a.storage, owner)) function mpi_remap_ainfo(a::Dagger.StridedAliasing{T,N,S}, owner::Int) where {T,N,S} base_ptr = mpi_remap_ptr(a.base_ptr, owner) return Dagger.StridedAliasing{T,N,typeof(base_ptr.space)}(base_ptr, diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 4b710e860..b7908b94a 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -605,6 +605,14 @@ function memory_spans(oa::ObjectAliasing{S}) where S return [span] end +"A field's storage: divisible alongside its parent, unlike a whole-object container." +struct FieldAliasing{A<:AbstractAliasing} <: AbstractAliasing + storage::A +end +memory_spans(fa::FieldAliasing) = memory_spans(fa.storage) +Base.:(==)(a::FieldAliasing, b::FieldAliasing) = a.storage == b.storage +Base.hash(a::FieldAliasing, h::UInt) = hash(a.storage, hash(FieldAliasing, h)) + # Acceleration entry point used by Datadeps. Unwrap whole-object containers # (e.g. views of `DSparseArray`) before computing aliasing. SPMD backends # (MPI) overload this for `Chunk`/`ChunkView` to broadcast owner-computed @@ -635,7 +643,9 @@ function field_aliasing(x::T, field::Symbol) where T FT = fieldtype(T, idx) if ismutabletype(T) && isbitstype(FT) addr = UInt(pointer_from_objref(x)) + UInt(fieldoffset(T, idx)) - return ObjectAliasing(RemotePtr{Cvoid}(addr, CPURAMMemorySpace(myid())), sizeof(FT)) + # A field is a splittable part of its parent object, unlike a bare + # ObjectAliasing (the contract for indivisible containers). + return FieldAliasing(ObjectAliasing(RemotePtr{Cvoid}(addr, CPURAMMemorySpace(myid())), sizeof(FT))) end return aliasing(getfield(x, field)) end diff --git a/test/field_deps_defs.jl b/test/field_deps_defs.jl index ea80d4703..b9f031a87 100644 --- a/test/field_deps_defs.jl +++ b/test/field_deps_defs.jl @@ -19,6 +19,18 @@ field_set_other!(X::FieldBox, x::Float64) = (X.other = x; nothing) field_get_value(X::FieldBox) = X.value field_set_ref!(R::Base.RefValue{Int}, x::Int) = (R[] = x; nothing) + mutable struct ScalarFieldBox + value::Int + other::Float64 + end + field_set_value!(X::ScalarFieldBox, x::Int) = (X.value = x; nothing) + field_get_value(X::ScalarFieldBox) = X.value + function Dagger.move!(::typeof(identity), to_space::Dagger.MemorySpace, + from_space::Dagger.MemorySpace, to::ScalarFieldBox, from::ScalarFieldBox) + to.value = from.value + to.other = from.other + return + end end function test_isbits_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) @@ -39,4 +51,21 @@ function test_isbits_field_writes(; scope, reader_scope=scope, writeback_visible @test X.other == 1.5 @test R[] == 42 end + + # A field overlaps the parent, in either access order. Callers place the + # writer and reader independently to exercise copies between spaces. + for whole_writer in (false, true) + X = ScalarFieldBox(0, 0.0) + Dagger.spawn_datadeps(; hierarchical) do + if whole_writer + Dagger.@spawn scope=scope field_set_value!(InOut(X), 42) + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + else + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), 42) + seen = Dagger.@spawn scope=reader_scope field_get_value(In(X)) + end + end + @test fetch(seen) == 42 + writeback_visible && @test X.value == 42 + end end From 2a61f6ee83e2d64927d0238e301a84a7fce76f8a Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:19:19 -0700 Subject: [PATCH 14/27] Serialize mutable field values without copying GC pointer bytes Review finding F1 (blocker) on PR #834: fields declared as Any, abstract, Union, String or Symbol lost their storage identity and were rejected as NoAliasing, even in place. Describe every mutable field's own storage, retaining referent spans where present. Derive the field width from its enclosing layout, supporting abstract and union declarations. For partial object copies, omit reference slots from the byte buffer and serialize scalar field values separately. Keep array-reference bindings and synchronize their referents through the existing spans. Resolve nested field-owned spans generically. MPI now serializes full field values and uses the same field-aware remainder payload while dense/device arrays retain their existing staging path. Validation: the previous head rejects the Any-field cross-worker probe. The focused Any/Union/String/Symbol/Ref{Any} probe passes, including both parent/field access orders and an assertion that reference-slot byte payloads are zero. Shared tests cover Any, Real, Union{Nothing,Int}, String, Symbol and Ref{Any}: 234 Distributed assertions and 104 MPI assertions pass across both planners and remote workers/ranks. The field descriptor's warmed allocation measurement remains unchanged (1,000 allocations / 32,000 bytes for 1,000 queries); dense-array packing is unchanged. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 11 ++++ docs/src/datadeps.md | 10 ++- ext/MPIExt.jl | 27 +++++++++ src/datadeps/remainders.jl | 121 ++++++++++++++++++++++++++++++++++++- src/memory-spaces.jl | 28 ++++++--- test/datadeps.jl | 2 + test/field_deps_defs.jl | 41 +++++++++++++ test/mpi/cpu.jl | 1 + 8 files changed, 227 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 40caad49c..7cd043d54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1058,3 +1058,14 @@ lesson. An immutable wrapper costs no extra descriptor allocation; wrapping it in a one-element `CombinedAliasing` vector added three allocations (80 bytes) per field query in the isolated warmed probe. + +102. **A mutable field is writable even when its declared type is not isbits, + but its reference bytes are never a wire format.** `Any`, abstract, + `Union`, `String` and `Symbol` fields have storage inside their parent just + like `Int` fields. Describing only the value incorrectly rejects writes + when that value is `NoAliasing`. Describe the field storage and retain + referent aliasing where present. For partial copies, split bytes around + reference-valued fields and serialize scalar field values separately; + scattering raw source-process pointers into a destination object bypasses + Julia's GC and is invalid. Both Distributed and MPI need this protocol; + MPI's previous partial-field path packed bytes even for `FullCopy`. diff --git a/docs/src/datadeps.md b/docs/src/datadeps.md index 788b67a94..32bf30057 100644 --- a/docs/src/datadeps.md +++ b/docs/src/datadeps.md @@ -207,9 +207,13 @@ A field dependency covers different memory depending on the field: ...) is stored inside the struct, so the dependency covers exactly that field. It may be written from any memory space: Datadeps copies just that field to where the task runs, and back afterwards. -- Any other field refers to another object (an array, say), and the dependency - covers that object. Writing *into* it (e.g. `X.v .= 0`) is tracked; replacing - the field with a different object is not. +- A non-isbits field of a mutable struct includes the field's own storage too. + Scalar writes to fields declared as `Any`, an abstract type, a `Union`, + `String` or `Symbol` are copied back just like isbits fields. Julia values are + serialized; process-local GC pointers are never copied as bytes. +- A field referring to another memory-bearing object (an array, say) also + covers that object. Writing *into* it (e.g. `X.v .= 0`) is tracked while its + backing storage remains fixed; replacing or resizing that storage is not. - A field of an immutable struct cannot be written. An isbits one describes no memory, so it may only be read (`In`). diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 561178e70..21421fd44 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1721,6 +1721,17 @@ function move!(dep_mod, to_space::MPIMemorySpace, from_space::MPIMemorySpace, to move!(dep_mod, to_space.innerSpace, from_space.innerSpace, to_val, val) end end + elseif dep_mod isa Symbol + # A field may contain a GC reference (Any, String, Union, ...). + # Serialize its value rather than packing process-local pointers. + if local_rank == from_space.rank + value = getfield(poolget(from.handle; uniform=false), dep_mod) + send_yield(value, to_space.comm, to_space.rank, tag) + elseif local_rank == to_space.rank + value = recv_yield(from_space.comm, from_space.rank, tag) + to_val = poolget(to.handle; uniform=false) + Dagger.move_field_value!(to_space.innerSpace, from_space.innerSpace, to_val, dep_mod, value) + end else # Partial copy (e.g. UpperTriangular): the destination must only # update the dep_mod-selected region. Both sides compute the @@ -1798,6 +1809,22 @@ function move!(dep_mod::Dagger.RemainderAliasing{<:MPIMemorySpace}, to_space::MP else tag = Dagger.in_task() ? to_tag() : to_tag(from.handle) @dagdebug nothing :mpi "[$local_rank][$tag] Moving from $(from_space.rank) to $(to_space.rank)\n" + if Dagger.remainder_needs_fields(chunktype(from)) + # This protocol choice depends only on the rank-uniform chunktype. + # Field values travel through Julia serialization; dense/device + # arrays retain the staging-buffer protocol below. + if local_rank == from_space.rank + from_raw = poolget(from.handle; uniform=false) + copies = Dagger.gather_field_remainder(from_raw, Iterators.map(first, dep_mod.spans)) + send_yield(copies, to_space.comm, to_space.rank, tag) + elseif local_rank == to_space.rank + copies = recv_yield(from_space.comm, from_space.rank, tag) + to_raw = poolget(to.handle; uniform=false) + Dagger.scatter_field_remainder!(to_raw, copies, Iterators.map(last, dep_mod.spans)) + Base.Threads.atomic_fence() + end + return + end if local_rank == from_space.rank # Gather the source spans into a host buffer (device arrays pack # via multi_span_gather! / one KA launch, then a single DtoH) diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index ed92a49c8..2113660de 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -590,10 +590,13 @@ function move!(dep_mod::RemainderAliasing{S}, to_space::MemorySpace, from_space: # Gather source spans into a host buffer (device arrays pack via KA first). # Pin when the source is device memory so DtoH hits page-locked host RAM. copies = remotecall_fetch(root_worker_id(from_space), from_space, dep_mod, from) do from_space, dep_mod, from + from_raw = unwrap(from) + if remainder_needs_fields(typeof(from_raw)) + return gather_field_remainder(from_raw, Iterators.map(first, dep_mod.spans)) + end len = sum(span_tuple->span_len(span_tuple[1]), dep_mod.spans) copies = Vector{UInt8}(undef, len) pin_buffer!(gpu_memory_kind(from_space), copies) - from_raw = unwrap(from) with_context!(from_space) # `from_raw` is preserved alongside `copies`. For device-backed arrays # (`CuArray`, `ROCArray`, `CLArray`, …) the underlying device memory is @@ -613,6 +616,11 @@ function move!(dep_mod::RemainderAliasing{S}, to_space::MemorySpace, from_space: # Scatter into the destination spans (pin again after remotecall deserialize) to_raw = unwrap(to) with_context!(to_space) + if copies isa FieldRemainder + scatter_field_remainder!(to_raw, copies, Iterators.map(last, dep_mod.spans)) + Base.Threads.atomic_fence() + return + end pin_buffer!(gpu_memory_kind(to_space), copies) # See the gather above -- the same finalizer lifetime hazard applies to # `to_raw` on the scatter side. @@ -659,6 +667,117 @@ function span_is_inline(x, ptr::UInt64, n::UInt64) base = UInt64(pointer_from_objref(x)) return base <= ptr && ptr + n <= base + UInt64(sizeof(typeof(x))) end +# A mutable object's reference fields contain process-local GC pointers. Keep +# those out of the byte payload and serialize scalar field values separately. +struct FieldRemainder + bytes::Vector{UInt8} + values::Vector{Pair{UInt64,Any}} +end + +function remainder_needs_fields(::Type{T}) where T + ismutabletype(T) && !(T <: AbstractArray) || return false + return any(FT -> !isbitstype(FT), fieldtypes(T)) +end + +function gather_field_remainder(from, spans) + len = sum(span_len, spans; init=UInt64(0)) + # Omitted reference slots stay zero, never uninitialized or pointer bytes. + copies = FieldRemainder(zeros(UInt8, len), Pair{UInt64,Any}[]) + offset = UInt64(1) + for span in spans + read_field_remainder!(copies, offset, from, UInt64(span_start(span)), UInt64(span_len(span))) + offset += span_len(span) + end + return copies +end +function scatter_field_remainder!(to, copies::FieldRemainder, spans) + offset = UInt64(1) + for span in spans + write_field_remainder!(copies, offset, to, UInt64(span_start(span)), UInt64(span_len(span))) + offset += span_len(span) + end + return +end +function read_field_remainder!(copies::FieldRemainder, offset::UInt64, from::AbstractArray, ptr::UInt64, n::UInt64) + read_remainder!(copies.bytes, offset, from, ptr, n) +end +function read_field_remainder!(copies::FieldRemainder, offset::UInt64, from::T, ptr::UInt64, n::UInt64) where T + if !span_is_inline(from, ptr, n) + holder = find_object_holding_ptr(from, ptr) + return read_field_remainder!(copies, offset, holder, ptr, n) + end + base = UInt64(pointer_from_objref(from)) + cursor = ptr + stop = ptr + n + GC.@preserve from copies begin + for i in 1:fieldcount(T) + isbitstype(fieldtype(T, i)) && continue + field_start = base + UInt64(fieldoffset(T, i)) + field_stop = field_start + UInt64(field_storage_size(T, i)) + (field_start >= stop || field_stop <= ptr) && continue + @assert ptr <= field_start && field_stop <= stop "Remainder splits a reference-valued field" + unsafe_copyto!(pointer(copies.bytes, offset + cursor - ptr), Ptr{UInt8}(cursor), field_start - cursor) + value = getfield(from, i) + # Memory-bearing fields retain the destination binding; their + # referent spans carry the contents separately, as for array fields. + if !(describes_memory(aliasing(value))::Bool) + push!(copies.values, (offset + field_start - ptr) => value) + end + cursor = field_stop + end + unsafe_copyto!(pointer(copies.bytes, offset + cursor - ptr), Ptr{UInt8}(cursor), stop - cursor) + end + return +end +function write_field_remainder!(copies::FieldRemainder, offset::UInt64, to::AbstractArray, ptr::UInt64, n::UInt64) + write_remainder!(copies.bytes, offset, to, ptr, n) +end +function write_field_remainder!(copies::FieldRemainder, offset::UInt64, to::T, ptr::UInt64, n::UInt64) where T + if !span_is_inline(to, ptr, n) + holder = find_object_holding_ptr(to, ptr) + return write_field_remainder!(copies, offset, holder, ptr, n) + end + base = UInt64(pointer_from_objref(to)) + cursor = ptr + stop = ptr + n + GC.@preserve to copies begin + for i in 1:fieldcount(T) + isbitstype(fieldtype(T, i)) && continue + field_start = base + UInt64(fieldoffset(T, i)) + field_stop = field_start + UInt64(field_storage_size(T, i)) + (field_start >= stop || field_stop <= ptr) && continue + @assert ptr <= field_start && field_stop <= stop "Remainder splits a reference-valued field" + unsafe_copyto!(Ptr{UInt8}(cursor), pointer(copies.bytes, offset + cursor - ptr), field_start - cursor) + key = offset + field_start - ptr + for value in copies.values + if first(value) == key + setfield!(to, i, last(value)) + break + end + end + cursor = field_stop + end + unsafe_copyto!(Ptr{UInt8}(cursor), pointer(copies.bytes, offset + cursor - ptr), stop - cursor) + end + return +end + +# An ordinary mutable struct's aliasing includes memory reachable through its +# fields. Resolve those spans without requiring a pointer hook per struct type. +function find_object_holding_ptr(x::T, ptr::UInt64) where T + for i in 1:fieldcount(T) + isdefined(x, i) || continue + value = getfield(x, i) + isbits(value) && continue + for span in memory_spans(aliasing(value)) + if UInt64(span_start(span)) <= ptr <= UInt64(span_end(span)) + return value + end + end + end + throw(ArgumentError("No field of $T holds remainder pointer $ptr")) +end + function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from, from_ptr::UInt64, n::UInt64) if span_is_inline(from, from_ptr, n) GC.@preserve from unsafe_copyto!(pointer(copies, copies_offset), Ptr{UInt8}(from_ptr), n) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index b7908b94a..bb6040d17 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -217,8 +217,10 @@ Copy one field of `from` into `to`, for a field dependency (see `field_aliasing`). """ function move_field!(to_space::MemorySpace, from_space::MemorySpace, to::T, from::T, field::Symbol) where T + return move_field_value!(to_space, from_space, to, field, getfield(from, field)) +end +function move_field_value!(to_space::MemorySpace, from_space::MemorySpace, to::T, field::Symbol, from_f) where T to_f = getfield(to, field) - from_f = getfield(from, field) if to_f isa AbstractArray && from_f isa AbstractArray && axes(to_f) == axes(from_f) # Update the field's storage in place: aliasing spans computed when the # destination slot was created point into that storage, and rebinding @@ -625,27 +627,33 @@ function aliasing(x, dep_mod) return aliasing(dep_mod(x)) end +field_storage_size(::Type{T}, i::Int) where T = + (i < fieldcount(T) ? fieldoffset(T, i + 1) : sizeof(T)) - fieldoffset(T, i) + """ field_aliasing(x, field::Symbol) -> AbstractAliasing The aliasing of a `Deps(x, In(:field))`-style dependency on one field of `x`. -- An isbits field of a mutable struct is stored inline, inside `x`'s own memory: - its aliasing is that memory, `sizeof` the field at its `fieldoffset`. It - therefore overlaps `x` as a whole, and is copied on its own (see `move_field!`). -- Any other field -- a reference field, or any field of an immutable struct -- - aliases whatever it refers to, so writing *through* it (e.g. into an array it - holds) is tracked, but rebinding the field itself is not. For an isbits field - of an immutable struct that is `NoAliasing`: there is nothing to write. +- Every field of a mutable struct includes its own storage inside `x`, so + rebinding scalar, `Any`, `Union`, string and symbol fields is tracked and + copied back. Memory reachable through a reference field is included too. +- A field of an immutable struct aliases its value. An isbits value then + describes no writable memory; an array value still supports writes through + the field. """ function field_aliasing(x::T, field::Symbol) where T idx = Base.fieldindex(T, field) FT = fieldtype(T, idx) - if ismutabletype(T) && isbitstype(FT) + if ismutabletype(T) addr = UInt(pointer_from_objref(x)) + UInt(fieldoffset(T, idx)) # A field is a splittable part of its parent object, unlike a bare # ObjectAliasing (the contract for indivisible containers). - return FieldAliasing(ObjectAliasing(RemotePtr{Cvoid}(addr, CPURAMMemorySpace(myid())), sizeof(FT))) + own = ObjectAliasing(RemotePtr{Cvoid}(addr, CPURAMMemorySpace(myid())), field_storage_size(T, idx)) + isbitstype(FT) && return FieldAliasing(own) + referent = aliasing(getfield(x, field)) + describes_memory(referent)::Bool || return FieldAliasing(own) + return FieldAliasing(CombinedAliasing(AbstractAliasing[own, referent])) end return aliasing(getfield(x, field)) end diff --git a/test/datadeps.jl b/test/datadeps.jl index da203a3c8..f73c1cecf 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1167,10 +1167,12 @@ include("field_deps_defs.jl") on(w) = Dagger.scope(worker=w) @testset "hierarchical=$hierarchical" for hierarchical in (false, true) @testset "in place" test_isbits_field_writes(; hierarchical, scope=on(1)) + @testset "reference fields in place" test_reference_field_writes(; hierarchical, scope=on(1)) if nprocs() >= 3 w1, w2 = workers()[1], workers()[2] @testset "on another worker" test_isbits_field_writes(; hierarchical, scope=on(w1)) @testset "read on a third worker" test_isbits_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) + @testset "reference fields across workers" test_reference_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) end end end diff --git a/test/field_deps_defs.jl b/test/field_deps_defs.jl index b9f031a87..3c8ba217c 100644 --- a/test/field_deps_defs.jl +++ b/test/field_deps_defs.jl @@ -31,6 +31,47 @@ to.other = from.other return end + mutable struct FlexibleFieldBox{T} + value::T + other::Int + end + field_set_value!(X::FlexibleFieldBox, x) = (X.value = x; nothing) + field_get_value(X::FlexibleFieldBox) = X.value + field_set_ref!(R::Base.RefValue{Any}, x) = (R[] = x; nothing) + function Dagger.move!(::typeof(identity), to_space::Dagger.MemorySpace, + from_space::Dagger.MemorySpace, to::FlexibleFieldBox{T}, from::FlexibleFieldBox{T}) where T + to.value = from.value + to.other = from.other + return + end +end + +function test_reference_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) + cases = ((Any, 0, 42), (Real, 0, 42), (Union{Nothing,Int}, nothing, 42), + (String, "before", "after"), (Symbol, :before, :after)) + for (T, initial, replacement) in cases, whole_writer in (false, true) + X = FlexibleFieldBox{T}(initial, 17) + seen = nothing + Dagger.spawn_datadeps(; hierarchical) do + if whole_writer + Dagger.@spawn scope=scope field_set_value!(InOut(X), replacement) + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + else + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), replacement) + seen = Dagger.@spawn scope=reader_scope field_get_value(In(X)) + end + end + @test fetch(seen) == replacement + if writeback_visible + @test X.value == replacement + @test X.other == 17 + end + end + R = Ref{Any}(0) + Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope field_set_ref!(Deps(R, InOut(:x)), 42) + end + writeback_visible && @test R[] == 42 end function test_isbits_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 35016e1f8..53cd4eaa9 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -614,6 +614,7 @@ end test_isbits_field_writes(; hierarchical, scope=rank_scope(0), writeback_visible = rank == 0) test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), writeback_visible = rank == 0) test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(nranks-1), writeback_visible = rank == 0) + test_reference_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(0), writeback_visible = rank == 0) end @testset "Field aliasing" begin From 3519a4367aa38065e1449bc375fe0d754b7f9a3d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:25:09 -0700 Subject: [PATCH 15/27] Document every effect of aliasing that describes no memory Review finding F6 (should-fix) on PR #834: describes_memory still claimed that it only controls cache slot sharing, although it now also establishes the read-only by-value contract. Document write rejection, initialized move copies, skipped later copies, and cleanup/result lifetime. Retain the distinction between bare NoAliasing and empty CombinedAliasing dependency tracking. Verified against _populate_arg_deps!, move_rewrap, compute_remainder_for_arg! and free_unkeyed_copies!. Written by an AI agent on jpsamaroo's review feedback. --- src/memory-spaces.jl | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bb6040d17..dc7e378b9 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -582,8 +582,13 @@ none". Two arguments with unknown aliasing may be one object reached through different wrappers, which separate copies would silently split. (Dagger's own `aliasing` methods throw rather than return it.) -This only decides slot sharing. Dependency tracking skips bare `NoAliasing` -alone, and is unaffected. +Datadeps treats such arguments as read-only, by-value inputs: `Out` and `InOut` +are rejected, a slot in another memory space is a complete `move` copy rather +than an uninitialized buffer, and no later copy-to or copy-back is scheduled. +Private copies are released after their readers finish. + +Dependency tracking skips bare `NoAliasing` alone. Empty `CombinedAliasing` +values retain their existing per-argument dependency tracking. """ describes_memory(::AbstractAliasing) = true describes_memory(::NoAliasing) = false From 32acd62085c778de8fb0c935a24b96fbd16e36a6 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:32:47 -0700 Subject: [PATCH 16/27] Keep returned by-value copies alive after the region ends Review finding F4 (should-fix) on PR #834: freeing an unkeyed input copy when its reader returns it leaves a result backed by freed storage; remote fetch then serializes dangling memory and can kill the worker. Pass resolved reader results as ordinary inputs to the cleanup meta task. Skip eager release when a result retains the copy directly, through a view, or inside a container, leaving its finalizer responsible instead. Use storage identity rather than NoAliasing, which deliberately hides this memory. Bound recursive inspection to handle cycles conservatively and avoid scalar indexing of arbitrary non-bits arrays. Validation: the old path marks a returned cross-worker copy freed before fetch; the fix preserves direct, view and nested returns on both planners (12 checks). Cleanup plus result-lifetime shared tests pass 10 Distributed and 16 MPI assertions, confirming unused copies still release normally. Deep-warmed summed driver/worker Base.gc_num deltas (10 warmups, GC.gc, minimum of five regions) were 5,026 allocations /250,928 bytes before and 4,652 /237,920 after; measurements include the same worker-control RPCs. No threshold changes. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 9 ++++++ src/datadeps/aliasing.jl | 58 +++++++++++++++++++++++++++++++++++-- src/memory-spaces.jl | 3 +- test/datadeps.jl | 2 ++ test/mpi/noaliasing_args.jl | 1 + test/noaliasing_defs.jl | 20 +++++++++++++ 6 files changed, 89 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7cd043d54..1b7e145b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1069,3 +1069,12 @@ lesson. scattering raw source-process pointers into a destination object bypasses Julia's GC and is invalid. Both Distributed and MPI need this protocol; MPI's previous partial-field path packed bytes even for `FullCopy`. + +103. **An eager slot free must preserve storage that escapes in a task result.** + A read-only, by-value input can be returned directly, through a view, or + inside a result container. Waiting for its readers to finish is therefore + necessary but insufficient: freeing their slot before the result is + serialized produces EFAULT or a worker crash. Pass resolved reader results + to cleanup as ordinary task inputs, inspect their owner-local storage + identities, and let GC own any escaping copy. `NoAliasing` itself cannot + answer this question because it deliberately hides the buffer's memory. diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 04a2855f9..205a1a8b9 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1512,8 +1512,9 @@ end """ free_unkeyed_copies!(state[, owner_syncdep!]) -Launch an `unsafe_free!` for every unkeyed copy in `state` (see -`unkeyed_object!`), once every task that used its slot has finished. +Release each unkeyed copy in `state` (see `unkeyed_object!`) once every task +that used its slot has finished. A copy retained by a reader's result is left +to GC, so the result remains valid after the region ends. The object cache's free loop cannot cover these: they are not in the cache, and even if they were, their aliasing describes no memory, so `get_write_deps!` @@ -1536,12 +1537,63 @@ function free_unkeyed_copies!(state::DataDepsState, owner_syncdep! = nothing) end owner_syncdep! === nothing || owner_syncdep!(free_syncdeps, entry.slot) # `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!(copies[i]) + # The results are ordinary task inputs, so they resolve to Chunks + # before this meta task runs. Returning a slot transfers its + # lifetime to that result; it must then be released by GC instead. + Dagger.@spawn scope=free_scope syncdeps=free_syncdeps meta=true tag=datadeps_task_tag() free_unkeyed_copy!(copies[i], entry.users...) end end return end +function free_unkeyed_copy!(copy::Chunk, results...) + payload = unwrap(copy) + for result in results + retains_unkeyed_storage(result, payload) && return + end + unsafe_free!(payload) + return +end + +# `NoAliasing` deliberately hides the copy's memory from dependency tracking, +# so use object identity / Base's storage identities to inspect returned values. +# A bounded walk handles cycles conservatively without allocating a visited set: +# when uncertain, leave the allocation to its ordinary GC finalizer. +function retains_unkeyed_storage(result, payload, depth::Int=0) + result === payload && return true + depth >= 128 && return true + if result isa Chunk + is_local(current_acceleration(), processor(result)) || return false + return retains_unkeyed_storage(unwrap(result), payload, depth + 1) + elseif result isa AbstractArray + if payload isa AbstractArray && Base.mightalias(result, payload) + return true + end + p = parent(result) + if p !== result && retains_unkeyed_storage(p, payload, depth + 1) + return true + end + isbitstype(eltype(result)) && return false + if result isa Array + for i in eachindex(result) + isassigned(result, i) || continue + retains_unkeyed_storage(result[i], payload, depth + 1) && return true + end + elseif p === result + # An arbitrary non-bits array may prohibit scalar indexing. + return true + end + elseif !(isbits(result) || result isa Union{String,Symbol,Type,Module}) + T = typeof(result) + isstructtype(T) || return false + for i in 1:fieldcount(T) + isdefined(result, i) || continue + retains_unkeyed_storage(getfield(result, i), payload, depth + 1) && return true + end + end + return false +end + # Make a copy of each piece of data on each worker # memory_space => {arg => copy_of_arg} isremotehandle(x) = false diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index dc7e378b9..42b3ffd0d 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -585,7 +585,8 @@ different wrappers, which separate copies would silently split. (Dagger's own Datadeps treats such arguments as read-only, by-value inputs: `Out` and `InOut` are rejected, a slot in another memory space is a complete `move` copy rather than an uninitialized buffer, and no later copy-to or copy-back is scheduled. -Private copies are released after their readers finish. +Private copies are released after their readers finish, except when retained +by a task result, which then owns their lifetime through GC. Dependency tracking skips bare `NoAliasing` alone. Empty `CombinedAliasing` values retain their existing per-argument dependency tracking. diff --git a/test/datadeps.jl b/test/datadeps.jl index f73c1cecf..1d8b5b33b 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1220,6 +1220,8 @@ include("noaliasing_defs.jl") w1, w2 = workers()[1], workers()[2] test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + test_noaliasing_returns(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) + test_noaliasing_returns(; hierarchical, src_scope=on(w1), dst_scope=on(1)) end end diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 6a9ba3a18..3ca4c05c8 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -37,6 +37,7 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) # MPI's slot transfer returns a `Chunk`, which `libc_backed` leaves # as it is, so its copies are not Libc-backed. test_noaliasing_copy_freed(; hierarchical, freeable=false, src_scope=on(0), dst_scope=on(1)) + test_noaliasing_returns(; hierarchical, src_scope=on(0), dst_scope=on(1)) end end end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index d33ecba36..3965c907e 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -80,6 +80,12 @@ end noalias_no_copy(Vector{NoAliasTile}) noalias_tiles(n::Int) = [NoAliasTile(i, i) for i in 1:n] noalias_sum(x::Vector{NoAliasTile}) = sum(t->t.b, x) + noalias_return_input(x) = x + noalias_return_view(x) = view(x, :) + noalias_return_nested(x) = (x,) + noalias_returned_storage(x::Tuple) = noalias_returned_storage(first(x)) + noalias_returned_storage(x::SubArray) = noalias_returned_storage(parent(x)) + noalias_returned_storage(x) = x # Readers hold on to the slot they were given, after checking that it was # not freed while they ran. @@ -99,6 +105,20 @@ end end end +function test_noaliasing_returns(; src_scope, dst_scope, hierarchical=nothing) + for returner in (noalias_return_input, noalias_return_view, noalias_return_nested) + input = Dagger.@spawn scope=src_scope noalias_tiles(8) + result = nothing + Dagger.spawn_datadeps(; hierarchical) do + result = Dagger.spawn(returner, Dagger.Options(; scope=dst_scope), In(input)) + end + # The returned value owns the copy now, including through a view or a + # returned container. Region cleanup must leave it valid to serialize. + actual = fetch(result) + @test noalias_sum(noalias_returned_storage(actual)) == 36 + end +end + # # `freeable=false` is for transports whose copies are ordinary GC-managed # arrays, which there is nothing to free eagerly; it then only checks that From 791d5aad647f1ddbe50d38fa451d8534aa7e5e8f Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:38:09 -0700 Subject: [PATCH 17/27] Allocate unkeyed-copy storage only when a copy exists Review finding F5 (should-fix) on PR #834: every Datadeps cache created an empty unkeyed-copy vector even when the region made no private copy. Keep the store mutable and its copy vector absent until the first entry. Reload that field after slot construction, since constructing the slot can create the vector. Assert the concrete vector type on the free path once unkeyed slots prove that it exists. Update the cache construction check to require absence until the first actual copy. Validation: deeply warmed Base.gc_num deltas (10 warmups of 50 local regions, GC.gc, minimum of five batches) fell from 36,781 allocations / 2,030,528 bytes to 35,802 /1,955,776. Existing bounds are unchanged. Private-copy freeing and escaped-result regressions pass 10 Distributed and 16 MPI assertions on both planners after lazy initialization. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 8 ++++++++ src/datadeps/aliasing.jl | 19 ++++++++++++------- test/datadeps.jl | 2 +- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1b7e145b6..6dc0cefee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1078,3 +1078,11 @@ lesson. to cleanup as ordinary task inputs, inspect their owner-local storage identities, and let GC own any escaping copy. `NoAliasing` itself cannot answer this question because it deliberately hides the buffer's memory. + +104. **Rare-copy bookkeeping must be lazy at the store as well as the planner.** + Making `DataDepsState.unkeyed_slots` lazy still allocated an empty vector + in every `AliasedObjectCacheStore`, even for entirely local regions. Keep + the store mutable so it can allocate that vector on first use, and reload + the field after `move_rewrap`: a local `nothing` captured before the move + is stale once the move records its first copy. The warmed 50-region probe + fell from 36,781 allocations /2,030,528 bytes to 35,802 /1,955,776 bytes. diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 205a1a8b9..22db2f95c 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -417,7 +417,7 @@ struct HistoryEntry task::WriterProducer end -struct AliasedObjectCacheStore +mutable struct AliasedObjectCacheStore accel::Acceleration keys::Vector{AbstractAliasing} derived::Dict{AbstractAliasing,AbstractAliasing} @@ -444,7 +444,7 @@ struct AliasedObjectCacheStore # `unkeyed_object!`). They never enter `values`, so the free loop over it # cannot see them; `free_unkeyed_copies!` frees them instead. In creation # order, which is rank-uniform. - unkeyed::Vector{Chunk} + unkeyed::Union{Nothing,Vector{Chunk}} end AliasedObjectCacheStore(accel::Acceleration) = AliasedObjectCacheStore(accel, @@ -455,7 +455,7 @@ AliasedObjectCacheStore(accel::Acceleration) = Dict{MemorySpace,Dict{AbstractAliasing,AbstractAliasing}}(), Set{Tuple{MemorySpace,AbstractAliasing}}(), Vector{Pair{AbstractAliasing,Chunk}}(), - Vector{Chunk}()) + nothing) """ resolve_pending!(cache) -> Bool @@ -647,7 +647,11 @@ function add_unkeyed_copy!(cache::AliasedObjectCache, value::Chunk) end @check_uniform(value) cache_raw = unwrap(cache.chunk)::AliasedObjectCacheStore - push!(cache_raw.unkeyed, value) + copies = cache_raw.unkeyed + if copies === nothing + copies = cache_raw.unkeyed = Chunk[] + end + push!(copies, value) return end @@ -1527,7 +1531,7 @@ the same order. function free_unkeyed_copies!(state::DataDepsState, owner_syncdep! = nothing) unkeyed = state.unkeyed_slots unkeyed === nothing && return - copies = state.ainfo_backing.unkeyed + copies = state.ainfo_backing.unkeyed::Vector{Chunk} for entry in unkeyed.slots free_scope = ExactScope(first(processors(entry.space))) for i in entry.copies @@ -1676,7 +1680,7 @@ function generate_slot!(state::DataDepsState, dest_space, data) timing = HIER_TIMING[] t0 = timing ? time_ns() : UInt64(0) unkeyed = state.ainfo_backing.unkeyed - n_unkeyed = length(unkeyed) + n_unkeyed = unkeyed === nothing ? 0 : length(unkeyed) 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 @@ -1701,7 +1705,8 @@ function generate_slot!(state::DataDepsState, dest_space, data) timing && hier_log!(LogHierSlot, 0x01, LogHierSlotId(:total), time_ns() - t0) logging && @logfinish ctx LogMove LogMoveId(0, ArgPosition(), to_proc, id) data_chunk # Any unkeyed copies made just now belong to this slot alone. - if length(unkeyed) > n_unkeyed + unkeyed = state.ainfo_backing.unkeyed + if unkeyed !== nothing && length(unkeyed) > n_unkeyed add_unkeyed_slot!(state, dest_space, data_chunk, (n_unkeyed + 1):length(unkeyed)) 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)" diff --git a/test/datadeps.jl b/test/datadeps.jl index 1d8b5b33b..1f1d07190 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1248,7 +1248,7 @@ include("noaliasing_defs.jl") proc = first(Dagger.processors(other)) y = Dagger.aliased_object!(_->Dagger.tochunk(Dagger.unwrap(x), proc, other), other_cache, x) @test Dagger.unwrap(y) === Dagger.unwrap(x) - @test isempty(store.unkeyed) + @test store.unkeyed === nothing y = Dagger.aliased_object!(_->Dagger.tochunk(noalias_val(1), proc, other), other_cache, x) @test store.unkeyed == [y] end From 2cdacabb90b11bbac58b236a368b90c39e5a5ed1 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 15:41:29 -0700 Subject: [PATCH 18/27] Exercise private copies nested below a view slot Review finding F7 (should-fix) on PR #834: the shared tests never reached unkeyed buffers created as children of a wrapper slot. Make a SubArray over a NoAliasing parent and send it to another worker or MPI rank. Check its selected data, hold the view in two readers, then inspect the parent buffer's allocation registry to prove cleanup waited for both readers and freed the nested copy. Share the fixture with the existing flat/hierarchical lifetime test instead of duplicating its checks. Validation: wrapper lifecycle checks pass 4 Distributed assertions. The MPI control-plus-wrapper checks pass 8 assertions across both planners, with the destination in another space. The readers also assert the view's value sum before retaining it. Written by an AI agent on jpsamaroo's review feedback. --- test/datadeps.jl | 2 ++ test/mpi/noaliasing_args.jl | 2 ++ test/noaliasing_defs.jl | 18 +++++++++++++----- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/test/datadeps.jl b/test/datadeps.jl index 1f1d07190..ce46f7724 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1220,6 +1220,8 @@ include("noaliasing_defs.jl") w1, w2 = workers()[1], workers()[2] test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2), + mk=noalias_view_tiles, reader=noalias_view_keep!) test_noaliasing_returns(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) test_noaliasing_returns(; hierarchical, src_scope=on(w1), dst_scope=on(1)) end diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 3ca4c05c8..619ca6790 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -37,6 +37,8 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) # MPI's slot transfer returns a `Chunk`, which `libc_backed` leaves # as it is, so its copies are not Libc-backed. test_noaliasing_copy_freed(; hierarchical, freeable=false, src_scope=on(0), dst_scope=on(1)) + test_noaliasing_copy_freed(; hierarchical, freeable=false, src_scope=on(0), dst_scope=on(1), + mk=noalias_view_tiles, reader=noalias_view_keep!) test_noaliasing_returns(; hierarchical, src_scope=on(0), dst_scope=on(1)) end end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 3965c907e..9f1d8fecf 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -79,6 +79,7 @@ end to::Vector{NoAliasTile}, from::Vector{NoAliasTile}) = noalias_no_copy(Vector{NoAliasTile}) noalias_tiles(n::Int) = [NoAliasTile(i, i) for i in 1:n] + noalias_view_tiles(n::Int) = view(noalias_tiles(n), 2:n-1) noalias_sum(x::Vector{NoAliasTile}) = sum(t->t.b, x) noalias_return_input(x) = x noalias_return_view(x) = view(x, :) @@ -91,14 +92,20 @@ end # not freed while they ran. const NOALIAS_SEEN = Vector{Any}() const NOALIAS_SEEN_LOCK = ReentrantLock() + noalias_copy_buffer(x::SubArray) = noalias_copy_buffer(parent(x)) + noalias_copy_buffer(x) = x function noalias_keep!(x) sleep(0.25) @lock NOALIAS_SEEN_LOCK push!(NOALIAS_SEEN, x) - return Dagger.is_libc_allocated(x) + return Dagger.is_libc_allocated(noalias_copy_buffer(x)) + end + function noalias_view_keep!(x) + @assert sum(t -> t.b, x) == 27 + return noalias_keep!(x) end function noalias_seen_freed() @lock NOALIAS_SEEN_LOCK begin - freed = !isempty(NOALIAS_SEEN) && !any(Dagger.is_libc_allocated, NOALIAS_SEEN) + freed = !isempty(NOALIAS_SEEN) && !any(x -> Dagger.is_libc_allocated(noalias_copy_buffer(x)), NOALIAS_SEEN) empty!(NOALIAS_SEEN) return freed end @@ -123,12 +130,13 @@ end # `freeable=false` is for transports whose copies are ordinary GC-managed # arrays, which there is nothing to free eagerly; it then only checks that # nothing is left allocated. -function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, freeable::Bool=true, hierarchical=nothing) - v = Dagger.@spawn scope=src_scope noalias_tiles(8) +function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, freeable::Bool=true, hierarchical=nothing, + mk=noalias_tiles, reader=noalias_keep!) + v = Dagger.@spawn scope=src_scope mk(8) kept = Vector{Dagger.DTask}(undef, nreaders) Dagger.spawn_datadeps(; hierarchical) do for i in 1:nreaders - kept[i] = Dagger.@spawn scope=dst_scope noalias_keep!(In(v)) + kept[i] = Dagger.@spawn scope=dst_scope reader(In(v)) end end # Each reader got a freeable copy, which was still allocated while it ran... From 177ef8dc6716f059d464f0b4c0cb3e1f8830b735 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:04:54 -0700 Subject: [PATCH 19/27] Preserve by-value dependencies across backend type conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A host-only NoAliasing declaration must still govern a complete device slot. Checking only the converted array descriptor instead compares unlike span sets or schedules an unordered copy-in. Reuse the source descriptor already cached during argument population, with the origin-space fallback for rebuilt handle wrappers. Add shared GPU and MPI×GPU read, write-rejection, no-copy-in and post-reader free checks. The strengthened OpenCL/pocl test fails both planners before the fix and passes all 11 assertions afterwards. With 10 warmups, GC and 5 runs of 1000 cached origin checks, replacing the general aliasing! lookup with the direct cache lookup reduces minimum allocations from 1000/32000 bytes to 0/0; the skipped-check control is also 0/0. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 12 +++- src/datadeps/remainders.jl | 10 ++++ test/gpu.jl | 7 +++ test/mpi/gpu_suite.jl | 5 ++ test/noaliasing_gpu_defs.jl | 110 ++++++++++++++++++++++++++++++++++++ 5 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 test/noaliasing_gpu_defs.jl diff --git a/AGENTS.md b/AGENTS.md index 733402ffb..5b3d4d1b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1232,7 +1232,7 @@ this section verbatim). Each entry is one bullet starting with `- `. must wait for a slot's users has to track them itself: a region-end free keyed on the slot's ainfo races the tasks still reading it (what happened to cached `NoAliasing` copies before PR #792), which is why - `free_unkeyed_copies!` waits on every task recorded in `add_reader!`. Test + `copy_users` records every reader for the matching `CopyKey` free. Test ordering with multithreaded workers, frees with slow readers that check the buffer is still allocated, and "nothing is copied in" with a `move!` that raises. Beware that aliasing is per *dependency*, and "no memory" must @@ -1281,3 +1281,13 @@ this section verbatim). Each entry is one bullet starting with `- `. vector altogether: the existing cache tables hold copies and the lazy `UnkeyedSlots` holds their readers. The store stays mutable to avoid re-boxing its large immutable value on dynamically typed planning paths. + +114. **A by-value dependency keeps its contract after backend conversion.** + A host `Vector` can declare `NoAliasing` while `move` returns a device + array whose ordinary aliasing describes its device buffer. Remainder + planning must check the original dependency before comparing destination + spans: those spans can differ in both count and address space. Otherwise + a host-only NoAliasing declaration fails a host-to-device read with a span + count assertion, or schedules an unordered copy into an already complete + by-value slot. Test the host declaration alone; declaring the converted + GPU type NoAliasing as well hides this failure. diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index e3f7e5707..9a4f05af5 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -121,6 +121,16 @@ function compute_remainder_for_arg!(state::DataDepsState, all_local && return NoAliasing(), 0 end + # A move may change the concrete value type (e.g. Array -> device array), + # and its physical aliasing can then differ. The original dependency's + # by-value contract still applies to every converted slot. + origin_ainfo = get(state.ainfo_cache, arg_w, nothing) + if origin_ainfo === nothing + # A wrapper containing handles can be rebuilt even in its own space. + origin_ainfo = aliasing!(state, state.arg_origin[arg_w.arg], arg_w) + end + describes_memory(origin_ainfo)::Bool || return NoAliasing(), 0 + target_ainfo = aliasing!(state, target_space, arg_w) # An argument whose aliasing describes no memory is read-only and passed by diff --git a/test/gpu.jl b/test/gpu.jl index 94f81e1d8..a7a771206 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -14,6 +14,13 @@ end include(joinpath(@__DIR__, "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "array", "linalg", "matvec_defs.jl")) include(joinpath(@__DIR__, "gpu_distributed.jl")) +include(joinpath(@__DIR__, "noaliasing_gpu_defs.jl")) + +@testset "NoAliasing device arguments ($name)" for (name, scope) in GPU_SCOPES + cpu_proc = first(filter(p -> p isa Dagger.ThreadProc, + collect(Dagger.get_processors(Dagger.OSProc())))) + test_noaliasing_gpu(; src_scope=Dagger.ExactScope(cpu_proc), dst_scope=scope) +end @testset "Dense matvec ($name)" for (name, scope) in GPU_SCOPES Dagger.with_options(; scope) do diff --git a/test/mpi/gpu_suite.jl b/test/mpi/gpu_suite.jl index 3455a28f4..aa23e69e5 100644 --- a/test/mpi/gpu_suite.jl +++ b/test/mpi/gpu_suite.jl @@ -40,6 +40,7 @@ include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "..", "array", "linalg", "matvec_defs.jl")) +include(joinpath(@__DIR__, "..", "noaliasing_gpu_defs.jl")) # Broadcast-only mutation helpers (scalar indexing is illegal on GPU arrays) add1!(X) = (X .+= 1; nothing) @@ -97,6 +98,10 @@ function run_mpi_gpu_suite(cfg) mixed_scope() = Dagger.UnionScope(vcat([cpu_scope(r) for r in 0:nranks-1], [gpu_scope(r) for r in 0:nranks-1])...) + @testset "NoAliasing host-to-device arguments ($(cfg.name))" begin + test_noaliasing_gpu(; src_scope=cpu_scope(0), dst_scope=gpu_scope(min(1, nranks-1))) + end + # `Dagger.scope(; =1)` composed with `mpi_rank`/`worker` (or, with # neither, dispatched via the active `:mpi` acceleration) should reproduce # the scopes built manually above. diff --git a/test/noaliasing_gpu_defs.jl b/test/noaliasing_gpu_defs.jl new file mode 100644 index 000000000..a9cb49f79 --- /dev/null +++ b/test/noaliasing_gpu_defs.jl @@ -0,0 +1,110 @@ +# Shared NoAliasing host-to-device copy/lifetime checks, called by test/gpu.jl +# and test/mpi/gpu_suite.jl. Int32/Float32 keeps the payload portable to Metal +# and devices without Float64 support. +@everywhere begin + struct NoAliasGPUTile + value::Int32 + other::Float32 + end + Dagger.aliasing(::Vector{NoAliasGPUTile}) = Dagger.NoAliasing() + noalias_gpu_tiles(n) = [NoAliasGPUTile(Int32(i), Float32(i)) for i in 1:n] + const NOALIAS_GPU_TYPES = Set{Type}() + const NOALIAS_GPU_FREES = Threads.Atomic{Int}(0) + const NOALIAS_GPU_FREED = Set{UInt64}() + const NOALIAS_GPU_LOCK = ReentrantLock() + + function noalias_gpu_substitute(ex, T, wrapper) + ex === :NOALIAS_GPU_ARRAY && return T + ex === :NOALIAS_GPU_WRAPPER && return wrapper + if ex isa Expr + for i in eachindex(ex.args) + ex.args[i] = noalias_gpu_substitute(ex.args[i], T, wrapper) + end + end + return ex + end + function install_noalias_gpu_type!(T) + T in NOALIAS_GPU_TYPES && return + push!(NOALIAS_GPU_TYPES, T) + wrapper = Base.typename(T).wrapper + methods = quote + # The host type alone declares the by-value contract. Conversion + # to a device array must not introduce a delayed copy-in. + function Dagger.move!(::typeof(identity), ::Dagger.MemorySpace, + ::Dagger.MemorySpace, ::NOALIAS_GPU_ARRAY, + ::AbstractVector{NoAliasGPUTile}) + error("NoAliasing device slot received a delayed copy-in") + end + function Dagger.unsafe_free!(x::NOALIAS_GPU_ARRAY) + key = UInt64(Dagger.data_address(x)) + lock(NOALIAS_GPU_LOCK) do + push!(NOALIAS_GPU_FREED, key) + end + Threads.atomic_add!(NOALIAS_GPU_FREES, 1) + # Invoke the backend's ordinary array method, not this more + # specific test-element method. + invoke(Dagger.unsafe_free!, Tuple{NOALIAS_GPU_WRAPPER}, x) + end + end + Core.eval(@__MODULE__, noalias_gpu_substitute(methods, T, wrapper)) + return + end + function noalias_gpu_reset_freed!() + lock(NOALIAS_GPU_LOCK) do + empty!(NOALIAS_GPU_FREED) + end + return NOALIAS_GPU_FREES[] + end + noalias_gpu_frees() = NOALIAS_GPU_FREES[] + function noalias_gpu_all_freed(keys) + lock(NOALIAS_GPU_LOCK) do + return all(key -> key in NOALIAS_GPU_FREED, keys) + end + end + function noalias_gpu_read(x) + key = UInt64(Dagger.data_address(x)) + sleep(0.01) + live = lock(NOALIAS_GPU_LOCK) do + !(key in NOALIAS_GPU_FREED) + end + total = live ? mapreduce(t -> t.value, +, x; init=Int32(0)) : Int32(-1) + return total, length(x), key, live + end +end + +function test_noaliasing_gpu(; src_scope, dst_scope) + # Query the value's actual device type, including under MPI where the + # Chunk's logical type can deliberately remain its host source type. + T = fetch(Dagger.@spawn scope=dst_scope typeof(noalias_gpu_tiles(1))) + @test T <: Dagger.GPUArraysCore.AbstractGPUArray + @everywhere install_noalias_gpu_type!($T) + # The planner and old processor runners must see the newly installed hook. + Dagger.with_options(; scope=Dagger.UnionScope(src_scope, dst_scope)) do + Base.invokelatest(test_noaliasing_gpu_body; src_scope, dst_scope) + end +end +function test_noaliasing_gpu_body(; src_scope, dst_scope) + for hierarchical in (false, true) + @testset "by-value device copies hierarchical=$hierarchical" begin + before = fetch(Dagger.@spawn scope=dst_scope noalias_gpu_reset_freed!()) + input = Dagger.@spawn scope=src_scope noalias_gpu_tiles(32) + readers = Dagger.DTask[] + Dagger.spawn_datadeps(; hierarchical) do + for _ in 1:2 + push!(readers, Dagger.@spawn scope=dst_scope noalias_gpu_read(In(input))) + end + end + results = fetch.(readers) + @test all(r -> r[1] == 528 && r[2] == 32 && r[4], results) + keys = Tuple(r[3] for r in results) + @test fetch(Dagger.@spawn scope=dst_scope noalias_gpu_all_freed(keys)) + after = fetch(Dagger.@spawn scope=dst_scope noalias_gpu_frees()) + @test after - before == length(unique(keys)) + for dep in (Out, InOut) + @test_throws ArgumentError Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=dst_scope noalias_gpu_read(dep(input)) + end + end + end + end +end From 3b69d4be49b34cb0e9ccca931fe4f0a3cb4ecebf Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:10:39 -0700 Subject: [PATCH 20/27] Serialize reference fields reached through immutable wrappers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An immutable aggregate can expose a mutable child’s reference-valued field spans. Selecting remainder staging from only root mutability lets that child’s GC pointers enter the raw byte payload. Recurse through non-array field types, preserving ordinary direct-array staging. Five focused payload checks pass, including zeroed reference bytes and a serialization/scatter round trip preserving the destination’s other field. With 10 warmups, GC and 5 runs of 1000 trait calls, both old and new predicates allocate 0 objects/0 bytes for direct arrays and nested mutable field containers. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 8 ++++++++ src/datadeps/remainders.jl | 10 ++++++++-- test/datadeps.jl | 1 + test/field_deps_defs.jl | 22 ++++++++++++++++++++++ test/mpi/cpu.jl | 1 + 5 files changed, 40 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5b3d4d1b5..0938f0bda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1291,3 +1291,11 @@ this section verbatim). Each entry is one bullet starting with `- `. count assertion, or schedules an unordered copy into an already complete by-value slot. Test the host declaration alone; declaring the converted GPU type NoAliasing as well hides this failure. + +115. **Reference-safe remainder selection must look through immutable wrappers.** + A tuple has no mutable fields of its own, but its aliasing spans can reach + a mutable child's `Any` or `String` field. Selecting raw-byte staging from + only the root's mutability then copies that child's GC pointer. Recurse + through non-array field types when selecting `FieldRemainder`, and keep + direct arrays on their ordinary staging path. Check that nested reference + slots are zero in the byte payload as well as checking their copied values. diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 9a4f05af5..edd3fec0e 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -684,8 +684,14 @@ struct FieldRemainder end function remainder_needs_fields(::Type{T}) where T - ismutabletype(T) && !(T <: AbstractArray) || return false - return any(FT -> !isbitstype(FT), fieldtypes(T)) + T <: AbstractArray && return false + isbitstype(T) && return false + isconcretetype(T) || return true + fields = fieldtypes(T) + ismutabletype(T) && any(FT -> !isbitstype(FT), fields) && return true + # Immutable wrappers have no writable storage of their own, but their + # spans can reach a mutable child's reference-valued fields. + return any(remainder_needs_fields, fields) end function gather_field_remainder(from, spans) diff --git a/test/datadeps.jl b/test/datadeps.jl index 6b7ba78b0..86a254838 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1235,6 +1235,7 @@ include(joinpath(@__DIR__, "array", "sparse_defs.jl")) end include("field_deps_defs.jl") +@testset "Nested field remainder payload" test_nested_field_remainders() # The same body runs under MPI from test/mpi/cpu.jl. @testset "Isbits Field Dependencies" begin diff --git a/test/field_deps_defs.jl b/test/field_deps_defs.jl index 3c8ba217c..8c579bad0 100644 --- a/test/field_deps_defs.jl +++ b/test/field_deps_defs.jl @@ -110,3 +110,25 @@ function test_isbits_field_writes(; scope, reader_scope=scope, writeback_visible writeback_visible && @test X.value == 42 end end + +function test_nested_field_remainders() + # An immutable wrapper's spans can reach a mutable child's reference slot. + X = FlexibleFieldBox{Any}("before", 17) + wrapped = (X,) + @test Dagger.remainder_needs_fields(typeof(wrapped)) + spans = Dagger.memory_spans(Dagger.field_aliasing(X, :value)) + payload = Dagger.gather_field_remainder(wrapped, spans) + @test all(iszero, payload.bytes) + @test only(payload.values).second == "before" + # Round-trip the actual payload, rather than copying process-local pointer + # bytes. Scatter into a separate object while preserving its other field. + buffer = IOBuffer() + Dagger.serialize(buffer, payload) + seekstart(buffer) + received = Dagger.deserialize(buffer) + Y = FlexibleFieldBox{Any}("destination", 23) + dest_spans = Dagger.memory_spans(Dagger.field_aliasing(Y, :value)) + Dagger.scatter_field_remainder!((Y,), received, dest_spans) + @test Y.value == "before" + @test Y.other == 23 +end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 63e7e84c7..8da3d52cf 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -45,6 +45,7 @@ include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "..", "field_deps_defs.jl")) +@testset "Nested field remainder payload" test_nested_field_remainders() Dagger.accelerate!(:mpi) Dagger.check_uniformity!(true) From 9ea71deaab17a3ec9504edaeaf131b0d0845355a Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:12:28 -0700 Subject: [PATCH 21/27] Describe the private-copy user lookup after integration The helper now returns reader tasks for both cleanup ordering and result lifetime checks, rather than directly appending syncdeps. Match its docstring to that responsibility. Written by an AI agent on jpsamaroo's review feedback. --- src/datadeps/aliasing.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index be2de7d0f..21a7d2e11 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1627,10 +1627,10 @@ function add_unkeyed_user!(unkeyed::UnkeyedSlots, state::DataDepsState, arg_w::A end """ - push_copy_users_syncdeps!(state, key::CopyKey, syncdeps) + copy_users(state, key::CopyKey) -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`). +Return every task that used the slot holding `key`, so its region-end free +can wait for them and inspect their results (see `UnkeyedSlots`). """ function copy_users(state::DataDepsState, key::CopyKey) unkeyed = state.unkeyed_slots From 5c913271a681928e5c5376cd650cbe0c02a0c049 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:20:59 -0700 Subject: [PATCH 22/27] Keep tuple aggregates distinct from their shared child slots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Tuple or NamedTuple can describe exactly its mutable child’s field storage. Treating both as cache leaves lets one become the other’s slot, corrupting the argument-to-history mapping. Rebuild aggregates with the existing header/children protocol and copy their memory-bearing children in place for whole-object moves. Field/whole overlap in both access orders passes 48 Distributed assertions across three placements and 24 MPI assertions across two ranks, for both planners. The previous failure was a missing child-history key; adding the wrapper protocol also exposed the required whole-copy method. With the same test-only Tuple{Vector{Float64}} copy hook on both snapshots, 10 warmup batches plus GC and 5 samples of 10 regions measure driver+worker minimum allocations 78256→90249 and bytes 3832160→4391288. This is the cost of retaining separate aggregate headers while sharing child slots; ordinary scalar tuples bypass Datadeps slot processing. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 5 +++++ src/datadeps/aliasing.jl | 13 +++++++++++++ src/memory-spaces.jl | 18 ++++++++++++++++++ test/datadeps.jl | 2 ++ test/field_deps_defs.jl | 21 +++++++++++++++++++++ test/mpi/cpu.jl | 1 + 6 files changed, 60 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 0938f0bda..71c843439 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1218,6 +1218,11 @@ this section verbatim). Each entry is one bullet starting with `- `. *and* a remote writer, in both orders: in one process every slot is the argument itself, so none of this is visible. + Tuple and NamedTuple aggregates need the same treatment when a child's + field storage supplies all their memory. Rebuild their headers around + shared child slots, and provide whole-copy movement of memory-bearing + children; bitstype/by-value children are already complete in the slot. + 109. **Datadeps orders nothing on `NoAliasing`, so such arguments must be passed by value.** The dependency helpers (`_get_write_deps!` and friends) return early for a `NoAliasing` ainfo, so no task ever waits on such a slot diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 21a7d2e11..c9bfaa2f0 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1915,6 +1915,19 @@ move_rewrap_parts(x) = nothing move_rewrap_child_types(::Type) = nothing move_rewrap_header_mode(::Type) = :none +# Tuple aggregates share their children's storage without becoming a child's +# cached leaf slot when both describe exactly the same memory. +move_rewrap_parts(x::Tuple) = (x, nothing) +move_rewrap_build(::Type{<:Tuple}, children, ::Nothing) = children +move_rewrap_child_types(::Type{T}) where {T<:Tuple} = fieldtypes(T) +move_rewrap_result_type(::Type{<:Tuple}, child_types, ::Nothing) = Tuple{child_types...} +move_rewrap_parts(x::NamedTuple) = (values(x), nothing) +move_rewrap_build(::Type{<:NamedTuple{names}}, children, ::Nothing) where names = + NamedTuple{names}(children) +move_rewrap_child_types(::Type{T}) where {T<:NamedTuple} = fieldtypes(T) +move_rewrap_result_type(::Type{<:NamedTuple{names}}, child_types, ::Nothing) where names = + NamedTuple{names,Tuple{child_types...}} + # SubArray: parent payload + indices header move_rewrap_parts(x::SubArray) = ((parent(x),), parentindices(x)) move_rewrap_build(::Type{<:SubArray}, (p,), inds) = view(p, inds...) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 0446aad56..04d8e4721 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -181,6 +181,24 @@ function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::T, f end throw(ArgumentError("No `move!` implementation defined for $F -> $T")) end +# Aggregates cannot rebind their fields, but their memory-bearing children can +# be updated in place. No-memory children already arrived by value with the slot. +function move!(::typeof(identity), to_space::MemorySpace, from_space::MemorySpace, + to::Tuple, from::Tuple) + length(to) == length(from) || throw(DimensionMismatch("Tuple copy lengths differ")) + for i in eachindex(to) + from_child = from[i] + describes_memory(aliasing(from_child))::Bool || continue + move!(identity, to_space, from_space, to[i], from_child) + end + return +end +function move!(::typeof(identity), to_space::MemorySpace, from_space::MemorySpace, + to::NamedTuple, from::NamedTuple) + keys(to) == keys(from) || throw(ArgumentError("NamedTuple copy keys differ")) + return move!(identity, to_space, from_space, values(to), values(from)) +end + function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Chunk, from::Chunk) to_w = root_worker_id(to_space) remotecall_wait(to_w, dep_mod, to_space, from_space, to, from) do dep_mod, to_space, from_space, to, from diff --git a/test/datadeps.jl b/test/datadeps.jl index 86a254838..acca0bde2 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1243,11 +1243,13 @@ include("field_deps_defs.jl") @testset "hierarchical=$hierarchical" for hierarchical in (false, true) @testset "in place" test_isbits_field_writes(; hierarchical, scope=on(1)) @testset "reference fields in place" test_reference_field_writes(; hierarchical, scope=on(1)) + @testset "nested fields in place" test_nested_field_writes(; hierarchical, scope=on(1)) if nprocs() >= 3 w1, w2 = workers()[1], workers()[2] @testset "on another worker" test_isbits_field_writes(; hierarchical, scope=on(w1)) @testset "read on a third worker" test_isbits_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) @testset "reference fields across workers" test_reference_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) + @testset "nested fields across workers" test_nested_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) end end end diff --git a/test/field_deps_defs.jl b/test/field_deps_defs.jl index 8c579bad0..bef14291d 100644 --- a/test/field_deps_defs.jl +++ b/test/field_deps_defs.jl @@ -37,6 +37,8 @@ end field_set_value!(X::FlexibleFieldBox, x) = (X.value = x; nothing) field_get_value(X::FlexibleFieldBox) = X.value + field_get_nested_value(X::Union{Tuple,NamedTuple}) = first(X).value + field_set_nested_value!(X::Union{Tuple,NamedTuple}, value) = (first(X).value = value; nothing) field_set_ref!(R::Base.RefValue{Any}, x) = (R[] = x; nothing) function Dagger.move!(::typeof(identity), to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, to::FlexibleFieldBox{T}, from::FlexibleFieldBox{T}) where T @@ -132,3 +134,22 @@ function test_nested_field_remainders() @test Y.value == "before" @test Y.other == 23 end + +function test_nested_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) + for named in (false, true), whole_writer in (false, true) + X = FlexibleFieldBox{Any}("before", 17) + wrapped = named ? (; box=X) : (X,) + seen = nothing + Dagger.spawn_datadeps(; hierarchical) do + if whole_writer + Dagger.@spawn scope=scope field_set_nested_value!(InOut(wrapped), "nested") + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + else + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), "nested") + seen = Dagger.@spawn scope=reader_scope field_get_nested_value(In(wrapped)) + end + end + @test fetch(seen) == "nested" + writeback_visible && @test X.value == "nested" + end +end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 8da3d52cf..3d7290118 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -788,6 +788,7 @@ end test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), writeback_visible = rank == 0) test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(nranks-1), writeback_visible = rank == 0) test_reference_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(0), writeback_visible = rank == 0) + test_nested_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(0), writeback_visible = rank == 0) end @testset "Field aliasing" begin From 4658776162089ac47c72fb9036c733a835bf0f13 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:21:15 -0700 Subject: [PATCH 23/27] Check outer-scope coverage with explicit placement Ten zero-work tasks need not visit every eligible processor. The merged-master full Datadeps run passed 2297 assertions but hit the known baseline fixture failure when ThreadProc(2,2) was unused. Port the independently validated #841/#798 fixture: retain unpinned membership checks and exercise each eligible processor with one pinned task. Written by an AI agent on jpsamaroo's review feedback. --- test/datadeps.jl | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/datadeps.jl b/test/datadeps.jl index acca0bde2..e57243306 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1054,10 +1054,12 @@ function test_datadeps(;args_chunks::Bool, for proc in exec_procs @test proc in scope_procs end - for proc in scope_procs - proc == Dagger.ThreadProc(1, 1) && continue - @test proc in exec_procs - end + # The unpinned tasks may all finish on one eligible processor. Exercise + # each processor in the outer scope with an explicitly placed task. + scoped_procs = fetch.(Dagger.spawn_datadeps() do + [Dagger.@spawn scope=ExactScope(proc) Dagger.task_processor() for proc in scope_procs] + end) + @test scoped_procs == scope_procs # Inner Scope @test_throws Dagger.Sch.SchedulingException Dagger.spawn_datadeps() do From 2c0a2549df15e438c5e9ba224e67dc00fa41ad05 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:21:15 -0700 Subject: [PATCH 24/27] Count result-aware frees in cleanup log assertions Unkeyed copies now use free_unkeyed_copy! so returned views and containers retain their storage. Keep existing exact free-task counts and syncdep assertions by recognizing that cleanup entry point alongside unsafe_free!. The full Datadeps run exposed two false counts of 3 rather than 6 while all data and lifetime checks passed. Written by an AI agent on jpsamaroo's review feedback. --- test/datadeps.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/datadeps.jl b/test/datadeps.jl index e57243306..814032b5a 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1477,7 +1477,7 @@ end 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!" + _logs[:taskfuncnames][idx] in ("unsafe_free!", "free_unkeyed_copy!") push!(free_tids, _logs[:id][idx].thunk_id::Int) end end @@ -1591,7 +1591,7 @@ function count_free_tasks(logs) 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!" + _logs[:taskfuncnames][idx] in ("unsafe_free!", "free_unkeyed_copy!") n += 1 end end From f80fc622430ed3df4f679b749a7ba75aa130e683 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:45:16 -0700 Subject: [PATCH 25/27] Bound escaped-storage inspection across shared object graphs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A depth limit does not bound a shared DAG: cleanup revisited exponentially many paths and could stall the region indefinitely. Carry a 256-node work budget across children and returned values; conservatively leave storage to GC when it runs out. Count undefined array/struct slots too. Matching non-bits immutable payload/result types are retained without invoking potentially recursive ===. Shared DAG, cycle, sibling budget, undefined-slot, immutable comparison and existing escape/free checks pass: 17 Distributed and 42 MPI assertions across both planners. Profiles of the exact extracted helper use 10 warmups, GC and 5 samples. The 22-node DAG drops from minimum 8388606 allocations/268435392 bytes and 215.6 ms to 256/8192 and 7.3 μs; ordinary result tuples remain 6/192. Comparing two cloned immutable DAGs drops from 54.9 ms to 20 ns with zero allocations in both versions. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 10 +++++++ src/datadeps/aliasing.jl | 58 +++++++++++++++++++++++++------------ test/datadeps.jl | 1 + test/mpi/noaliasing_args.jl | 1 + test/noaliasing_defs.jl | 30 +++++++++++++++++++ 5 files changed, 81 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 71c843439..259e22645 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1304,3 +1304,13 @@ this section verbatim). Each entry is one bullet starting with `- `. through non-array field types when selecting `FieldRemainder`, and keep direct arrays on their ordinary staging path. Check that nested reference slots are zero in the byte payload as well as checking their copied values. + +116. **A depth limit does not bound a shared-graph walk.** Each node of a + small DAG can reference the same child twice, making recursive inspection + revisit exponentially many paths without approaching its depth limit. + Cleanup must also cap total visits and retain storage conservatively when + proof runs out. Pass the remaining work through sibling inspections and + returned values; resetting it on each edge does not bound the total work. + Even `===` can recursively compare non-bits immutable aggregates: avoid + that comparison for matching immutable payload/result types and retain + conservatively instead. diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index c9bfaa2f0..e3e117502 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1648,10 +1648,14 @@ function push_copy_users_syncdeps!(state::DataDepsState, key::CopyKey, syncdeps) return end +const UNKEYED_RETENTION_BUDGET = 256 + function free_unkeyed_copy!(copy::Chunk, results...) payload = unwrap(copy) + budget = UNKEYED_RETENTION_BUDGET for result in results - retains_unkeyed_storage(result, payload) && return + budget = unkeyed_retention_budget(result, payload, 0, budget) + budget < 0 && return end unsafe_free!(payload) return @@ -1659,41 +1663,57 @@ end # `NoAliasing` deliberately hides the copy's memory from dependency tracking, # so use object identity / Base's storage identities to inspect returned values. -# A bounded walk handles cycles conservatively without allocating a visited set: -# when uncertain, leave the allocation to its ordinary GC finalizer. -function retains_unkeyed_storage(result, payload, depth::Int=0) - result === payload && return true - depth >= 128 && return true +# Bound both depth and total visits: a shared DAG can expand exponentially even +# at a shallow depth. Exhaustion conservatively leaves storage to its GC owner. +retains_unkeyed_storage(result, payload, depth::Int=0) = + unkeyed_retention_budget(result, payload, depth, UNKEYED_RETENTION_BUDGET) < 0 + +# Negative means retain; otherwise return the budget left for the next child. +# Passing one integer through the walk avoids a visited set or mutable counter. +function unkeyed_retention_budget(result, payload, depth::Int, budget::Int)::Int + if typeof(result) === typeof(payload) + # Equality of non-bits immutable aggregates can recursively revisit a + # shared DAG before the walk even starts. A matching immutable type is + # sufficient uncertainty to retain; mutable values use pointer identity. + T = typeof(payload) + (!ismutabletype(T) && !isbitstype(T)) && return -1 + result === payload && return -1 + end + (budget <= 0 || depth >= 128) && return -1 + budget -= 1 if result isa Chunk - is_local(current_acceleration(), processor(result)) || return false - return retains_unkeyed_storage(unwrap(result), payload, depth + 1) + is_local(current_acceleration(), processor(result)) || return budget + return unkeyed_retention_budget(unwrap(result), payload, depth + 1, budget) elseif result isa AbstractArray if payload isa AbstractArray && Base.mightalias(result, payload) - return true + return -1 end p = parent(result) - if p !== result && retains_unkeyed_storage(p, payload, depth + 1) - return true + if p !== result + budget = unkeyed_retention_budget(p, payload, depth + 1, budget) + budget < 0 && return budget end - isbitstype(eltype(result)) && return false + isbitstype(eltype(result)) && return budget if result isa Array for i in eachindex(result) - isassigned(result, i) || continue - retains_unkeyed_storage(result[i], payload, depth + 1) && return true + child = isassigned(result, i) ? result[i] : nothing + budget = unkeyed_retention_budget(child, payload, depth + 1, budget) + budget < 0 && return budget end elseif p === result # An arbitrary non-bits array may prohibit scalar indexing. - return true + return -1 end elseif !(isbits(result) || result isa Union{String,Symbol,Type,Module}) T = typeof(result) - isstructtype(T) || return false + isstructtype(T) || return budget for i in 1:fieldcount(T) - isdefined(result, i) || continue - retains_unkeyed_storage(getfield(result, i), payload, depth + 1) && return true + child = isdefined(result, i) ? getfield(result, i) : nothing + budget = unkeyed_retention_budget(child, payload, depth + 1, budget) + budget < 0 && return budget end end - return false + return budget end function enqueue_cached_free!(state::DataDepsState, key::CopyKey, copy::Chunk, scope, syncdeps) diff --git a/test/datadeps.jl b/test/datadeps.jl index 814032b5a..d099aeaea 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1257,6 +1257,7 @@ include("field_deps_defs.jl") end include("noaliasing_defs.jl") +@testset "Bounded escaped-storage inspection" test_noaliasing_retention_budget() # The same bodies run under MPI from test/mpi/noaliasing_args.jl. @testset "NoAliasing Arguments" begin diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index a97d4bbb6..9f6e76d44 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -3,6 +3,7 @@ # rank. The bodies are shared with test/datadeps.jl; see test/noaliasing_defs.jl. include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) +@testset "Bounded escaped-storage inspection" test_noaliasing_retention_budget() @testset "NoAliasing Arguments" begin # Two values per rank, so that distinct values meet in one memory space. diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 9f1d8fecf..154c54e61 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -183,3 +183,33 @@ function test_immutable_field_write_rejected(; scope, hierarchical=nothing) Dagger.@spawn scope=scope noalias_touch(Deps(B, InOut(:value))) end end + +@everywhere begin + struct NoAliasRetentionNode + left::Any + right::Any + end + function noalias_retention_dag(n) + root = nothing + for _ in 1:n + root = NoAliasRetentionNode(root, root) + end + return root + end +end +function test_noaliasing_retention_budget() + payload = noalias_tiles(8) + @test !Dagger.retains_unkeyed_storage((1, :unrelated, nothing), payload) + @test Dagger.retains_unkeyed_storage(view(payload, :), payload) + # Only 22 unique nodes, but an unbounded recursive walk unfolds 2^23-1. + # This size still finishes promptly if the work bound regresses. + @test Dagger.retains_unkeyed_storage(noalias_retention_dag(22), payload) + cycle = Any[nothing] + cycle[1] = cycle + @test Dagger.retains_unkeyed_storage(cycle, payload) + # Every child fits individually, but their combined inspection is bounded. + siblings = ntuple(_ -> noalias_retention_dag(5), 5) + @test Dagger.retains_unkeyed_storage(siblings, payload) + @test Dagger.retains_unkeyed_storage(Vector{Any}(undef, 1000), payload) + @test Dagger.retains_unkeyed_storage(noalias_retention_dag(22), noalias_retention_dag(22)) +end From 150dbaa24d79e2411933e873e9d8191bfb9574ea Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:28:52 -0700 Subject: [PATCH 26/27] Retain copies returned through opaque owning handles A pending DTask can still use and later return the copied input while its future exposes only pool IDs. Treat work, future, pool and channel handles as owning unknown storage; do not wait or load their contents during cleanup. Nonlocal chunks and foreign mutable result objects can also hide storage in private tables, so leave those copies to GC. Keep array identities, local completed chunks and ordinary Core/Base containers inspectable. The gated child, owning-reference/future and opaque-ID-holder regression fails 7 of 11 assertions before the fix and passes afterwards. Focused suites pass 28 CPU and 64 MPI checks, including existing escape/view and explicit-free controls. With 10 warmups, GC and 5 samples of 1000 checks, pending-DTask inspection drops from 1000 allocations/16000 bytes to 0/0; ordinary tuples remain 6000/192000. A fully pinned 10-region driver+worker control measures minima 47490/2454304 bytes before and 45291/2355736 after. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 10 +++++++ src/datadeps/aliasing.jl | 17 +++++++++++- test/datadeps.jl | 1 + test/mpi/noaliasing_args.jl | 1 + test/noaliasing_defs.jl | 53 +++++++++++++++++++++++++++++++++++++ 5 files changed, 81 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 259e22645..3c4095758 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1314,3 +1314,13 @@ this section verbatim). Each entry is one bullet starting with `- `. Even `===` can recursively compare non-bits immutable aggregates: avoid that comparison for matching immutable payload/result types and retain conservatively instead. + +117. **An owning handle's fields do not reveal all the storage it retains.** + A pending `DTask` can keep an argument alive in its running work and return + it later, while its `DFuture`/`DRef` fields expose only pool identifiers. + Reflecting those fields claimed that the input did not escape, and a + Datadeps cleanup could free it while the child still used it. Treat known + work/future/pool/channel handles, foreign mutable values and nonlocal + chunks conservatively; do not block on pending work or load remote + storage merely to decide a free. Native and third-party objects can root + Julia storage through private tables without any visible field reference. diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index e3e117502..f8eab85a8 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1650,6 +1650,14 @@ end const UNKEYED_RETENTION_BUDGET = 256 +# These handles can own values or pending work through storage that field +# reflection cannot follow. Inspecting or waiting for them is not cleanup work. +opaque_retention_owner(x) = + x isa Union{DTask,Thunk,ThunkFuture,DFuture,DRef,FileRef,Future,RemoteChannel,Task,Channel} +@static if isdefined(MemPool, :DEvent) + opaque_retention_owner(::MemPool.DEvent) = true +end + function free_unkeyed_copy!(copy::Chunk, results...) payload = unwrap(copy) budget = UNKEYED_RETENTION_BUDGET @@ -1681,8 +1689,9 @@ function unkeyed_retention_budget(result, payload, depth::Int, budget::Int)::Int end (budget <= 0 || depth >= 128) && return -1 budget -= 1 + opaque_retention_owner(result) && return -1 if result isa Chunk - is_local(current_acceleration(), processor(result)) || return budget + is_local(current_acceleration(), processor(result)) || return -1 return unkeyed_retention_budget(unwrap(result), payload, depth + 1, budget) elseif result isa AbstractArray if payload isa AbstractArray && Base.mightalias(result, payload) @@ -1706,6 +1715,12 @@ function unkeyed_retention_budget(result, payload, depth::Int, budget::Int)::Int end elseif !(isbits(result) || result isa Union{String,Symbol,Type,Module}) T = typeof(result) + if ismutabletype(T) + mod = parentmodule(T) + # A foreign mutable value can own Julia storage through native or + # pool tables even when its visible fields contain only IDs. + (mod === Core || mod === Base) || return -1 + end isstructtype(T) || return budget for i in 1:fieldcount(T) child = isdefined(result, i) ? getfield(result, i) : nothing diff --git a/test/datadeps.jl b/test/datadeps.jl index d099aeaea..3e75a7960 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1258,6 +1258,7 @@ end include("noaliasing_defs.jl") @testset "Bounded escaped-storage inspection" test_noaliasing_retention_budget() +@testset "Pending handles retain escaped storage" test_noaliasing_pending_handles() # The same bodies run under MPI from test/mpi/noaliasing_args.jl. @testset "NoAliasing Arguments" begin diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index 9f6e76d44..945e663a0 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -4,6 +4,7 @@ include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) @testset "Bounded escaped-storage inspection" test_noaliasing_retention_budget() +@testset "Pending handles retain escaped storage" test_noaliasing_pending_handles() @testset "NoAliasing Arguments" begin # Two values per rank, so that distinct values meet in one memory space. diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl index 154c54e61..8cb531625 100644 --- a/test/noaliasing_defs.jl +++ b/test/noaliasing_defs.jl @@ -213,3 +213,56 @@ function test_noaliasing_retention_budget() @test Dagger.retains_unkeyed_storage(Vector{Any}(undef, 1000), payload) @test Dagger.retains_unkeyed_storage(noalias_retention_dag(22), noalias_retention_dag(22)) end + +@everywhere begin + mutable struct NoAliasOpaqueHolder + key::UInt + end + const NOALIAS_OPAQUE_ROOTS = Dict{UInt,Any}() +end + +@everywhere function noalias_pending_return(payload, started, gate) + notify(started) + Dagger.Sch.thunk_yield() do + wait(gate) + end + return payload +end + +function test_noaliasing_pending_handles() + # This local graph uses the Distributed backend on every MPI rank too: + # asynchronous handles are inspected without collective fetches or waits. + Dagger.with_options(; acceleration=Dagger.DistributedAcceleration()) do + payload = Dagger.alloc_libc_array(NoAliasTile, 8) + fill!(payload, NoAliasTile(1.0, 1)) + started = Base.Event() + gate = Base.Event() + child = Dagger.@spawn scope=Dagger.scope(worker=1) noalias_pending_return(payload, started, gate) + holder = NoAliasOpaqueHolder(UInt(0)) + holder.key = objectid(holder) + NOALIAS_OPAQUE_ROOTS[holder.key] = payload + try + wait(started) + @test !istaskdone(child) + @test Dagger.retains_unkeyed_storage(child, payload) + @test Dagger.retains_unkeyed_storage((child,), payload) + @test Dagger.retains_unkeyed_storage((holder,), payload) + @test NOALIAS_OPAQUE_ROOTS[holder.key] === payload + ref = Dagger.MemPool.poolset(payload) + @test Dagger.retains_unkeyed_storage((ref,), payload) + future = Dagger.ThunkFuture() + @test Dagger.retains_unkeyed_storage(future, payload) + @test Dagger.retains_unkeyed_storage(future.future, payload) + @static if isdefined(Dagger.MemPool, :DFuture) && isdefined(Dagger.MemPool, :DEvent) + @test Dagger.retains_unkeyed_storage(future.future.event, payload) + end + put!(future, payload) + @test fetch(future; move_value=false) === payload + finally + delete!(NOALIAS_OPAQUE_ROOTS, holder.key) + notify(gate) + @test fetch(child) === payload + Dagger.unsafe_free!(payload) + end + end +end From 1b865182bb84f21f13ecc784a42133f05cc8280e Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:28:52 -0700 Subject: [PATCH 27/27] Distinguish immutable field bindings from mutable contents An immutable field cannot be rebound, but a memory-bearing value reached through it may still be written in place. Align the manual with field_aliasing and retain the In-only rule for isbits fields. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/datadeps.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/src/datadeps.md b/docs/src/datadeps.md index 32bf30057..8642122e3 100644 --- a/docs/src/datadeps.md +++ b/docs/src/datadeps.md @@ -214,8 +214,9 @@ A field dependency covers different memory depending on the field: - A field referring to another memory-bearing object (an array, say) also covers that object. Writing *into* it (e.g. `X.v .= 0`) is tracked while its backing storage remains fixed; replacing or resizing that storage is not. -- A field of an immutable struct cannot be written. An isbits one describes no - memory, so it may only be read (`In`). +- A field of an immutable struct cannot be rebound. Writes into a memory-bearing + field value remain supported. An isbits field describes no memory, so it may + only be read (`In`). ## In-place data movement rules