Skip to content
55 changes: 55 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
29 changes: 29 additions & 0 deletions docs/src/datadeps.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions ext/MPIExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
107 changes: 107 additions & 0 deletions src/datadeps/aliasing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/datadeps/hierarchical.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions src/memory-spaces.jl
Original file line number Diff line number Diff line change
Expand Up @@ -267,13 +267,32 @@ 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
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)
Expand All @@ -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
Expand Down
43 changes: 43 additions & 0 deletions test/datadeps.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -1685,3 +1726,5 @@ end
end
end
end

include("datadeps/slot_metadata.jl")
Loading
Loading