From efcec07478cf0e43c525c77533215027c476e4ba Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 24 Nov 2026 13:41:24 -0700 Subject: [PATCH 1/6] datadeps: track values held in non-concretely-typed fields `type_may_alias` answered `false` for any field whose declared type is not concrete (abstract, `Union`, or untyped), and Datadeps passes such arguments through untracked. So `struct Box; v::AbstractVector{Float64}; end` (or `v::Union{Nothing,Vector{Float64}}`, or plain `v`) got no reader/writer ordering: an `In(b)` reader ran concurrently with the `InOut(b)` writer and saw the old data, while the same struct with `v::Vector{Float64}` was ordered correctly. No error, just wrong results. A non-concrete field now counts as possibly aliasing, except a Union of plain data (`Union{Nothing,Int}`), which can never hold mutable memory. Whether a given value actually does is then decided from the value, but only for types where the type alone cannot say (`type_alias_depends_on_value`), so arrays and other concretely typed arguments take exactly the path they did before. That per-value check (`value_may_alias`) is required, not an optimization: a tracked value with no memory spans has aliasing without an address, so all such values compare equal and the aliased-object cache hands one argument's slot to the next. With only the type change, MPI tasks given `S(1)..S(4)` of `struct S; part::Int; x; end` received `S(2), S(2), S(4), S(4)`. Values with no spans are therefore passed through untracked, as before. The hierarchical pre-scan makes the same decision so both paths agree. Values whose aliasing cannot be computed now error as they already do for a concretely typed field (e.g. a `Dict` held in an untyped field), rather than being silently skipped; declare `type_may_alias(::Type{T}) = false` for types that are never mutated. Tests: the Distributed ordering tests fail on master (reader sees 0.0), and the MPI test fails when the per-value check is disabled; both pass here. Co-Authored-By: Claude Opus 5.5 --- src/datadeps/aliasing.jl | 27 +++++++++++++++++++ src/datadeps/hierarchical.jl | 4 +++ src/memory-spaces.jl | 47 ++++++++++++++++++++++++++++++++++ test/datadeps.jl | 41 +++++++++++++++++++++++++++++ test/mpi/cpu.jl | 1 + test/mpi/nonconcrete_fields.jl | 29 +++++++++++++++++++++ 6 files changed, 149 insertions(+) create mode 100644 test/mpi/nonconcrete_fields.jl diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index cfce21de5..0ff84134e 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -933,6 +933,9 @@ function _populate_arg_deps!(state::DataDepsState, infos::Vector{TaskArgInfo}, # Skip non-aliasing arguments or arguments that don't support in-place move may_alias = type_may_alias(typeof(arg)) inplace_move = may_alias && supports_inplace_move(state, arg) + if inplace_move && type_alias_depends_on_value(typeof(arg)) + may_alias = inplace_move = value_may_alias(arg) + end dep_start = length(deps_vec) + 1 if !may_alias || !inplace_move arg_w = ArgumentWrapper(arg, identity) @@ -1120,6 +1123,30 @@ supports_inplace_move(c::Chunk) = supports_inplace_move(chunktype(c)) supports_inplace_move(::Type) = true supports_inplace_move(::Type{<:Function}) = false +""" + value_may_alias(arg) -> Bool + +Whether `arg`, whose type `type_alias_depends_on_value`, actually holds mutable +memory, i.e. whether its aliasing has any memory spans. + +Datadeps tracks only values that do. Besides being pointless, tracking a value +with no spans would be wrong: its aliasing carries no address, so every such +value has the *same* aliasing (e.g. an empty `CombinedAliasing`), and the +aliased-object cache, which is keyed by aliasing, would hand one argument's +slot to another (`S(1)` and `S(2)` of `struct S; x::Any; end` would share a +slot, and one task would see the other's value). Such a value is instead passed +through untracked, exactly like an `isbits` value. + +Under MPI, `aliasing` of a `Chunk` is computed by its owner and broadcast (and +memoized for the region), so every rank reaches the same answer. +""" +function value_may_alias(arg) + ainfo = aliasing(current_acceleration(), arg, identity) + may_alias = !isempty(memory_spans(ainfo)) + @check_uniform(may_alias) + return may_alias +end + # Read/write dependency management function get_write_deps!(state::DataDepsState, dest_space::MemorySpace, ainfo::AbstractAliasing, write_num, syncdeps) # We need to sync with both writers and readers diff --git a/src/datadeps/hierarchical.jl b/src/datadeps/hierarchical.jl index b195a879e..375b9982d 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -769,6 +769,10 @@ function _collect_aliased_args_range!(task_metas::Vector{HierarchicalTaskMeta}, inplace_move = may_alias && _cached_get!(supports_cache, cache_lock, arg) do supports_inplace_move(arg) end + # Must match `_populate_arg_deps!`, which makes the same decision. + if inplace_move && type_alias_depends_on_value(typeof(arg)) + may_alias = inplace_move = value_may_alias(arg) + end if !may_alias || !inplace_move continue diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bfc5afb8f..b1545e204 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -263,6 +263,19 @@ inplace_mpi_build(::Type{T}, parts, header) where T = ### Aliasing and Memory Spans +""" + type_may_alias(T) -> Bool + +Whether a value of type `T` may hold mutable memory, and so must be tracked by +Datadeps. A `false` answer is a promise: Datadeps passes such values to tasks +as plain, untracked arguments, without ordering their readers and writers. + +A non-concrete type (an abstract type, a `Union`, or a `UnionAll` -- e.g. a +field declared `v::AbstractVector`, `v::Union{Nothing,Vector{Float64}}`, or +left untyped) is `true`, since such a field can hold a mutable value. Whether a +particular value actually does is then decided from the value; see +`type_alias_depends_on_value`. +""" type_may_alias(::Type{String}) = false type_may_alias(::Type{Symbol}) = false type_may_alias(::Type{<:Type}) = false @@ -270,6 +283,12 @@ type_may_alias(::Type{C}) where C<:Chunk{T} where T = type_may_alias(T) function type_may_alias(::Type{T}) where T if isbitstype(T) return false + elseif _is_bits_union(T) + # e.g. `Union{Nothing,Int}`: every member is immutable plain data + return false + elseif !isconcretetype(T) + # The declared type cannot rule out a mutable value. + return true elseif ismutabletype(T) return true elseif isstructtype(T) @@ -279,6 +298,34 @@ function type_may_alias(::Type{T}) where T end return false end +_is_bits_union(T) = T isa Union && _is_bits_union_member(T.a) && _is_bits_union_member(T.b) +_is_bits_union_member(T) = T isa Union ? _is_bits_union(T) : isbitstype(T) + +""" + type_alias_depends_on_value(T) -> Bool + +Whether `type_may_alias(T)` is `true` only because some (possibly nested) +field of `T` has a non-concrete declared type. Then the type alone cannot say +whether a value of `T` holds mutable memory: `struct S; x::Any; end` does for +`S([1.0])` and does not for `S(1)`. Datadeps checks such values individually +(see `value_may_alias`), rather than tracking every one. + +`false` whenever some field certainly may alias (a concretely typed mutable +field such as a `Vector`), since every value of `T` then needs tracking. +""" +type_alias_depends_on_value(::Type{C}) where C<:Chunk{T} where T = type_alias_depends_on_value(T) +function type_alias_depends_on_value(::Type{T}) where T + type_may_alias(T) || return false + isconcretetype(T) || return true + (isbitstype(T) || ismutabletype(T) || !isstructtype(T)) && return false + depends = false + for FT in fieldtypes(T) + type_may_alias(FT) || continue + type_alias_depends_on_value(FT) || return false + depends = true + end + return depends +end may_alias(::MemorySpace, ::MemorySpace) = false may_alias(space1::M, space2::M) where M<:MemorySpace = space1 == space2 diff --git a/test/datadeps.jl b/test/datadeps.jl index a7d020350..8d6e16163 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -98,6 +98,47 @@ end @test s.sz == sizeof(3) end +# A field whose declared type is not concrete can still hold mutable memory. +struct AbstractFieldBox; v::AbstractVector{Float64}; end +struct UnionFieldBox; v::Union{Nothing,Vector{Float64}}; end +struct UntypedFieldBox; v; end +struct MixedFieldBox; v::Vector{Float64}; x; end +nonconcrete_box_write!(b) = (sleep(0.5); fill!(b.v, 1.0); nothing) +nonconcrete_box_sum(b) = sum(b.v) + +@testset "Non-concrete fields" begin + @testset "type_may_alias" begin + for B in (AbstractFieldBox, UnionFieldBox, UntypedFieldBox) + @test Dagger.type_may_alias(B) + @test Dagger.type_alias_depends_on_value(B) + end + # A concretely typed mutable field decides it for every value + @test Dagger.type_may_alias(MixedFieldBox) + @test !Dagger.type_alias_depends_on_value(MixedFieldBox) + # A Union of plain data can never hold mutable memory + @test !Dagger.type_may_alias(Union{Nothing,Int}) + @test !Dagger.type_may_alias(Union{Nothing,Int,Float64}) + + @test Dagger.value_may_alias(UntypedFieldBox(zeros(2))) + @test Dagger.value_may_alias(UnionFieldBox(zeros(2))) + @test !Dagger.value_may_alias(UntypedFieldBox(1)) + @test !Dagger.value_may_alias(UnionFieldBox(nothing)) + end + + # Previously these types were treated as never aliasing, so the reader was + # not ordered after the writer and saw the original zeros. + @testset "writer is ordered before reader: $B" for B in (AbstractFieldBox, UnionFieldBox, UntypedFieldBox) + b = B(zeros(4)) + local t + Dagger.spawn_datadeps() do + Dagger.@spawn scope=Dagger.scope(worker=1) nonconcrete_box_write!(InOut(b)) + t = Dagger.@spawn scope=Dagger.scope(worker=1) nonconcrete_box_sum(In(b)) + end + @test fetch(t) == 4.0 + @test all(==(1.0), b.v) + end +end + @testset "ChunkView" begin DA = rand(Blocks(8, 8), 64, 64) task1 = DA.chunks[1,1]::DTask diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index ba97dfd08..61425f543 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -147,6 +147,7 @@ end include("spawn.jl") include("noaliasing_args.jl") +include("nonconcrete_fields.jl") @testset "Datadeps" begin diff --git a/test/mpi/nonconcrete_fields.jl b/test/mpi/nonconcrete_fields.jl new file mode 100644 index 000000000..1f8efe4c2 --- /dev/null +++ b/test/mpi/nonconcrete_fields.jl @@ -0,0 +1,29 @@ +# A struct field declared with a non-concrete type (here, untyped) may or may +# not hold mutable memory, so Datadeps decides from each value. A value that +# holds none must be passed through untracked: its aliasing has no address, so +# tracking it would give every such value the same key in the aliased-object +# cache, and a task would receive another task's value. +struct UntypedFieldVal; part::Int; x; end +untyped_field_val(part::Int) = UntypedFieldVal(part, part) +function check_untyped_field_val!(buf::Vector{Float64}, x::UntypedFieldVal) + buf[1] = x.part + buf[2] = x.x + return +end + +@testset "Values of non-concrete fields keep their own value" begin + owner_of(i) = (i - 1) รท 2 + P = 2 * nranks + bufs = [Dagger.tochunk(zeros(2), proc_for_rank(owner_of(i)), space_for_rank(owner_of(i))) for i in 1:P] + # From upstream tasks (as `Chunk`s), and as plain values + for vals in ([Dagger.@spawn(scope=Dagger.scope(mpi_rank=owner_of(i)), untyped_field_val(i)) for i in 1:P], + [untyped_field_val(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_untyped_field_val!(InOut(bufs[i]), vals[i]) + end + end + seen = [fetch(Dagger.@spawn(scope=Dagger.scope(mpi_rank=owner_of(i)), copy(bufs[i]))) for i in 1:P] + @test seen == [[i, i] for i in 1:P] + end +end From 39d058bb8e54fd58a950a2ebce63629bf8a38d6a Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 24 Nov 2026 13:41:24 -0700 Subject: [PATCH 2/6] AGENTS: lesson on type_may_alias promises and span-less aliasing Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 61b1c43b8..92ec20c0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1023,3 +1023,40 @@ 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`. + +96. **`type_may_alias(T) == false` is a promise, and a non-concrete field + cannot make it.** Datadeps passes such values through untracked, with no + reader/writer ordering. `type_may_alias` used to answer `false` for any + abstract, `Union`, or untyped field type, so `struct Box; v::AbstractVector; + end` was silently untracked: an `In(b)` reader ran concurrently with the + `InOut(b)` writer and saw the old data, while the same struct with + `v::Vector{Float64}` was ordered correctly. Such a type must be checked per + value (`type_alias_depends_on_value` / `value_may_alias`). And a tracked value + with *no memory spans* is a hazard in its own right: its aliasing carries no + address, so every such value has an equal aliasing (`NoAliasing`, an empty + `CombinedAliasing`), and the aliased-object cache, keyed by aliasing, hands one + argument's slot to the next. Under MPI, `S(1)` and `S(2)` of `struct S; x; + end` reached tasks as `S(2), S(2)`. Pass span-less values through untracked + rather than giving them slots. The ordering bug reproduces with threads in + one process; the slot collision reproduced only under MPI. + +83. **Equal memory spans can belong to different argument values.** With + default aliasing, `Part(1, v)` and `Part(2, v)` of + `struct Part; id::Int; data::Vector{Float64}; end` have the same spans. + An `In(Part(2, v))` reader correctly waited for an `InOut(Part(1, v))` + writer, then received `id == 1` because `aliased_object!` reused the + writer's entire `Chunk`. This reproduced on one process with both + Datadeps planners. Slot reuse must preserve wrapper metadata while + sharing the backing storage. A guard for `NoAliasing()` alone does not + address this case, and it cannot restore dependencies for buffers hidden + by an `aliasing` override that returns `NoAliasing()`. + +84. **An untracked argument needs an empty dependency range.** A placeholder + `DataDepsTaskDependency` with both flags false still constructs an + `ArgumentWrapper` and checks its identity hash across MPI ranks. Two ranks + can hold equivalent `Part` values with vector fields and produce different + hashes, so `check_uniformity!(true)` rejects a plain input even when + `type_may_alias(::Type{Part}) = false`. Keeping `TaskArgInfo.arg` with an + empty range avoids the check and lets normal task transport pass the + argument through. Both planners passed a two-rank probe with plain values + and upstream task results produced on the opposite rank. From b0dc24ef575fc204cc813ae6e2f07808856a2120 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:03:10 -0700 Subject: [PATCH 3/6] Reject slot reuse that would replace immutable wrapper metadata Leaf wrappers sharing spans cannot reuse another header unless they register the existing move_rewrap protocol. Compare ambiguous immutable metadata on its owner and broadcast the MPI decision, preserving registered wrappers and ordinary arrays. Document all required hooks instead of attempting to bypass constructors. Focused Distributed checks pass18; independent2rank MPI controls pass14+10 across both planners including rejection recovery. Allocation bounds remain25/25 unchanged; deep warmed minima retain178 task allocations /6.5KiB and60 empty-region allocations /2.7KiB before and after. Full Datadeps before guard2222pass2broken. Written by an AI agent on jpsamaroo's review feedback. --- docs/src/datadeps.md | 29 +++++++++++++++ ext/MPIExt.jl | 23 ++++++++++++ src/datadeps/aliasing.jl | 51 ++++++++++++++++++++++++++ test/datadeps.jl | 2 ++ test/datadeps/slot_metadata.jl | 65 ++++++++++++++++++++++++++++++++++ test/mpi/nonconcrete_fields.jl | 56 +++++++++++++++++++++++++++++ 6 files changed, 226 insertions(+) create mode 100644 test/datadeps/slot_metadata.jl diff --git a/docs/src/datadeps.md b/docs/src/datadeps.md index 2d9e27c4f..0fd43c562 100644 --- a/docs/src/datadeps.md +++ b/docs/src/datadeps.md @@ -322,6 +322,35 @@ Hierarchical scheduling does not yet parallelize everything it could. These are - **Phases 2 and 3 are single-threaded.** Building the DAG and computing aliasing overlaps are incremental, order-dependent algorithms. They are cheap relative to phases 1 and 4 today, but will become the bottleneck as those scale. +## Wrappers that share storage + +For a custom non-array container, a `move!` implementation describes how to copy +its data. A wrapper that shares a buffer with other argument values also needs +the header/children protocol below. Aliasing identifies shared memory, so it +cannot distinguish two wrappers such as `Part(1, data)` and `Part(2, data)` by +their labels. Reusing one entire wrapper as the other's slot would lose that +metadata. Datadeps rejects such cross-space leaf reuse with an `ArgumentError` +instead of substituting one wrapper's immutable metadata for another's. + +Register these methods to keep one shared payload and rebuild each wrapper: + +- `Dagger.move_rewrap_parts(value)` returns `(children::Tuple, header)`. +- `Dagger.move_rewrap_build(T, children, header)` reconstructs the wrapper. +- `Dagger.move_rewrap_child_types(T)` returns the child types, consistently on + every MPI rank. +- `Dagger.move_rewrap_header_mode(T)` returns `:none` for a `nothing` header or + `:broadcast` for owner-held metadata such as a label or shape. +- `Dagger.move_rewrap_result_type(T, child_types, header)` returns the rebuilt + value's type, consistently on every MPI rank. + +The children are transferred or shared through their own movement methods; the +header preserves each argument's non-buffer metadata. Rebuilding calls the +registered method and never bypasses the wrapper's constructors. Existing array +wrappers such as views, transposes, and triangular wrappers already implement +this protocol. Custom containers must also provide the movement and remainder +copy hooks needed for the storage they expose. Defining `move!` alone does not +register a storage-sharing wrapper. + ## Chunk and DTask slicing with `view` The `view` function allows you to efficiently create a "view" of a `Chunk` or `DTask` that contains an array. This enables operations on specific parts of your distributed data using standard Julia array slicing, without needing to materialize the entire array. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index f867b1cc5..29afacc88 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2160,6 +2160,29 @@ function mpi_endpoint_alloc(accel::MPIAcceleration, to_proc, to_space, ::Type{T_ end end +# Wire types carry only owner-local payloads. Check an ambiguous immutable leaf +# on that owner, then share the answer so every rank takes the same error path. +Dagger.slot_metadata_needs_check(::Type{<:MPIWireValue{T}}) where T = + Dagger.slot_metadata_needs_check(T) +function Dagger.check_aliased_leaf_metadata!(accel::MPIAcceleration, + cache::AliasedObjectCache, + w::MPIWireValue{T}, ainfo::AbstractAliasing, + x_space::MemorySpace) where T + source_cache = AliasedObjectCache(accel, x_space, cache.chunk) + original = Dagger.get_stored(source_cache, ainfo) + tag = to_tag() + matches = if has_value(w) + value = wire_value(w) + answer = !Dagger.slot_metadata_needs_check(typeof(value)) || + Dagger.leaf_metadata_equal(value, unwrap(original)) + bcast_meta_yield(accel.comm, w.space.rank, tag, answer) + else + bcast_meta_yield(accel.comm, w.space.rank, tag) + end + matches || Dagger.reject_aliased_leaf_metadata(T) + return +end + # Generic / wrapper MPIWireValue: leaf transfer, or header+children rebuild function move_rewrap(accel::MPIAcceleration, cache::AliasedObjectCache, from_proc::Processor, to_proc::Processor, from_space::MemorySpace, to_space::MemorySpace, w::MPIWireValue{T}) where T child_types = move_rewrap_child_types(T) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index c8e828338..78b7c37df 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -692,6 +692,52 @@ function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCac set_key_stored!(cache_raw, space, ainfo, value) end +# Concrete arrays and registered wrappers retain their existing cache path. +# Unknown declared types are checked on their owner, where their value is known. +function slot_metadata_needs_check(::Type{T}) where T + type_may_alias(T) || return false + isconcretetype(T) || return true + return isstructtype(T) && !ismutabletype(T) && !isbitstype(T) && + !(T <: AbstractArray) && move_rewrap_child_types(T) === nothing +end +slot_metadata_needs_check(::Type{C}) where {T,C<:Chunk{T}} = slot_metadata_needs_check(T) + +# Aliasing already identifies the mutable payload. Only immutable metadata must +# match; payload contents may have changed since the source was registered. +leaf_metadata_equal(x, y) = false +leaf_metadata_equal(x::String, y::String) = isequal(x, y) +function leaf_metadata_equal(x::T, y::T) where T + ismutabletype(T) && return true + isbitstype(T) && return x === y + isstructtype(T) || return x === y + for i in 1:fieldcount(T) + isdefined(x, i) == isdefined(y, i) || return false + isdefined(x, i) || continue + leaf_metadata_equal(getfield(x, i), getfield(y, i)) || return false + end + return true +end +function leaf_metadata_matches_chunk(x, original::Chunk) + value = x isa Chunk ? unwrap(x) : x + return !slot_metadata_needs_check(typeof(value)) || leaf_metadata_equal(value, unwrap(original)) +end +function reject_aliased_leaf_metadata(::Type{T}) where T + throw(ArgumentError("Aliased leaf values of type $T have different metadata. " * + "Define Dagger.move_rewrap_parts and Dagger.move_rewrap_build " * + "(plus the MPI metadata hooks when using MPI) to rebuild " * + "each wrapper around the shared storage.")) +end +function check_aliased_leaf_metadata!(accel::Acceleration, cache::AliasedObjectCache, + x, ainfo::AbstractAliasing, x_space::MemorySpace) + source_cache = AliasedObjectCache(accel, x_space, cache.chunk) + original = get_stored(source_cache, ainfo) + owner = root_worker_id(original) + matches = owner == myid() ? leaf_metadata_matches_chunk(x, original) : + remotecall_fetch(leaf_metadata_matches_chunk, owner, x, original) + matches || reject_aliased_leaf_metadata(typeof(x)) + return +end + function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.accel, x, identity)) # An aliasing without identity (`NoAliasing`, an empty `CombinedAliasing`, # ...) is equal for every value that has it, so it cannot be the cache key: @@ -708,6 +754,11 @@ function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.a set_key_stored!(cache.accel, cache, x_space, ainfo, x_chunk) end if is_stored(cache, ainfo) + # In-place slots return the requested object in `generate_slot!`. + # Cross-space leaf reuse must not substitute another wrapper's header. + if slot_metadata_needs_check(typeof(x)) && x_space != cache.space + check_aliased_leaf_metadata!(cache.accel, cache, x, ainfo, x_space) + end return get_stored(cache, ainfo) else y = f(x) diff --git a/test/datadeps.jl b/test/datadeps.jl index 672f5ded4..fb2fb1e22 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1726,3 +1726,5 @@ end end end end + +include("datadeps/slot_metadata.jl") diff --git a/test/datadeps/slot_metadata.jl b/test/datadeps/slot_metadata.jl new file mode 100644 index 000000000..e90122a3d --- /dev/null +++ b/test/datadeps/slot_metadata.jl @@ -0,0 +1,65 @@ +# These wrappers provide ordinary movement/span hooks. The second additionally +# registers the header/children protocol required for storage-sharing wrappers. +@everywhere begin + struct LeafMetadataBox + id::Int + data + end + struct RewrappedMetadataBox + id::Int + data + end + Dagger.find_object_holding_ptr(x::Union{LeafMetadataBox,RewrappedMetadataBox}, ::UInt64) = x.data + function Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, + from_space::Dagger.MemorySpace, to::T, from::T) where {T<:Union{LeafMetadataBox,RewrappedMetadataBox}} + copyto!(dep_mod(to.data), dep_mod(from.data)) + return + end + Dagger.move_rewrap_parts(x::RewrappedMetadataBox) = ((x.data,), x.id) + Dagger.move_rewrap_build(::Type{RewrappedMetadataBox}, (data,), id) = + RewrappedMetadataBox(id, data) + Dagger.move_rewrap_child_types(::Type{RewrappedMetadataBox}) = (Vector{Float64},) + Dagger.move_rewrap_header_mode(::Type{RewrappedMetadataBox}) = :broadcast + Dagger.move_rewrap_result_type(::Type{RewrappedMetadataBox}, _, _) = RewrappedMetadataBox + metadata_box_write!(x) = (x.data .+= 1; nothing) + metadata_box_read(x) = (x.id, sum(x.data)) +end + +@testset "Aliased leaves retain metadata or request wrapper hooks" begin + @test !Dagger.slot_metadata_needs_check(Vector{Float64}) + @test !Dagger.slot_metadata_needs_check(Transpose{Float64,Matrix{Float64}}) + @test Dagger.slot_metadata_needs_check(LeafMetadataBox) + @test !Dagger.slot_metadata_needs_check(RewrappedMetadataBox) + @test Dagger.leaf_metadata_equal(LeafMetadataBox(1, [0.0]), LeafMetadataBox(1, [2.0])) + @test !Dagger.leaf_metadata_equal(LeafMetadataBox(1, [0.0]), LeafMetadataBox(2, [0.0])) + if length(procs()) > 1 + worker = first(workers()) + for hierarchical in (false, true) + for (Box, id) in ((LeafMetadataBox, 1), (RewrappedMetadataBox, 2)) + data = zeros(4) + a, b = Box(1, data), Box(id, data) + result = Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=Dagger.scope(;worker) metadata_box_write!(InOut(a)) + Dagger.@spawn scope=Dagger.scope(;worker) metadata_box_read(In(b)) + end + @test fetch(result) == (id, 4.0) + @test data == ones(4) + end + data = zeros(4) + a, b = LeafMetadataBox(1, data), LeafMetadataBox(2, data) + err = try + Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=Dagger.scope(;worker) metadata_box_write!(InOut(a)) + Dagger.@spawn scope=Dagger.scope(;worker) metadata_box_read(In(b)) + end + nothing + catch ex + ex + end + @test err !== nothing + @test occursin("move_rewrap_parts", sprint(showerror, err)) + end + else + @test_skip false + end +end diff --git a/test/mpi/nonconcrete_fields.jl b/test/mpi/nonconcrete_fields.jl index 1f8efe4c2..bc3ed3eec 100644 --- a/test/mpi/nonconcrete_fields.jl +++ b/test/mpi/nonconcrete_fields.jl @@ -27,3 +27,59 @@ end @test seen == [[i, i] for i in 1:P] end end + +# Storage-sharing wrappers need explicit rewrap hooks when their headers differ. +struct MPILeafMetadataBox + id::Int + data +end +struct MPIRewrappedMetadataBox + id::Int + data +end +Dagger.find_object_holding_ptr(x::Union{MPILeafMetadataBox,MPIRewrappedMetadataBox}, ::UInt64) = x.data +function Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, to::T, from::T) where {T<:Union{MPILeafMetadataBox,MPIRewrappedMetadataBox}} + copyto!(dep_mod(to.data),dep_mod(from.data)) + nothing +end +Dagger.move_rewrap_parts(x::MPIRewrappedMetadataBox) = ((x.data,),x.id) +Dagger.move_rewrap_build(::Type{MPIRewrappedMetadataBox}, (data,), id) = MPIRewrappedMetadataBox(id,data) +Dagger.move_rewrap_child_types(::Type{MPIRewrappedMetadataBox}) = (Vector{Float64},) +Dagger.move_rewrap_header_mode(::Type{MPIRewrappedMetadataBox}) = :broadcast +Dagger.move_rewrap_result_type(::Type{MPIRewrappedMetadataBox}, _, _) = MPIRewrappedMetadataBox +mpi_metadata_write!(x) = (x.data .+= 1; nothing) +mpi_metadata_read(x) = (x.id,sum(x.data)) +@testset "Cross-rank slots preserve wrapper metadata" begin + for hierarchical in (false,true) + data=zeros(4) + a,b=MPILeafMetadataBox(1,data),MPILeafMetadataBox(1,data) + task=Dagger.spawn_datadeps(;hierarchical) do + Dagger.@spawn scope=rank_scope(min(1,nranks-1)) mpi_metadata_write!(InOut(a)) + Dagger.@spawn scope=rank_scope(min(1,nranks-1)) mpi_metadata_read(In(b)) + end + @test fetch(task)==(1,4.0) + rank==0 && (@test data==ones(4)) + data=zeros(4) + a,b=MPILeafMetadataBox(1,data),MPILeafMetadataBox(2,data) + err=try + Dagger.spawn_datadeps(;hierarchical) do + Dagger.@spawn scope=rank_scope(min(1,nranks-1)) mpi_metadata_write!(InOut(a)) + Dagger.@spawn scope=rank_scope(min(1,nranks-1)) mpi_metadata_read(In(b)) + end + nothing + catch ex + ex + end + @test err!==nothing + @test occursin("move_rewrap_parts",sprint(showerror,err)) + data=zeros(4) + a,b=MPIRewrappedMetadataBox(1,data),MPIRewrappedMetadataBox(2,data) + task=Dagger.spawn_datadeps(;hierarchical) do + Dagger.@spawn scope=rank_scope(min(1,nranks-1)) mpi_metadata_write!(InOut(a)) + Dagger.@spawn scope=rank_scope(min(1,nranks-1)) mpi_metadata_read(In(b)) + end + @test fetch(task)==(2,4.0) + rank==0 && (@test data==ones(4)) + @test fetch(Dagger.@spawn scope=rank_scope(0) identity(19))==19 + end +end From 9ae2e536fdd4cf4c8ac0dd2d9c5c845542092e40 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:11:43 -0700 Subject: [PATCH 4/6] Compare by-value metadata before ignoring mutable payloads Julia Type objects are internally mutable but passed by value in Datadeps. Preserve Type, Symbol and custom nonaliasing headers rather than treating them as mutable storage. Focused controls reject different integer, Type and Symbol wrapper headers on both Distributed planners;30assertions pass. Written by an AI agent on jpsamaroo's review feedback. --- src/datadeps/aliasing.jl | 3 +++ test/datadeps/slot_metadata.jl | 10 ++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 78b7c37df..c53939e9f 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -706,7 +706,10 @@ slot_metadata_needs_check(::Type{C}) where {T,C<:Chunk{T}} = slot_metadata_needs # match; payload contents may have changed since the source was registered. leaf_metadata_equal(x, y) = false leaf_metadata_equal(x::String, y::String) = isequal(x, y) +leaf_metadata_equal(x::Type, y::Type) = x === y +leaf_metadata_equal(x::Symbol, y::Symbol) = x === y function leaf_metadata_equal(x::T, y::T) where T + type_may_alias(T) || return isequal(x, y) ismutabletype(T) && return true isbitstype(T) && return x === y isstructtype(T) || return x === y diff --git a/test/datadeps/slot_metadata.jl b/test/datadeps/slot_metadata.jl index e90122a3d..7e29e5582 100644 --- a/test/datadeps/slot_metadata.jl +++ b/test/datadeps/slot_metadata.jl @@ -2,7 +2,7 @@ # registers the header/children protocol required for storage-sharing wrappers. @everywhere begin struct LeafMetadataBox - id::Int + id data end struct RewrappedMetadataBox @@ -32,6 +32,10 @@ end @test !Dagger.slot_metadata_needs_check(RewrappedMetadataBox) @test Dagger.leaf_metadata_equal(LeafMetadataBox(1, [0.0]), LeafMetadataBox(1, [2.0])) @test !Dagger.leaf_metadata_equal(LeafMetadataBox(1, [0.0]), LeafMetadataBox(2, [0.0])) + @test Dagger.leaf_metadata_equal(Float64, Float64) + @test !Dagger.leaf_metadata_equal(Float64, Int) + @test !Dagger.leaf_metadata_equal(:left, :right) + @test !Dagger.leaf_metadata_equal(LeafMetadataBox(Float64, [0.0]), LeafMetadataBox(Int, [0.0])) if length(procs()) > 1 worker = first(workers()) for hierarchical in (false, true) @@ -45,8 +49,9 @@ end @test fetch(result) == (id, 4.0) @test data == ones(4) end + for (first_header, second_header) in ((1, 2), (Float64, Int), (:left, :right)) data = zeros(4) - a, b = LeafMetadataBox(1, data), LeafMetadataBox(2, data) + a, b = LeafMetadataBox(first_header, data), LeafMetadataBox(second_header, data) err = try Dagger.spawn_datadeps(; hierarchical) do Dagger.@spawn scope=Dagger.scope(;worker) metadata_box_write!(InOut(a)) @@ -58,6 +63,7 @@ end end @test err !== nothing @test occursin("move_rewrap_parts", sprint(showerror, err)) + end end else @test_skip false From 47f3debc8c4ee615e1671502b6790042efb172b3 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:11:43 -0700 Subject: [PATCH 5/6] Check dynamic argument span presence without materializing vectors Use recursive presence checks for core aliasing shapes and retain memory_spans fallback for custom shapes. Empty and zero-sized view/triangular controls match the existing span contract; final metadata suite46assertions passes. After10warmups+GC,min5 runs of1000value_may_alias calls on an Any-field vector wrapper:6000allocations/224000bytes before,3000/112000after. This measures the actual value-dependent path, including aliasing construction, rather than only an emptiness helper. Written by an AI agent on jpsamaroo's review feedback. --- src/datadeps/aliasing.jl | 28 +++++++++++++++++++++++++++- test/datadeps/slot_metadata.jl | 13 +++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index c53939e9f..b0c977e59 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1401,6 +1401,32 @@ supports_inplace_move(c::Chunk) = supports_inplace_move(chunktype(c)) supports_inplace_move(::Type) = true supports_inplace_move(::Type{<:Function}) = false +# Ask whether spans exist without constructing their vectors. Preserve the +# memory_spans extension contract for custom aliasing representations. +aliasing_has_memory(a::AbstractAliasing) = !isempty(memory_spans(a)) +aliasing_has_memory(::NoAliasing) = false +aliasing_has_memory(::UnknownAliasing) = true +aliasing_has_memory(::ObjectAliasing) = true +aliasing_has_memory(::ContiguousAliasing) = true +aliasing_has_memory(::CopyKey) = false +aliasing_has_memory(a::AliasingWrapper) = aliasing_has_memory(a.inner) +function aliasing_has_memory(a::CombinedAliasing) + for child in a.sub_ainfos + aliasing_has_memory(child) && return true + end + return false +end +function aliasing_has_memory(a::StridedAliasing{T,N}) where {T,N} + N == 0 && return !isempty(memory_spans(a)) + for i in 2:N + a.lengths[i] > 0 || return false + end + return true +end +aliasing_has_memory(a::TriangularAliasing{T}) where T = + sizeof(T) > 0 && a.stride > (a.diagonal ? 0 : 1) +aliasing_has_memory(a::DiagonalAliasing) = a.stride > 0 + """ value_may_alias(arg) -> Bool @@ -1420,7 +1446,7 @@ memoized for the region), so every rank reaches the same answer. """ function value_may_alias(arg) ainfo = aliasing(current_acceleration(), arg, identity) - may_alias = !isempty(memory_spans(ainfo)) + may_alias = aliasing_has_memory(ainfo) @check_uniform(may_alias) return may_alias end diff --git a/test/datadeps/slot_metadata.jl b/test/datadeps/slot_metadata.jl index 7e29e5582..244861473 100644 --- a/test/datadeps/slot_metadata.jl +++ b/test/datadeps/slot_metadata.jl @@ -36,6 +36,19 @@ end @test !Dagger.leaf_metadata_equal(Float64, Int) @test !Dagger.leaf_metadata_equal(:left, :right) @test !Dagger.leaf_metadata_equal(LeafMetadataBox(Float64, [0.0]), LeafMetadataBox(Int, [0.0])) + # Match the span contract even for zero-sized views and triangular tiles. + for A in (zeros(0,0), zeros(0,2), zeros(2,0), ones(3,3)) + for value in (A, view(A,:,:), Diagonal(diag(A))) + ainfo = Dagger.aliasing(value) + @test Dagger.aliasing_has_memory(ainfo) == !isempty(Dagger.memory_spans(ainfo)) + end + if size(A,1) == size(A,2) + for value in (UpperTriangular(A), UnitUpperTriangular(A)) + ainfo = Dagger.aliasing(value) + @test Dagger.aliasing_has_memory(ainfo) == !isempty(Dagger.memory_spans(ainfo)) + end + end + end if length(procs()) > 1 worker = first(workers()) for hierarchical in (false, true) From 2d9655d049a51d7ff2624f53bc4fca155b0d3e10 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:13:33 -0700 Subject: [PATCH 6/6] Record metadata and span-presence rules learned from dynamic fields Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index bc0b05d53..118913325 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1254,3 +1254,21 @@ this section verbatim). Each entry is one bullet starting with `- `. empty range avoids the check and lets normal task transport pass the argument through. Both planners passed a two-rank probe with plain values and upstream task results produced on the opposite rank. + +112. **Julia's internal mutability does not identify Datadeps metadata.** + `DataType` is mutable internally, but `Type` values are read-only, by-value + Datadeps arguments. Treating every mutable field as interchangeable backing + storage therefore lets `Box(Float64, v)` reuse `Box(Int, v)`'s header. Compare + `Type` and `Symbol` values by identity and other nonaliasing metadata by + value before skipping mutable payload contents. Register storage-sharing + wrapper headers through the existing `move_rewrap` protocol. + +113. **A span-presence question must not materialize span vectors.** + `memory_spans` constructs vectors for core aliasing shapes, and combined + aliasing also copies child lists and concatenates their spans. Calling it + solely for `isempty` on every dynamic-field argument doubled a measured + 1000-call `value_may_alias` probe from 3000 allocations / 112000 bytes to + 6000 / 224000. Recurse through core shapes with `aliasing_has_memory`, while + retaining `memory_spans` as the extension fallback. Preserve its exact + emptiness semantics: a zero-length contiguous span is still one span, but + a strided view with an empty outer dimension has none.