diff --git a/AGENTS.md b/AGENTS.md index 966591995..3977148ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1325,3 +1325,58 @@ this section verbatim). Each entry is one bullet starting with `- `. coincidence. Test those fields with different values. Keep the Float64 case on capable hardware and run the same behavioral assertion with a supported initializer elsewhere; a vendor-wide skip loses coverage on devices that support it. + +120. **`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. + +121. **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()`. + +122. **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. + +123. **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. + +124. **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. 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 40d5edee5..b0c977e59 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -692,6 +692,55 @@ 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) +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 + 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 +757,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) @@ -1097,6 +1151,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) @@ -1344,6 +1401,56 @@ 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 + +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 = aliasing_has_memory(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 d7b41b6ec..8325da65e 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -814,6 +814,10 @@ function _collect_arg_value!(all_deps::Vector{HierarchicalTaskInfo}, inplace_move = may_alias && _cached_get!(supports_cache, cache_lock, arg) do supports_inplace_move(arg) end + # Match `_populate_arg_deps!` for values whose fields may hold no memory. + if inplace_move && type_alias_depends_on_value(typeof(arg)) + may_alias = inplace_move = value_may_alias(arg) + end if !may_alias || !inplace_move return nothing diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index ffca9678b..be6f98a55 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -267,6 +267,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 @@ -274,6 +287,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) @@ -283,6 +302,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 a97720a5e..fb2fb1e22 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -128,6 +128,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 "merge_history! keeps write order" begin # `compute_remainder_for_arg!` walks an argument's history newest-first. # Here `A` is written (write 2), then `view(A, ...)` is written (write 4), @@ -1685,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..244861473 --- /dev/null +++ b/test/datadeps/slot_metadata.jl @@ -0,0 +1,84 @@ +# 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 + 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])) + @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])) + # 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) + 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 + for (first_header, second_header) in ((1, 2), (Float64, Int), (:left, :right)) + data = zeros(4) + 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)) + 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 + end + else + @test_skip false + end +end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index e950e75de..5ab3d8390 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -172,6 +172,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..bc3ed3eec --- /dev/null +++ b/test/mpi/nonconcrete_fields.jl @@ -0,0 +1,85 @@ +# 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 + +# 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