From 7795a0dca499412b71176ede1f21d3b74da5d434 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Mon, 19 Oct 2026 11:57:11 +0200 Subject: [PATCH 01/14] MPI: send structs that hold bit arrays as raw buffers automatically A struct with an array travelled through MPI.isend(serialize): Serialization copies the array into a fresh buffer, the receiver reads that into another fresh buffer and deserializes it into a third. Fresh memory is expensive on the Opterons, so a 40 MB struct of three arrays moved at ~80 MB/s. Dagger already had a raw-buffer path (inplace_mpi_parts / alloc / build), but only for dense arrays and for types that define the three hooks by hand. Types that define nothing now get it automatically when they qualify: a concrete struct with at least one plain Array of bits, directly or inside an immutable struct field. The arrays travel as raw buffers and every other field (bits, String, Dict, Vector{Any}, ...) in the header, which is serialized as before, so such a field costs what it did. Rebuilt like Serialization does (jl_new_structv, no constructor call), so a type with an inner constructor round-trips unchanged. A value in which one array is reachable twice opts out, so the sharing survives. Everything else is untouched; a more specific method (DenseArray, SparseMatrixCSC, user hooks) still wins. our cluster (Open MPI), a struct of three arrays made on rank 0 and consumed on rank 1 (the time includes making it), median of 5, serialize -> automatic raw buffers: two nodes 0.4 MB 6.6 -> 3.1 ms 4 MB 53.4 -> 19.5 ms 40 MB 580 -> 210 ms one node 0.4 MB 5.0 -> 8.6 ms* 4 MB 37.3 -> 13.4 ms 40 MB 580 -> 174 ms (* noise: 0.4 MB runs are dominated by task latency; min 3.4 -> 5.4 ms) Equal to defining the three hooks by hand (172 / 208 ms at 40 MB). Laptop, MPICH: 40 MB 119 -> 84 ms. Test (test/mpi/struct_transport.jl, 2 and 3 ranks, MPICH 5.0.2 and Open MPI 5.0.10): the decomposition, an eligible struct, a struct with a String and a Dict, a nested struct, a shared array (sharing must survive), an inner constructor with an invariant; a struct without arrays stays on the old path. --- src/memory-spaces.jl | 95 +++++++++++++++++++++++++++++++++--- test/mpi/cpu.jl | 1 + test/mpi/struct_transport.jl | 78 +++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 6 deletions(-) create mode 100644 test/mpi/struct_transport.jl diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bfc5afb8f..450a48603 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -252,14 +252,97 @@ move_type(from_proc::Processor, to_proc::Processor, ::Type{<:Chunk{T}}) where T # Decompose `x` -> `(parts::Tuple, header)`, where each part is a `DenseArray` # with a bitstype eltype. Return `nothing` to opt out of the raw-bytes path. -inplace_mpi_parts(x) = nothing +# +# Types that define nothing get the automatic decomposition below when they qualify: a concrete +# struct that holds at least one plain `Array` of bits, directly or inside an immutable struct field. +# The arrays travel as raw buffers; every other field (bits, `String`, `Dict`, `Vector{Any}`, ...) travels +# in the header, which is serialized as usual, so such a field costs what it always did. Measured on +# our cluster for a struct of three arrays, 40 MB between two nodes: 580 ms with `serialize`, 172 ms as raw +# buffers (`serialize` copies the data into a fresh buffer, the receiver reads it into another fresh +# buffer and deserializes it into a third; the raw path receives straight into the final array). +# A value in which one array is reachable twice (a shared field) opts out, so that the sharing, which +# `serialize` keeps, survives the transfer. +raw_field_kind(::Type{F}) where {F} = + isbitstype(F) ? :value : + (F <: Array && isconcretetype(F) && isbitstype(eltype(F))) ? :array : + (isconcretetype(F) && isstructtype(F) && !ismutabletype(F) && raw_has_array(F)) ? :struct : :value +function raw_has_array(::Type{T}) where {T} + (isconcretetype(T) && isstructtype(T) && !(T <: Array) && fieldcount(T) > 0) || return false + any(i -> raw_field_kind(fieldtype(T, i)) in (:array, :struct), 1:fieldcount(T)) +end +# Emit the expressions that read the parts / header values / array sizes of `x::T`, in field order +function raw_collect!(parts, vals, sizes, ::Type{T}, x) where {T} + for i in 1:fieldcount(T) + F = fieldtype(T, i) + f = :(getfield($x, $i)) + k = raw_field_kind(F) + if k === :array + push!(parts, f); push!(sizes, :(size($f))) + elseif k === :struct + raw_collect!(parts, vals, sizes, F, f) + else + push!(vals, f) + end + end +end +@generated function inplace_mpi_parts(x::T) where {T} + raw_has_array(T) || return :(nothing) + parts = Any[]; vals = Any[]; sizes = Any[] + raw_collect!(parts, vals, sizes, T, :x) + n = length(parts) + return quote + parts = ($(parts...),) + # one array reachable twice: leave it to `serialize`, which preserves the sharing + for i in 1:$n, j in (i + 1):$n + parts[i] === parts[j] && return nothing + end + (parts, (($(vals...),), ($(sizes...),))) + end +end # Allocate the receive buffers for `T` from `header` (host-resident; the sender # host-stages device arrays, and callers convert to the destination space). -inplace_mpi_alloc(::Type{T}, header) where T = - error("inplace_mpi_alloc not defined for $T") -# Rebuild a value of type `T` from received `parts` and `header`. -inplace_mpi_build(::Type{T}, parts, header) where T = - error("inplace_mpi_build not defined for $T") +function raw_alloc!(allocs, counter, ::Type{T}) where {T} + for i in 1:fieldcount(T) + F = fieldtype(T, i) + k = raw_field_kind(F) + if k === :array + counter[] += 1 + push!(allocs, :($F(undef, header[2][$(counter[])]))) + elseif k === :struct + raw_alloc!(allocs, counter, F) + end + end +end +@generated function inplace_mpi_alloc(::Type{T}, header) where {T} + raw_has_array(T) || return :(error("inplace_mpi_alloc not defined for ", $T)) + allocs = Any[] + raw_alloc!(allocs, Ref(0), T) + return :(($(allocs...),)) +end +# Rebuild a value of type `T` from received `parts` and `header`. Like `Serialization`, this does +# not call a constructor, so a type with an inner constructor round-trips as it was. +function raw_build(::Type{T}, pi, vi) where {T} + fields = Any[] + for i in 1:fieldcount(T) + F = fieldtype(T, i) + k = raw_field_kind(F) + if k === :array + pi[] += 1; push!(fields, :(parts[$(pi[])])) + elseif k === :struct + push!(fields, raw_build(F, pi, vi)) + else + vi[] += 1; push!(fields, :(header[1][$(vi[])])) + end + end + return quote + vals = Any[$(fields...)] + GC.@preserve vals ccall(:jl_new_structv, Any, (Any, Ptr{Any}, UInt32), $T, pointer(vals), $(length(fields)))::$T + end +end +@generated function inplace_mpi_build(::Type{T}, parts, header) where {T} + raw_has_array(T) || return :(error("inplace_mpi_build not defined for ", $T)) + return raw_build(T, Ref(0), Ref(0)) +end ### Aliasing and Memory Spans diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index ba97dfd08..cf6bf93da 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -147,6 +147,7 @@ end include("spawn.jl") include("noaliasing_args.jl") +include("struct_transport.jl") @testset "Datadeps" begin diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl new file mode 100644 index 000000000..174fca1dc --- /dev/null +++ b/test/mpi/struct_transport.jl @@ -0,0 +1,78 @@ +# A struct whose fields are bits or plain Arrays of bits travels between ranks as raw buffers (automatic +# `inplace_mpi_parts`), anything else as before; values and types must arrive unchanged either way. +struct RawBundle + keys::Vector{UInt64} + scale::Float64 + grid::Matrix{Float32} + n::Int +end +struct MixedBundle # a String and a Dict next to an array: the arrays go raw, the rest in the header + name::String + v::Vector{Float64} + tags::Dict{Symbol,Int} +end +struct InnerParts + xs::Vector{Float64} + id::Int +end +struct NestedBundle # an immutable struct holding arrays inside a struct: flattened + inner::InnerParts + ys::Vector{Int32} + label::String +end +struct NoArrays # nothing to send raw + name::String + a::Int +end +struct SharedBundle # one array reachable twice: must stay shared after the transfer + a::Vector{Float64} + b::Vector{Float64} +end +struct GuardedBundle # an inner constructor with an invariant: rebuilt without calling it, like Serialization + v::Vector{Float64} + total::Float64 + GuardedBundle(v) = new(v, sum(v)) +end +raw_make(n::Int) = RawBundle(collect(UInt64, 1:n), 2.5, fill(Float32(n), 3, 4), n) +raw_check(b::RawBundle) = (b.keys == collect(UInt64, 1:b.n)) && b.scale == 2.5 && b.grid == fill(Float32(b.n), 3, 4) +mixed_make(n::Int) = MixedBundle("m$n", fill(1.5, n), Dict(:a => n)) +mixed_check(b::MixedBundle) = b.name == "m" * string(length(b.v)) && all(==(1.5), b.v) && b.tags == Dict(:a => length(b.v)) +nested_make(n::Int) = NestedBundle(InnerParts(fill(3.0, n), n), fill(Int32(7), 2n), "nest") +nested_check(b::NestedBundle) = b.inner.id == length(b.inner.xs) && all(==(3.0), b.inner.xs) && length(b.ys) == 2 * b.inner.id && b.label == "nest" +shared_make(n::Int) = (v = fill(4.0, n); SharedBundle(v, v)) +shared_check(b::SharedBundle) = b.a === b.b && all(==(4.0), b.a) +guard_make(n::Int) = GuardedBundle(fill(2.0, n)) +guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) + +@testset "Automatic raw transport of structs of arrays" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pinned(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + other = nranks - 1 + @testset "the decomposition" begin + @test Dagger.inplace_mpi_parts(raw_make(5)) !== nothing + @test Dagger.inplace_mpi_parts(mixed_make(5)) !== nothing # the String and the Dict ride in the header + @test Dagger.inplace_mpi_parts(nested_make(5)) !== nothing + @test length(first(Dagger.inplace_mpi_parts(nested_make(5)))) == 2 # both arrays, the inner struct is flattened + @test Dagger.inplace_mpi_parts(NoArrays("x", 1)) === nothing + @test Dagger.inplace_mpi_parts(shared_make(5)) === nothing # shared array: left to serialize + @test Dagger.inplace_mpi_parts(3.0) === nothing + parts, header = Dagger.inplace_mpi_parts(raw_make(5)) + @test length(parts) == 2 && parts[1] isa Vector{UInt64} && parts[2] isa Matrix{Float32} + b = Dagger.inplace_mpi_build(RawBundle, Dagger.inplace_mpi_alloc(RawBundle, header), header) + @test size(b.keys) == (5,) && size(b.grid) == (3, 4) && b.n == 5 && b.scale == 2.5 + end + for (name, make, check, ret) in (("eligible struct", raw_make, raw_check, RawBundle), + ("struct with a String and a Dict", mixed_make, mixed_check, MixedBundle), + ("nested struct", nested_make, nested_check, NestedBundle), + ("shared array", shared_make, shared_check, SharedBundle), + ("inner constructor", guard_make, guard_check, GuardedBundle)) + @testset "$name moves between ranks" begin + for n in (3, 100_000) + a = Dagger.@spawn scope=pinned(0) return_type=ret make(n) + ok = Dagger.@spawn scope=pinned(other) return_type=Bool check(a) + @test fetch(ok) + end + end + end + MPI.Barrier(comm) +end From 91b36faa212c0fad3c3b1ae26aff581e3bd86b81 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 23 Oct 2026 21:26:43 +0200 Subject: [PATCH 02/14] MPI: restrict the automatic raw transport to values it rebuilds exactly The automatic decomposition of structs that hold bit arrays has to leave a value to serialize whenever taking it apart would not rebuild the same value, or would send the wrong bytes. A value now travels through serialize, as before the automatic path, when: - it is an array wrapper (SubArray, ReshapedArray, PermutedDimsArray, ...), at the top level or as a field. Its array field is the whole parent it views, so a 256 x 256 block view of a 2048 x 2048 matrix travelled as all 32 MB of the parent. copyto!(::DArray, ::Matrix) copies from one view per block, so the bytes grew with blocks x matrix size; 2 ranks, 256^2 blocks (laptop, MPICH), darray_copyto! from a matrix: 1024^2 0.15 s -> 0.023 s, 2048^2 2.1-2.9 s -> 0.056-0.105 s. At 8192^2 a single copyto! took longer than a 15-minute benchmark case. - a field is undefined (an inner constructor that leaves one unset): reading it field by field threw UndefRefError in the sender, which under MPI is a hang. - the type or a nested struct has its own Serialization.serialize method (Thunk, WeakChunk, user types): taking it apart would bypass it. This is decided at run time, once per type, because a generated function may not use reflection. - an array holds elements with padding between their fields: the MPI datatype of such a struct carries the packed bytes only, so the receiver's buffer did not match ("expected 24 bytes, got 15") and the task hung. - an array in the header shares memory with a raw part (a view or reshape of it), in addition to the shared-field case: the raw path would rebuild independent arrays. Types with their own hooks (Array, SparseMatrixCSC) are unchanged. Tests (test/mpi/struct_transport.jl, 2 and 3 ranks): wrappers are not decomposed and a struct holding a view sends only its own array raw (fails without the wrapper rule); an undefined field, a type with its own serialize, padded elements, an empty array, a Union field, tuples and named tuples, and 300 random nested tuples of arrays, strings and integers that must round-trip with the same type and contents. The undefined-field and padded-element cases hang the job without the opt-outs. --- src/memory-spaces.jl | 76 ++++++++++++++++++---- test/mpi/struct_transport.jl | 123 ++++++++++++++++++++++++++++++++++- 2 files changed, 185 insertions(+), 14 deletions(-) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 450a48603..33f677dc4 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -262,41 +262,91 @@ move_type(from_proc::Processor, to_proc::Processor, ::Type{<:Chunk{T}}) where T # buffer and deserializes it into a third; the raw path receives straight into the final array). # A value in which one array is reachable twice (a shared field) opts out, so that the sharing, which # `serialize` keeps, survives the transfer. +# Elements whose bytes are all data: the MPI datatype of a struct with padding between its fields +# carries the packed bytes only, so a buffer of such elements would not match the one the receiver allocates +raw_dense(::Type{T}) where {T} = isprimitivetype(T) || + (isbitstype(T) && fieldcount(T) > 0 && all(i -> raw_dense(fieldtype(T, i)), 1:fieldcount(T)) && + sum(i -> sizeof(fieldtype(T, i)), 1:fieldcount(T)) == sizeof(T)) raw_field_kind(::Type{F}) where {F} = isbitstype(F) ? :value : - (F <: Array && isconcretetype(F) && isbitstype(eltype(F))) ? :array : + (F <: Array && isconcretetype(F) && raw_dense(eltype(F))) ? :array : (isconcretetype(F) && isstructtype(F) && !ismutabletype(F) && raw_has_array(F)) ? :struct : :value +# An array *wrapper* (`SubArray`, `ReshapedArray`, `PermutedDimsArray`, ...) is never decomposed: its +# array field is the whole parent, which it does not own. A 256 x 256 view of a 2048 x 2048 matrix +# travelled as all 32 MB of the parent, so `copyto!(::DArray, ::Matrix)` (one view per block) grew +# with blocks x matrix size: 2048^2 in 256^2 blocks, 2 ranks: 2.1-2.9 s. `serialize` sends only the +# viewed elements. +# A type with its own `Serialization.serialize` method (`Thunk`, `WeakChunk`, ...) must keep it: taking the +# value apart would bypass it. Only the generic method (and the one for tuples) is replaced. This needs +# reflection, which a generated function may not use, so it is decided at run time, once per type. +function raw_plain_serialize(::Type{T}) where {T} + try + m = which(Serialization.serialize, Tuple{Serialization.AbstractSerializer, T}) + p = Base.unwrap_unionall(m.sig).parameters[3] + return p === Any || p === Tuple + catch + return false + end +end function raw_has_array(::Type{T}) where {T} - (isconcretetype(T) && isstructtype(T) && !(T <: Array) && fieldcount(T) > 0) || return false + (isconcretetype(T) && isstructtype(T) && !(T <: AbstractArray) && fieldcount(T) > 0) || return false any(i -> raw_field_kind(fieldtype(T, i)) in (:array, :struct), 1:fieldcount(T)) end -# Emit the expressions that read the parts / header values / array sizes of `x::T`, in field order -function raw_collect!(parts, vals, sizes, ::Type{T}, x) where {T} +# Emit the expressions that read the parts / header values / array sizes of `x::T`, in field order. `checks` +# collects `isdefined` tests, outermost first: a struct with an undefined field (an inner constructor that +# leaves one unset) cannot be read field by field, so it is left to `serialize`, which handles it. +function raw_collect!(parts, vals, sizes, checks, ::Type{T}, x) where {T} for i in 1:fieldcount(T) F = fieldtype(T, i) f = :(getfield($x, $i)) + isbitstype(F) || push!(checks, :(isdefined($x, $i))) k = raw_field_kind(F) if k === :array push!(parts, f); push!(sizes, :(size($f))) elseif k === :struct - raw_collect!(parts, vals, sizes, F, f) + raw_collect!(parts, vals, sizes, checks, F, f) else push!(vals, f) end end end -@generated function inplace_mpi_parts(x::T) where {T} - raw_has_array(T) || return :(nothing) - parts = Any[]; vals = Any[]; sizes = Any[] - raw_collect!(parts, vals, sizes, T, :x) +function raw_all_plain(::Type{T}) where {T} + raw_plain_serialize(T) || return false + for i in 1:fieldcount(T) + F = fieldtype(T, i) + raw_field_kind(F) === :struct && !raw_all_plain(F) && return false + end + return true +end +const RAW_ENABLED = Dict{DataType,Bool}() +const RAW_ENABLED_LOCK = ReentrantLock() +function raw_enabled(::Type{T}) where {T} + lock(RAW_ENABLED_LOCK) do + get!(() -> raw_all_plain(T), RAW_ENABLED, T) + end +end +@generated raw_candidate(::T) where {T} = raw_has_array(T) # decided at compile time: no lock for the common values +inplace_mpi_parts(x::T) where {T} = raw_candidate(x) && raw_enabled(T) ? raw_parts(x) : nothing +@generated function raw_parts(x::T) where {T} + parts = Any[]; vals = Any[]; sizes = Any[]; checks = Any[] + raw_collect!(parts, vals, sizes, checks, T, :x) n = length(parts) + ok = isempty(checks) ? true : foldr((c, r) -> :($c && $r), checks) return quote + $ok || return nothing parts = ($(parts...),) - # one array reachable twice: leave it to `serialize`, which preserves the sharing - for i in 1:$n, j in (i + 1):$n - parts[i] === parts[j] && return nothing + vals = ($(vals...),) + # Memory reachable twice (a shared field, or an array next to a view or reshape of it): leave it + # to `serialize`, which keeps the sharing; the raw path would rebuild two independent arrays + for i in 1:$n + for j in (i + 1):$n + Base.mightalias(parts[i], parts[j]) && return nothing + end + for v in vals + v isa AbstractArray && Base.mightalias(parts[i], v) && return nothing + end end - (parts, (($(vals...),), ($(sizes...),))) + (parts, (vals, ($(sizes...),))) end end # Allocate the receive buffers for `T` from `header` (host-resident; the sender diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index 174fca1dc..3147f163b 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -1,3 +1,4 @@ +import Serialization # A struct whose fields are bits or plain Arrays of bits travels between ranks as raw buffers (automatic # `inplace_mpi_parts`), anything else as before; values and types must arrive unchanged either way. struct RawBundle @@ -20,6 +21,10 @@ struct NestedBundle # an immutable struct holding arrays insi ys::Vector{Int32} label::String end +struct ViewBundle # an array next to a view: only the array goes raw + a::Vector{Float64} + v::SubArray{Float64,2,Matrix{Float64},Tuple{UnitRange{Int},UnitRange{Int}},false} +end struct NoArrays # nothing to send raw name::String a::Int @@ -33,6 +38,77 @@ struct GuardedBundle # an inner constructor with an invariant: total::Float64 GuardedBundle(v) = new(v, sum(v)) end +struct PartlyUndefined # an inner constructor that leaves a field unset: cannot be read field by field + v::Vector{Float64} + note::String + PartlyUndefined(v) = new(v) +end +struct Padded # padding between the fields: an array of these is left to serialize + x::Float32 + y::Int8 +end +struct PaddedBundle + a::Vector{Padded} + empty::Matrix{Float64} + n::Union{Nothing,Vector{Int}} # a Union field rides in the header +end +struct OwnSerialized # a type with its own `serialize` keeps it + v::Vector{Float64} +end +Serialization.serialize(s::Serialization.AbstractSerializer, x::OwnSerialized) = + (Serialization.serialize_type(s, OwnSerialized); Serialization.serialize(s, x.v .* 2)) +Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnSerialized}) = + OwnSerialized(Serialization.deserialize(s)) +struct ViewSharing # a view of the array next to it: the sharing must survive + a::Vector{Float64} + v::SubArray{Float64,1,Vector{Float64},Tuple{UnitRange{Int}},true} +end +padded_make(n::Int) = PaddedBundle([Padded(Float32(i), Int8(i % 100)) for i in 1:n], zeros(0, 3), n > 3 ? collect(1:n) : nothing) +padded_check(b::PaddedBundle) = b.a == [Padded(Float32(i), Int8(i % 100)) for i in 1:length(b.a)] && size(b.empty) == (0, 3) && + (length(b.a) > 3 ? b.n == collect(1:length(b.a)) : b.n === nothing) +undef_make(n::Int) = PartlyUndefined(fill(1.0, n)) +undef_check(b::PartlyUndefined) = all(==(1.0), b.v) && !isdefined(b, :note) +tuple_make(n::Int) = (fill(2.0, n), n, "tuple", (collect(Int16, 1:n),)) +tuple_check(t::Tuple) = t[1] == fill(2.0, t[2]) && t[3] == "tuple" && t[4][1] == collect(Int16, 1:t[2]) +own_make(n::Int) = OwnSerialized(fill(1.0, n)) +own_check(b::OwnSerialized) = all(==(2.0), b.v) +view_make(n::Int) = (a = fill(1.0, n); ViewSharing(a, view(a, 1:n))) +view_check(b::ViewSharing) = (b.v[1] = 9.0; b.a[1] == 9.0) # still the same memory + +# Random values built only from arrays of bits, strings and integers inside nested tuples: whatever the +# decomposition does, the value that arrives must be `isequal` to the one sent, with the same type. +function random_value(rng, depth=0) + eltypes = (Int8, UInt16, Int32, Float32, Float64, ComplexF64, Bool) + items = Any[] + for _ in 1:rand(rng, 1:4) + r = rand(rng) + if r < 0.5 + T = rand(rng, eltypes) + dims = ntuple(_ -> rand(rng, 0:5), rand(rng, 1:3)) + push!(items, T === Bool ? rand(rng, Bool, dims...) : rand(rng, T, dims...)) + elseif r < 0.7 + push!(items, rand(rng, Int)) + elseif r < 0.85 + push!(items, randstring(rng, rand(rng, 0:6))) + elseif depth < 2 + push!(items, random_value(rng, depth + 1)) + end + end + return rand(rng, Bool) ? Tuple(items) : NamedTuple{ntuple(i -> Symbol("f", i), length(items))}(Tuple(items)) +end +function local_roundtrip(x) + r = Dagger.inplace_mpi_parts(x) + r === nothing && return x + parts, header = r + io = IOBuffer(); Serialization.serialize(io, header); seekstart(io) + header = Serialization.deserialize(io) + T = typeof(x) + alloc = Dagger.inplace_mpi_alloc(T, header) + foreach((d, s) -> copyto!(d, s), alloc, parts) + return Dagger.inplace_mpi_build(T, alloc, header) +end +random_make(seed::Int) = random_value(Random.MersenneTwister(seed)) + raw_make(n::Int) = RawBundle(collect(UInt64, 1:n), 2.5, fill(Float32(n), 3, 4), n) raw_check(b::RawBundle) = (b.keys == collect(UInt64, 1:b.n)) && b.scale == 2.5 && b.grid == fill(Float32(b.n), 3, 4) mixed_make(n::Int) = MixedBundle("m$n", fill(1.5, n), Dict(:a => n)) @@ -56,16 +132,52 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) @test Dagger.inplace_mpi_parts(NoArrays("x", 1)) === nothing @test Dagger.inplace_mpi_parts(shared_make(5)) === nothing # shared array: left to serialize @test Dagger.inplace_mpi_parts(3.0) === nothing + # An array wrapper is not decomposed: its array field is the whole parent + big = rand(64, 64) + @test Dagger.inplace_mpi_parts(view(big, 1:8, 1:8)) === nothing + @test Dagger.inplace_mpi_parts(reshape(view(big, :, 1), 8, 8)) === nothing + @test Dagger.inplace_mpi_parts(PermutedDimsArray(big, (2, 1))) === nothing + # ...also not as a field of a struct: the view rides in the serialized header + vb = ViewBundle(collect(1.0:4.0), view(big, 1:2, 1:2)) + vparts, vheader = Dagger.inplace_mpi_parts(vb) + @test length(vparts) == 1 && vparts[1] === vb.a parts, header = Dagger.inplace_mpi_parts(raw_make(5)) @test length(parts) == 2 && parts[1] isa Vector{UInt64} && parts[2] isa Matrix{Float32} b = Dagger.inplace_mpi_build(RawBundle, Dagger.inplace_mpi_alloc(RawBundle, header), header) @test size(b.keys) == (5,) && size(b.grid) == (3, 4) && b.n == 5 && b.scale == 2.5 end + @testset "edge cases fall back to serialize or round-trip exactly" begin + @test Dagger.inplace_mpi_parts(undef_make(3)) === nothing # an undefined field cannot be read + @test Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])) !== nothing # the other array still goes raw + @test length(first(Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])))) == 1 + @test Dagger.inplace_mpi_parts(own_make(3)) === nothing # its own `serialize` is kept + @test Dagger.inplace_mpi_parts(view_make(3)) === nothing # array and a view of it: sharing kept + let a = collect(1.0:4.0) + @test Dagger.inplace_mpi_parts(ViewBundle(a, view(reshape(rand(4, 4), 4, 4), 1:2, 1:2))) !== nothing + @test Dagger.inplace_mpi_parts((a, reshape(a, 2, 2))) === nothing # a reshape shares the memory + @test Dagger.inplace_mpi_parts((a, a)) === nothing + end + @test Dagger.inplace_mpi_parts(Union{Nothing,Vector{Int}}[nothing][1]) === nothing + b = local_roundtrip(padded_make(10)); @test padded_check(b) && b isa PaddedBundle + b = local_roundtrip(tuple_make(4)); @test tuple_check(b) + b = local_roundtrip(padded_make(2)); @test padded_check(b) + end + @testset "random values keep their type and contents" begin + for seed in 1:300 + x = random_make(seed) + y = local_roundtrip(x) + @test typeof(y) === typeof(x) + @test isequal(y, x) + end + end for (name, make, check, ret) in (("eligible struct", raw_make, raw_check, RawBundle), ("struct with a String and a Dict", mixed_make, mixed_check, MixedBundle), ("nested struct", nested_make, nested_check, NestedBundle), ("shared array", shared_make, shared_check, SharedBundle), - ("inner constructor", guard_make, guard_check, GuardedBundle)) + ("inner constructor", guard_make, guard_check, GuardedBundle), + ("padded elements, empty array, Union field", padded_make, padded_check, PaddedBundle), + ("undefined field", undef_make, undef_check, PartlyUndefined), + ("own serialize", own_make, own_check, OwnSerialized)) @testset "$name moves between ranks" begin for n in (3, 100_000) a = Dagger.@spawn scope=pinned(0) return_type=ret make(n) @@ -74,5 +186,14 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) end end end + @testset "tuples and random values move between ranks" begin + a = Dagger.@spawn scope=pinned(0) return_type=Any tuple_make(1000) + @test fetch(Dagger.@spawn scope=pinned(other) return_type=Bool tuple_check(a)) + for seed in (3, 17, 42, 99, 123) + a = Dagger.@spawn scope=pinned(0) return_type=Any random_make(seed) + r = Dagger.@spawn scope=pinned(other) return_type=Any identity(a) + @test isequal(fetch(r), random_make(seed)) + end + end MPI.Barrier(comm) end From a32e9056c89f05db7982f34de6f4b3bc335ad63b Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:01:53 -0700 Subject: [PATCH 03/14] Preserve raw-buffer sharing through serialized header graphs Direct field checks miss raw arrays referenced through Dict, Ref, non-isbits arrays, SimpleVector, or cycles. Trace the serialized header graph with an identity visited set and fall back when it reaches a raw part. Handle host Memory storage and conservatively reject unsupported non-isbits backends. Scalar metadata and scalar-entry Dicts retain their allocation-free path. The focused pre-fix round-trip probe loses nested and cyclic identities; fixed probes preserve them. The full two-rank, two-default/one-interactive thread struct transport suite passes 658 assertions per rank, including cross-rank header sharing and 300 randomized nested values. After ten warmups and GC, minimum of five 5000-call allocation measurements remains zero bytes and allocations before/after for plain and scalar-Dict headers. Final minima are 0.139/0.256 ms versus 0.182/0.150 ms on the base; these small metadata probes do not measure end-to-end transport throughput. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 11 ++++++ src/memory-spaces.jl | 65 ++++++++++++++++++++++++++++++++++-- test/mpi/struct_transport.jl | 24 ++++++++++++- 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ad8c5740e..4f830deed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1217,3 +1217,14 @@ this section verbatim). Each entry is one bullet starting with `- `. 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. + +109. **A separately serialized header can sever a raw buffer's aliases.** + A struct's array can also be reachable through a Dict, Ref, non-isbits + array, SimpleVector, or cyclic header graph. Serializing that header + apart from its raw array duplicates the array and loses sharing. Trace + serialized header contents with an identity visited set and fall back + for sharing or unsupported array backends. Dict serializes entries, so + scalar key/value dictionaries need no graph allocation; Julia 1.11+ + Memory storage must be handled when walking ordinary containers. Test + actual serialization and cross-rank identity, not a fallback that simply + returns the original object. diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 28a733fc8..3bcdb9a77 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -331,6 +331,64 @@ function raw_enabled(::Type{T}) where {T} end @generated raw_candidate(::T) where {T} = raw_has_array(T) # decided at compile time: no lock for the common values inplace_mpi_parts(x::T) where {T} = raw_candidate(x) && raw_enabled(T) ? raw_parts(x) : nothing + +raw_header_scalar_type(::Type{T}) where {T} = isbitstype(T) || T <: Union{String,Symbol,Type,Module} +raw_header_atomic(x) = raw_header_scalar_type(typeof(x)) +# Dict serializes its entries, not its backing arrays. Scalar key/value types +# cannot carry raw parts; avoid a visited set for ordinary Symbol/Int metadata. +raw_header_atomic(x::Dict{K,V}) where {K,V} = raw_header_scalar_type(K) && raw_header_scalar_type(V) +raw_header_array(x) = x isa Array +@static if isdefined(Core, :Memory) + raw_header_array(x::Core.Memory) = true +end +function raw_header_disjoint(x, parts, seen) + raw_header_atomic(x) && return true + if x isa AbstractArray || raw_header_array(x) + for part in parts + Base.mightalias(part, x) && return false + end + isbitstype(eltype(x)) && return true + # Unknown array backends need not support scalar element access. + raw_header_array(x) || return false + end + x in seen && return true + push!(seen, x) + if raw_header_array(x) + for i in eachindex(x) + isassigned(x, i) || continue + raw_header_disjoint(x[i], parts, seen) || return false + end + elseif x isa Dict + for (key, value) in x + raw_header_disjoint(key, parts, seen) || return false + raw_header_disjoint(value, parts, seen) || return false + end + elseif x isa Core.SimpleVector + for value in x + raw_header_disjoint(value, parts, seen) || return false + end + else + for i in 1:fieldcount(typeof(x)) + isdefined(x, i) || continue + raw_header_disjoint(getfield(x, i), parts, seen) || return false + end + end + return true +end +@noinline function raw_headers_disjoint_slow(vals, parts) + seen = Base.IdSet{Any}() + for value in vals + raw_header_disjoint(value, parts, seen) || return false + end + return true +end +function raw_headers_disjoint(vals, parts) + # Ordinary scalar/string headers need no graph walk or visited set. + for value in vals + raw_header_atomic(value) || return raw_headers_disjoint_slow(vals, parts) + end + return true +end @generated function raw_parts(x::T) where {T} parts = Any[]; vals = Any[]; sizes = Any[]; checks = Any[] raw_collect!(parts, vals, sizes, checks, T, :x) @@ -346,10 +404,11 @@ inplace_mpi_parts(x::T) where {T} = raw_candidate(x) && raw_enabled(T) ? raw_par for j in (i + 1):$n Base.mightalias(parts[i], parts[j]) && return nothing end - for v in vals - v isa AbstractArray && Base.mightalias(parts[i], v) && return nothing - end end + # Header objects can hide a reference to a raw part inside a Dict, + # Ref, non-isbits array or another struct. Serializing the header + # separately would sever that sharing, including cyclic graphs. + raw_headers_disjoint(vals, parts) || return nothing (parts, (vals, ($(sizes...),))) end end diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index 3147f163b..368f5b050 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -33,6 +33,10 @@ struct SharedBundle # one array reachable twice: must stay sh a::Vector{Float64} b::Vector{Float64} end +struct HeaderGraphSharing + a::Vector{Float64} + header::Any +end struct GuardedBundle # an inner constructor with an invariant: rebuilt without calling it, like Serialization v::Vector{Float64} total::Float64 @@ -98,7 +102,10 @@ function random_value(rng, depth=0) end function local_roundtrip(x) r = Dagger.inplace_mpi_parts(x) - r === nothing && return x + if r === nothing + io = IOBuffer(); Serialization.serialize(io, x); seekstart(io) + return Serialization.deserialize(io) + end parts, header = r io = IOBuffer(); Serialization.serialize(io, header); seekstart(io) header = Serialization.deserialize(io) @@ -117,6 +124,8 @@ nested_make(n::Int) = NestedBundle(InnerParts(fill(3.0, n), n), fill(Int32(7), 2 nested_check(b::NestedBundle) = b.inner.id == length(b.inner.xs) && all(==(3.0), b.inner.xs) && length(b.ys) == 2 * b.inner.id && b.label == "nest" shared_make(n::Int) = (v = fill(4.0, n); SharedBundle(v, v)) shared_check(b::SharedBundle) = b.a === b.b && all(==(4.0), b.a) +graph_make(n::Int) = (a = fill(5.0, n); HeaderGraphSharing(a, Dict{Symbol,Any}(:a => Any[Ref(a)]))) +graph_check(b::HeaderGraphSharing) = b.a === b.header[:a][1][] && all(==(5.0), b.a) guard_make(n::Int) = GuardedBundle(fill(2.0, n)) guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) @@ -152,6 +161,18 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) @test length(first(Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])))) == 1 @test Dagger.inplace_mpi_parts(own_make(3)) === nothing # its own `serialize` is kept @test Dagger.inplace_mpi_parts(view_make(3)) === nothing # array and a view of it: sharing kept + let a = ones(4) + header = Dict{Symbol,Any}(:a => Any[Ref(a)]) + @test Dagger.inplace_mpi_parts(HeaderGraphSharing(a, header)) === nothing + @test Dagger.inplace_mpi_parts(HeaderGraphSharing(a, Core.svec(a))) === nothing + cyclic = Dict{Symbol,Any}(:a => a) + cyclic[:self] = cyclic + @test Dagger.inplace_mpi_parts(HeaderGraphSharing(a, cyclic)) === nothing + separate = Dict{Symbol,Any}(:a => Any[Ref(zeros(4))]) + @test Dagger.inplace_mpi_parts(HeaderGraphSharing(a, separate)) !== nothing + result = local_roundtrip(HeaderGraphSharing(a, header)) + @test result.a === result.header[:a][1][] + end let a = collect(1.0:4.0) @test Dagger.inplace_mpi_parts(ViewBundle(a, view(reshape(rand(4, 4), 4, 4), 1:2, 1:2))) !== nothing @test Dagger.inplace_mpi_parts((a, reshape(a, 2, 2))) === nothing # a reshape shares the memory @@ -174,6 +195,7 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) ("struct with a String and a Dict", mixed_make, mixed_check, MixedBundle), ("nested struct", nested_make, nested_check, NestedBundle), ("shared array", shared_make, shared_check, SharedBundle), + ("shared header graph", graph_make, graph_check, HeaderGraphSharing), ("inner constructor", guard_make, guard_check, GuardedBundle), ("padded elements, empty array, Union field", padded_make, padded_check, PaddedBundle), ("undefined field", undef_make, undef_check, PartlyUndefined), From d5bfb2f7d6d1bcc92ca8be34c0d476bbd6093e58 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:02:02 -0700 Subject: [PATCH 04/14] Invalidate automatic transport eligibility after method additions A type first transferred with default serialization remained eligible forever after a package defined custom serialization. Track the method world while holding the eligibility lock and re-evaluate cached answers when methods change. The late-method probe fails before this repair and passes afterwards; the final two-rank transport suite passes 658 assertions per rank. Written by an AI agent on jpsamaroo's review feedback. --- src/memory-spaces.jl | 8 ++++++++ test/mpi/struct_transport.jl | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 3bcdb9a77..8597a469d 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -324,8 +324,16 @@ function raw_all_plain(::Type{T}) where {T} end const RAW_ENABLED = Dict{DataType,Bool}() const RAW_ENABLED_LOCK = ReentrantLock() +const RAW_ENABLED_WORLD = Ref{UInt}(0) function raw_enabled(::Type{T}) where {T} lock(RAW_ENABLED_LOCK) do + # A package loaded after the first transfer can add a custom + # serializer. Cached eligibility must follow that method-table change. + world = Base.get_world_counter() + if RAW_ENABLED_WORLD[] != world + empty!(RAW_ENABLED) + RAW_ENABLED_WORLD[] = world + end get!(() -> raw_all_plain(T), RAW_ENABLED, T) end end diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index 368f5b050..85d85c663 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -59,6 +59,9 @@ end struct OwnSerialized # a type with its own `serialize` keeps it v::Vector{Float64} end +struct LateSerialized + v::Vector{Float64} +end Serialization.serialize(s::Serialization.AbstractSerializer, x::OwnSerialized) = (Serialization.serialize_type(s, OwnSerialized); Serialization.serialize(s, x.v .* 2)) Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnSerialized}) = @@ -160,6 +163,11 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) @test Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])) !== nothing # the other array still goes raw @test length(first(Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])))) == 1 @test Dagger.inplace_mpi_parts(own_make(3)) === nothing # its own `serialize` is kept + late = LateSerialized(ones(3)) + @test Dagger.inplace_mpi_parts(late) !== nothing + @eval Serialization.serialize(s::Serialization.AbstractSerializer, x::LateSerialized) = + (Serialization.serialize_type(s, LateSerialized); Serialization.serialize(s, 2 .* x.v)) + @test Base.invokelatest(Dagger.inplace_mpi_parts, late) === nothing @test Dagger.inplace_mpi_parts(view_make(3)) === nothing # array and a view of it: sharing kept let a = ones(4) header = Dict{Symbol,Any}(:a => Any[Ref(a)]) From 44c5a87a024679bde5db77f67167d2da7a2331c2 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:02:11 -0700 Subject: [PATCH 05/14] Query the serializer dispatch actually used by MPI buffers Eligibility queried at AbstractSerializer misses custom methods specialized on the IOBuffer-backed Serializer that MPI uses. Query that concrete dispatch so these types retain their own wire representation. The concrete-serializer probe fails before the repair and passes afterwards, alongside the 658-assertion two-rank suite. Written by an AI agent on jpsamaroo's review feedback. --- src/memory-spaces.jl | 5 ++++- test/mpi/struct_transport.jl | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 8597a469d..58ced981f 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -285,7 +285,10 @@ raw_field_kind(::Type{F}) where {F} = # reflection, which a generated function may not use, so it is decided at run time, once per type. function raw_plain_serialize(::Type{T}) where {T} try - m = which(Serialization.serialize, Tuple{Serialization.AbstractSerializer, T}) + # MPI.serialize uses an IOBuffer-backed Serializer. Query its actual + # dispatch too: a method specialized on Serializer would be invisible + # when asking which method accepts AbstractSerializer in general. + m = which(Serialization.serialize, Tuple{Serialization.Serializer{IOBuffer}, T}) p = Base.unwrap_unionall(m.sig).parameters[3] return p === Any || p === Tuple catch diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index 85d85c663..e4727a118 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -62,6 +62,11 @@ end struct LateSerialized v::Vector{Float64} end +struct ConcreteSerialized + v::Vector{Float64} +end +Serialization.serialize(s::Serialization.Serializer{IOBuffer}, x::ConcreteSerialized) = + (Serialization.serialize_type(s, ConcreteSerialized); Serialization.serialize(s, 2 .* x.v)) Serialization.serialize(s::Serialization.AbstractSerializer, x::OwnSerialized) = (Serialization.serialize_type(s, OwnSerialized); Serialization.serialize(s, x.v .* 2)) Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnSerialized}) = @@ -163,6 +168,7 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) @test Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])) !== nothing # the other array still goes raw @test length(first(Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])))) == 1 @test Dagger.inplace_mpi_parts(own_make(3)) === nothing # its own `serialize` is kept + @test Dagger.inplace_mpi_parts(ConcreteSerialized(ones(3))) === nothing late = LateSerialized(ones(3)) @test Dagger.inplace_mpi_parts(late) !== nothing @eval Serialization.serialize(s::Serialization.AbstractSerializer, x::LateSerialized) = From 0ea7100e39a15cb6070dcfdc21fab0ce1507d0de Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 16:02:24 -0700 Subject: [PATCH 06/14] Keep custom deserializers on the ordinary serialization path Automatic reconstruction bypasses deserialize methods even when serialize is generic. Require generic deserializer dispatch for every decomposed type as well, so a custom receive-side transformation is preserved. The deserialize-only probe fails before this check and passes afterwards; the final two-rank suite passes 658 assertions on each rank. Written by an AI agent on jpsamaroo's review feedback. --- src/memory-spaces.jl | 17 +++++++++++++---- test/mpi/struct_transport.jl | 6 ++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 58ced981f..b2014dd2d 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -280,9 +280,10 @@ raw_field_kind(::Type{F}) where {F} = # travelled as all 32 MB of the parent, so `copyto!(::DArray, ::Matrix)` (one view per block) grew # with blocks x matrix size: 2048^2 in 256^2 blocks, 2 ranks: 2.1-2.9 s. `serialize` sends only the # viewed elements. -# A type with its own `Serialization.serialize` method (`Thunk`, `WeakChunk`, ...) must keep it: taking the -# value apart would bypass it. Only the generic method (and the one for tuples) is replaced. This needs -# reflection, which a generated function may not use, so it is decided at run time, once per type. +# Types with their own Serialization serialize or deserialize methods must keep +# those methods: taking a value apart or rebuilding it would bypass them. Only +# generic struct/tuple dispatch is replaced. Reflection runs outside generated +# functions and its per-type answers are invalidated when methods are added. function raw_plain_serialize(::Type{T}) where {T} try # MPI.serialize uses an IOBuffer-backed Serializer. Query its actual @@ -295,6 +296,14 @@ function raw_plain_serialize(::Type{T}) where {T} return false end end +function raw_plain_deserialize(::Type{T}) where {T} + try + m = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Type{T}}) + return Base.unwrap_unionall(m.sig).parameters[3] === DataType + catch + return false + end +end function raw_has_array(::Type{T}) where {T} (isconcretetype(T) && isstructtype(T) && !(T <: AbstractArray) && fieldcount(T) > 0) || return false any(i -> raw_field_kind(fieldtype(T, i)) in (:array, :struct), 1:fieldcount(T)) @@ -318,7 +327,7 @@ function raw_collect!(parts, vals, sizes, checks, ::Type{T}, x) where {T} end end function raw_all_plain(::Type{T}) where {T} - raw_plain_serialize(T) || return false + (raw_plain_serialize(T) && raw_plain_deserialize(T)) || return false for i in 1:fieldcount(T) F = fieldtype(T, i) raw_field_kind(F) === :struct && !raw_all_plain(F) && return false diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index e4727a118..53a92b570 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -67,6 +67,11 @@ struct ConcreteSerialized end Serialization.serialize(s::Serialization.Serializer{IOBuffer}, x::ConcreteSerialized) = (Serialization.serialize_type(s, ConcreteSerialized); Serialization.serialize(s, 2 .* x.v)) +struct OwnDeserialized + v::Vector{Float64} +end +Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnDeserialized}) = + OwnDeserialized(2 .* Serialization.deserialize(s)) Serialization.serialize(s::Serialization.AbstractSerializer, x::OwnSerialized) = (Serialization.serialize_type(s, OwnSerialized); Serialization.serialize(s, x.v .* 2)) Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnSerialized}) = @@ -169,6 +174,7 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) @test length(first(Dagger.inplace_mpi_parts((Padded[Padded(1, 2)], [1.0])))) == 1 @test Dagger.inplace_mpi_parts(own_make(3)) === nothing # its own `serialize` is kept @test Dagger.inplace_mpi_parts(ConcreteSerialized(ones(3))) === nothing + @test Dagger.inplace_mpi_parts(OwnDeserialized(ones(3))) === nothing late = LateSerialized(ones(3)) @test Dagger.inplace_mpi_parts(late) !== nothing @eval Serialization.serialize(s::Serialization.AbstractSerializer, x::LateSerialized) = From 536648c92bb2952485661e49255b172e332c8a45 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:13:18 -0700 Subject: [PATCH 07/14] Preserve empty array identities in automatic MPI decomposition mightalias reports no memory overlap for the same empty array. Check object identity too, and inspect immutable array-header fields before treating their bits elements as scalar data; unsupported mutable handles keep ordinary serialization. Independent pre-fix controls lose aliases for direct, Ref and custom-wrapper sharing. Focused two-rank tests now pass 14 assertions per rank, including push! propagation across ranks, empty ordinary-view serialization controls, disjoint wrapper/view eligibility and a wrapper whose scalar indexing throws. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 3 ++ src/memory-spaces.jl | 15 +++++--- test/mpi/struct_transport.jl | 2 ++ test/mpi/struct_transport_empty.jl | 57 ++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 test/mpi/struct_transport_empty.jl diff --git a/AGENTS.md b/AGENTS.md index 4f830deed..8639cb644 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1228,3 +1228,6 @@ this section verbatim). Each entry is one bullet starting with `- `. Memory storage must be handled when walking ordinary containers. Test actual serialization and cross-rank identity, not a fallback that simply returns the original object. + Empty arrays share object identity even though `mightalias` reports no + memory overlap. Check `===` too, and inspect immutable array-wrapper + fields: an isbits element type does not make the wrapper's parent scalar. diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index b2014dd2d..02026803c 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -365,11 +365,16 @@ function raw_header_disjoint(x, parts, seen) raw_header_atomic(x) && return true if x isa AbstractArray || raw_header_array(x) for part in parts - Base.mightalias(part, x) && return false + (part === x || Base.mightalias(part, x)) && return false + end + if !raw_header_array(x) + # Immutable wrappers can preserve their parents even when empty, + # where mightalias is false. Walk their fields without indexing + # arbitrary backends; mutable backend handles stay serialized. + ismutabletype(typeof(x)) && return false + elseif isbitstype(eltype(x)) + return true end - isbitstype(eltype(x)) && return true - # Unknown array backends need not support scalar element access. - raw_header_array(x) || return false end x in seen && return true push!(seen, x) @@ -422,7 +427,7 @@ end # to `serialize`, which keeps the sharing; the raw path would rebuild two independent arrays for i in 1:$n for j in (i + 1):$n - Base.mightalias(parts[i], parts[j]) && return nothing + (parts[i] === parts[j] || Base.mightalias(parts[i], parts[j])) && return nothing end end # Header objects can hide a reference to a raw part inside a Dict, diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index 53a92b570..942b34c9c 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -239,3 +239,5 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) end MPI.Barrier(comm) end + +include("struct_transport_empty.jl") diff --git a/test/mpi/struct_transport_empty.jl b/test/mpi/struct_transport_empty.jl new file mode 100644 index 000000000..8ab42f4e5 --- /dev/null +++ b/test/mpi/struct_transport_empty.jl @@ -0,0 +1,57 @@ +struct RawHeaderVector <: AbstractVector{Float64} + parent::Vector{Float64} +end +Base.size(x::RawHeaderVector) = size(x.parent) +Base.getindex(::RawHeaderVector, ::Int) = error("Header transport must not require scalar indexing") +Base.dataids(x::RawHeaderVector) = Base.dataids(x.parent) + +function empty_shared_check(x::SharedBundle) + x.a === x.b || return false + push!(x.a, 7.0) + return x.b == [7.0] +end +empty_ref_make(::Int) = (a = Float64[]; HeaderGraphSharing(a, Ref(a))) +function empty_ref_check(x::HeaderGraphSharing) + x.a === x.header[] || return false + push!(x.a, 7.0) + return x.header[] == [7.0] +end +empty_wrapper_make(::Int) = (a = Float64[]; HeaderGraphSharing(a, RawHeaderVector(a))) +function empty_wrapper_check(x::HeaderGraphSharing) + x.a === x.header.parent || return false + push!(x.a, 7.0) + return x.header.parent == [7.0] +end + +@testset "Empty raw arrays preserve shared object identity" begin + for (make, check) in ((shared_make, empty_shared_check), + (empty_ref_make, empty_ref_check), + (empty_wrapper_make, empty_wrapper_check)) + x = make(0) + @test Dagger.inplace_mpi_parts(x) === nothing + @test check(local_roundtrip(x)) + end + # Distinct empty arrays remain eligible; sharing needs object identity, + # since mightalias correctly reports that empty arrays share no memory. + @test Dagger.inplace_mpi_parts(SharedBundle(Float64[], Float64[])) !== nothing + @test Dagger.inplace_mpi_parts(HeaderGraphSharing(ones(4), RawHeaderVector(zeros(4)))) !== nothing + @test Dagger.inplace_mpi_parts(view_make(3)) === nothing + @test Dagger.inplace_mpi_parts(ViewBundle(ones(4), view(rand(4, 4), 1:2, 1:2))) !== nothing + # Match Serialization's own copy semantics for an empty ordinary view. + a = Float64[] + x = HeaderGraphSharing(a, view(a, :)) + io = IOBuffer(); Serialization.serialize(io, x); seekstart(io) + ordinary = Serialization.deserialize(io) + raw = local_roundtrip(x) + @test (ordinary.a === parent(ordinary.header)) == (raw.a === parent(raw.header)) + + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pin(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + for (make, check, result_type) in ((shared_make, empty_shared_check, SharedBundle), + (empty_ref_make, empty_ref_check, HeaderGraphSharing), + (empty_wrapper_make, empty_wrapper_check, HeaderGraphSharing)) + source = Dagger.@spawn scope=pin(0) return_type=result_type make(0) + @test fetch(Dagger.@spawn(scope=pin(nranks - 1), return_type=Bool, check(source))) + end + MPI.Barrier(comm) +end From 066bfc660ff49a7c20966e1ec7ac34722a2ca572 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:13:26 -0700 Subject: [PATCH 08/14] Keep flat immutable array headers allocation-free A full identity visited set costs 208 bytes and 5 allocations for each independent one-parent wrapper header. Check direct scalar/host-bits fields without a visited set, while retaining full graph memoization for complex headers. After ten warmups and GC, minimum of five 5000-call samples returns this wrapper path to zero bytes/allocations; plain and scalar-Dict headers remain zero, and two-array tuples retain their pre-existing 48 bytes per call. Final two-rank empty-sharing/control tests pass 14 assertions per rank. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 4 ++++ src/memory-spaces.jl | 24 +++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 8639cb644..babfdf374 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1231,3 +1231,7 @@ this section verbatim). Each entry is one bullet starting with `- `. Empty arrays share object identity even though `mightalias` reports no memory overlap. Check `===` too, and inspect immutable array-wrapper fields: an isbits element type does not make the wrapper's parent scalar. + Flat immutable wrapper headers need no visited-set allocation when their + direct fields are atomic metadata or host buffers of bits. Keep the full + identity memo for complex graphs; repeated immutable subgraphs can share + mutable descendants too. diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 02026803c..2df280cc1 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -400,6 +400,24 @@ function raw_header_disjoint(x, parts, seen) end return true end +# Flat immutable wrappers need only direct parent checks. Their serialized +# fields contain only atomic values or host buffers of bits. +function raw_flat_header_disjoint(x, parts) + (x isa AbstractArray && !ismutabletype(typeof(x))) || return nothing + for part in parts + (part === x || Base.mightalias(part, x)) && return false + end + for i in 1:fieldcount(typeof(x)) + isdefined(x, i) || continue + value = getfield(x, i) + raw_header_atomic(value) && continue + (raw_header_array(value) && isbitstype(eltype(value))) || return nothing + for part in parts + (part === value || Base.mightalias(part, value)) && return false + end + end + return true +end @noinline function raw_headers_disjoint_slow(vals, parts) seen = Base.IdSet{Any}() for value in vals @@ -410,7 +428,11 @@ end function raw_headers_disjoint(vals, parts) # Ordinary scalar/string headers need no graph walk or visited set. for value in vals - raw_header_atomic(value) || return raw_headers_disjoint_slow(vals, parts) + raw_header_atomic(value) && continue + flat = raw_flat_header_disjoint(value, parts) + flat === true && continue + flat === false && return false + return raw_headers_disjoint_slow(vals, parts) end return true end From a1c7520cd5fba666e20b2eb3772c29dce098cc68 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:51:17 -0700 Subject: [PATCH 09/14] Keep custom-coded headers in the ordinary serialization stream A header codec can recover an array from a registry rather than a field, including for isbits header keys. Splitting that header from a raw array loses sharing that ordinary Serialization preserves. Require standard codecs before atomic/header graph shortcuts and raw-array decomposition; cache reflected eligibility with method-world invalidation. Recheck nested bits metadata and scalar Dict types before skipping their graph walks. Two-rank, 2-default+1-interactive full transport suite passes 695 assertions per rank (658 existing, 14 empty-sharing, 23 custom-header). Registry tests cover concrete/Any/Ref/Dict and nested isbits headers, late definitions, and actual cross-rank identity. Independent pre-fix control demonstrated ordinary sharing=true and split sharing=false. After ten 5000-call warmups and GC, minimum of five GC-delta runs: scalar, Symbol/Int Dict and flat-wrapper cases remain 0 bytes/0 allocations; two-array results retain the prior 240000 bytes/5000 allocations per 5000 calls. These are focused mechanism probes, not a whole-workload benchmark. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 7 +++ src/memory-spaces.jl | 64 ++++++++++++++++--- test/mpi/struct_transport.jl | 2 + test/mpi/struct_transport_custom_headers.jl | 69 +++++++++++++++++++++ 4 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 test/mpi/struct_transport_custom_headers.jl diff --git a/AGENTS.md b/AGENTS.md index babfdf374..0d5200dd8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1235,3 +1235,10 @@ this section verbatim). Each entry is one bullet starting with `- `. direct fields are atomic metadata or host buffers of bits. Keep the full identity memo for complex graphs; repeated immutable subgraphs can share mutable descendants too. + + A header's custom Serialization codec can reach raw arrays through a + registry even when no field contains them. Check codecs before scalar or + isbits shortcuts, including nested bits fields and scalar Dict entries. + A graph walk only describes supported standard codecs; custom dispatch + must keep the whole object in one stream. Invalidate both header and outer + eligibility answers after later Serialization method definitions. diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 2df280cc1..41254b9d7 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -330,25 +330,66 @@ function raw_all_plain(::Type{T}) where {T} (raw_plain_serialize(T) && raw_plain_deserialize(T)) || return false for i in 1:fieldcount(T) F = fieldtype(T, i) - raw_field_kind(F) === :struct && !raw_all_plain(F) && return false + kind = raw_field_kind(F) + kind === :struct && !raw_all_plain(F) && return false + kind === :array && !raw_header_type_known(F) && return false end return true end const RAW_ENABLED = Dict{DataType,Bool}() +const RAW_HEADER_KNOWN = Dict{Type,Bool}() const RAW_ENABLED_LOCK = ReentrantLock() const RAW_ENABLED_WORLD = Ref{UInt}(0) +# Both eligibility caches depend on the current Serialization method table. +function raw_refresh_world!() + world = Base.get_world_counter() + if RAW_ENABLED_WORLD[] != world + empty!(RAW_ENABLED) + empty!(RAW_HEADER_KNOWN) + RAW_ENABLED_WORLD[] = world + end +end function raw_enabled(::Type{T}) where {T} lock(RAW_ENABLED_LOCK) do - # A package loaded after the first transfer can add a custom - # serializer. Cached eligibility must follow that method-table change. - world = Base.get_world_counter() - if RAW_ENABLED_WORLD[] != world - empty!(RAW_ENABLED) - RAW_ENABLED_WORLD[] = world + raw_refresh_world!() + known = get(RAW_ENABLED, T, nothing) + known === nothing || return known + # Computing this answer can populate the header cache. Publish only + # after reflection has finished, outside a Dict get! callback. + enabled = raw_all_plain(T) + RAW_ENABLED[T] = enabled + return enabled + end +end +# Field traversal describes Serialization's generic/standard codecs only. A +# custom codec may reach an array through a registry rather than through any +# field, even when its header is isbits. Keep the entire value in one stream. +function raw_header_type_known(::Type{T}) where {T} + lock(RAW_ENABLED_LOCK) do + raw_refresh_world!() + known = get(RAW_HEADER_KNOWN, T, nothing) + known === nothing || return known + trusted = try + serializer = which(Serialization.serialize, Tuple{Serialization.Serializer{IOBuffer}, T}) + deserializer = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Type{T}}) + serializer.module === Serialization && deserializer.module === Serialization + catch + false + end + if trusted && isbitstype(T) && !isprimitivetype(T) + # Atomic bits headers can themselves contain a custom-coded bits + # field; those fields are skipped by the runtime graph walk. + for i in 1:fieldcount(T) + raw_header_type_known(fieldtype(T, i)) || (trusted = false; break) + end end - get!(() -> raw_all_plain(T), RAW_ENABLED, T) + RAW_HEADER_KNOWN[T] = trusted + return trusted end end +raw_header_known(x) = raw_header_type_known(typeof(x)) +# Query actual type-value dispatch, including serialize(::Type{SomeType}). +raw_header_known(x::Type{T}) where {T} = raw_header_type_known(Type{T}) @generated raw_candidate(::T) where {T} = raw_has_array(T) # decided at compile time: no lock for the common values inplace_mpi_parts(x::T) where {T} = raw_candidate(x) && raw_enabled(T) ? raw_parts(x) : nothing @@ -356,12 +397,15 @@ raw_header_scalar_type(::Type{T}) where {T} = isbitstype(T) || T <: Union{String raw_header_atomic(x) = raw_header_scalar_type(typeof(x)) # Dict serializes its entries, not its backing arrays. Scalar key/value types # cannot carry raw parts; avoid a visited set for ordinary Symbol/Int metadata. -raw_header_atomic(x::Dict{K,V}) where {K,V} = raw_header_scalar_type(K) && raw_header_scalar_type(V) +raw_header_atomic(x::Dict{K,V}) where {K,V} = + raw_header_scalar_type(K) && raw_header_scalar_type(V) && + raw_header_type_known(K) && raw_header_type_known(V) raw_header_array(x) = x isa Array @static if isdefined(Core, :Memory) raw_header_array(x::Core.Memory) = true end function raw_header_disjoint(x, parts, seen) + raw_header_known(x) || return false raw_header_atomic(x) && return true if x isa AbstractArray || raw_header_array(x) for part in parts @@ -410,6 +454,7 @@ function raw_flat_header_disjoint(x, parts) for i in 1:fieldcount(typeof(x)) isdefined(x, i) || continue value = getfield(x, i) + raw_header_known(value) || return false raw_header_atomic(value) && continue (raw_header_array(value) && isbitstype(eltype(value))) || return nothing for part in parts @@ -428,6 +473,7 @@ end function raw_headers_disjoint(vals, parts) # Ordinary scalar/string headers need no graph walk or visited set. for value in vals + raw_header_known(value) || return false raw_header_atomic(value) && continue flat = raw_flat_header_disjoint(value, parts) flat === true && continue diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index 942b34c9c..d3b1001e7 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -241,3 +241,5 @@ guard_check(b::GuardedBundle) = b.total == 2.0 * length(b.v) end include("struct_transport_empty.jl") + +include("struct_transport_custom_headers.jl") diff --git a/test/mpi/struct_transport_custom_headers.jl b/test/mpi/struct_transport_custom_headers.jl new file mode 100644 index 000000000..48da3588f --- /dev/null +++ b/test/mpi/struct_transport_custom_headers.jl @@ -0,0 +1,69 @@ +# A custom codec can hide array identity in a registry, with no array field for +# the graph walk to inspect. Even an isbits key must keep the ordinary stream. +const RAW_HEADER_REGISTRY = Dict{Any,Vector{Float64}}() +struct RegistryRawHeader{K} + key::K +end +struct RegistryRawRoot{H} + a::Vector{Float64} + header::H +end +struct NestedBitsRawHeader + header::RegistryRawHeader{Int} +end +function Serialization.serialize(s::Serialization.AbstractSerializer, h::RegistryRawHeader) + Serialization.serialize_type(s, typeof(h)) + Serialization.serialize(s, RAW_HEADER_REGISTRY[h.key]) +end +function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{RegistryRawHeader{K}}) where {K} + a = Serialization.deserialize(s) + key = K === Symbol ? gensym(:received) : length(RAW_HEADER_REGISTRY) + 1000 + RAW_HEADER_REGISTRY[key] = a + return RegistryRawHeader(key) +end +registry_raw_make(::Int) = begin + a = ones(3) + RAW_HEADER_REGISTRY[1] = a + RegistryRawRoot(a, RegistryRawHeader(1)) +end +registry_raw_check(x) = x.a === RAW_HEADER_REGISTRY[x.header.key] +struct LateRawHeader + key::Int +end + +@testset "Custom header codecs retain one serialization stream" begin + @test isbitstype(RegistryRawHeader{Int}) + @test isbitstype(NestedBitsRawHeader) + for key in (:original, 1) + a = ones(3) + RAW_HEADER_REGISTRY[key] = a + h = RegistryRawHeader(key) + for x in (RegistryRawRoot(a, h), HeaderGraphSharing(a, h), + HeaderGraphSharing(a, Ref(h)), HeaderGraphSharing(a, Dict(:header => h))) + @test Dagger.inplace_mpi_parts(x) === nothing + result = local_roundtrip(x) + header = result.header isa Ref ? result.header[] : + result.header isa Dict ? result.header[:header] : result.header + @test result.a === RAW_HEADER_REGISTRY[header.key] + end + end + a = ones(3) + RAW_HEADER_REGISTRY[1] = a + nested = RegistryRawRoot(a, NestedBitsRawHeader(RegistryRawHeader(1))) + @test Dagger.inplace_mpi_parts(nested) === nothing + result = local_roundtrip(nested) + @test result.a === RAW_HEADER_REGISTRY[result.header.header.key] + + # The initial reflection answer must not survive a later codec definition. + late = RegistryRawRoot(a, LateRawHeader(1)) + @test Dagger.inplace_mpi_parts(late) !== nothing + @eval Serialization.serialize(s::Serialization.AbstractSerializer, h::LateRawHeader) = + (Serialization.serialize_type(s, LateRawHeader); Serialization.serialize(s, h.key)) + @test Dagger.inplace_mpi_parts(late) === nothing + + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pin(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + source = Dagger.@spawn scope=pin(0) return_type=RegistryRawRoot{RegistryRawHeader{Int}} registry_raw_make(0) + @test fetch(Dagger.@spawn(scope=pin(nranks - 1), return_type=Bool, registry_raw_check(source))) + MPI.Barrier(comm) +end From 242bc3ed7d5e0adfc9eb14f6327e4ed91a8cae95 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 17:56:33 -0700 Subject: [PATCH 10/14] Distinguish standard codecs from methods evaluated in Serialization Packages may validly define custom codecs with @eval Serialization, so module ownership alone does not establish that field traversal describes that codec. Require the standard generic codec's source file as well. Keep custom methods in an ordinary stream regardless of their module. The independent exact-head registry control failed sharing before this follow-up. Two-rank2default+1interactive controls now pass25 custom-header and14 empty-sharing assertions per rank, including the module-evaluated codec. The preceding head passed the full695-assertion transport suite per rank; this focused follow-up verifies the additional eligibility boundary. The origin reflection is cached and changes no warmed traversal logic. Written by an AI agent on jpsamaroo's review feedback. --- src/memory-spaces.jl | 8 ++++++- test/mpi/struct_transport_custom_headers.jl | 23 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 41254b9d7..05e3e7e2c 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -372,7 +372,13 @@ function raw_header_type_known(::Type{T}) where {T} trusted = try serializer = which(Serialization.serialize, Tuple{Serialization.Serializer{IOBuffer}, T}) deserializer = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Type{T}}) - serializer.module === Serialization && deserializer.module === Serialization + # Module ownership alone is insufficient: packages can define + # their codecs with @eval Serialization. Standard codec methods + # must also come from the generic codec's stdlib source file. + serialize_source = which(Serialization.serialize, Tuple{Serialization.AbstractSerializer, Any}).file + deserialize_source = which(Serialization.deserialize, Tuple{Serialization.AbstractSerializer, DataType}).file + serializer.module === Serialization && serializer.file === serialize_source && + deserializer.module === Serialization && deserializer.file === deserialize_source catch false end diff --git a/test/mpi/struct_transport_custom_headers.jl b/test/mpi/struct_transport_custom_headers.jl index 48da3588f..a3c9eb64b 100644 --- a/test/mpi/struct_transport_custom_headers.jl +++ b/test/mpi/struct_transport_custom_headers.jl @@ -31,6 +31,24 @@ struct LateRawHeader key::Int end +struct RegistryModuleRawHeader + key::Int +end +# Defining an extension inside Serialization is valid too; module ownership +# does not make these methods part of the supported standard codec set. +@eval Serialization begin + function serialize(s::AbstractSerializer, h::Main.RegistryModuleRawHeader) + serialize_type(s, Main.RegistryModuleRawHeader) + serialize(s, Main.RAW_HEADER_REGISTRY[h.key]) + end + function deserialize(s::AbstractSerializer, ::Type{Main.RegistryModuleRawHeader}) + a = deserialize(s) + key = length(Main.RAW_HEADER_REGISTRY) + 2000 + Main.RAW_HEADER_REGISTRY[key] = a + return Main.RegistryModuleRawHeader(key) + end +end + @testset "Custom header codecs retain one serialization stream" begin @test isbitstype(RegistryRawHeader{Int}) @test isbitstype(NestedBitsRawHeader) @@ -54,6 +72,11 @@ end result = local_roundtrip(nested) @test result.a === RAW_HEADER_REGISTRY[result.header.header.key] + module_header = RegistryRawRoot(a, RegistryModuleRawHeader(1)) + @test Dagger.inplace_mpi_parts(module_header) === nothing + result = local_roundtrip(module_header) + @test result.a === RAW_HEADER_REGISTRY[result.header.key] + # The initial reflection answer must not survive a later codec definition. late = RegistryRawRoot(a, LateRawHeader(1)) @test Dagger.inplace_mpi_parts(late) !== nothing From 208f47bf96619a41034f862de50cb657e0d5aa80 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 08:35:17 -0700 Subject: [PATCH 11/14] Restore raw transport eligibility for exact type values Review finding F1 (blocker) on PR #817: restore Julia 1.14 beta2 eligibility. Use the runtime's Core.Typeof key when reflecting deserialize dispatch. For type-valued headers, distinguish the exact serializer key from the runtime type passed to deserialization. Keep custom-codec origin checks and method-world invalidation; add registered type-header roundtrip and late custom-serializer fallback tests. A native beta2 negative reproduces the original Type{T} lookup failure. Exact beta2 local raw controls pass 677 assertions; full two-rank Julia 1.13.4 transport tests pass 702 assertions per rank, including the five new registered assertions. The same full suite also passes 702 assertions per rank on beta2. After ten 5000-call warmups and GC, five before/after GC-delta samples are identical in all five controlled Julia 1.13.4 cases. Minima, including escaped results and counter overhead: scalar, Dict and type-valued headers 160032 bytes/5001 allocations; flat wrapper 2400064/50001; two-array tuple 240032/5001. These are raw-decomposition controls, not whole-workload benchmarks. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 9 +++++++++ src/memory-spaces.jl | 10 ++++++---- test/mpi/struct_transport_custom_headers.jl | 17 +++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0d5200dd8..3dbc5c957 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1242,3 +1242,12 @@ this section verbatim). Each entry is one bullet starting with `- `. A graph walk only describes supported standard codecs; custom dispatch must keep the whole object in one stream. Invalidate both header and outer eligibility answers after later Serialization method definitions. + +110. **Reflect type-value dispatch with `Core.Typeof`, not `Type{T}`.** + Julia 1.14's closed type values have exact egality dispatch keys. A + `which(deserialize, Tuple{Serializer{IOBuffer}, Type{T}})` query can fail + even though deserializing the actual concrete type calls the generic + `DataType` codec; catching that error silently disabled every automatic + raw transport. Query `Core.Typeof(T)` instead. For a type-valued header, + distinguish its exact serializer key from its runtime type passed to + deserialization, and retain custom-codec guards and world invalidation. diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 05e3e7e2c..1982ca858 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -298,7 +298,7 @@ function raw_plain_serialize(::Type{T}) where {T} end function raw_plain_deserialize(::Type{T}) where {T} try - m = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Type{T}}) + m = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Core.Typeof(T)}) return Base.unwrap_unionall(m.sig).parameters[3] === DataType catch return false @@ -364,14 +364,14 @@ end # Field traversal describes Serialization's generic/standard codecs only. A # custom codec may reach an array through a registry rather than through any # field, even when its header is isbits. Keep the entire value in one stream. -function raw_header_type_known(::Type{T}) where {T} +function raw_header_type_known(::Type{T}, ::Type{D}=T) where {T,D} lock(RAW_ENABLED_LOCK) do raw_refresh_world!() known = get(RAW_HEADER_KNOWN, T, nothing) known === nothing || return known trusted = try serializer = which(Serialization.serialize, Tuple{Serialization.Serializer{IOBuffer}, T}) - deserializer = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Type{T}}) + deserializer = which(Serialization.deserialize, Tuple{Serialization.Serializer{IOBuffer}, Core.Typeof(D)}) # Module ownership alone is insufficient: packages can define # their codecs with @eval Serialization. Standard codec methods # must also come from the generic codec's stdlib source file. @@ -395,7 +395,9 @@ function raw_header_type_known(::Type{T}) where {T} end raw_header_known(x) = raw_header_type_known(typeof(x)) # Query actual type-value dispatch, including serialize(::Type{SomeType}). -raw_header_known(x::Type{T}) where {T} = raw_header_type_known(Type{T}) +# Its serializer sees this particular type value; its deserializer receives +# the runtime type (e.g. DataType), rather than a dispatch key for that value. +raw_header_known(x::Type{T}) where {T} = raw_header_type_known(Core.Typeof(x), typeof(x)) @generated raw_candidate(::T) where {T} = raw_has_array(T) # decided at compile time: no lock for the common values inplace_mpi_parts(x::T) where {T} = raw_candidate(x) && raw_enabled(T) ? raw_parts(x) : nothing diff --git a/test/mpi/struct_transport_custom_headers.jl b/test/mpi/struct_transport_custom_headers.jl index a3c9eb64b..dc4d9aace 100644 --- a/test/mpi/struct_transport_custom_headers.jl +++ b/test/mpi/struct_transport_custom_headers.jl @@ -30,6 +30,12 @@ registry_raw_check(x) = x.a === RAW_HEADER_REGISTRY[x.header.key] struct LateRawHeader key::Int end +struct RawTypeHeader +end +struct RawTypeHeaderRoot + a::Vector{Float64} + header::Type +end struct RegistryModuleRawHeader key::Int @@ -84,6 +90,17 @@ end (Serialization.serialize_type(s, LateRawHeader); Serialization.serialize(s, h.key)) @test Dagger.inplace_mpi_parts(late) === nothing + # Type{T} describes equality, while the runtime's exact type-value + # dispatch key can be narrower (Core.TypeEgal on Julia 1.14+). + typed = RawTypeHeaderRoot(ones(3), RawTypeHeader) + @test Dagger.inplace_mpi_parts(RawTypeHeaderRoot(ones(3), Int)) !== nothing + @test Dagger.inplace_mpi_parts(typed) !== nothing + @test local_roundtrip(typed).header === RawTypeHeader + @eval Serialization.serialize(s::Serialization.AbstractSerializer, ::Type{RawTypeHeader}) = + error("custom type-value codec must not be bypassed") + @test Dagger.inplace_mpi_parts(typed) === nothing + @test_throws ErrorException local_roundtrip(typed) + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) pin(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) source = Dagger.@spawn scope=pin(0) return_type=RegistryRawRoot{RegistryRawHeader{Int}} registry_raw_make(0) From 1429777d8974ef82e58142df681ced0136a62510 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 09:41:58 -0700 Subject: [PATCH 12/14] Preserve raw-buffer aliases in serialized type metadata Address the independent review's sharing blocker on PR #817. The standard DataType codec serializes type parameters, whose custom codecs can reach a raw buffer through a registry. This metadata also accompanies the outer value and container headers, including empty dictionaries. Keep those values in one ordinary stream unless all serialized metadata is safe. Validate nominal type parameters before atomic shortcuts, retain fallback for functions/whole definitions/unsupported type representations, and key codec checks by both serializer and deserializer dispatch inputs. Memoize atomic metadata per method world, with conservative recursion fallback; inspect actual Type dictionary slots while preserving scalar fast paths. Add direct/nested/type-dictionary/empty-declared-type/outer-type sharing regressions, late-codec invalidation and actual cross-rank validation. Exact published-source negative: ordinary sharing=true, split sharing=false. Final full MPI suites pass 718 assertions per rank on Julia 1.13.4 and 1.14-beta2 (2 ranks, 2 default plus 1 interactive thread). The beta2 run using the registered barrier/exit protocol records worker exits 0/0 and no signal; earlier extra-Timer/accelerator-switch harness shutdown faults are retained in the review receipts, without a universal clean-teardown claim. Minimum Julia 1.10.11 standalone eligibility/reconstruction checks pass. After ten 5000-call warmups and GC, all five before/after GC samples match in six Julia 1.13.4 cases. Minima include escaped results/counter overhead: scalar, Dict, type-header and type-Dict 160032 bytes/5001 allocations; flat wrapper 2400064/50001; two-array tuple 240032/5001. At metadata DAG depth 18, instrumentation visits 19 distinct types cold and none warm for a 243-byte serialized type. These are mechanism probes, not whole-workload benchmarks or a hosted-CI pass claim. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 14 ++++ src/memory-spaces.jl | 80 +++++++++++++++++++-- test/mpi/struct_transport_custom_headers.jl | 44 ++++++++++++ 3 files changed, 131 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3dbc5c957..f6e93f71a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1251,3 +1251,17 @@ this section verbatim). Each entry is one bullet starting with `- `. raw transport. Query `Core.Typeof(T)` instead. For a type-valued header, distinguish its exact serializer key from its runtime type passed to deserialization, and retain custom-codec guards and world invalidation. + +111. **Type values are serialized graphs, not scalar metadata.** The standard + DataType codec serializes each parameter, and a custom codec for an + isbits parameter can recover a raw array from a registry. Check parameter + codecs before treating a type-valued header as atomic. Include the outer + value's type, which MPI sends alongside its header, and the serialized + type of every header value, even an empty dictionary. Visit actual Type + keys/values in dictionaries instead of skipping them by their field type. + Keep function metadata, whole type definitions and unsupported type + representations in the ordinary stream. Cache codec checks by both + serializer key and the type passed to deserialization when they differ. + Memoize atomic metadata per method world too: a shared type DAG such as + `T = Tuple{T,T}` has linear serialized size, but an uncached recursive + validation walks exponentially many parameter occurrences. diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 1982ca858..e4cd8a882 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -328,6 +328,9 @@ function raw_collect!(parts, vals, sizes, checks, ::Type{T}, x) where {T} end function raw_all_plain(::Type{T}) where {T} (raw_plain_serialize(T) && raw_plain_deserialize(T)) || return false + # MPI sends the reconstructed value's type alongside its header too. + # A type parameter's codec can reach an array outside the value's fields. + (raw_header_known(T) && raw_header_atomic(T)) || return false for i in 1:fieldcount(T) F = fieldtype(T, i) kind = raw_field_kind(F) @@ -337,7 +340,8 @@ function raw_all_plain(::Type{T}) where {T} return true end const RAW_ENABLED = Dict{DataType,Bool}() -const RAW_HEADER_KNOWN = Dict{Type,Bool}() +const RAW_HEADER_KNOWN = Dict{Tuple{Type,Type},Bool}() +const RAW_TYPE_ATOMIC = Dict{Type,Bool}() const RAW_ENABLED_LOCK = ReentrantLock() const RAW_ENABLED_WORLD = Ref{UInt}(0) # Both eligibility caches depend on the current Serialization method table. @@ -346,6 +350,7 @@ function raw_refresh_world!() if RAW_ENABLED_WORLD[] != world empty!(RAW_ENABLED) empty!(RAW_HEADER_KNOWN) + empty!(RAW_TYPE_ATOMIC) RAW_ENABLED_WORLD[] = world end end @@ -367,7 +372,8 @@ end function raw_header_type_known(::Type{T}, ::Type{D}=T) where {T,D} lock(RAW_ENABLED_LOCK) do raw_refresh_world!() - known = get(RAW_HEADER_KNOWN, T, nothing) + key = (T, D) + known = get(RAW_HEADER_KNOWN, key, nothing) known === nothing || return known trusted = try serializer = which(Serialization.serialize, Tuple{Serialization.Serializer{IOBuffer}, T}) @@ -382,6 +388,11 @@ function raw_header_type_known(::Type{T}, ::Type{D}=T) where {T,D} catch false end + if trusted && D === T + # The value's codec serializes its type before its fields. Check + # that metadata too, including a Dict's declared key/value types. + trusted = raw_header_known(T) && raw_header_atomic(T) + end if trusted && isbitstype(T) && !isprimitivetype(T) # Atomic bits headers can themselves contain a custom-coded bits # field; those fields are skipped by the runtime graph walk. @@ -389,7 +400,7 @@ function raw_header_type_known(::Type{T}, ::Type{D}=T) where {T,D} raw_header_type_known(fieldtype(T, i)) || (trusted = false; break) end end - RAW_HEADER_KNOWN[T] = trusted + RAW_HEADER_KNOWN[key] = trusted return trusted end end @@ -401,13 +412,66 @@ raw_header_known(x::Type{T}) where {T} = raw_header_type_known(Core.Typeof(x), t @generated raw_candidate(::T) where {T} = raw_has_array(T) # decided at compile time: no lock for the common values inplace_mpi_parts(x::T) where {T} = raw_candidate(x) && raw_enabled(T) ? raw_parts(x) : nothing -raw_header_scalar_type(::Type{T}) where {T} = isbitstype(T) || T <: Union{String,Symbol,Type,Module} +raw_header_scalar_type(::Type{T}) where {T} = + !(T <: Type) && (isbitstype(T) || T <: Union{String,Symbol,Module}) raw_header_atomic(x) = raw_header_scalar_type(typeof(x)) +# A nominal DataType is serialized by name and then by parameter value. +# Custom parameter codecs can hide raw arrays; whole type definitions and +# other type representations retain the ordinary stream conservatively. +function raw_header_atomic(x::Type) + x isa DataType || return false + x <: Function && return false + @lock RAW_ENABLED_LOCK begin + raw_refresh_world!() + known = get(RAW_TYPE_ATOMIC, x, nothing) + known === nothing || return known + # Recursive metadata keeps the ordinary stream. Publish true only + # after the complete DAG is validated, once per method world. + RAW_TYPE_ATOMIC[x] = false + atomic = raw_type_metadata_atomic(x) + RAW_TYPE_ATOMIC[x] = atomic + return atomic + end +end +function raw_type_metadata_atomic(x::DataType) + by_name = try + !Serialization.should_send_whole_type(nothing, x) + catch + false + end + by_name || return false + for value in x.parameters + raw_type_parameter_atomic(value) || return false + end + return true +end +raw_type_parameter_atomic(x) = raw_header_known(x) && raw_header_atomic(x) +function raw_type_parameter_atomic(x::Tuple) + raw_header_known(x) || return false + for value in x + raw_type_parameter_atomic(value) || return false + end + return true +end # Dict serializes its entries, not its backing arrays. Scalar key/value types # cannot carry raw parts; avoid a visited set for ordinary Symbol/Int metadata. -raw_header_atomic(x::Dict{K,V}) where {K,V} = - raw_header_scalar_type(K) && raw_header_scalar_type(V) && - raw_header_type_known(K) && raw_header_type_known(V) +function raw_header_atomic(x::Dict{K,V}) where {K,V} + scalar_keys = raw_header_scalar_type(K) + scalar_values = raw_header_scalar_type(V) + if scalar_keys && scalar_values + return raw_header_type_known(K) && raw_header_type_known(V) + end + type_keys = K <: Type + type_values = V <: Type + ((scalar_keys || type_keys) && (scalar_values || type_values)) || return false + scalar_keys && !raw_header_type_known(K) && return false + scalar_values && !raw_header_type_known(V) && return false + for (key, value) in x + type_keys && !(raw_header_known(key) && raw_header_atomic(key)) && return false + type_values && !(raw_header_known(value) && raw_header_atomic(value)) && return false + end + return true +end raw_header_array(x) = x isa Array @static if isdefined(Core, :Memory) raw_header_array(x::Core.Memory) = true @@ -415,6 +479,7 @@ end function raw_header_disjoint(x, parts, seen) raw_header_known(x) || return false raw_header_atomic(x) && return true + x isa Type && return false if x isa AbstractArray || raw_header_array(x) for part in parts (part === x || Base.mightalias(part, x)) && return false @@ -483,6 +548,7 @@ function raw_headers_disjoint(vals, parts) for value in vals raw_header_known(value) || return false raw_header_atomic(value) && continue + value isa Type && return false flat = raw_flat_header_disjoint(value, parts) flat === true && continue flat === false && return false diff --git a/test/mpi/struct_transport_custom_headers.jl b/test/mpi/struct_transport_custom_headers.jl index dc4d9aace..e4f0061ba 100644 --- a/test/mpi/struct_transport_custom_headers.jl +++ b/test/mpi/struct_transport_custom_headers.jl @@ -36,6 +36,17 @@ struct RawTypeHeaderRoot a::Vector{Float64} header::Type end +struct ParametricRawHeader{H} +end +struct ParametricRawRoot{H} + a::Vector{Float64} +end +parametric_raw_make(::Int) = begin + a = ones(3) + RAW_HEADER_REGISTRY[1] = a + ParametricRawRoot{RegistryRawHeader(1)}(a) +end +parametric_raw_check(x) = x.a === RAW_HEADER_REGISTRY[typeof(x).parameters[1].key] struct RegistryModuleRawHeader key::Int @@ -86,9 +97,12 @@ end # The initial reflection answer must not survive a later codec definition. late = RegistryRawRoot(a, LateRawHeader(1)) @test Dagger.inplace_mpi_parts(late) !== nothing + late_parameter = RawTypeHeaderRoot(a, ParametricRawHeader{LateRawHeader(1)}) + @test Dagger.inplace_mpi_parts(late_parameter) !== nothing @eval Serialization.serialize(s::Serialization.AbstractSerializer, h::LateRawHeader) = (Serialization.serialize_type(s, LateRawHeader); Serialization.serialize(s, h.key)) @test Dagger.inplace_mpi_parts(late) === nothing + @test Dagger.inplace_mpi_parts(late_parameter) === nothing # Type{T} describes equality, while the runtime's exact type-value # dispatch key can be narrower (Core.TypeEgal on Julia 1.14+). @@ -101,9 +115,39 @@ end @test Dagger.inplace_mpi_parts(typed) === nothing @test_throws ErrorException local_roundtrip(typed) + # Standard type codecs serialize parameters, which can themselves have + # custom codecs. Type metadata is also sent for the outer raw value. + RAW_HEADER_REGISTRY[1] = a + for parameter in (RegistryRawHeader(1), (RegistryRawHeader(1),)) + header = ParametricRawHeader{parameter} + value = RawTypeHeaderRoot(a, header) + @test Dagger.inplace_mpi_parts(value) === nothing + result = local_roundtrip(value) + key = result.header.parameters[1] + key = key isa Tuple ? only(key) : key + @test result.a === RAW_HEADER_REGISTRY[key.key] + end + dictionary = HeaderGraphSharing(a, Dict(:type => ParametricRawHeader{RegistryRawHeader(1)})) + @test Dagger.inplace_mpi_parts(dictionary) === nothing + result = local_roundtrip(dictionary) + @test result.a === RAW_HEADER_REGISTRY[result.header[:type].parameters[1].key] + declared = HeaderGraphSharing(a, Dict{ParametricRawHeader{RegistryRawHeader(1)},Int}()) + @test Dagger.inplace_mpi_parts(declared) === nothing + result = local_roundtrip(declared) + parameter = keytype(typeof(result.header)).parameters[1] + @test result.a === RAW_HEADER_REGISTRY[parameter.key] + outer = parametric_raw_make(0) + @test Dagger.inplace_mpi_parts(outer) === nothing + @test parametric_raw_check(local_roundtrip(outer)) + @test Dagger.inplace_mpi_parts(RawTypeHeaderRoot(a, ParametricRawHeader{Int})) !== nothing + @test Dagger.inplace_mpi_parts(HeaderGraphSharing(a, Dict(:type => Int))) !== nothing + @test Dagger.inplace_mpi_parts((a = a, flag = 1)) !== nothing + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) pin(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) source = Dagger.@spawn scope=pin(0) return_type=RegistryRawRoot{RegistryRawHeader{Int}} registry_raw_make(0) @test fetch(Dagger.@spawn(scope=pin(nranks - 1), return_type=Bool, registry_raw_check(source))) + parametric = Dagger.@spawn scope=pin(0) parametric_raw_make(0) + @test fetch(Dagger.@spawn(scope=pin(nranks - 1), return_type=Bool, parametric_raw_check(parametric))) MPI.Barrier(comm) end From 26d00d7bf65e31644431e88a0917a758639aa0bc Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 15:58:01 -0700 Subject: [PATCH 13/14] ci: collect coverage from MPI CPU test ranks The MPI test launcher kept only the parent's executable, so registered raw transport tests ran without instrumentation and contributed no coverage. Reuse the reviewed #850 fix: preserve enabled user/all/path coverage flags, and process/upload one existing latest-Julia two-rank cell with the same settings already used by ordinary jobs. Leave thresholds and permissions unchanged, and keep the other MPI cells uninstrumented. On Julia 1.13.4, the unchanged registered raw-transport subtree passes 718 assertions per rank in each of three two-rank controls (4308 total, zero failures/errors). The original launcher drops requested coverage; the fix produces both ranks' sidecars and actual CoverageTools hits; disabled coverage still produces none. All source files remain unchanged and all processes are reaped. This is local functional/collection validation; the new hosted upload and Codecov verdict remain pending. Written by an AI agent on jpsamaroo's review feedback. --- .github/workflows/CI.yml | 15 ++++++++++++++- AGENTS.md | 6 ++++++ test/mpi/run.jl | 16 +++++++++++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index c8767be61..e4fc9158e 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -447,6 +447,11 @@ jobs: ranks: - 2 - 4 + include: + # Instrument one existing cell; the other nine keep their normal cost. + - version: '1' + ranks: 2 + coverage: true steps: - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 @@ -463,7 +468,15 @@ jobs: - name: Instantiate CPU MPI environment run: julia --project=test/mpi/env -e 'using Pkg; Pkg.develop([PackageSpec(path=pwd()), PackageSpec(path="lib/TimespanLogging")]); Pkg.instantiate()' - name: Run CPU MPI tests - run: julia --project=test/mpi/env test/mpi/run.jl ${{ matrix.ranks }} 2 test/mpi/cpu.jl + run: julia ${{ matrix.coverage && '--code-coverage=user' || '' }} --project=test/mpi/env test/mpi/run.jl ${{ matrix.ranks }} 2 test/mpi/cpu.jl + - uses: julia-actions/julia-processcoverage@v1 + if: matrix.coverage + - uses: codecov/codecov-action@v7 + if: matrix.coverage + with: + files: lcov.info + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: false mpi-opencl: # OpenCL runs against a CPU-backed ICD (no physical GPU required), unlike diff --git a/AGENTS.md b/AGENTS.md index f6e93f71a..2ddf2165b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1265,3 +1265,9 @@ this section verbatim). Each entry is one bullet starting with `- `. Memoize atomic metadata per method world too: a shared type DAG such as `T = Tuple{T,T}` has linear serialized size, but an uncached recursive validation walks exponentially many parameter occurrences. + +112. **Enable coverage in MPI ranks, not only in their launcher.** Selecting + `Base.julia_cmd().exec[1]` keeps the executable but drops coverage options. + A launcher can therefore be instrumented while the extension exercised by + every rank reports zero hits. Forward the enabled mode/path and merge the + PID-qualified rank reports. diff --git a/test/mpi/run.jl b/test/mpi/run.jl index a670d63fb..ec86deae2 100644 --- a/test/mpi/run.jl +++ b/test/mpi/run.jl @@ -16,9 +16,23 @@ script = ARGS[3] extra = ARGS[4:end] project = Base.active_project() juliabin = Base.julia_cmd().exec[1] +# Base.julia_cmd().exec[1] selects only the executable. Preserve enabled +# instrumentation explicitly so ranks emit coverage too. Each rank uses +# Julia's default PID-qualified .cov files, which the coverage action merges. +options = Base.JLOptions() +coverage_args = if options.code_coverage == 1 + ["--code-coverage=user"] +elseif options.code_coverage == 2 + ["--code-coverage=all"] +elseif options.code_coverage == 3 + ["--code-coverage=@$(unsafe_string(options.tracked_path))"] +else + String[] +end + MPI.mpiexec() do mpiexec - cmd = `$mpiexec -n $nranks $juliabin --project=$project --threads=$threads $script $extra` + cmd = `$mpiexec -n $nranks $juliabin $coverage_args --project=$project --threads=$threads $script $extra` @info "Launching MPI job" nranks threads script proc = run(ignorestatus(cmd)) exit(proc.exitcode) From c01d47c453d2c8200d9f4e9cf3bce26a8f2381ee Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Wed, 2 Dec 2026 12:17:20 -0700 Subject: [PATCH 14/14] Keep synthesized MPI headers on standard serialization codecs Review finding F1 on PR #817 (blocker): raw decomposition creates tuple containers which ordinary payload serialization never visits. A custom codec for one of those containers can change the payload or raise an exception only on the optimized transport path. Use the existing world-aware codec checks for the field-values tuple, shape aggregate, each dimensions tuple, and outer descriptor, including their exact type metadata. Fall back to the ordinary stream when any codec is custom. Generate fixed-index dimensions checks so mixed ranks retain their concrete tuple types instead of boxing in a runtime loop. Register independent field, descriptor, type-metadata and shape codec regressions, retain ordinary dimensions-codec exceptions, and check that unrelated eligible payloads still use raw transport. Record the invariant. Slurm job 101 on Helios, Julia 1.13.2, CPU-only 2 CPUs/4 GiB: the exact new registered regression passes 19/19 against the extracted complete raw implementation; the original source fails with both field/descriptor codec errors. Return-type inference is unchanged for both fixtures. After 10 x 1000 warmup calls and GC, all five paired 1000-call allocation samples are flat: scalar two-array fixture 5001 allocations/192032 bytes, String/Dict header fixture 1001 allocations/48032 bytes, base and head. These are isolated raw-helper measurements, not a full MPI suite. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 10 +++ src/memory-spaces.jl | 16 +++- test/mpi/struct_transport.jl | 2 + .../mpi/struct_transport_synthetic_headers.jl | 80 +++++++++++++++++++ 4 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 test/mpi/struct_transport_synthetic_headers.jl diff --git a/AGENTS.md b/AGENTS.md index 2ddf2165b..310a5110f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1243,6 +1243,16 @@ this section verbatim). Each entry is one bullet starting with `- `. must keep the whole object in one stream. Invalidate both header and outer eligibility answers after later Serialization method definitions. + Transport also creates containers the original stream never serialized: + the tuple of retained fields, the tuple of shapes, and the complete header + tuple. A custom codec for any such tuple can run + unexpectedly even when every original field uses standard serialization. + Validate these synthetic containers and their exact type-value metadata + before taking the raw path. Preserve the dimensions tuples' codecs too: + ordinary multidimensional array serialization already calls them. Compare + ordinary struct serialization with the transport round trip; checking only + the original fields misses this case. + 110. **Reflect type-value dispatch with `Core.Typeof`, not `Type{T}`.** Julia 1.14's closed type values have exact egality dispatch keys. A `which(deserialize, Tuple{Serializer{IOBuffer}, Type{T}})` query can fail diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index e4cd8a882..93a5f17a7 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -561,6 +561,12 @@ end raw_collect!(parts, vals, sizes, checks, T, :x) n = length(parts) ok = isempty(checks) ? true : foldr((c, r) -> :($c && $r), checks) + shape_checks = Expr(:block) + for i in 1:n + # Preserve each concrete dimensions-tuple type; iterating mixed ranks + # at runtime boxes the tuples before their codec lookup. + push!(shape_checks.args, :(raw_header_known(sizes[$i]) || return nothing)) + end return quote $ok || return nothing parts = ($(parts...),) @@ -576,7 +582,15 @@ end # Ref, non-isbits array or another struct. Serializing the header # separately would sever that sharing, including cyclic graphs. raw_headers_disjoint(vals, parts) || return nothing - (parts, (vals, ($(sizes...),))) + sizes = ($(sizes...),) + header = (vals, sizes) + # Header assembly introduces tuple containers and moves dimensions + # out of the original array stream. Keep nonstandard tuple codecs + # (including type metadata) on the original serialization path. + raw_header_known(header) && raw_header_known(vals) && + raw_header_known(sizes) || return nothing + $shape_checks + (parts, header) end end # Allocate the receive buffers for `T` from `header` (host-resident; the sender diff --git a/test/mpi/struct_transport.jl b/test/mpi/struct_transport.jl index d3b1001e7..9a10cece2 100644 --- a/test/mpi/struct_transport.jl +++ b/test/mpi/struct_transport.jl @@ -243,3 +243,5 @@ end include("struct_transport_empty.jl") include("struct_transport_custom_headers.jl") + +include("struct_transport_synthetic_headers.jl") diff --git a/test/mpi/struct_transport_synthetic_headers.jl b/test/mpi/struct_transport_synthetic_headers.jl new file mode 100644 index 000000000..92cbcee18 --- /dev/null +++ b/test/mpi/struct_transport_synthetic_headers.jl @@ -0,0 +1,80 @@ +# Transport may synthesize tuples that ordinary struct serialization never +# visits. A custom codec for those tuples must not change a payload's stream. +struct SyntheticRawHeader{Tag} + value::Int +end +struct SyntheticRawRoot{N,H} + a::Array{Float64,N} + header::H +end + +function synthetic_serialized_roundtrip(x) + io = IOBuffer() + Serialization.serialize(io, x) + seekstart(io) + return Serialization.deserialize(io) +end +synthetic_raw_equal(x, y) = typeof(x) === typeof(y) && x.a == y.a && x.header === y.header + +@testset "Synthetic transport containers keep ordinary codec semantics" begin + @testset "field tuple" begin + x = SyntheticRawRoot(ones(3), SyntheticRawHeader{:fields}(7)) + @test Dagger.inplace_mpi_parts(x) !== nothing + ordinary = synthetic_serialized_roundtrip(x) + @eval Serialization.serialize(s::Serialization.AbstractSerializer, + h::Tuple{SyntheticRawHeader{:fields}}) = + error("synthetic field tuple codec must not run") + @test Dagger.inplace_mpi_parts(x) === nothing + @test synthetic_raw_equal(local_roundtrip(x), ordinary) + end + @testset "outer descriptor tuple" begin + x = SyntheticRawRoot(ones(3), SyntheticRawHeader{:descriptor}(8)) + @test Dagger.inplace_mpi_parts(x) !== nothing + ordinary = synthetic_serialized_roundtrip(x) + @eval Serialization.serialize(s::Serialization.AbstractSerializer, + h::Tuple{Tuple{SyntheticRawHeader{:descriptor}},Tuple{Tuple{Int}}}) = + error("synthetic descriptor codec must not run") + @test Dagger.inplace_mpi_parts(x) === nothing + @test synthetic_raw_equal(local_roundtrip(x), ordinary) + end + @testset "exact tuple type-value codec" begin + x = SyntheticRawRoot(ones(3), SyntheticRawHeader{:metadata}(9)) + @test Dagger.inplace_mpi_parts(x) !== nothing + ordinary = synthetic_serialized_roundtrip(x) + @eval Serialization.serialize(s::Serialization.AbstractSerializer, + ::Type{Tuple{SyntheticRawHeader{:metadata}}}) = + error("synthetic tuple metadata codec must not run") + @test Dagger.inplace_mpi_parts(x) === nothing + @test synthetic_raw_equal(local_roundtrip(x), ordinary) + end + # Dimensions contain only Ints, so their tuple types cannot include an + # owned marker. Restore these temporary codecs before other MPI tests run. + @testset "shape containers" begin + x = SyntheticRawRoot(ones(ntuple(_ -> 1, 7)), SyntheticRawHeader{:shape}(10)) + ordinary = synthetic_serialized_roundtrip(x) + for T in (NTuple{7,Int}, Tuple{NTuple{7,Int}}) + @test Dagger.inplace_mpi_parts(x) !== nothing + @eval Serialization.serialize(s::Serialization.AbstractSerializer, h::$T) = + error("synthetic shape codec must not run") + method = which(Serialization.serialize, Tuple{Serialization.Serializer{IOBuffer},T}) + try + @test Dagger.inplace_mpi_parts(x) === nothing + if T === NTuple{7,Int} + # Array serialization already calls the dimensions codec; + # the fallback must retain its error too. + @test_throws ErrorException synthetic_serialized_roundtrip(x) + @test_throws ErrorException local_roundtrip(x) + else + @test synthetic_raw_equal(local_roundtrip(x), ordinary) + end + finally + Base.delete_method(method) + end + end + @test Dagger.inplace_mpi_parts(x) !== nothing + end + # Unrelated custom tuple codecs must not disable ordinary raw payloads. + x = SyntheticRawRoot(collect(1.0:4.0), SyntheticRawHeader{:plain}(11)) + @test Dagger.inplace_mpi_parts(x) !== nothing + @test synthetic_raw_equal(local_roundtrip(x), synthetic_serialized_roundtrip(x)) +end