From 210097d94d8e15573b265c693172062c2d924013 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:41:04 -0700 Subject: [PATCH 1/8] datadeps: link arguments whose aliasing is identical `populate_ainfo!` links a new argument to every argument it overlaps, so a write through one records history on the other. But it only does so when the argument's aliasing is new: the overlap search skips equal ainfos, and the whole block is skipped when the ainfo is already known. Two *distinct* arguments with exactly the same aliasing (`transpose(A)` and `A`, or `reshape(A, n)` and `A`) were therefore never linked. The second one then had no history and its owner was still its origin, so when a task on worker 2 wrote `InOut(A)` and a later task on worker 2 read `In(transpose(A))`, the read was preceded by a full copy from the stale origin into the shared slot, overwriting the write: the reader saw the old values and the write was lost on copy-back. Link the new argument to every argument of every ainfo overlapping the known one, itself included, merging their history once per pair. This only runs when a different argument has already registered the same ainfo, so the common path (one argument per memory) is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- src/datadeps/aliasing.jl | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index cfce21de5..4a808dbcc 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1045,6 +1045,27 @@ function populate_ainfo!(state::DataDepsState, original_arg_w::ArgumentWrapper, # Initialize owner and readers state.ainfos_owner[target_ainfo] = nothing state.ainfos_readers[target_ainfo] = Pair{DTask,Int}[] + else + # The ainfo is already known, but `original_arg_w` may not be: a + # *different* argument with exactly this aliasing registered it + # (`transpose(A)` and `A`, or `reshape(A, n)` and `A`). The overlap + # search above never sees that argument, since it skips equal ainfos, + # so without this the two would not be linked: a write through one + # would leave no history on the other, which would then be "refreshed" + # from its stale origin, overwriting the write. Link this argument to + # every argument of every ainfo overlapping this one, itself included. + for other_ainfo in state.ainfos_overlaps[target_ainfo] + for other_remote_arg_w in state.ainfo_arg[other_ainfo] + other_arg = state.remote_arg_to_original[other_remote_arg_w.arg] + other_arg_w = ArgumentWrapper(other_arg, other_remote_arg_w.dep_mod) + other_arg_w == original_arg_w && continue + if !(other_arg_w in state.arg_overlaps[original_arg_w]) + push!(state.arg_overlaps[original_arg_w], other_arg_w) + push!(state.arg_overlaps[other_arg_w], original_arg_w) + merge_history!(state, original_arg_w, other_arg_w) + end + end + end end end function merge_history!(state::DataDepsState, arg_w::ArgumentWrapper, other_arg_w::ArgumentWrapper) From f6e7ee4d2368ee45d668e8c79901b7fbbc1ff949 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:41:16 -0700 Subject: [PATCH 2/8] datadeps: an in-place slot is the argument itself, not the cache's value When an argument already lives in the destination space, `generate_slot!` skips `move_rewrap` and uses the argument as its own slot. It still routed the argument through `aliased_object!` to record it in the aliased-object cache, but then used whatever that call returned -- which, on a cache hit, is the object some *other* argument registered for the same aliasing key. A `Transpose` has exactly its parent's aliasing, so the origin-space slot of `transpose(A)` could come back as `A` itself. Copies out of the origin then read the `Matrix` into a destination `Transpose` (or vice versa), and the data arrived transposed: a region reading `In(transpose(A))` and then writing `InOut(A)` on worker 2 wrote `A[2,1]` instead of `A[1,2]`. Use the argument itself as the slot, as the comment above already says, and register only leaves: `move_rewrap` caches only leaves and rebuilds wrappers around them, so a wrapper registered here could be handed out as a later argument's *parent* copy. The decision is by type (`chunktype`), so it is uniform across MPI ranks, and a wrapper now skips the (collective) aliasing query that registering it used to make. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- src/datadeps/aliasing.jl | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 4a808dbcc..cb7085e15 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1457,10 +1457,20 @@ function generate_slot!(state::DataDepsState, dest_space, data) # 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 # (and DRef) over the very same memory, which costs a MemPool round-trip - # per argument per region and buys nothing. Still route through + # per argument per region and buys nothing. Still route a leaf through # `aliased_object!` so the cache records this object as the (never-freed) # original for its aliasing key, exactly as the general path does. - aliased_object!(Returns(data), aliased_object_cache, data)::Chunk + # + # N.B. The slot is `data` itself, never the cache's value: another + # argument with the same aliasing key may have registered a different + # object for it (a `Transpose`'s key is its parent's). And only a leaf + # may be registered, because `move_rewrap` caches only leaves and + # rebuilds wrappers around them; a wrapper registered here would be + # handed out as some later argument's parent copy. + if move_rewrap_child_types(chunktype(data)) === nothing + aliased_object!(Returns(data), aliased_object_cache, data)::Chunk + end + data else moved = with(DATADEPS_THUNK_ID=>tid) do remotecall_endpoint_toplevel(move_rewrap, current_acceleration(), aliased_object_cache, from_proc, to_proc, orig_space, dest_space, data) From 12c836999e30cac6bc84b55a7722b13f2cafc79e Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:41:36 -0700 Subject: [PATCH 3/8] datadeps: move Transpose and Adjoint as wrappers of their parent Datadeps shares one copy of each piece of memory per memory space through its aliased-object cache, keyed by aliasing. `move_rewrap` decomposes known wrappers (`SubArray`, the triangular types) and caches only the leaf, then rebuilds each wrapper around the shared leaf copy. `Transpose` and `Adjoint` were not registered, so they were cached as leaves -- and because their aliasing is exactly their parent's, a wrapper and its parent shared one cache entry. Whichever reached a space first became the slot of the other: a task asking for `InOut(A)` on worker 2 after one reading `In(transpose(A))` received a `Transpose` (its `x[1,2] += 10` landed in `A[2,1]`), and in the other order the transpose task received the plain `Matrix`. Register both with the `move_rewrap` header/children protocol (no header, the parent as the only child), like the triangular wrappers, so each argument gets a slot of its own type around the one shared parent copy. The protocol is shared by the Distributed and MPI paths and the decision is type-level, so it stays rank-uniform. The result type comes from `promote_op` rather than `{eltype(PT),PT}`, since a transpose's eltype is the transposed element type for nested arrays. Remainder (partial) copies also forward through both wrappers to their parent, as they already do for `SubArray` and the triangular types; without that, a remainder copy into a transposed slot hit `find_object_holding_ptr`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- src/datadeps/aliasing.jl | 18 ++++++++++++++++++ src/datadeps/remainders.jl | 5 +++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index cb7085e15..ae51713f6 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1592,6 +1592,24 @@ for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLower end end +# Transpose/Adjoint: parent payload, empty header. These must not be leaves: +# their `aliasing` *is* their parent's, so as leaves a wrapper and its parent +# shared one aliased-object cache key, and whichever reached a space first +# became the other's slot (a `Transpose` handed to a task asking for the +# `Matrix`, or vice versa). As wrappers, only the parent is cached, and each +# argument gets its own wrapper rebuilt around the shared copy. +for wrapper in (Transpose, Adjoint) + @eval begin + move_rewrap_parts(x::$wrapper) = ((parent(x),), nothing) + move_rewrap_build(::Type{<:$wrapper}, (p,), ::Nothing) = $wrapper(p) + move_rewrap_child_types(::Type{T}) where {T<:$wrapper} = (T.parameters[2],) + # N.B. Not `$wrapper{eltype(PT),PT}`: the wrapper's eltype is the + # transposed/adjointed element type, which differs for nested arrays. + move_rewrap_result_type(::Type{<:$wrapper}, (PT,), ::Nothing) = + Base.promote_op($wrapper, PT) + end +end + # Nested Chunk: unwrap on the owner and recurse move_rewrap(accel, cache::AliasedObjectCache, from_proc::Processor, to_proc::Processor, from_space::MemorySpace, to_space::MemorySpace, data::Chunk) = remotecall_endpoint_toplevel(move_rewrap, accel, cache, from_proc, to_proc, from_space, to_space, data) diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 509da2f8e..28f794cdc 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -675,8 +675,9 @@ function write_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, to, to_p return write_remainder!(copies, copies_offset, real_to, to_ptr, n) end -# Remainder copies for common objects -for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular, SubArray) +# Remainder copies for common objects: each wrapper's spans lie in its parent +for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular, SubArray, + Transpose, Adjoint) @eval function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from::$wrapper, from_ptr::UInt64, n::UInt64) read_remainder!(copies, copies_offset, parent(from), from_ptr, n) end From 76bf5ba4f41bfd6307806319ab58e63aa5998fe3 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:41:49 -0700 Subject: [PATCH 4/8] datadeps: move PermutedDimsArray and ReshapedArray as wrappers too Neither has an `aliasing` method of its own; the generic struct fallback describes each by its parent's memory. But `move_rewrap` treated them as leaves and moved them whole, so in a destination space each got a *private* copy of its parent's memory, separate from the parent's own slot there. Dependency tracking assumes one copy of any memory per space, so the two copies silently diverged: after a remote `InOut(A)`, a remote read of `PermutedDimsArray(A, (2, 1))` saw the old values, and other orders failed span assertions ("Spans only partially match") during remainder copies. Register both with the `move_rewrap` protocol so they share the parent's copy, as `Transpose`/`Adjoint` now do. `PermutedDimsArray`'s permutation is a type parameter, so it needs no header; a `ReshapedArray`'s shape is a value, so it travels as a broadcast header (the `SubArray` mode). Remainder copies forward through both to their parent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- src/datadeps/aliasing.jl | 23 +++++++++++++++++++++++ src/datadeps/remainders.jl | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index ae51713f6..aa34e7057 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1610,6 +1610,29 @@ for wrapper in (Transpose, Adjoint) end end +# PermutedDimsArray and ReshapedArray have no `aliasing` method of their own; +# the generic struct fallback describes them by their parent's memory. As +# leaves they were therefore *moved whole*, giving each one a private copy of +# its parent's memory in the destination space, which the dependency tracking +# (which assumes one copy of any memory per space) cannot keep coherent: a +# write through the parent was invisible to the wrapper, and vice versa. As +# wrappers they share the parent's copy. +# +# PermutedDimsArray: the permutation is a type parameter, so no header is needed +move_rewrap_parts(x::PermutedDimsArray) = ((parent(x),), nothing) +move_rewrap_build(::Type{<:PermutedDimsArray{T,N,perm}}, (p,), ::Nothing) where {T,N,perm} = + PermutedDimsArray(p, perm) +move_rewrap_child_types(::Type{T}) where {T<:PermutedDimsArray} = (T.parameters[5],) +move_rewrap_result_type(::Type{<:PermutedDimsArray{T,N,perm,iperm}}, (PT,), ::Nothing) where {T,N,perm,iperm} = + PermutedDimsArray{eltype(PT),N,perm,iperm,PT} +# ReshapedArray: the shape is a value, so it is carried as the header +move_rewrap_parts(x::Base.ReshapedArray) = ((parent(x),), size(x)) +move_rewrap_build(::Type{<:Base.ReshapedArray}, (p,), dims) = reshape(p, dims) +move_rewrap_child_types(::Type{T}) where {T<:Base.ReshapedArray} = (T.parameters[3],) +move_rewrap_header_mode(::Type{<:Base.ReshapedArray}) = :broadcast +move_rewrap_result_type(::Type{<:Base.ReshapedArray}, (PT,), dims) = + Base.promote_op(reshape, PT, typeof(dims)) + # Nested Chunk: unwrap on the owner and recurse move_rewrap(accel, cache::AliasedObjectCache, from_proc::Processor, to_proc::Processor, from_space::MemorySpace, to_space::MemorySpace, data::Chunk) = remotecall_endpoint_toplevel(move_rewrap, accel, cache, from_proc, to_proc, from_space, to_space, data) diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 28f794cdc..da9468339 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -677,7 +677,7 @@ end # Remainder copies for common objects: each wrapper's spans lie in its parent for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular, SubArray, - Transpose, Adjoint) + Transpose, Adjoint, PermutedDimsArray, Base.ReshapedArray) @eval function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from::$wrapper, from_ptr::UInt64, n::UInt64) read_remainder!(copies, copies_offset, parent(from), from_ptr, n) end From 8105f08bd1e69a320ebcd18e4d6e71dfcda52a94 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:46:42 -0700 Subject: [PATCH 5/8] test: wrappers and their parents share one Datadeps slot Regression tests for the wrapper-slot fixes. `test/datadeps.jl` runs short read/write sequences on a remote worker through a wrapper and its parent -- both orders, writes through either side, a local reader after a remote writer, and a partial (remainder) write -- for `Transpose`, `Adjoint` (real and complex), `PermutedDimsArray`, `ReshapedArray`, a transpose of a view, and `SubArray` as a control, under both planners. Every read and the final array are compared with running the same sequence serially. On master, 72 of the 192 checks fail and 30 error; all 252 pass now. `test/gpu.jl` covers host data with a device task in the same region, per backend in `GPU_SCOPES`: on master, a host read of `transpose(A)` followed by a device write of `A` fails with scalar indexing, and the other orders read stale data. Run against CUDA (RTX 5060, Julia 1.11): errors on master, 8/8 pass with the fixes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- test/datadeps.jl | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ test/gpu.jl | 53 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) diff --git a/test/datadeps.jl b/test/datadeps.jl index a7d020350..3b36c1036 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1312,3 +1312,66 @@ end end end end + +@everywhere wrapper_bump!(x, idx...) = (x[idx...] += 10; nothing) +@everywhere wrapper_snapshot(x) = (typeof(x), collect(x)) +@testset "Wrappers share their parent's slot" begin + # `transpose(A)` has exactly `A`'s aliasing, and a `PermutedDimsArray` or + # `ReshapedArray` is described by its parent's memory. Datadeps must give + # each such argument a slot of its own type, built around the *same* copy + # of the parent's memory as every other argument touching it, so a write + # through one is seen through the other. Each case runs a sequence of + # reads and writes, through the wrapper and its parent, and compares every + # read and the final array against running the same sequence serially. + # (On master, a remote `InOut(A)` after `In(transpose(A))` wrote `A[2,1]`.) + if nprocs() >= 2 + w = workers()[1] + P = A -> A + Vs = A -> view(A, 1:2, 1:2) + wrappers = [ + ("Transpose", A -> transpose(A), (2, 1), Float64), + ("Adjoint", A -> adjoint(A), (2, 1), Float64), + ("Adjoint (complex)", A -> adjoint(A), (2, 1), ComplexF64), + ("PermutedDimsArray", A -> PermutedDimsArray(A, (2, 1)), (2, 1), Float64), + ("ReshapedArray", A -> reshape(view(A, 1:3, 1:2), 6), (4,), Float64), + ("Transpose of a SubArray", A -> transpose(view(A, 1:3, 1:3)), (2, 1), Float64), + ("SubArray", A -> view(A, 1:2, 1:3), (1, 2), Float64), + ] + for hierarchical in (true, false) + @testset "$name (hierarchical=$hierarchical)" for (name, Wr, widx, T) in wrappers + sequences = [ + "read wrapper, write parent" => [(Wr, :R, (), w), (P, :W, (1, 2), w)], + "write parent, read wrapper" => [(P, :W, (1, 2), w), (Wr, :R, (), w)], + "write wrapper, read parent" => [(Wr, :W, widx, w), (P, :R, (), w)], + "read parent, write wrapper" => [(P, :R, (), w), (Wr, :W, widx, w)], + "write parent remotely, read wrapper locally" => [(P, :W, (1, 2), w), (Wr, :R, (), 1)], + "write part remotely, read wrapper" => [(Vs, :W, (1, 2), w), (Wr, :R, (), w)], + ] + @testset "$seq_name" for (seq_name, ops) in sequences + A = reshape(T <: Complex ? T.(1:9, 1:9) : T.(1:9), 3, 3) + B = copy(A) + expected = Any[] + for (mk, mode, idx, _) in ops + mode == :W ? wrapper_bump!(mk(B), idx...) : push!(expected, wrapper_snapshot(mk(B))) + end + reads = DTask[] + Dagger.spawn_datadeps(; hierarchical) do + for (mk, mode, idx, wid) in ops + scope = Dagger.scope(worker=wid) + if mode == :W + Dagger.@spawn scope=scope wrapper_bump!(InOut(mk(A)), idx...) + else + push!(reads, Dagger.@spawn scope=scope wrapper_snapshot(In(mk(A)))) + end + end + end + for (r, e) in zip(map(fetch, reads), expected) + @test r[1] == e[1] + @test r[2] == e[2] + end + @test A == B + end + end + end + end +end diff --git a/test/gpu.jl b/test/gpu.jl index 4f19c1d55..b28a69e64 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -21,6 +21,59 @@ include(joinpath(@__DIR__, "gpu_distributed.jl")) end end +@everywhere begin + wrapper_gpu_add!(x) = (x .+= 1f0; nothing) + wrapper_gpu_copy!(dst, src) = (dst .= src; nothing) +end +@testset "Datadeps wrapper and parent with a GPU task ($name)" for (name, scope) in GPU_SCOPES + # `transpose(A)` shares `A`'s aliasing. Each argument must still get a + # slot of its own type, around one shared copy of `A`'s memory per space. + # Before, a host read of `transpose(A)` followed by a device write of `A` + # handed one argument the other's slot, and the copy into the device slot + # failed with scalar indexing. + host = Dagger.scope(worker=1, thread=1) + A0 = reshape(Float32.(1:16), 4, 4) + Dagger.with_options(; scope=Dagger.UnionScope(host, scope)) do + # Host reads the transpose, then the device writes the parent + A = copy(A0) + local r + Dagger.spawn_datadeps() do + r = Dagger.@spawn scope=host collect(In(transpose(A))) + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(A)) + end + @test fetch(r) == transpose(A0) + @test A == A0 .+ 1f0 + + # Device writes the parent, then the host reads the transpose + A = copy(A0) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(A)) + r = Dagger.@spawn scope=host collect(In(transpose(A))) + end + @test fetch(r) == transpose(A0 .+ 1f0) + @test A == A0 .+ 1f0 + + # Device writes the parent, then the device reads the transpose + A = copy(A0) + B = zeros(Float32, 4, 4) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(A)) + Dagger.@spawn scope=scope wrapper_gpu_copy!(Out(B), In(transpose(A))) + end + @test B == transpose(A0 .+ 1f0) + @test A == A0 .+ 1f0 + + # Device writes through the transpose, then the host reads the parent + A = copy(A0) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(transpose(A))) + r = Dagger.@spawn scope=host copy(In(A)) + end + @test fetch(r) == A0 .+ 1f0 + @test A == A0 .+ 1f0 + end +end + @testset "DArray reductions ($name)" for (name, scope) in GPU_SCOPES Dagger.with_options(; scope) do DA = rand(Blocks(4, 4), Float32, 16, 16) From de2e58d5401b6d52f94120e3fc41bdb5b8c60327 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 20:46:42 -0700 Subject: [PATCH 6/8] AGENTS.md: lesson 103, a wrapper reaches the slot cache only through its leaf Records the three places that assumed one argument per aliasing key, the opposite failure of generic-struct wrappers, the two wrappers this does not fix (`reshape(::Array)` and `Symmetric`/`Hermitian`), and how to test it. Numbered 103 to avoid colliding with lessons in other open PRs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- AGENTS.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 61b1c43b8..d1cb4e10a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1023,3 +1023,28 @@ 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`. + +103. **A wrapper reaches the aliased-object cache only through its leaf, and + two arguments can share one aliasing exactly.** `transpose(A)`'s + `aliasing` *is* `A`'s, and three places assumed one argument per aliasing + key. `move_rewrap` cached unregistered wrappers as leaves, so `Transpose` + and `A` shared a cache entry and one received the other's slot: a remote + `InOut(A)` after `In(transpose(A))` got a `Transpose`, and its + `x[1,2] += 10` landed in `A[2,1]`. `generate_slot!`'s in-place path + returned the cache's value rather than the argument, so a copy's + origin-space source could be the *other* argument, and the data arrived + transposed. And `populate_ainfo!` links arguments only when an ainfo is + new, so a second argument with an *equal* ainfo had no history and was + "refreshed" from its stale origin over a write. Wrappers that use the + generic struct `aliasing` (`PermutedDimsArray`, `ReshapedArray`) fail the + opposite way: their key differs from the parent's, so as leaves each got + a private copy of the parent's memory in a space that must hold only one. + Any wrapper whose memory is its parent's needs the `move_rewrap` protocol + and remainder forwarding; the cache holds only leaves. Two gaps remain: + `reshape(A::Array, n)` is a second *leaf* over `A`'s memory with a + different shape, which the cache cannot tell apart without per-hit shape + information (a collective under MPI); and `Symmetric`/`Hermitian` claim + the whole parent while `copyto!` between them copies one triangle, so + the protocol alone is not enough for them. Test with a remote reader + *and* a remote writer, in both orders: in one process every slot is the + argument itself, so none of this is visible. From b652f10e8b4df4cb83773d0eeddc7390332c9005 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 21:04:00 -0700 Subject: [PATCH 7/8] test/mpi: wrappers and their parents share one slot across ranks Mirrors the Distributed "Wrappers share their parent's slot" testset through the MPIWireValue `move_rewrap` path: `Transpose`, `Adjoint`, `PermutedDimsArray` and `ReshapedArray` read and written across ranks, with rank 0 checking the write-backs and every read against a serial run. On master (2 ranks x 2 threads) 13 checks fail and 2 error, including the transposed write (`A[2,1]` instead of `A[1,2]`); the full CPU MPI suite passes here (1147 and 1182 on the two ranks). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr --- test/mpi/cpu.jl | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 6ba4aded8..8b8e91532 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -451,6 +451,62 @@ end end end +# A wrapper whose memory is its parent's (`transpose(A)` has exactly `A`'s +# aliasing) must get a slot of its own type around the *one* copy of the +# parent per rank. Mirrors the Distributed "Wrappers share their parent's +# slot" testset, through the MPIWireValue `move_rewrap` path. +wrapper_bump!(x, idx...) = (x[idx...] += 10; nothing) +wrapper_snap!(dst, x) = (dst .= x; nothing) +@testset "Cross-rank wrapper dataflow" begin + r1 = min(1, nranks-1) + r2 = min(2, nranks-1) + P = A -> A + wrappers = [ + ("Transpose", A -> transpose(A), (2, 1)), + ("Adjoint", A -> adjoint(A), (2, 1)), + ("PermutedDimsArray", A -> PermutedDimsArray(A, (2, 1)), (2, 1)), + ("ReshapedArray", A -> reshape(view(A, 1:3, 1:2), 6), (4,)), + ] + @testset "$name" for (name, Wr, widx) in wrappers + sequences = [ + [(Wr, :R, (), r1), (P, :W, (1, 2), r1)], + [(P, :W, (1, 2), r1), (Wr, :R, (), r1)], + [(Wr, :W, widx, r1), (P, :R, (), r2)], + [(P, :W, (1, 2), r1), (Wr, :R, (), 0)], + ] + for ops in sequences + A = reshape(collect(1.0:9.0), 3, 3) + B = copy(A) + expected = Any[] + outs = Any[] + for (mk, mode, idx, _) in ops + if mode == :W + wrapper_bump!(mk(B), idx...) + else + push!(expected, collect(mk(B))) + push!(outs, zeros(size(mk(B)))) + end + end + Dagger.spawn_datadeps() do + i = 0 + for (mk, mode, idx, r) in ops + if mode == :W + Dagger.@spawn scope=rank_scope(r) wrapper_bump!(InOut(mk(A)), idx...) + else + i += 1 + Dagger.@spawn scope=rank_scope(r) wrapper_snap!(Out(outs[i]), In(mk(A))) + end + end + end + # Rank 0 owns the original arguments and receives the write-backs + if rank == 0 + @test A == B + @test outs == expected + end + end + end +end + @testset "ChunkView dataflow" begin # Views over a DArray block as datadeps arguments, mixed with whole-chunk # access (exercises cross-rank remainder copies through the shared backing From 3c4a4e1d816041c7bae9b7e7356ba628237f5e1d Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:37:26 -0700 Subject: [PATCH 8/8] Datadeps: copy whole-object wrappers from the latest writer Review finding 1 on PR #840 (blocker): Linking equal-aliasing arguments makes a DSparseArray used next to transpose(D) or view(D) fail with an AssertionError, including an order that worked on master Requested: Fix before merge: a whole-object container and a wrapper of it in one region must work in both orders, with the wrapper still treated as aliasing the whole object (e.g. skip the new equal-aliasing linking for whole-object aliasing, or source that copy from the latest history entry); add a test for both orders. Use the latest overlapping history entry to choose the source space and transfer the aliasing root so a narrow view cannot mark untouched parts of its parent current. Cover both access orders for transpose and view, with either the parent or wrapper writing, on Distributed and MPI. The focused Distributed tests pass all 32 assertions under both planners. On Julia 1.12.6, minimum driver allocations after ten warmup regions and GC before each of five samples were 4,908 to 5,010 (246,744 to 251,720 bytes) for a remotely written sparse container and 4,858 to 5,032 (241,320 to 249,624 bytes) for the dense matrix control. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 6 ++++- ext/MPIExt.jl | 10 ++++---- src/datadeps/hierarchical.jl | 2 +- src/datadeps/queue.jl | 4 ++-- src/datadeps/remainders.jl | 45 ++++++++++++++++++------------------ src/memory-spaces.jl | 6 ++++- test/datadeps.jl | 35 ++++++++++++++++++++++++++++ test/mpi/cpu.jl | 33 ++++++++++++++++++++++++++ 8 files changed, 109 insertions(+), 32 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d1cb4e10a..c7361a611 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1040,7 +1040,11 @@ lesson. opposite way: their key differs from the parent's, so as leaves each got a private copy of the parent's memory in a space that must hold only one. Any wrapper whose memory is its parent's needs the `move_rewrap` protocol - and remainder forwarding; the cache holds only leaves. Two gaps remain: + and remainder forwarding; the cache holds only leaves. For a whole-object + container such as `DSparseArray`, use the latest overlapping history entry + to find the source space. Copy the aliasing root itself: a view's copy + would update only part of the destination while marking the entire + container current. Two gaps remain: `reshape(A::Array, n)` is a second *leaf* over `A`'s memory with a different shape, which the cache cannot tell apart without per-hit shape information (a collective under MPI); and `Symmetric`/`Hermitian` claim diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 0d2d640ab..cfff05b6b 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1693,7 +1693,8 @@ function move!(dep_mod, to_space::MPIMemorySpace, from_space::MPIMemorySpace, to # source handle's tag outside of task context 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 dep_mod === identity + # A whole-object wrapper transports its aliasing root as a full value. + if dep_mod === identity || dep_mod === Dagger.aliasing_root # Below the crossover, handle+ack overhead makes host staging # competitive; each side checks its own (equal-sized) buffer local_nbytes = local_rank == from_space.rank ? from.handle.size : @@ -1710,15 +1711,16 @@ function move!(dep_mod, to_space::MPIMemorySpace, from_space::MPIMemorySpace, to end # Full copy: receive directly into the destination buffer when possible elseif local_rank == from_space.rank - send_yield!(poolget(from.handle; uniform=false), to_space.comm, to_space.rank, tag) + from_val = dep_mod(poolget(from.handle; uniform=false)) + send_yield!(from_val, to_space.comm, to_space.rank, tag) elseif local_rank == to_space.rank - to_val = poolget(to.handle; uniform=false) + to_val = dep_mod(poolget(to.handle; uniform=false)) val, inplace = recv_yield!(to_val, from_space.comm, from_space.rank, tag) if !inplace # Dense payloads may arrive host-staged; materialize in # dest storage so inner move! sees matching spaces val = mpi_localize(to_space.innerSpace, val) - move!(dep_mod, to_space.innerSpace, from_space.innerSpace, to_val, val) + move!(identity, to_space.innerSpace, from_space.innerSpace, to_val, val) end end else diff --git a/src/datadeps/hierarchical.jl b/src/datadeps/hierarchical.jl index b195a879e..b58b72497 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -1832,7 +1832,7 @@ function _hierarchical_copy_from!(state::DataDepsState, arg_w::ArgumentWrapper, enqueue_remainder_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) elseif remainder isa FullCopy origin_scope = UnionScope(map(ExactScope, collect(processors(origin_space)))...) - enqueue_copy_from!(state, origin_space, arg_w, origin_scope, write_num) + enqueue_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) else @assert remainder isa NoAliasing "Expected NoAliasing, got $(typeof(remainder))" # Emit the same elision event as flat `distribute_tasks!`. Consumers of diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index e22866428..b1702dad3 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -185,7 +185,7 @@ function distribute_tasks!(queue::DataDepsTaskQueue) enqueue_remainder_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) elseif remainder isa FullCopy origin_scope = UnionScope(map(ExactScope, collect(processors(origin_space)))...) - enqueue_copy_from!(state, origin_space, arg_w, origin_scope, write_num) + enqueue_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) else @assert remainder isa NoAliasing "Expected NoAliasing, got $(typeof(remainder))" @dagdebug nothing :spawn_datadeps "Skipped copy-from (up-to-date): $origin_space" @@ -378,7 +378,7 @@ function distribute_task!(queue::DataDepsTaskQueue, state::DataDepsState, all_pr if remainder isa MultiRemainderAliasing enqueue_remainder_copy_to!(state, our_space, arg_w, remainder, value(f), idx, our_scope, task, write_num) elseif remainder isa FullCopy - enqueue_copy_to!(state, our_space, arg_w, value(f), idx, our_scope, task, write_num) + enqueue_copy_to!(state, our_space, arg_w, remainder, value(f), idx, our_scope, task, write_num) else @assert remainder isa NoAliasing "Expected NoAliasing, got $(typeof(remainder))" @dagdebug tid :spawn_datadeps "($(repr(value(f))))[$(idx-1)][$dep_mod] Skipped copy-to (up-to-date): $our_space" diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index da9468339..8fe467b57 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -43,8 +43,19 @@ memory_spans(mra::MultiRemainderAliasing) = vcat(memory_spans.(mra.remainders).. Base.hash(mra::MultiRemainderAliasing, h::UInt) = hash(mra.remainders, hash(MultiRemainderAliasing, h)) Base.:(==)(mra1::MultiRemainderAliasing, mra2::MultiRemainderAliasing) = mra1.remainders == mra2.remainders -# A whole-object copy from the argument's recorded owner space. -struct FullCopy end +# An ordinary full copy uses the argument's direct owner and dependency +# modifier. An indivisible object uses the latest writer of its aliasing root. +struct FullCopy{S<:Union{Nothing,MemorySpace}} + whole_object_source::S +end +FullCopy() = FullCopy(nothing) +full_copy_source(state, arg_w, ::FullCopy{Nothing}) = (state.arg_owner[arg_w], arg_w.dep_mod) +function full_copy_source(state, arg_w, copy::FullCopy) + # An explicit modifier may select the whole object from a field of a + # larger argument. Keep that selection for the in-place move. + dep_mod = arg_w.dep_mod === identity ? aliasing_root : arg_w.dep_mod + return copy.whole_object_source, dep_mod +end """ compute_remainder_for_arg!(state::DataDepsState, @@ -115,23 +126,13 @@ function compute_remainder_for_arg!(state::DataDepsState, # memory space -- the whole object is current in exactly one space: the most # recent writer (or the origin owner if never written). There is thus never a # meaningful span "remainder" to compute, so we short-circuit to a whole-object - # `FullCopy` from the owner space (or `NoAliasing` if the target already holds - # it). This avoids the span-diff computation and the construction + transfer of - # a `RemainderAliasing` entirely. We detect this from the aliasing info, which - # is a bare `ObjectAliasing` for such containers (see `aliases_as_whole`). - # - # `arg_owner` is the most-recent *direct* writer of `arg_w`, while the merged - # `arg_history` records the latest write through *any* overlapping argument. - # For every path Datadeps currently exercises a whole-object container is only - # ever reached through a single argument, so these agree -- the assertion below - # guards that invariant. They could only diverge under cross-argument aliasing - # 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`. + # `FullCopy` of the aliasing root. The latest history entry includes writes + # through overlapping wrappers, while `arg_owner` only records direct + # writes to this argument. if aliases_as_whole(aliasing!(state, target_space, arg_w)) 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) + source_space = isempty(history) ? owner_space : history[end].space + return source_space == target_space ? (NoAliasing(), 0) : (FullCopy(source_space), 0) end spaces_set = Set{MemorySpace}() @@ -471,10 +472,9 @@ function enqueue_remainder_copy_from!(state::DataDepsState, dest_space::MemorySp end # FIXME: Document me -function enqueue_copy_to!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, +function enqueue_copy_to!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, copy::FullCopy, f, idx, dest_scope, task, write_num::Int) - dep_mod = arg_w.dep_mod - source_space = state.arg_owner[arg_w] + source_space, dep_mod = full_copy_source(state, arg_w, copy) target_ainfo = aliasing!(state, dest_space, arg_w) @dagdebug task.uid :spawn_datadeps "($(repr(f)))[$(idx-1)][$dep_mod] Enqueueing full copy-to for $(typeof(arg_w.arg))[$(arg_w.dep_mod)]: $source_space => $dest_space" @@ -506,10 +506,9 @@ function enqueue_copy_to!(state::DataDepsState, dest_space::MemorySpace, arg_w:: add_reader!(state, arg_w, source_space, source_ainfo, copy_task, write_num) add_writer!(state, arg_w, dest_space, target_ainfo, copy_task, write_num; copied=true) end -function enqueue_copy_from!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, +function enqueue_copy_from!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, copy::FullCopy, dest_scope, write_num::Int) - dep_mod = arg_w.dep_mod - source_space = state.arg_owner[arg_w] + source_space, dep_mod = full_copy_source(state, arg_w, copy) target_ainfo = aliasing!(state, dest_space, arg_w) @dagdebug nothing :spawn_datadeps "($(typeof(arg_w.arg)))[$dep_mod] Enqueueing full copy-from: $source_space => $dest_space" diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bfc5afb8f..0b43e212d 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -181,7 +181,11 @@ function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Chun from_w = root_worker_id(from_space) # TODO: Use dep_mod to fetch with less memory usage from_raw = to_w == from_w ? unwrap(from) : fetch_copy_source(from, to) - move!(dep_mod, to_space, from_space, to_raw, from_raw) + if dep_mod === aliasing_root + move!(identity, to_space, from_space, aliasing_root(to_raw), aliasing_root(from_raw)) + else + move!(dep_mod, to_space, from_space, to_raw, from_raw) + end end return end diff --git a/test/datadeps.jl b/test/datadeps.jl index 3b36c1036..dd92bcbe7 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1,6 +1,7 @@ import Dagger: ChunkView, Chunk, AbstractAliasing, MemorySpace, ArgumentWrapper import Dagger: aliasing, memory_space using LinearAlgebra, Graphs +using SparseArrays @testset "Hierarchical timing gates" begin # Exercise both the identity slot and the general move_rewrap path. Timing @@ -1315,6 +1316,8 @@ end @everywhere wrapper_bump!(x, idx...) = (x[idx...] += 10; nothing) @everywhere wrapper_snapshot(x) = (typeof(x), collect(x)) +@everywhere wrapper_sparse_update!(D::Dagger.DSparseArray) = (D.mat = 2 * D.mat; nothing) +@everywhere wrapper_sparse_update!(W) = wrapper_bump!(W, 1, 2) @testset "Wrappers share their parent's slot" begin # `transpose(A)` has exactly `A`'s aliasing, and a `PermutedDimsArray` or # `ReshapedArray` is described by its parent's memory. Datadeps must give @@ -1375,3 +1378,35 @@ end end end end + +@testset "Wrappers share the complete sparse container" begin + if nprocs() >= 2 + write_scope = Dagger.scope(worker=first(workers())) + read_scope = Dagger.scope(worker=last(workers())) + wrappers = [("transpose", transpose), ("view", D -> view(D, 1:2, 1:2))] + @testset "$name (hierarchical=$hierarchical, write_parent=$write_parent, write_first=$write_first)" for + (name, wrap) in wrappers, hierarchical in (false, true), + write_parent in (false, true), write_first in (false, true) + D = Dagger.DSparseArray(sparse([1.0 0 2; 0 3 0; 4 0 5])) + reference = Dagger.DSparseArray(copy(D.mat)) + writer, reader = write_parent ? (D, wrap(D)) : (wrap(D), D) + ref_writer, ref_reader = write_parent ? (reference, wrap(reference)) : (wrap(reference), reference) + write_first && wrapper_sparse_update!(ref_writer) + expected = collect(ref_reader) + write_first || wrapper_sparse_update!(ref_writer) + + local result + Dagger.spawn_datadeps(; hierarchical) do + if write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + result = Dagger.@spawn scope=read_scope collect(In(reader)) + if !write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + end + @test fetch(result) == expected + @test D.mat == reference.mat + end + end +end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 8b8e91532..a60216fe9 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -507,6 +507,39 @@ wrapper_snap!(dst, x) = (dst .= x; nothing) end end +wrapper_sparse_update!(D::Dagger.DSparseArray) = (D.mat = 2 * D.mat; nothing) +wrapper_sparse_update!(W) = wrapper_bump!(W, 1, 2) +@testset "Cross-rank whole-object wrapper dataflow" begin + write_scope = rank_scope(min(1, nranks-1)) + read_scope = rank_scope(min(2, nranks-1)) + wrappers = [("transpose", transpose), ("view", D -> view(D, 1:2, 1:2))] + @testset "$name (write_parent=$write_parent, write_first=$write_first)" for + (name, wrap) in wrappers, write_parent in (false, true), write_first in (false, true) + D = Dagger.DSparseArray(sparse([1.0 0 2; 0 3 0; 4 0 5])) + reference = Dagger.DSparseArray(copy(D.mat)) + writer, reader = write_parent ? (D, wrap(D)) : (wrap(D), D) + ref_writer, ref_reader = write_parent ? (reference, wrap(reference)) : (wrap(reference), reference) + write_first && wrapper_sparse_update!(ref_writer) + expected = collect(ref_reader) + write_first || wrapper_sparse_update!(ref_writer) + + result = zeros(size(reader)) + Dagger.spawn_datadeps() do + if write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + Dagger.@spawn scope=read_scope wrapper_snap!(Out(result), In(reader)) + if !write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + end + if rank == 0 + @test result == expected + @test D.mat == reference.mat + end + end +end + @testset "ChunkView dataflow" begin # Views over a DArray block as datadeps arguments, mixed with whole-chunk # access (exercises cross-rank remainder copies through the shared backing