From 54b5071f09619d1c38d7c96b67e081b2b4264ef1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 11:13:47 +0100 Subject: [PATCH 001/324] Store canonical execution targets in persistent typed cohorts --- src/composite_model/execution_cohorts.jl | 173 +++++++++++ src/composite_model/execution_storage.jl | 77 +++++ src/composite_model/runtime_outputs.jl | 59 +++- src/composite_model_api.jl | 2 + test/runtests.jl | 5 + test/test-execution-cohorts.jl | 136 +++++++++ test/test-model-canonical-cohorts.jl | 355 +++++++++++++++++++++++ 7 files changed, 799 insertions(+), 8 deletions(-) create mode 100644 src/composite_model/execution_cohorts.jl create mode 100644 src/composite_model/execution_storage.jl create mode 100644 test/test-execution-cohorts.jl create mode 100644 test/test-model-canonical-cohorts.jl diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl new file mode 100644 index 000000000..fcb2f5f83 --- /dev/null +++ b/src/composite_model/execution_cohorts.jl @@ -0,0 +1,173 @@ +abstract type AbstractExecutionCohort end + +mutable struct ExecutionCohort{T} <: AbstractExecutionCohort + owner::Any + application_id::Symbol + rows::Vector{Union{Nothing,T}} + indices::Dict{ObjectId,Int} +end + +struct ExecutionCohortLocation + cohort::AbstractExecutionCohort + row::Int +end + +"""Persistent typed execution payloads, indexed independently of schedule order.""" +mutable struct ExecutionCohortStore + cohorts::Dict{Tuple{Any,Symbol,DataType},AbstractExecutionCohort} + locations::Dict{Tuple{Any,Symbol,ObjectId},ExecutionCohortLocation} +end + +ExecutionCohortStore() = ExecutionCohortStore( + Dict{Tuple{Any,Symbol,DataType},AbstractExecutionCohort}(), + Dict{Tuple{Any,Symbol,ObjectId},ExecutionCohortLocation}(), +) + +"""An ordered membership view over one application's concrete payload family.""" +struct ExecutionCohortRows{T} <: AbstractVector{T} + store::ExecutionCohortStore + cohort::ExecutionCohort{T} + indices::Vector{Int} +end + +Base.IndexStyle(::Type{<:ExecutionCohortRows}) = IndexLinear() +Base.size(rows::ExecutionCohortRows) = size(rows.indices) +Base.length(rows::ExecutionCohortRows) = length(rows.indices) +Base.dataids(rows::ExecutionCohortRows) = + (Base.dataids(rows.indices)..., Base.dataids(rows.cohort.rows)...) + +Base.@propagate_inbounds function Base.getindex(rows::ExecutionCohortRows{T}, index::Int) where {T} + @boundscheck checkbounds(rows.indices, index) + slot = @inbounds rows.indices[index] + target = @inbounds rows.cohort.rows[slot] + isnothing(target) && throw(ArgumentError( + "This execution target was removed or changed its payload schema.", + )) + return target::T +end + +function _execution_cohort(store::ExecutionCohortStore, owner, application_id::Symbol, ::Type{T}) where {T} + isconcretetype(T) && T !== Nothing || throw(ArgumentError( + "An execution cohort requires a concrete target payload type.", + )) + cohort = get!(store.cohorts, (owner, application_id, T)) do + ExecutionCohort{T}(owner, application_id, Union{Nothing,T}[], Dict{ObjectId,Int}()) + end + return cohort::ExecutionCohort{T} +end + +function _clear_execution_cohort_row!(cohort::ExecutionCohort, row::Int) + cohort.rows[row] = nothing + return nothing +end + +function _store_execution_cohort_target!( + store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T, +) where {T} + object_id = ObjectId(target.object_id) + key = (cohort.owner, cohort.application_id, object_id) + previous = get(store.locations, key, nothing) + if !isnothing(previous) && previous.cohort !== cohort + _clear_execution_cohort_row!(previous.cohort, previous.row) + end + slot = get(cohort.indices, object_id, 0) + if iszero(slot) + push!(cohort.rows, target) + slot = length(cohort.rows) + cohort.indices[object_id] = slot + else + cohort.rows[slot] = target + end + store.locations[key] = ExecutionCohortLocation(cohort, slot) + return slot +end + +""" + cohort_rows!(store, application_id, targets::AbstractVector{T}; owner=nothing) + +Intern concrete target payloads and return a view in the supplied order. A +schedule can contain several views of the same cohort, including separate +runs around another payload family. Their membership vectors are independent. +`owner` separates execution contexts and cache leases, such as root scheduling +and distinct hard-call bindings, while their targets can share canonical status +references. +""" +function cohort_rows!( + store::ExecutionCohortStore, application_id::Symbol, targets::AbstractVector{T}; owner=nothing, +) where {T} + cohort = _execution_cohort(store, owner, application_id, T) + rows = ExecutionCohortRows{T}(store, cohort, Int[]) + sizehint!(rows, length(targets)) + append!(rows, targets) + return rows +end + +function Base.setindex!(rows::ExecutionCohortRows{T}, target::T, index::Int) where {T} + checkbounds(rows.indices, index) + rows.indices[index] = _store_execution_cohort_target!(rows.store, rows.cohort, target) + return rows +end + +function Base.push!(rows::ExecutionCohortRows{T}, target::T) where {T} + push!(rows.indices, _store_execution_cohort_target!(rows.store, rows.cohort, target)) + return rows +end + +function Base.insert!(rows::ExecutionCohortRows{T}, index::Integer, target::T) where {T} + 1 <= index <= length(rows) + 1 || throw(BoundsError(rows, index)) + slot = _store_execution_cohort_target!(rows.store, rows.cohort, target) + insert!(rows.indices, index, slot) + return rows +end + +function Base.append!(rows::ExecutionCohortRows{T}, targets::AbstractVector{T}) where {T} + rows === targets && return append!(rows, copy(rows)) + for target in targets + push!(rows, target) + end + return rows +end + +function Base.deleteat!(rows::ExecutionCohortRows, indices) + # Membership changes do not remove a payload used by another view. Its + # execution owner removes it explicitly after all affected views refresh. + deleteat!(rows.indices, indices) + return rows +end + +function Base.empty!(rows::ExecutionCohortRows) + empty!(rows.indices) + return rows +end + +function Base.sizehint!(rows::ExecutionCohortRows, size::Integer) + sizehint!(rows.indices, size) + return rows +end + +Base.copy(rows::ExecutionCohortRows{T}) where {T} = + ExecutionCohortRows{T}(rows.store, rows.cohort, copy(rows.indices)) + +"""Reset one view's ordered membership while retaining the store's stable slots.""" +function reset_cohort_rows!(rows::ExecutionCohortRows{T}, targets::AbstractVector{T}) where {T} + rows === targets && return rows + indices = Int[ + _store_execution_cohort_target!(rows.store, rows.cohort, target) + for target in targets + ] + empty!(rows.indices) + append!(rows.indices, indices) + return rows +end + +cohort_location(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing) = + get(store.locations, (owner, application_id, ObjectId(object_id)), nothing) + +"""Remove an execution payload without renumbering any cohort's row slots.""" +function remove_cohort_target!(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing) + key = (owner, application_id, ObjectId(object_id)) + location = pop!(store.locations, key, nothing) + isnothing(location) && return false + _clear_execution_cohort_row!(location.cohort, location.row) + return true +end diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl new file mode 100644 index 000000000..efebf67b8 --- /dev/null +++ b/src/composite_model/execution_storage.jl @@ -0,0 +1,77 @@ +"""Mutable storage owned by one simulation, shared by scheduled and manual execution. + +Stream values retain the existing dictionary interface. Execution cohorts share +that lifetime, rather than the model's reusable structural plan, so a fresh run +cannot replace another simulation's targets or call-context leases. +""" +struct RuntimeStorage{K,V,D<:AbstractDict{K,V}} <: AbstractDict{K,V} + streams::D + cohorts::ExecutionCohortStore +end + +RuntimeStorage(streams::AbstractDict{K,V}) where {K,V} = + RuntimeStorage{K,V,typeof(streams)}(streams, ExecutionCohortStore()) + +Base.length(storage::RuntimeStorage) = length(storage.streams) +Base.iterate(storage::RuntimeStorage, state...) = iterate(storage.streams, state...) +Base.getindex(storage::RuntimeStorage, key) = storage.streams[key] +Base.setindex!(storage::RuntimeStorage, value, key) = setindex!(storage.streams, value, key) +Base.haskey(storage::RuntimeStorage, key) = haskey(storage.streams, key) +Base.get(storage::RuntimeStorage, key, default) = get(storage.streams, key, default) +Base.get!(storage::RuntimeStorage, key, default) = get!(storage.streams, key, default) +Base.get!(default::Union{Function,Type}, storage::RuntimeStorage, key) = + get!(default, storage.streams, key) +Base.delete!(storage::RuntimeStorage, key) = (delete!(storage.streams, key); storage) +Base.empty!(storage::RuntimeStorage) = (empty!(storage.streams); storage) +Base.empty(storage::RuntimeStorage) = RuntimeStorage(empty(storage.streams)) +Base.copy(storage::RuntimeStorage) = RuntimeStorage(copy(storage.streams)) +Base.keys(storage::RuntimeStorage) = keys(storage.streams) +Base.values(storage::RuntimeStorage) = values(storage.streams) +Base.pairs(storage::RuntimeStorage) = pairs(storage.streams) +Base.sizehint!(storage::RuntimeStorage, n::Integer) = (sizehint!(storage.streams, n); storage) + +_execution_cohort_store(storage::RuntimeStorage) = storage.cohorts +_execution_cohort_store(::Nothing) = ExecutionCohortStore() + +_insert_with_spare_capacity!(rows::ExecutionCohortRows, position::Integer, target) = + insert!(rows, position, target) + +function _retire_scheduled_cohort_targets!(store::ExecutionCohortStore, compiled) + obsolete = Tuple{Symbol,ObjectId}[] + for (owner, application_id, object_id) in keys(store.locations) + isnothing(owner) || continue + application = get(compiled.applications_by_id, application_id, nothing) + if isnothing(application) || !first(_sorted_object_id_position(application.target_ids, object_id)) + push!(obsolete, (application_id, object_id)) + end + end + for (application_id, object_id) in obsolete + remove_cohort_target!(store, application_id, object_id) + end + return nothing +end + +function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches) + store = storage.cohorts + owner = _execution_call_owner(binding) + current = Set((batch.application.id, target.object_id) + for batch in batches for target in batch.targets) + obsolete = Tuple{Symbol,ObjectId}[] + for (candidate_owner, application_id, object_id) in keys(store.locations) + isequal(owner, candidate_owner) || continue + (application_id, object_id) in current || push!(obsolete, (application_id, object_id)) + end + for (application_id, object_id) in obsolete + remove_cohort_target!(store, application_id, object_id; owner) + end + return nothing +end + +_retire_call_cohort_targets!(::Nothing, binding, batches) = nothing + +_execution_call_owner(binding) = ( + binding.application_id, + binding.consumer_id, + _compiled_call_name(binding), + _compiled_call_mode(binding), +) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 659757daf..b3dc1c980 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -833,6 +833,7 @@ function _record_call_execution_batch_cache!( else batches end + _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches) return batches end @@ -1022,6 +1023,11 @@ mutable struct CompiledExecutionTarget{M,S,CS,IB,BI,OT,OB,CB,EB,RC,I<:ObjectId} call_context_cache::CallContextCache{RC} end +function Base.show(io::IO, target::CompiledExecutionTarget) + print(io, "CompiledExecutionTarget(", target.object_id, + ", model=", nameof(typeof(target.model)), ")") +end + function _call_bindings_signature(call_bindings) signature = hash(length(call_bindings)) for binding in call_bindings @@ -1095,6 +1101,7 @@ mutable struct RuntimeApplicationSchedule end struct CompiledExecutionPlan{G,B,I,S} + cohorts::ExecutionCohortStore groups::G batches::B groups_by_application_slot::I @@ -3576,8 +3583,20 @@ function _compiled_model_execution_target( object_id::ObjectId, temporal_streams=nothing, output_retention=nothing, - constants=nothing, -) + constants=nothing; + owner=nothing, +) + if temporal_streams isa RuntimeStorage + location = cohort_location(temporal_streams.cohorts, application.id, object_id; owner) + if !isnothing(location) + previous = location.cohort.rows[location.row] + if !isnothing(previous) && isnothing(_model_execution_target_change_reason( + previous, compiled, env_bindings, application, output_retention, temporal_streams, + )) + return previous + end + end + end status_view = _model_status_view_for_application( compiled, application, @@ -3651,14 +3670,21 @@ function _compiled_model_execution_target( ) end -function _typed_model_execution_targets(targets, first_index::Int, last_index::Int) +function _typed_model_execution_targets( + cohorts::ExecutionCohortStore, + application_id::Symbol, + targets, + first_index::Int, + last_index::Int; + owner=nothing, +) target_type = typeof(targets[first_index]) typed = Vector{target_type}(undef, last_index - first_index + 1) sizehint!(typed, length(typed) + 1) for (destination, source) in enumerate(first_index:last_index) typed[destination] = targets[source] end - return typed + return cohort_rows!(cohorts, application_id, typed; owner) end function _compiled_model_execution_environment_provider( @@ -3698,6 +3724,8 @@ function _append_model_execution_batches!( application::CompiledModelApplication, targets, output_retention, + cohorts::ExecutionCohortStore; + owner=nothing, ) isempty(targets) && return batches output_publication = _compiled_output_publication( @@ -3712,7 +3740,7 @@ function _append_model_execution_batches!( batches, CompiledExecutionBatch( application, - _typed_model_execution_targets(targets, first_index, index - 1), + _typed_model_execution_targets(cohorts, application.id, targets, first_index, index - 1; owner), _compiled_model_execution_environment_provider( env_bindings, application, @@ -3728,7 +3756,7 @@ function _append_model_execution_batches!( batches, CompiledExecutionBatch( application, - _typed_model_execution_targets(targets, first_index, lastindex(targets)), + _typed_model_execution_targets(cohorts, application.id, targets, first_index, lastindex(targets); owner), _compiled_model_execution_environment_provider( env_bindings, application, @@ -3748,6 +3776,7 @@ function _compiled_call_execution_batches( output_retention, constants, ) + cohorts = _execution_cohort_store(temporal_streams) batches = AbstractExecutionBatch[] for application_id in binding.callee_application_ids application = _compiled_application_by_id(compiled, application_id) @@ -3764,7 +3793,8 @@ function _compiled_call_execution_batches( object_id, temporal_streams, output_retention, - constants, + constants; + owner=_execution_call_owner(binding), ), ) end @@ -3774,6 +3804,8 @@ function _compiled_call_execution_batches( application, targets, output_retention, + cohorts; + owner=_execution_call_owner(binding), ) end return Tuple(batches) @@ -3786,6 +3818,7 @@ function compile_model_execution_plan( output_retention=nothing, constants=nothing, ) + cohorts = _execution_cohort_store(temporal_streams) manual_application_ids = _manual_call_application_ids(compiled) groups = CompiledApplicationExecutionGroup[] batches = AbstractExecutionBatch[] @@ -3810,6 +3843,7 @@ function compile_model_execution_plan( application, targets, output_retention, + cohorts, ) first_batch > length(batches) && continue push!( @@ -3822,6 +3856,7 @@ function compile_model_execution_plan( end application_count = length(compiled.scenario_plan.applications) return CompiledExecutionPlan( + cohorts, groups, batches, _execution_groups_by_application_slot(groups, application_count), @@ -4886,6 +4921,7 @@ function _try_refresh_model_execution_plan_for_pure_addition!( return ( plan=CompiledExecutionPlan( + previous.cohorts, previous.groups, previous.batches, previous.groups_by_application_slot, @@ -5096,6 +5132,7 @@ function _refresh_model_execution_plan( application, targets, output_retention, + previous.cohorts, ) isempty(application_batches) && continue push!( @@ -5111,6 +5148,7 @@ function _refresh_model_execution_plan( return ( plan=CompiledExecutionPlan( + previous.cohorts, groups, batches, _execution_groups_by_application_slot( @@ -5135,6 +5173,8 @@ function explain_execution_plan(plan::CompiledExecutionPlan) process=batch.application.process, object_ids=[target.object_id.value for target in batch.targets], batch_size=length(batch.targets), + target_storage=:cohort, + cohort_schema=eltype(batch.targets), target_type=eltype(batch.targets), model_type=fieldtype(eltype(batch.targets), :model), status_type=fieldtype(eltype(batch.targets), :status), @@ -7594,6 +7634,9 @@ function _refresh_simulation_runtime!(simulation::Simulation) changed_execution_application_ids, ) simulation.execution_plan = execution_refresh.plan + if !simulation.compiled.status_view_refresh_is_pure_addition + _retire_scheduled_cohort_targets!(simulation.execution_plan.cohorts, simulation.compiled) + end _runtime_performance_finish!( simulation.performance, :execution_plan_compile, @@ -8277,7 +8320,7 @@ function _prepare_simulation!( :initial_output_retention_compile, started_at, ) - temporal_streams = Dict{Tuple{Symbol,ObjectId,Symbol},Any}() + temporal_streams = RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},Any}()) _initialize_model_output_streams!( temporal_streams, compiled, diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index 9dbd03f81..b9f7a4bbd 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -4,6 +4,8 @@ include("composite_model/status_conversion.jl") include("composite_model/registry_topology.jl") include("composite_model/selectors.jl") +include("composite_model/execution_cohorts.jl") +include("composite_model/execution_storage.jl") include("composite_model/compilation.jl") include("composite_model/bound_many.jl") include("composite_model/output_targets.jl") diff --git a/test/runtests.jl b/test/runtests.jl index 61df0c9a5..a0b42bcbf 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -45,6 +45,11 @@ else include("test-model-concrete-object-identities.jl") end + @testset "Persistent typed execution cohorts" begin + include("test-execution-cohorts.jl") + include("test-model-canonical-cohorts.jl") + end + @testset "Organ creation allocations" begin include("test-organ-creation-allocation.jl") end diff --git a/test/test-execution-cohorts.jl b/test/test-execution-cohorts.jl new file mode 100644 index 000000000..12abe8844 --- /dev/null +++ b/test/test-execution-cohorts.jl @@ -0,0 +1,136 @@ +using PlantSimEngine +using Test + +mutable struct ExecutionCohortTestTarget{I,S} + object_id::I + status::S +end + +@testset "Execution cohorts preserve typed payloads and ordered membership" begin + store = PlantSimEngine.ExecutionCohortStore() + first = ExecutionCohortTestTarget(ObjectId(1), Status(value=1.0)) + middle = ExecutionCohortTestTarget(ObjectId(2), Status(value=2.0f0)) + last = ExecutionCohortTestTarget(ObjectId(3), Status(value=3.0)) + left = PlantSimEngine.cohort_rows!(store, :growth, [first]) + center = PlantSimEngine.cohort_rows!(store, :growth, [middle]) + right = PlantSimEngine.cohort_rows!(store, :growth, [last]) + + @test left isa AbstractVector{typeof(first)} + @test eltype(center) === typeof(middle) + @test left.cohort === right.cohort + @test left.cohort !== center.cohort + @test left.store === right.store === store + @test [target.object_id.value for rows in (left, center, right) for target in rows] == [1, 2, 3] + @test left[1] === first + @test center[1] === middle + @test right[1] === last + @test left[1].status === first.status + @test PlantSimEngine.refvalue(left[1].status, :value) === PlantSimEngine.refvalue(first.status, :value) + + another_app = PlantSimEngine.cohort_rows!(store, :another_application, [first]) + @test another_app.cohort !== left.cohort + @test another_app[1] === first + @test left.indices !== right.indices + @test Base.mightalias(left, right) + @test !Base.mightalias(left, center) + + copied = copy(left) + @test copied.cohort === left.cohort + @test copied.indices !== left.indices + empty!(copied) + @test isempty(copied) + @test length(left) == 1 + append!(copied, left) + append!(copied, copied) + @test length(copied) == 2 + @test copied[1] === copied[2] === first +end + +@testset "Execution owners retain separate target contexts" begin + store = PlantSimEngine.ExecutionCohortStore() + status = Status(value=1.0) + root_target = ExecutionCohortTestTarget(ObjectId(:leaf), status) + call_target = ExecutionCohortTestTarget(ObjectId(:leaf), status) + owner = (:controller, ObjectId(:plant), :leaf_call, :manual) + roots = PlantSimEngine.cohort_rows!(store, :growth, [root_target]) + calls = PlantSimEngine.cohort_rows!(store, :growth, [call_target]; owner) + @test roots.store === calls.store + @test roots.cohort !== calls.cohort + @test roots[1] === root_target + @test calls[1] === call_target + @test roots[1].status === calls[1].status + @test PlantSimEngine.cohort_location(store, :growth, :leaf; owner).cohort === calls.cohort + @test PlantSimEngine.cohort_location(store, :growth, :leaf).cohort === roots.cohort + @test PlantSimEngine.remove_cohort_target!(store, :growth, :leaf) + @test calls[1] === call_target + @test isnothing(PlantSimEngine.cohort_location(store, :growth, :leaf)) + @test !isnothing(PlantSimEngine.cohort_location(store, :growth, :leaf; owner)) +end + +@testset "Cohort updates leave unaffected rows and references stable" begin + store = PlantSimEngine.ExecutionCohortStore() + first = ExecutionCohortTestTarget(ObjectId(10), Status(value=10.0)) + last = ExecutionCohortTestTarget(ObjectId(30), Status(value=30.0)) + rows = PlantSimEngine.cohort_rows!(store, :growth, [first, last]) + first_location = PlantSimEngine.cohort_location(store, :growth, first.object_id) + last_location = PlantSimEngine.cohort_location(store, :growth, last.object_id) + last_reference = PlantSimEngine.refvalue(last.status, :value) + + earlier = ExecutionCohortTestTarget(ObjectId(0), Status(value=0.0)) + insert!(rows, 1, earlier) + @test getproperty.(rows, :object_id) == ObjectId.([0, 10, 30]) + @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location + @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location + @test rows[3] === last + @test PlantSimEngine.refvalue(rows[3].status, :value) === last_reference + + replacement = ExecutionCohortTestTarget(ObjectId(10), Status(value=12.0)) + @test setindex!(rows, replacement, 2) === rows + @test rows[2] === replacement + @test PlantSimEngine.cohort_location(store, :growth, replacement.object_id) === first_location + @test rows[3] === last + + deleteat!(rows, 2) + @test getproperty.(rows, :object_id) == ObjectId.([0, 30]) + @test PlantSimEngine.remove_cohort_target!(store, :growth, ObjectId(10)) + @test isnothing(PlantSimEngine.cohort_location(store, :growth, ObjectId(10))) + @test isnothing(rows.cohort.rows[first_location.row]) + @test !PlantSimEngine.remove_cohort_target!(store, :growth, ObjectId(10)) + insert!(rows, 2, first) + @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location + @test rows[2] === first + @test rows[3] === last + + PlantSimEngine.reset_cohort_rows!(rows, [last, first]) + @test rows[1] === last + @test rows[2] === first + @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location + @test PlantSimEngine.reset_cohort_rows!(rows, rows) === rows +end + +@testset "A new payload schema extends the persistent store" begin + store = PlantSimEngine.ExecutionCohortStore() + first = ExecutionCohortTestTarget(ObjectId(:first), Status(value=1.0)) + last = ExecutionCohortTestTarget(ObjectId(:last), Status(value=3.0)) + rows = PlantSimEngine.cohort_rows!(store, :growth, [first, last]) + first_location = PlantSimEngine.cohort_location(store, :growth, first.object_id) + last_location = PlantSimEngine.cohort_location(store, :growth, last.object_id) + + changed = ExecutionCohortTestTarget(ObjectId(:first), Status(value=1.0f0, additional=7)) + changed_rows = PlantSimEngine.cohort_rows!(store, :growth, [changed]) + @test changed_rows.cohort !== rows.cohort + @test changed_rows[1] === changed + @test PlantSimEngine.cohort_location(store, :growth, changed.object_id).cohort === changed_rows.cohort + @test isnothing(rows.cohort.rows[first_location.row]) + @test_throws ArgumentError rows[1] + @test rows[2] === last + @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location + @test length(store.cohorts) == 2 + + restored = PlantSimEngine.cohort_rows!(store, :growth, [first]) + @test restored.cohort === rows.cohort + @test restored[1] === first + @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location + @test rows[2] === last + @test isnothing(changed_rows.cohort.rows[1]) +end diff --git a/test/test-model-canonical-cohorts.jl b/test/test-model-canonical-cohorts.jl new file mode 100644 index 000000000..be0abdf08 --- /dev/null +++ b/test/test-model-canonical-cohorts.jl @@ -0,0 +1,355 @@ +module CanonicalCohortChecks + +using PlantSimEngine, Random, Test +using PlantSimEngine.Diagnostics +const PSE = PlantSimEngine + +PSE.@process "canonical_cohort_accumulator" verbose=false +PSE.@process "canonical_cohort_random" verbose=false +PSE.@process "canonical_cohort_caller" verbose=false + +struct Accumulator{T} <: AbstractCanonical_Cohort_AccumulatorModel + increment::T +end +struct ScaledAccumulator{T} <: AbstractCanonical_Cohort_AccumulatorModel + increment::T +end +PSE.outputs_(model::Union{Accumulator,ScaledAccumulator}) = (value=zero(model.increment), visits=0) +function PSE.run!(model::Accumulator, status, environment, constants, ::RunContext) + status.value += model.increment + status.visits += 1 + return nothing +end +function PSE.run!(model::ScaledAccumulator, status, environment, constants, ::RunContext) + status.value += 2 * model.increment + status.visits += 1 + return nothing +end + +struct RandomProbe{R,V} <: AbstractCanonical_Cohort_RandomModel + rng::R + trace::V +end +PSE.outputs_(::RandomProbe) = (draw=0.0, visits=0) +function PSE.run!(model::RandomProbe, status, environment, constants, context::RunContext) + push!(model.trace, object_id(context)) + status.draw = rand(model.rng) + status.visits += 1 + return nothing +end + +struct Caller{C} <: AbstractCanonical_Cohort_CallerModel + context::C +end +PSE.outputs_(::Caller) = (total=0,) +function PSE.run!(model::Caller, status, environment, constants, context::RunContext) + model.context[] = context + status.total = 0 + for target in run_call!(context, :work; publish=true) + status.total += target.status.visits + end + return nothing +end + +function aliased_status(value) + reference = Ref(value) + return Status((value=reference, alias=reference, visits=Ref(0))) +end + +function execution_target(simulation, application_id, object_id) + id = ObjectId(object_id) + return only(target for batch in simulation.execution_plan.batches + if batch.application.id == application_id + for target in batch.targets if target.object_id == id) +end + +function assert_canonical_storage(simulation) + batches = simulation.execution_plan.batches + @test !isempty(batches) + store = simulation.execution_plan.cohorts + @test store isa PSE.ExecutionCohortStore + report = explain_execution_plan(simulation) + @test length(report) == length(batches) + for (row, batch) in zip(report, batches) + @test row.target_storage === :cohort + @test row.cohort_schema === eltype(batch.targets) + end + for batch in batches + view = batch.targets + @test view isa PSE.ExecutionCohortRows + @test view.store === store + @test view.cohort.application_id == batch.application.id + @test isconcretetype(eltype(view)) + @test length(view.indices) == length(view) + for (index, target) in enumerate(view) + @test view.cohort.rows[view.indices[index]] === target + location = PSE.cohort_location(store, batch.application.id, target.object_id) + @test location.cohort === view.cohort + @test location.row == view.indices[index] + @test target.canonical_status === model_status(simulation.model, target.object_id) + end + end + return store +end + +@testset "ordinary run owns typed cohorts for same-scale effective model schemas" begin + default_status = aliased_status(10.0f0) + override_status = aliased_status(20.0) + default_reference = PSE.refvalue(default_status, :value) + override_reference = PSE.refvalue(override_status, :value) + template = CompositeModelTemplate(( + ModelSpec(Accumulator(2.0f0); name=:accumulate, on=Many(scale=:Leaf)), + )) + instance = ObjectInstance(:plant, template; + root=Object(:plant; scale=:Plant), + objects=( + Object(:leaf_default; scale=:Leaf, parent=:plant, status=default_status), + Object(:leaf_override; scale=:Leaf, parent=:plant, status=override_status), + ), + object_overrides=(Override(object=:leaf_override, application=:accumulate, + model=ScaledAccumulator(3.0)),), + ) + model = CompositeModel(instance) + simulation = run!(model; steps=0, outputs=:all) + store = assert_canonical_storage(simulation) + default_target = execution_target(simulation, :plant__accumulate, :leaf_default) + override_target = execution_target(simulation, :plant__accumulate, :leaf_override) + @test default_target.model isa Accumulator{Float32} + @test override_target.model isa ScaledAccumulator{Float64} + @test PSE.cohort_location(store, :plant__accumulate, ObjectId(:leaf_default)).cohort !== + PSE.cohort_location(store, :plant__accumulate, ObjectId(:leaf_override)).cohort + @test default_target.canonical_status === default_status + @test override_target.canonical_status === override_status + + continue!(simulation; steps=2) + @test assert_canonical_storage(simulation) === store + @test default_status.value === 14.0f0 + @test override_status.value === 32.0 + @test default_status.visits == override_status.visits == 2 + @test PSE.refvalue(default_status, :value) === default_reference === PSE.refvalue(default_status, :alias) + @test PSE.refvalue(override_status, :value) === override_reference === PSE.refvalue(override_status, :alias) + @test last.(outputs(simulation)[(:plant__accumulate, ObjectId(:leaf_default), :value)]) == Float32[12, 14] + @test last.(outputs(simulation)[(:plant__accumulate, ObjectId(:leaf_override), :value)]) == [26.0, 32.0] + + # A new timeline on the same authored model owns new execution shells while + # the public model continues to own its mutable scientific status. + restarted = run!(model; steps=0, outputs=:none) + restarted_store = assert_canonical_storage(restarted) + restarted_target = execution_target(restarted, :plant__accumulate, :leaf_default) + @test restarted_store !== store + @test restarted_target !== default_target + @test restarted_target.context !== default_target.context + @test restarted_target.canonical_status === default_status + @test current_step(restarted) == 0 + step!(restarted) + @test default_status.value === 16.0f0 + @test override_status.value === 38.0 + @test default_target.context.time == 2.0 + @test restarted_target.context.time == 1.0 + @test current_step(simulation) == 2 +end + +@testset "cohort families preserve object order and the authored shared RNG" begin + rng = Xoshiro(392) + reference_rng = Xoshiro(392) + trace = ObjectId{Int}[] + status(marker) = Status(draw=0.0, visits=0, marker=marker) + model = CompositeModel( + Object(3; scale=:Leaf, status=status(1)), + Object(1; scale=:Leaf, status=status(1)), + Object(2; scale=:Leaf, status=status(1.0)); + applications=(ModelSpec(RandomProbe(rng, trace); name=:draw, on=Many(scale=:Leaf)),), + ) + simulation = run!(model; steps=1, outputs=:all) + store = assert_canonical_storage(simulation) + expected = [rand(reference_rng) for _ in 1:3] + @test trace == ObjectId.([1, 2, 3]) + @test [model_status(model, id).draw for id in 1:3] == expected + @test all(model_status(model, id).visits == 1 for id in 1:3) + @test length(simulation.execution_plan.batches) == 3 + @test first(simulation.execution_plan.batches).targets.cohort === + last(simulation.execution_plan.batches).targets.cohort + @test rand(copy(rng), UInt64) == rand(copy(reference_rng), UInt64) + original_targets = Dict(id => execution_target(simulation, :draw, id) for id in 1:3) + original_locations = Dict(id => PSE.cohort_location(store, :draw, ObjectId(id)) for id in 1:3) + + # A lower-ID newborn is appended to storage but executes first by identity. + register_object!(model, Object(0; scale=:Leaf, status=status(1.0))) + continue!(simulation) + @test assert_canonical_storage(simulation) === store + expected = [rand(reference_rng) for _ in 0:3] + @test trace == ObjectId.([1, 2, 3, 0, 1, 2, 3]) + @test [model_status(model, id).draw for id in 0:3] == expected + @test model_status(model, 0).visits == 1 + @test all(model_status(model, id).visits == 2 for id in 1:3) + @test rand(copy(rng), UInt64) == rand(copy(reference_rng), UInt64) + for id in 1:3 + @test execution_target(simulation, :draw, id) === original_targets[id] + location = PSE.cohort_location(store, :draw, ObjectId(id)) + @test location.cohort === original_locations[id].cohort + @test location.row == original_locations[id].row + end +end + +function scoped_fixture() + return CompositeModel( + Object(:scene; scale=:Scene, status=aliased_status(0)), + Object(:plant_a; scale=:Plant, parent=:scene), + Object(:plant_b; scale=:Plant, parent=:scene), + Object(:a; scale=:Leaf, parent=:plant_a, status=aliased_status(0)), + Object(:b; scale=:Leaf, parent=:plant_a, status=aliased_status(0)), + Object(:c; scale=:Leaf, parent=:plant_b, status=aliased_status(0)); + applications=( + ModelSpec(Accumulator(1); name=:leaves, on=Many(scale=:Leaf, within=Scope(ObjectId(:plant_a)))), + ModelSpec(Accumulator(1); name=:scene, on=One(id=:scene)), + ), + ) +end + +@testset "ordinary structural refresh preserves survivor slots and canonical aliases" begin + model = scoped_fixture() + a_status = model_status(model, :a) + removed_status = model_status(model, :b) + a_reference = PSE.refvalue(a_status, :value) + simulation = run!(model; steps=1, outputs=:all) + store = assert_canonical_storage(simulation) + scene_target = execution_target(simulation, :scene, :scene) + removed_target = execution_target(simulation, :leaves, :b) + @test a_status.value == removed_status.value == 1 + + newborn_status = aliased_status(0) + newborn_reference = PSE.refvalue(newborn_status, :value) + register_object!(model, Object(:d; scale=:Leaf, parent=:plant_a, status=newborn_status)) + continue!(simulation) + newborn_target = execution_target(simulation, :leaves, :d) + newborn_location = PSE.cohort_location(store, :leaves, ObjectId(:d)) + @test assert_canonical_storage(simulation) === store + @test a_status.value == removed_status.value == 2 + @test newborn_status.value == 1 + + remove_object!(model, :b) + reparent_object!(model, :a, :plant_b) + continue!(simulation) + @test assert_canonical_storage(simulation) === store + @test [target.object_id for batch in simulation.execution_plan.batches + if batch.application.id == :leaves for target in batch.targets] == [ObjectId(:d)] + @test execution_target(simulation, :leaves, :d) === newborn_target + @test execution_target(simulation, :scene, :scene) === scene_target + @test PSE.cohort_location(store, :leaves, ObjectId(:d)).cohort === newborn_location.cohort + @test PSE.cohort_location(store, :leaves, ObjectId(:d)).row == newborn_location.row + @test a_status.value == removed_status.value == newborn_status.value == 2 + @test model_status(model, :c).value == 0 + @test PSE.refvalue(a_status, :value) === a_reference === PSE.refvalue(a_status, :alias) + @test PSE.refvalue(newborn_status, :value) === newborn_reference === PSE.refvalue(newborn_status, :alias) + + replacement_status = aliased_status(0) + reparent_object!(model, :a, :plant_a) + register_object!(model, Object(:b; scale=:Leaf, parent=:plant_a, status=replacement_status)) + continue!(simulation) + @test assert_canonical_storage(simulation) === store + @test a_status.value == newborn_status.value == 3 + @test replacement_status.value == 1 + @test removed_status.value == 2 + @test model_status(model, :scene).value == 4 + @test execution_target(simulation, :leaves, :b) !== removed_target + @test PSE.refvalue(replacement_status, :value) !== PSE.refvalue(removed_status, :value) + @test first.(outputs(simulation)[(:leaves, ObjectId(:a), :value)]) == [1.0, 2.0, 4.0] + @test last.(outputs(simulation)[(:leaves, ObjectId(:b), :value)]) == [1, 2, 1] +end + +function assert_manual_location(store, application, target, owner) + location = PSE.cohort_location(store, application, object_id(target); owner) + @test location.cohort.rows[location.row] === target.execution_target + return nothing +end + +@testset "retained hard-call identities use the same canonical store" begin + captured = Ref{Any}() + model = CompositeModel( + Object(:plant_a; scale=:Plant), + Object(:plant_b; scale=:Plant), + Object(:b; scale=:Leaf, parent=:plant_a, status=aliased_status(0)); + applications=( + ModelSpec(Caller(captured); name=:caller, on=One(id=:plant_a), + calls=(work=Many(scale=:Leaf, within=Subtree(), application=:work),)), + ModelSpec(Accumulator(1); name=:work, on=Many(scale=:Leaf)), + ), + ) + simulation = run!(model; steps=1, outputs=:all) + store = assert_canonical_storage(simulation) + retained = only(call_targets(captured[], :work)) + call_owner = PSE._execution_call_owner(only(captured[].calls).binding) + retained_execution_target = retained.execution_target + retained_status = retained.status + @test object_id(retained) == ObjectId(:b) + @test model_status(model, :plant_a).total == 1 + assert_manual_location(store, :work, retained, call_owner) + + register_object!(model, Object(:a; scale=:Leaf, parent=:plant_a, status=aliased_status(0))) + continue!(simulation) + current = collect(call_targets(captured[], :work)) + @test object_id.(current) == ObjectId.([:a, :b]) + @test model_status(model, :plant_a).total == 3 + @test retained.status === retained_status === model_status(model, :b) + @test retained.execution_target === retained_execution_target + @test retained_status.value == retained_status.visits == 2 + @test retained.time == 1.0 + for target in current + assert_manual_location(store, :work, target, call_owner) + end + + remove_object!(model, :a) + continue!(simulation) + @test model_status(model, :plant_a).total == 3 + @test retained_status.value == retained_status.visits == 3 + @test only(call_targets(captured[], :work)).execution_target === retained_execution_target + reparent_object!(model, :b, :plant_b) + continue!(simulation) + @test assert_canonical_storage(simulation) === store + @test isempty(call_targets(captured[], :work)) + @test model_status(model, :plant_a).total == 0 + @test retained.status === model_status(model, :b) + @test retained_status.value == retained_status.visits == 3 + @test retained.time == 1.0 +end + +@testset "diagnostics leave live cohort membership and pending changes untouched" begin + model = scoped_fixture() + simulation = run!(model; steps=1, outputs=:all, performance=true) + store = assert_canonical_storage(simulation) + views = [batch.targets for batch in simulation.execution_plan.batches] + memberships = [copy(view.indices) for view in views] + row_counts = [length(view.cohort.rows) for view in views] + source_target = execution_target(simulation, :leaves, :a) + source_reference = PSE.refvalue(model_status(model, :a), :value) + retained = outputs(simulation)[(:leaves, ObjectId(:a), :value)] + retained_samples = copy(retained) + counts = copy(Advanced.runtime_performance(simulation).counts) + register_object!(model, Object(:d; scale=:Leaf, parent=:plant_a, status=aliased_status(10))) + + rows = explain_execution_plan(model) + @test any(row -> row.application_id == :leaves && :d in row.object_ids, rows) + for explain in (explain_bindings, explain_schedule, explain_writers, + explain_output_bindings, explain_output_retention, explain_initialization) + @test explain(model) isa AbstractVector + end + @test assert_canonical_storage(simulation) === store + @test Advanced.bindings_dirty(model) + @test Advanced.environment_bindings_dirty(model) + @test [copy(view.indices) for view in views] == memberships + @test [length(view.cohort.rows) for view in views] == row_counts + @test execution_target(simulation, :leaves, :a) === source_target + @test PSE.refvalue(model_status(model, :a), :value) === source_reference + @test model_status(model, :a).value == 1 + @test model_status(model, :d).value == 10 + @test outputs(simulation)[(:leaves, ObjectId(:a), :value)] === retained + @test retained == retained_samples + @test Advanced.runtime_performance(simulation).counts == counts + + continue!(simulation) + @test assert_canonical_storage(simulation) === store + @test model_status(model, :a).value == 2 + @test model_status(model, :d).value == 11 +end + +end # module CanonicalCohortChecks From 3334223aa5acdb448103405931a04abad1edaa90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 11:55:08 +0100 Subject: [PATCH 002/324] Refresh execution cohorts in place and share native scheduling --- src/composite_model/compilation.jl | 33 +- .../execution_cohort_refresh.jl | 259 ++++ src/composite_model/execution_cohorts.jl | 19 +- src/composite_model/execution_dispatch.jl | 84 ++ src/composite_model/execution_storage.jl | 15 - src/composite_model/runtime_outputs.jl | 1141 +++++------------ src/composite_model_api.jl | 2 + src/native_compilation.jl | 51 +- src/visualization/model_graph_view.jl | 3 + test/runtests.jl | 2 + test/test-compilation-metadata.jl | 60 + test/test-execution-cohort-refresh.jl | 330 +++++ test/test-execution-cohorts.jl | 3 + test/test-model-api-stabilization.jl | 115 +- test/test-model-hard-calls.jl | 17 + test/test-model-input-plan-output-metadata.jl | 13 +- test/test-native-compilation.jl | 9 + 17 files changed, 1268 insertions(+), 888 deletions(-) create mode 100644 src/composite_model/execution_cohort_refresh.jl create mode 100644 src/composite_model/execution_dispatch.jl create mode 100644 test/test-compilation-metadata.jl create mode 100644 test/test-execution-cohort-refresh.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 9664815d1..d6cec5165 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2,7 +2,7 @@ Immutable scenario-level metadata for one model application. Runtime object membership is stored separately in [`CompiledModelApplication`](@ref). """ -struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO} +struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,ON,CN} slot::Int id::Symbol spec::S @@ -13,6 +13,8 @@ struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO} timestep::TS clock::CL model_overrides::MO + output_names::ON + canonical_output_names::CN end """ @@ -2164,7 +2166,7 @@ Base.@nospecializeinfer function _compile_added_consumer_bindings!( # variables/producers. Keep this cache local to this invocation so neither # scene identity nor lifecycle invalidation needs persistent cache state. share_object_queries = count( - plan -> plan.origin != :inferred_same_object && plan.selector isa Many, + plan -> plan.origin != :inferred_same_object, input_plans, ) > 1 object_query_cache = share_object_queries ? Dict{Any,Vector{ObjectId}}() : nothing @@ -4539,6 +4541,7 @@ function _compile_model_applications(model::CompositeModel, raw_specs, timeline) _model_application_hint_scale(model, target_ids), ) model_overrides = _compiled_object_model_overrides(spec, target_ids, app_id) + output_names, canonical_output_names = _compiled_output_names(spec) push!( applications, CompiledModelApplication( @@ -4558,6 +4561,8 @@ function _compile_model_applications(model::CompositeModel, raw_specs, timeline) timeline, ), model_overrides, + output_names, + canonical_output_names, ), target_ids, ), @@ -4641,16 +4646,21 @@ function _application_model(application::CompiledModelApplication, object_id::Ob ) end -function _model_output_names(application::CompiledModelApplication) - return Symbol[Symbol(var) for var in keys(_local_output_schema(application.spec))] +function _compiled_output_names(spec) + # Port names belong to the immutable application schema. Reading a model's + # declarations again during growth can allocate fresh default arrays even + # though writer matching needs only their names. + names = Tuple(Symbol(var) for var in keys(_local_output_schema(spec))) + canonical = Tuple(variable for variable in names + if _publish_mode_for_output(spec, variable) === :canonical) + return names, canonical end -function _model_canonical_output_names(application::CompiledModelApplication) - return Symbol[ - variable for variable in _model_output_names(application) - if _publish_mode_for_output(application.spec, variable) == :canonical - ] -end +_model_output_names(application::CompiledModelApplication) = + getfield(application, :plan).output_names + +_model_canonical_output_names(application::CompiledModelApplication) = + getfield(application, :plan).canonical_output_names function _model_writer_groups(applications, skipped_application_ids=Set{Symbol}()) groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() @@ -5129,9 +5139,10 @@ function _cached_dependency_object_ids( matcher::CompiledSelectorMatcher, context::ObjectId, ) - (isnothing(cache) || !(selector isa Many)) && + isnothing(cache) && return _dependency_object_ids(model, selector, matcher, context) key = ( + multiplicity(selector), matcher.scope, matcher.relation, matcher.scale, matcher.kind, matcher.species, matcher.id, matcher.defaults_to_context, ) diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl new file mode 100644 index 000000000..8f82baa78 --- /dev/null +++ b/src/composite_model/execution_cohort_refresh.jl @@ -0,0 +1,259 @@ +"""Ordered schedule membership, separate from persistent execution payloads.""" +struct ExecutionCohortMembership + store::ExecutionCohortStore + owner::Any + application_id::Symbol + object_ids::Vector{ObjectId} + locations::Vector{ExecutionCohortLocation} + runs::Vector{ExecutionCohortRows} + run_starts::Vector{Int} +end + +function _execution_cohort_target(cohort::ExecutionCohort{T}, row::Int) where {T} + target = cohort.rows[row] + isnothing(target) && throw(ArgumentError( + "An execution membership refers to a removed or replaced payload schema.", + )) + return target::T +end + +_execution_cohort_target(location::ExecutionCohortLocation) = + _execution_cohort_target(location.cohort, location.row) + +function _execution_cohort_rows( + store::ExecutionCohortStore, cohort::ExecutionCohort{T}, indices::Vector{Int}, +) where {T} + return ExecutionCohortRows{T}(store, cohort, indices) +end + +function _shift_execution_run_starts!(membership, first_run, delta) + for index in first_run:lastindex(membership.run_starts) + membership.run_starts[index] += delta + end + return nothing +end + +function _insert_execution_membership_row!(membership, position, object_id, location) + count = length(membership.object_ids) + runs = membership.runs + starts = membership.run_starts + if isempty(runs) || position == count + 1 + if !isempty(runs) && last(runs).cohort === location.cohort + push!(last(runs).indices, location.row) + else + push!(runs, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) + push!(starts, position) + end + else + run_index = searchsortedlast(starts, position) + rows = runs[run_index] + local_index = position - starts[run_index] + 1 + if rows.cohort === location.cohort + insert!(rows.indices, local_index, location.row) + _shift_execution_run_starts!(membership, run_index + 1, 1) + elseif local_index == 1 && run_index > 1 && + runs[run_index - 1].cohort === location.cohort + push!(runs[run_index - 1].indices, location.row) + _shift_execution_run_starts!(membership, run_index, 1) + elseif local_index == 1 + insert!(runs, run_index, _execution_cohort_rows( + membership.store, location.cohort, Int[location.row], + )) + insert!(starts, run_index, position) + _shift_execution_run_starts!(membership, run_index + 1, 1) + else + # A new family inside a run needs one additional view of its right + # part. Other runs and all scientific payloads retain identity. + right_indices = rows.indices[local_index:end] + sizehint!(right_indices, length(right_indices) + max(16, length(right_indices) ÷ 4)) + right = _execution_cohort_rows(membership.store, rows.cohort, right_indices) + resize!(rows.indices, local_index - 1) + insert!(runs, run_index + 1, _execution_cohort_rows( + membership.store, location.cohort, Int[location.row], + )) + insert!(starts, run_index + 1, position) + insert!(runs, run_index + 2, right) + insert!(starts, run_index + 2, position + 1) + _shift_execution_run_starts!(membership, run_index + 3, 1) + end + end + insert!(membership.object_ids, position, object_id) + insert!(membership.locations, position, location) + return nothing +end + +function _delete_execution_membership_row!(membership, position) + runs = membership.runs + starts = membership.run_starts + run_index = searchsortedlast(starts, position) + rows = runs[run_index] + deleteat!(rows.indices, position - starts[run_index] + 1) + _shift_execution_run_starts!(membership, run_index + 1, -1) + if isempty(rows.indices) + deleteat!(runs, run_index) + deleteat!(starts, run_index) + if run_index > 1 && run_index <= length(runs) && + runs[run_index - 1].cohort === runs[run_index].cohort + append!(runs[run_index - 1].indices, runs[run_index].indices) + deleteat!(runs, run_index) + deleteat!(starts, run_index) + end + end + deleteat!(membership.object_ids, position) + deleteat!(membership.locations, position) + return nothing +end + +function _check_execution_cohort_target(target, object_id) + T = typeof(target) + hasfield(T, :object_id) || throw(ArgumentError( + "An execution target requires an object_id field.", + )) + I = fieldtype(T, :object_id) + I <: ObjectId && isconcretetype(I) || throw(ArgumentError( + "An execution target requires a concrete ObjectId field.", + )) + target.object_id == object_id || throw(ArgumentError( + "An execution target's identity must match its membership identity.", + )) + return nothing +end + +function _new_execution_cohort_membership(store, owner, application_id, count) + ids = ObjectId[] + locations = ExecutionCohortLocation[] + # Reserve initial spare capacity once. Ordinary push!/insert! growth then + # remains amortized; requesting exactly one spare slot on every refresh + # would itself force repeated allocations proportional to live object count. + capacity = count + max(16, count ÷ 4) + sizehint!(ids, capacity) + sizehint!(locations, capacity) + return ExecutionCohortMembership( + store, owner, application_id, ids, locations, ExecutionCohortRows[], Int[], + ) +end + +""" + refresh_cohort_membership!(build_target, store, application_id, current_ids, + changed_ids; previous=nothing, owner=nothing) + +Refresh one execution owner's persistent ordered membership. `current_ids` and +`changed_ids` use the compiler's canonical, unique object order. A supplied +change set covers all added, removed, and semantically changed target identities. +A `nothing` change set validates every current target and discovers removals by +merging identities. Initial construction also validates every current target. + +`build_target(object_id, previous_target)` returns the existing target when +reusable, including after a valid in-place call-cache update, or a newly compiled +target. All constructions finish before this helper changes payload storage or +membership; the callback itself keeps its existing mutation/failure contract. + +Changed owners are looked up independently of batch count. Membership arrays +and typed runs are spliced in place. Appending a same-schema target touches no +surviving membership entries; insertion/removal shifts only affected metadata. +A new family inside a run splits that run, preserving global object/RNG order. +No retained target, status, context, or binding cache is cloned. +""" +function refresh_cohort_membership!( + build_target, + store::ExecutionCohortStore, + application_id::Symbol, + current_ids, + changed_ids; + previous::Union{Nothing,ExecutionCohortMembership}=nothing, + owner=nothing, +) + if !isnothing(previous) + previous.store === store && previous.application_id === application_id && + isequal(previous.owner, owner) || throw(ArgumentError( + "Previous execution membership belongs to a different store or execution owner.", + )) + end + staged_targets = Tuple{ObjectId,Any}[] + removed_ids = ObjectId[] + checked_ids = isnothing(previous) || isnothing(changed_ids) ? current_ids : changed_ids + for object_id in checked_ids + location = cohort_location(store, application_id, object_id; owner) + is_current = isnothing(previous) || isnothing(changed_ids) || + first(_sorted_object_id_position(current_ids, object_id)) + if !is_current + push!(removed_ids, object_id) + continue + end + previous_target = isnothing(location) ? nothing : _execution_cohort_target(location) + target = build_target(object_id, previous_target) + _check_execution_cohort_target(target, object_id) + target === previous_target || push!(staged_targets, (object_id, target)) + end + if !isnothing(previous) && isnothing(changed_ids) + current_index = firstindex(current_ids) + for object_id in previous.object_ids + while current_index <= lastindex(current_ids) && + _object_id_isless(current_ids[current_index], object_id) + current_index += 1 + end + if current_index > lastindex(current_ids) || current_ids[current_index] != object_id + push!(removed_ids, object_id) + end + end + end + + membership = isnothing(previous) ? + _new_execution_cohort_membership(store, owner, application_id, length(current_ids)) : + previous + membership_changed = isnothing(previous) + targets_removed = 0 + # Every fallible target construction has completed before the first splice. + for object_id in removed_ids + found, position = _sorted_object_id_position(membership.object_ids, object_id) + if found + _delete_execution_membership_row!(membership, position) + targets_removed += 1 + membership_changed = true + end + remove_cohort_target!(store, application_id, object_id; owner) + end + for (object_id, target) in staged_targets + cohort = _execution_cohort(store, owner, application_id, typeof(target)) + _store_execution_cohort_target!(store, cohort, target) + isnothing(previous) && continue + location = cohort_location(store, application_id, object_id; owner) + found, position = if isempty(membership.object_ids) || + _object_id_isless(last(membership.object_ids), object_id) + (false, length(membership.object_ids) + 1) + else + _sorted_object_id_position(membership.object_ids, object_id) + end + if !found + _insert_execution_membership_row!(membership, position, object_id, location) + membership_changed = true + elseif membership.locations[position].cohort !== location.cohort + _delete_execution_membership_row!(membership, position) + _insert_execution_membership_row!(membership, position, object_id, location) + membership_changed = true + else + membership.locations[position] = location + end + end + if isnothing(previous) + for object_id in current_ids + location = cohort_location(store, application_id, object_id; owner) + _insert_execution_membership_row!( + membership, length(membership.object_ids) + 1, object_id, location, + ) + end + for rows in membership.runs + count = length(rows) + sizehint!(rows.indices, count + max(16, count ÷ 4)) + family_count = length(rows.cohort.rows) + sizehint!(rows.cohort.rows, family_count + max(16, family_count ÷ 4)) + end + end + return ( + membership=membership, + targets_constructed=length(staged_targets), + targets_reused=length(current_ids) - length(staged_targets), + targets_removed=targets_removed, + membership_changed=membership_changed, + ) +end diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index fcb2f5f83..332556ee2 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -1,10 +1,10 @@ abstract type AbstractExecutionCohort end -mutable struct ExecutionCohort{T} <: AbstractExecutionCohort +mutable struct ExecutionCohort{T,I<:ObjectId} <: AbstractExecutionCohort owner::Any application_id::Symbol rows::Vector{Union{Nothing,T}} - indices::Dict{ObjectId,Int} + indices::Dict{I,Int} end struct ExecutionCohortLocation @@ -24,12 +24,15 @@ ExecutionCohortStore() = ExecutionCohortStore( ) """An ordered membership view over one application's concrete payload family.""" -struct ExecutionCohortRows{T} <: AbstractVector{T} +struct ExecutionCohortRows{T,C<:ExecutionCohort{T}} <: AbstractVector{T} store::ExecutionCohortStore - cohort::ExecutionCohort{T} + cohort::C indices::Vector{Int} end +ExecutionCohortRows{T}(store::ExecutionCohortStore, cohort::C, indices::Vector{Int}) where {T,C<:ExecutionCohort{T}} = + ExecutionCohortRows{T,C}(store, cohort, indices) + Base.IndexStyle(::Type{<:ExecutionCohortRows}) = IndexLinear() Base.size(rows::ExecutionCohortRows) = size(rows.indices) Base.length(rows::ExecutionCohortRows) = length(rows.indices) @@ -50,10 +53,14 @@ function _execution_cohort(store::ExecutionCohortStore, owner, application_id::S isconcretetype(T) && T !== Nothing || throw(ArgumentError( "An execution cohort requires a concrete target payload type.", )) + I = fieldtype(T, :object_id) + I <: ObjectId && isconcretetype(I) || throw(ArgumentError( + "An execution cohort requires a concrete ObjectId field in its target payload.", + )) cohort = get!(store.cohorts, (owner, application_id, T)) do - ExecutionCohort{T}(owner, application_id, Union{Nothing,T}[], Dict{ObjectId,Int}()) + ExecutionCohort{T,I}(owner, application_id, Union{Nothing,T}[], Dict{I,Int}()) end - return cohort::ExecutionCohort{T} + return cohort::ExecutionCohort{T,I} end function _clear_execution_cohort_row!(cohort::ExecutionCohort, row::Int) diff --git a/src/composite_model/execution_dispatch.jl b/src/composite_model/execution_dispatch.jl new file mode 100644 index 000000000..362179903 --- /dev/null +++ b/src/composite_model/execution_dispatch.jl @@ -0,0 +1,84 @@ +abstract type ExecutionTopology end +struct DynamicExecution <: ExecutionTopology end +struct FixedExecution <: ExecutionTopology end + +@inline function _run_execution_slot!(groups::AbstractVector, slot::Int, simulation::Simulation, step::Integer) + group = groups[slot] + isnothing(group) && return false + _run_model_execution_group!(group, simulation, step, simulation.performance) + return true +end + +# Application slots are part of a closed plan's schema. Both representations +# enter the same group/batch executor, while this dispatch keeps tuple members +# concrete when the caller supplies an ordinary runtime slot number. +@generated function _run_execution_slot!(groups::G, slot::Int, simulation::Simulation, step::Integer) where {G<:Tuple} + branches = map(1:fieldcount(G)) do index + body = fieldtype(G, index) === Nothing ? :(return false) : quote + _run_model_execution_group!(getfield(groups, $index), simulation, step, simulation.performance) + return true + end + :(if slot == $index + $body + end) + end + return quote + $(branches...) + throw(BoundsError(groups, slot)) + end +end + +function _refresh_timeline!(simulation::Simulation, ::DynamicExecution) + lifecycle = _pending_output_request_lifecycle_delta(simulation.model) + _refresh_simulation_runtime!(simulation) + _refresh_output_request_targets!(simulation, lifecycle) + return simulation +end + +@inline function _refresh_timeline!(simulation::Simulation, ::FixedExecution) + _simulation_runtime_dirty(simulation, nothing) && throw(ArgumentError( + "Compiled simulation topology and bindings must stay fixed.", + )) + return simulation +end + +"""Close schedule container schemas without copying the live execution payloads.""" +function _fixed_execution_plan(plan::CompiledExecutionPlan) + groups = Tuple(CompiledApplicationExecutionGroup(group.application, Tuple(group.batches), group.membership) + for group in plan.groups) + groups_by_id = Dict(group.application.id => group for group in groups) + groups_by_slot = Tuple(isnothing(group) ? nothing : groups_by_id[group.application.id] + for group in plan.groups_by_application_slot) + batches = Tuple(batch for group in groups for batch in group.batches) + return CompiledExecutionPlan( + plan.cohorts, + FixedExecution(), + groups, + batches, + groups_by_slot, + plan.schedule, + plan.model_revision, + plan.environment_revision, + ) +end + +"""Replace only the execution-plan schema in a freshly prepared simulation.""" +function _simulation_with_execution_plan(simulation::Simulation, plan::CompiledExecutionPlan) + return Simulation( + simulation.model, + simulation.compiled, + simulation.environment_bindings, + plan, + simulation.output_retention, + simulation.temporal_streams, + simulation.output_datetimes, + simulation.output_requests, + simulation.output_request_matchers, + simulation.output_request_targets, + simulation.output_request_model_revision, + simulation.runtime_revision, + simulation.current_step, + simulation.constants, + simulation.performance, + ) +end diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl index efebf67b8..0728aea20 100644 --- a/src/composite_model/execution_storage.jl +++ b/src/composite_model/execution_storage.jl @@ -36,21 +36,6 @@ _execution_cohort_store(::Nothing) = ExecutionCohortStore() _insert_with_spare_capacity!(rows::ExecutionCohortRows, position::Integer, target) = insert!(rows, position, target) -function _retire_scheduled_cohort_targets!(store::ExecutionCohortStore, compiled) - obsolete = Tuple{Symbol,ObjectId}[] - for (owner, application_id, object_id) in keys(store.locations) - isnothing(owner) || continue - application = get(compiled.applications_by_id, application_id, nothing) - if isnothing(application) || !first(_sorted_object_id_position(application.target_ids, object_id)) - push!(obsolete, (application_id, object_id)) - end - end - for (application_id, object_id) in obsolete - remove_cohort_target!(store, application_id, object_id) - end - return nothing -end - function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches) store = storage.cohorts owner = _execution_call_owner(binding) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index b3dc1c980..114879647 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -833,7 +833,12 @@ function _record_call_execution_batch_cache!( else batches end - _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches) + # Explicit `objects=` selections share the call owner's payloads with its + # complete cached view. Only that complete membership can retire rows; + # absence from one selection does not remove a target from the call. + if cached.tracks_full_membership + _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches) + end return batches end @@ -1071,26 +1076,27 @@ CompiledExecutionBatch( ExecutionBatchContextState(nothing, nothing), ) -struct CompiledApplicationExecutionGroup{A,B} +mutable struct CompiledApplicationExecutionGroup{A,B} application::A batches::B + membership::ExecutionCohortMembership end -function _compiled_application_execution_group(application, batches) +function _compiled_application_execution_group(application, batches, membership) if !isempty(batches) batch_type = typeof(first(batches)) eltype(batches) === batch_type && - return CompiledApplicationExecutionGroup(application, batches) + return CompiledApplicationExecutionGroup(application, batches, membership) if all(batch -> typeof(batch) === batch_type, batches) # Dispatch once at the application boundary, then retain the batch # schema through its loop. Counts and object identities remain # runtime data, including after same-schema lifecycle changes. typed = Vector{batch_type}(undef, length(batches)) copyto!(typed, batches) - return CompiledApplicationExecutionGroup(application, typed) + return CompiledApplicationExecutionGroup(application, typed, membership) end end - return CompiledApplicationExecutionGroup(application, batches) + return CompiledApplicationExecutionGroup(application, batches, membership) end mutable struct RuntimeApplicationSchedule @@ -1100,8 +1106,9 @@ mutable struct RuntimeApplicationSchedule last_step::Int end -struct CompiledExecutionPlan{G,B,I,S} +struct CompiledExecutionPlan{G,B,I,S,TP} cohorts::ExecutionCohortStore + topology::TP groups::G batches::B groups_by_application_slot::I @@ -1537,11 +1544,11 @@ function _environment_binding_for(env_bindings::CompiledEnvironmentBindings, app end function _model_object_status(model::CompositeModel, object_id::ObjectId) - object = _model_object(model, object_id) - object.status isa Status || error( + status = model_status(model, object_id) + status isa Status || error( "CompositeModel object `$(object_id.value)` has no `Status`; model runtime requires status-backed objects." ) - return object.status + return status end @inline function _model_status_view_for_application( @@ -3597,6 +3604,21 @@ function _compiled_model_execution_target( end end end + return _new_model_execution_target( + compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants, + ) +end + +function _new_model_execution_target( + compiled::CompiledCompositeModel, + env_bindings::CompiledEnvironmentBindings, + application::CompiledModelApplication, + object_id::ObjectId, + temporal_streams, + output_retention, + constants, +) status_view = _model_status_view_for_application( compiled, application, @@ -3670,23 +3692,6 @@ function _compiled_model_execution_target( ) end -function _typed_model_execution_targets( - cohorts::ExecutionCohortStore, - application_id::Symbol, - targets, - first_index::Int, - last_index::Int; - owner=nothing, -) - target_type = typeof(targets[first_index]) - typed = Vector{target_type}(undef, last_index - first_index + 1) - sizehint!(typed, length(typed) + 1) - for (destination, source) in enumerate(first_index:last_index) - typed[destination] = targets[source] - end - return cohort_rows!(cohorts, application_id, typed; owner) -end - function _compiled_model_execution_environment_provider( env_bindings::CompiledEnvironmentBindings, application::CompiledModelApplication, @@ -3718,54 +3723,81 @@ end _compiled_output_publication(::Nothing, application) = CompiledOutputPublication((), false) -function _append_model_execution_batches!( - batches, +function _execution_batch_matches( + batch, application, provider, output_publication, +) + return batch.application === application && + isequal(batch.environment_provider, provider) && + batch.output_publication.variables == output_publication.variables && + batch.output_publication.enabled == output_publication.enabled +end + +function _model_execution_batches( env_bindings::CompiledEnvironmentBindings, application::CompiledModelApplication, - targets, + membership::ExecutionCohortMembership, output_retention, - cohorts::ExecutionCohortStore; - owner=nothing, -) - isempty(targets) && return batches - output_publication = _compiled_output_publication( - output_retention, - application, - ) - first_index = firstindex(targets) - target_type = typeof(targets[first_index]) - for index in (first_index + 1):lastindex(targets) - typeof(targets[index]) == target_type && continue - push!( - batches, - CompiledExecutionBatch( - application, - _typed_model_execution_targets(cohorts, application.id, targets, first_index, index - 1; owner), - _compiled_model_execution_environment_provider( - env_bindings, - application, - targets[first_index], - ), - output_publication, - ), - ) - first_index = index - target_type = typeof(targets[index]) + previous_group=nothing, +) + output_publication = _compiled_output_publication(output_retention, application) + live_views = IdDict{ExecutionCohortRows,Nothing}(rows => nothing for rows in membership.runs) + previous_by_view = IdDict{ExecutionCohortRows,Any}() + spare_by_cohort = IdDict{AbstractExecutionCohort,Vector{Any}}() + next_spare = IdDict{AbstractExecutionCohort,Int}() + if !isnothing(previous_group) && previous_group.application === application + for batch in previous_group.batches + previous_by_view[batch.targets] = batch + if !haskey(live_views, batch.targets) + candidates = get!(spare_by_cohort, batch.targets.cohort) do + Any[] + end + push!(candidates, batch) + end + end end - push!( - batches, - CompiledExecutionBatch( - application, - _typed_model_execution_targets(cohorts, application.id, targets, first_index, lastindex(targets); owner), - _compiled_model_execution_environment_provider( - env_bindings, - application, - targets[first_index], - ), - output_publication, - ), - ) - return batches + batches = AbstractExecutionBatch[] + batches_constructed = 0 + for (index, rows) in pairs(membership.runs) + provider = _compiled_model_execution_environment_provider( + env_bindings, application, first(rows), + ) + reused = get(previous_by_view, rows, nothing) + if !isnothing(reused) && + !_execution_batch_matches(reused, application, provider, output_publication) + reused = nothing + end + if isnothing(reused) + candidates = get(spare_by_cohort, rows.cohort, ()) + candidate_index = get(next_spare, rows.cohort, 1) + while candidate_index <= length(candidates) + candidate = candidates[candidate_index] + candidate_index += 1 + if _execution_batch_matches(candidate, application, provider, output_publication) + reused = candidate + break + end + end + next_spare[rows.cohort] = candidate_index + end + if isnothing(reused) + push!(batches, CompiledExecutionBatch( + application, rows, provider, output_publication, + )) + batches_constructed += 1 + else + if reused.targets !== rows + # Never consume a view still reserved for a later ordered run. + # Spares are retired views, and shared index vectors need no copy. + if reused.targets.indices !== rows.indices + empty!(reused.targets.indices) + append!(reused.targets.indices, rows.indices) + end + membership.runs[index] = reused.targets + end + push!(batches, reused) + end + end + return (batches=batches, batches_constructed=batches_constructed) end function _compiled_call_execution_batches( @@ -3777,36 +3809,26 @@ function _compiled_call_execution_batches( constants, ) cohorts = _execution_cohort_store(temporal_streams) + owner = _execution_call_owner(binding) batches = AbstractExecutionBatch[] for application_id in binding.callee_application_ids application = _compiled_application_by_id(compiled, application_id) - targets = Any[] - for object_id in binding.callee_object_ids - _call_binding_target_matches(binding, application, object_id) || - continue - push!( - targets, - _compiled_model_execution_target( - compiled, - env_bindings, - application, - object_id, - temporal_streams, - output_retention, - constants; - owner=_execution_call_owner(binding), - ), + current_ids = ObjectId[ + object_id for object_id in binding.callee_object_ids + if _call_binding_target_matches(binding, application, object_id) + ] + refreshed = refresh_cohort_membership!( + cohorts, application.id, current_ids, nothing; owner, + ) do object_id, previous_target + _compiled_model_execution_target( + compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants; owner, ) end - _append_model_execution_batches!( - batches, - env_bindings, - application, - targets, - output_retention, - cohorts; - owner=_execution_call_owner(binding), + assembled = _model_execution_batches( + env_bindings, application, refreshed.membership, output_retention, ) + append!(batches, assembled.batches) end return Tuple(batches) end @@ -3824,45 +3846,22 @@ function compile_model_execution_plan( batches = AbstractExecutionBatch[] for application in _ordered_model_applications(compiled) application.id in manual_application_ids && continue - first_batch = length(batches) + 1 - targets = Any[ - _compiled_model_execution_target( - compiled, - env_bindings, - application, - object_id, - temporal_streams, - output_retention, - constants, - ) - for object_id in application.target_ids - ] - _append_model_execution_batches!( - batches, - env_bindings, - application, - targets, - output_retention, - cohorts, - ) - first_batch > length(batches) && continue - push!( - groups, - _compiled_application_execution_group( - application, - batches[first_batch:end], - ), + refreshed = _refresh_model_execution_group!( + nothing, cohorts, compiled, env_bindings, application, + temporal_streams, output_retention, constants, nothing, nothing, ) + isnothing(refreshed.group) && continue + push!(groups, refreshed.group) + append!(batches, refreshed.group.batches) end application_count = length(compiled.scenario_plan.applications) return CompiledExecutionPlan( cohorts, + DynamicExecution(), groups, batches, _execution_groups_by_application_slot(groups, application_count), - _runtime_application_schedule( - compiled.scenario_plan.application_schedule, - ), + _runtime_application_schedule(compiled.scenario_plan.application_schedule), compiled.revision, env_bindings.environment_revision, ) @@ -4220,89 +4219,6 @@ function _count_model_execution_target_rebuild!( return _runtime_performance_count!(performance, counter) end -function _model_execution_group_reusable( - group::CompiledApplicationExecutionGroup, - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - application::CompiledModelApplication, - output_retention=nothing, - temporal_streams=nothing, -) - group.application === application || return false - target_index = 0 - for batch in group.batches - for target in batch.targets - target_index += 1 - target_index <= length(application.target_ids) || return false - target.object_id == application.target_ids[target_index] || - return false - isnothing(_model_execution_target_change_reason( - target, - compiled, - env_bindings, - application, - output_retention, - temporal_streams, - )) || return false - end - end - return target_index == length(application.target_ids) -end - -function _sorted_execution_target_position( - targets, - object_id::ObjectId, -) - lower = firstindex(targets) - upper = lastindex(targets) - while lower <= upper - middle = (lower + upper) >>> 1 - candidate_id = @inbounds targets[middle].object_id - candidate_id == object_id && return (true, middle) - if _object_id_isless(candidate_id, object_id) - lower = middle + 1 - else - upper = middle - 1 - end - end - return (false, lower) -end - -function _model_execution_target_location( - group::CompiledApplicationExecutionGroup, - object_id::ObjectId, -) - for (batch_index, batch) in pairs(group.batches) - found, target_index = - _sorted_execution_target_position(batch.targets, object_id) - found && return (batch_index, target_index) - end - return nothing -end - -function _model_execution_target_insertion( - group::CompiledApplicationExecutionGroup, - object_id::ObjectId, -) - for (batch_index, batch) in pairs(group.batches) - isempty(batch.targets) && continue - if !_object_id_isless(last(batch.targets).object_id, object_id) - _, target_index = - _sorted_execution_target_position( - batch.targets, - object_id, - ) - return (batch_index, target_index) - end - end - isempty(group.batches) && return nothing - batch_index = lastindex(group.batches) - return ( - batch_index, - length(group.batches[batch_index].targets) + 1, - ) -end - function _model_execution_batch_accepts_target( batch::CompiledExecutionBatch, target::CompiledExecutionTarget, @@ -4387,7 +4303,8 @@ function _extend_execution_target_call_batches_by_prefix!( object_id, temporal_streams, output_retention, - constants, + constants; + owner=_execution_call_owner(binding), ) _model_execution_batch_accepts_target( destination_batch, @@ -4525,7 +4442,8 @@ function _extend_execution_target_call_batches_for_pure_addition!( object_id, temporal_streams, output_retention, - constants, + constants; + owner=_execution_call_owner(binding), ) _model_execution_batch_accepts_target( destination_batch, @@ -4594,8 +4512,14 @@ function _extend_execution_target_call_batches!( ) end -function _refresh_model_execution_group_delta!( - previous_group::CompiledApplicationExecutionGroup, +function _same_execution_members(left, right) + length(left) == length(right) || return false + return all(index -> left[index] === right[index], eachindex(left)) +end + +function _refresh_model_execution_group!( + previous_group, + cohorts::ExecutionCohortStore, compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, application::CompiledModelApplication, @@ -4605,150 +4529,64 @@ function _refresh_model_execution_group_delta!( performance, changed_object_ids, ) - previous_group.application === application || return nothing - isempty(changed_object_ids) && return nothing - actions = NamedTuple[] - targets_constructed = 0 - for object_id in changed_object_ids - location = _model_execution_target_location( - previous_group, - object_id, - ) - is_current_target = - first(_sorted_object_id_position(application.target_ids, object_id)) - if !is_current_target - isnothing(location) || push!( - actions, - ( - kind=:remove, - object_id=object_id, - target=nothing, - reason=nothing, - ), - ) - continue - end - previous_target = if isnothing(location) - nothing - else - batch_index, target_index = location - previous_group.batches[batch_index].targets[target_index] - end - change_reason = if isnothing(previous_target) - :new_target - else - _model_execution_target_change_reason( - previous_target, - compiled, - env_bindings, - application, - output_retention, - temporal_streams, - ) - end - isnothing(change_reason) && continue - if change_reason === :call_bindings && - _extend_execution_target_call_batches!( - previous_target, - compiled, - env_bindings, - temporal_streams, - output_retention, - constants, - performance, - ) - _runtime_performance_count!( - performance, - :execution_target_call_batches_extended, - ) - continue + previous_membership = isnothing(previous_group) ? nothing : previous_group.membership + calls_extended = Ref(false) + refreshed = refresh_cohort_membership!( + cohorts, application.id, application.target_ids, changed_object_ids; + previous=previous_membership, + ) do object_id, previous_target + reason = isnothing(previous_target) ? :new_target : + _model_execution_target_change_reason( + previous_target, compiled, env_bindings, application, + output_retention, temporal_streams, + ) + isnothing(reason) && return previous_target + if reason === :call_bindings && _extend_execution_target_call_batches!( + previous_target, compiled, env_bindings, temporal_streams, + output_retention, constants, performance, + ) + calls_extended[] = true + _runtime_performance_count!(performance, :execution_target_call_batches_extended) + return previous_target end - target = _compiled_model_execution_target( - compiled, - env_bindings, - application, - object_id, - temporal_streams, - output_retention, - constants, - ) - insertion = isnothing(location) ? - _model_execution_target_insertion( - previous_group, - object_id, - ) : location - isnothing(insertion) && return nothing - batch = previous_group.batches[first(insertion)] - _model_execution_batch_accepts_target( - batch, - target, - env_bindings, - application, - ) || return nothing - push!( - actions, - ( - kind=isnothing(location) ? :insert : :replace, - object_id=object_id, - target=target, - reason=change_reason, - ), - ) - targets_constructed += 1 - end - - for action in actions - isnothing(action.reason) && continue - _count_model_execution_target_rebuild!( - performance, - action.reason, + target = _new_model_execution_target( + compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants, + ) + _count_model_execution_target_rebuild!(performance, reason) + return target + end + assembled = _model_execution_batches( + env_bindings, application, refreshed.membership, + output_retention, previous_group, + ) + reused_group = !isnothing(previous_group) && + previous_group.application === application && + _same_execution_members(previous_group.batches, assembled.batches) + group_changed = refreshed.membership_changed || + refreshed.targets_constructed > 0 || calls_extended[] + group = if isempty(assembled.batches) + nothing + elseif reused_group + previous_group.membership = refreshed.membership + group_changed && _runtime_performance_count!( + performance, :execution_groups_updated_in_place, + ) + previous_group + else + _compiled_application_execution_group( + application, assembled.batches, refreshed.membership, ) end - isempty(actions) || _runtime_performance_count!( - performance, - :execution_groups_updated_in_place, - ) - batches = copy(previous_group.batches) - working_group = _compiled_application_execution_group(application, batches) - batches = working_group.batches - for action in actions - location = _model_execution_target_location( - working_group, - action.object_id, - ) - if action.kind === :remove - isnothing(location) && continue - batch_index, target_index = location - deleteat!(batches[batch_index].targets, target_index) - elseif action.kind === :replace - isnothing(location) && return nothing - batch_index, target_index = location - batches[batch_index].targets[target_index] = action.target - else - insertion = _model_execution_target_insertion( - working_group, - action.object_id, - ) - isnothing(insertion) && return nothing - batch_index, target_index = insertion - _insert_with_spare_capacity!( - batches[batch_index].targets, - target_index, - action.target, - ) - end - end - filter!(batch -> !isempty(batch.targets), batches) return ( - group=isempty(batches) ? nothing : working_group, - targets_constructed=targets_constructed, - batches_constructed=0, + group=group, + targets_constructed=refreshed.targets_constructed, + batches_constructed=assembled.batches_constructed, + group_reused=reused_group && !group_changed, ) end -function _changed_execution_target_ids_by_application( - changed_execution_target_ids, -) +function _changed_execution_target_ids_by_application(changed_execution_target_ids) changed_by_application = Dict{Symbol,Vector{ObjectId}}() for (application_id, object_id) in changed_execution_target_ids object_ids = get!(changed_by_application, application_id) do @@ -4762,179 +4600,6 @@ function _changed_execution_target_ids_by_application( return changed_by_application end -function _try_refresh_model_execution_plan_for_pure_addition!( - previous::CompiledExecutionPlan, - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - temporal_streams, - output_retention, - constants, - performance, - changed_application_ids, - changed_targets_by_application, - manual_application_ids, - is_pure_addition::Bool, -) - is_pure_addition || return nothing - isnothing(changed_application_ids) && return nothing - - staged_targets = Dict{Tuple{Symbol,ObjectId},Any}() - applications = CompiledModelApplication[] - for application_id in changed_application_ids - application_id in manual_application_ids && continue - application = get(compiled.applications_by_id, application_id, nothing) - isnothing(application) && return ( - plan=nothing, - staged_targets=staged_targets, - ) - push!(applications, application) - end - sort!(applications; by=application -> application.slot) - - # Validate every affected group before constructing a target. Target - # construction is then staged globally, and no batch is mutated unless all - # applications can extend their existing final batch. - candidates = NamedTuple[] - for application in applications - previous_group = previous.groups_by_application_slot[application.slot] - isnothing(previous_group) && return ( - plan=nothing, - staged_targets=staged_targets, - ) - previous_group.application === application || return ( - plan=nothing, - staged_targets=staged_targets, - ) - changed_object_ids = get( - changed_targets_by_application, - application.id, - (), - ) - isempty(changed_object_ids) && return ( - plan=nothing, - staged_targets=staged_targets, - ) - isempty(previous_group.batches) && return ( - plan=nothing, - staged_targets=staged_targets, - ) - last_batch = last(previous_group.batches) - isempty(last_batch.targets) && return ( - plan=nothing, - staged_targets=staged_targets, - ) - last_existing_id = last(last_batch.targets).object_id - _object_id_isless(last_existing_id, first(changed_object_ids)) || - return ( - plan=nothing, - staged_targets=staged_targets, - ) - length(application.target_ids) >= length(changed_object_ids) || return ( - plan=nothing, - staged_targets=staged_targets, - ) - suffix_start = length(application.target_ids) - length(changed_object_ids) + 1 - all( - index -> - application.target_ids[suffix_start + index - 1] == - changed_object_ids[index], - eachindex(changed_object_ids), - ) || return ( - plan=nothing, - staged_targets=staged_targets, - ) - previous_target_count = sum( - batch -> length(batch.targets), - previous_group.batches; - init=0, - ) - ( - previous_target_count + length(changed_object_ids) == - length(application.target_ids) - ) || return ( - plan=nothing, - staged_targets=staged_targets, - ) - for object_id in changed_object_ids - isnothing( - _model_execution_target_location(previous_group, object_id), - ) || return ( - plan=nothing, - staged_targets=staged_targets, - ) - end - push!( - candidates, - ( - application=application, - batch=last_batch, - object_ids=changed_object_ids, - ), - ) - end - - staged_appends = NamedTuple[] - for candidate in candidates - targets = Any[] - for object_id in candidate.object_ids - target = _compiled_model_execution_target( - compiled, - env_bindings, - candidate.application, - object_id, - temporal_streams, - output_retention, - constants, - ) - staged_targets[(candidate.application.id, object_id)] = target - _model_execution_batch_accepts_target( - candidate.batch, - target, - env_bindings, - candidate.application, - ) || return ( - plan=nothing, - staged_targets=staged_targets, - ) - push!(targets, target) - end - push!( - staged_appends, - ( - application=candidate.application, - batch=candidate.batch, - targets=targets, - ), - ) - end - - for staged in staged_appends - for target in staged.targets - push!(staged.batch.targets, target) - _count_model_execution_target_rebuild!(performance, :new_target) - end - isempty(staged.targets) || _runtime_performance_count!( - performance, - :execution_groups_updated_in_place, - ) - end - - return ( - plan=CompiledExecutionPlan( - previous.cohorts, - previous.groups, - previous.batches, - previous.groups_by_application_slot, - previous.schedule, - compiled.revision, - env_bindings.environment_revision, - ), - targets_constructed=length(staged_targets), - batches_constructed=0, - groups_reused=length(previous.groups) - length(staged_appends), - ) -end - function _refresh_model_execution_plan( previous::CompiledExecutionPlan, compiled::CompiledCompositeModel, @@ -4947,47 +4612,11 @@ function _refresh_model_execution_plan( changed_execution_target_ids=compiled.changed_execution_target_ids, ) manual_application_ids = _manual_call_application_ids(compiled) - changed_targets_by_application = isnothing(changed_application_ids) ? - nothing : - _changed_execution_target_ids_by_application( + changed_by_application = isnothing(changed_application_ids) ? nothing : + _changed_execution_target_ids_by_application( changed_execution_target_ids, ) - staged_execution_targets = nothing - force_general_changed_groups = false - if !isnothing(changed_targets_by_application) - pure_addition_refresh = - _try_refresh_model_execution_plan_for_pure_addition!( - previous, - compiled, - env_bindings, - temporal_streams, - output_retention, - constants, - performance, - changed_application_ids, - changed_targets_by_application, - manual_application_ids, - compiled.status_view_refresh_is_pure_addition && - changed_execution_target_ids === - compiled.changed_execution_target_ids, - ) - if !isnothing(pure_addition_refresh) - isnothing(pure_addition_refresh.plan) || - return pure_addition_refresh - staged_execution_targets = - pure_addition_refresh.staged_targets - # The transactional attempt did not touch the old plan. Rebuild - # changed groups directly only when target construction actually - # started, reusing every staged target instead of retrying the - # in-place group delta. A preflight rejection leaves this empty and - # must retain the normal incremental-delta fallback. - force_general_changed_groups = - !isempty(staged_execution_targets) - end - end - previous_groups = Dict( - group.application.id => group for group in previous.groups - ) + previous_groups = Dict(group.application.id => group for group in previous.groups) groups = CompiledApplicationExecutionGroup[] batches = AbstractExecutionBatch[] sizehint!(groups, length(previous.groups)) @@ -4995,166 +4624,51 @@ function _refresh_model_execution_plan( targets_constructed = 0 batches_constructed = 0 groups_reused = 0 - for application in _ordered_model_applications(compiled) application.id in manual_application_ids && continue - previous_group = get(previous_groups, application.id, nothing) - if !isnothing(previous_group) - if !isnothing(changed_application_ids) - if !(application.id in changed_application_ids) - push!(groups, previous_group) - append!(batches, previous_group.batches) - groups_reused += 1 - continue - end - if !force_general_changed_groups - delta_group = _refresh_model_execution_group_delta!( - previous_group, - compiled, - env_bindings, - application, - temporal_streams, - output_retention, - constants, - performance, - get( - changed_targets_by_application, - application.id, - (), - ), - ) - if !isnothing(delta_group) - if !isnothing(delta_group.group) - push!(groups, delta_group.group) - append!(batches, delta_group.group.batches) - end - targets_constructed += - delta_group.targets_constructed - batches_constructed += - delta_group.batches_constructed - continue - end - end - elseif _model_execution_group_reusable( - previous_group, - compiled, - env_bindings, - application, - output_retention, - temporal_streams, - ) - push!(groups, previous_group) - append!(batches, previous_group.batches) - groups_reused += 1 - continue - end + previous_group = pop!(previous_groups, application.id, nothing) + if !isnothing(previous_group) && !isnothing(changed_application_ids) && + !(application.id in changed_application_ids) + push!(groups, previous_group) + append!(batches, previous_group.batches) + groups_reused += 1 + continue end - - targets = Any[] - previous_batch_index = 1 - previous_target_index = 1 - for object_id in application.target_ids - previous_target = nothing - while !isnothing(previous_group) && - previous_batch_index <= length(previous_group.batches) - previous_batch = - previous_group.batches[previous_batch_index] - if previous_target_index > length(previous_batch.targets) - previous_batch_index += 1 - previous_target_index = 1 - continue - end - candidate = - previous_batch.targets[previous_target_index] - if candidate.object_id == object_id - previous_target = candidate - previous_target_index += 1 - break - elseif _object_id_isless(candidate.object_id, object_id) - previous_target_index += 1 - continue - end - break - end - target_key = (application.id, object_id) - change_reason = if isnothing(previous_target) - :new_target - elseif !isnothing(changed_application_ids) && - !(target_key in compiled.changed_execution_target_ids) - nothing - else - _model_execution_target_change_reason( - previous_target, - compiled, - env_bindings, - application, - output_retention, - temporal_streams, - ) - end - if isnothing(change_reason) - push!(targets, previous_target) - else - execution_target = isnothing(staged_execution_targets) ? - nothing : - get( - staged_execution_targets, - target_key, - nothing, - ) - if isnothing(execution_target) - execution_target = _compiled_model_execution_target( - compiled, - env_bindings, - application, - object_id, - temporal_streams, - output_retention, - constants, - ) - end - push!( - targets, - execution_target, - ) - _count_model_execution_target_rebuild!( - performance, - change_reason, - ) - targets_constructed += 1 - end + changed_ids = isnothing(changed_by_application) ? nothing : + get(changed_by_application, application.id, ()) + refreshed = _refresh_model_execution_group!( + previous_group, previous.cohorts, compiled, env_bindings, application, + temporal_streams, output_retention, constants, performance, changed_ids, + ) + if !isnothing(refreshed.group) + push!(groups, refreshed.group) + append!(batches, refreshed.group.batches) + end + targets_constructed += refreshed.targets_constructed + batches_constructed += refreshed.batches_constructed + groups_reused += refreshed.group_reused + end + # A removed application (or one now exclusively called) has no scheduled + # membership to merge. Retire only its former owners, never scan survivors. + for group in values(previous_groups) + for object_id in group.membership.object_ids + remove_cohort_target!(previous.cohorts, group.application.id, object_id) end - - application_batches = AbstractExecutionBatch[] - _append_model_execution_batches!( - application_batches, - env_bindings, - application, - targets, - output_retention, - previous.cohorts, - ) - isempty(application_batches) && continue - push!( - groups, - _compiled_application_execution_group( - application, - application_batches, - ), - ) - append!(batches, application_batches) - batches_constructed += length(application_batches) end - + same_groups = _same_execution_members(previous.groups, groups) + same_batches = _same_execution_members(previous.batches, batches) + application_count = length(compiled.scenario_plan.applications) + groups_by_slot = same_groups && + length(previous.groups_by_application_slot) == application_count ? + previous.groups_by_application_slot : + _execution_groups_by_application_slot(groups, application_count) return ( plan=CompiledExecutionPlan( previous.cohorts, - groups, - batches, - _execution_groups_by_application_slot( - groups, - length(compiled.scenario_plan.applications), - ), + previous.topology, + same_groups ? previous.groups : groups, + same_batches ? previous.batches : batches, + groups_by_slot, previous.schedule, compiled.revision, env_bindings.environment_revision, @@ -6256,7 +5770,7 @@ function _targeted_application_set!( added_applications_by_object, ) return _TargetedApplicationSet( - output_applications, + Tuple(output_applications), _ApplicationsByObjectOverlay( runtime.compiled.applications_by_object, runtime.added_applications_by_object, @@ -6320,7 +5834,7 @@ function _targeted_callee_applications( "Hard call `$(binding.call)` from application `$(binding.application_id)` does not ", "resolve requested object(s) `$(Tuple(id.value for id in unresolved_ids))`." ) - return applications + return Tuple(applications) end function _applications_use_only_global_environment( @@ -6473,7 +5987,6 @@ function _targeted_new_object_call_targets( return nothing end output_applications = application_set.applications - applications_by_object = application_set.applications_by_object callee_applications = _targeted_callee_applications( binding, requested_ids, @@ -6498,6 +6011,26 @@ function _targeted_new_object_call_targets( ) end + return _prepare_targeted_newborn_targets( + context, name, targeted_runtime, application_set, callee_applications, initializer, + ) +end + +# Application membership is assembled dynamically, but its finite schema is +# stable for newborns selected by the same application recipe. Keep that tuple +# concrete across the canonical status and binding preparation below. +function _prepare_targeted_newborn_targets( + context::RunContext, + name::Symbol, + targeted_runtime::_TargetedTopologyRuntime, + application_set::_TargetedApplicationSet, + callee_applications::Tuple, + initializer::Bool, +) + model = runtime_model(context) + compiled = context.compiled + output_applications = application_set.applications + applications_by_object = application_set.applications_by_object if !application_set.outputs_prepared _prepare_model_output_statuses_batched!(model, output_applications) application_set.outputs_prepared = true @@ -6570,69 +6103,10 @@ function _targeted_new_object_call_targets( targets = CallTarget[] for partial_application in callee_applications - application = compiled.applications_by_id[partial_application.id] - for object_id in partial_application.target_ids - key = (application.id, object_id) - status_view = _compile_model_status_view( - model, - partial_application, - object_id, - get(targeted_input_bindings, key, ()), - compiled.applications_by_id, - targeted_runtime.application_positions, - compiled.distributed_outputs, - ) - # Targeted newborns have no ordinary compiled execution owner yet. - # Keep only their exact application-local payload, without adding - # a second mutable CompiledExecutionTarget allocation. - execution_target = ( - model=_application_model(application, object_id), - status=status_view.status, - canonical_status=status_view.canonical_status, - input_bindings=status_view.temporal_inputs, - output_bindings=_runtime_model_output_streams( - status_view.status, - application, - object_id, - context.temporal_streams, - context.output_retention, - true, - ), - bound_inputs=status_view.bound_inputs, - output_targets=_runtime_model_output_targets( - compiled, - application, - object_id, - ), - environment_binding=_environment_binding_for( - environment_bindings, - application.id, - object_id, - ), - # Re-resolving the same newborn preserves its physical call - # owner, including execution stamps used by pending evaluations. - call_context_cache=get!(targeted_runtime.call_context_caches, key) do - CallContextCache(nothing) - end, - ) - push!( - targets, - CallTarget( - execution_target, - compiled, - environment_bindings, - application, - object_id, - (), - context.temporal_streams, - context.output_retention, - context.time, - context.constants, - context.publication_allowed, - context.environment, - ), - ) - end + _append_targeted_newborn_targets!( + targets, context, targeted_runtime, partial_application, + targeted_input_bindings, environment_bindings, + ) end if initializer length(targets) == 1 || error( @@ -6643,6 +6117,75 @@ function _targeted_new_object_call_targets( return targets end +function _append_targeted_newborn_targets!( + targets, + context::RunContext, + targeted_runtime::_TargetedTopologyRuntime, + partial_application::CompiledModelApplication, + targeted_input_bindings, + environment_bindings::CompiledEnvironmentBindings, +) + compiled = context.compiled + # A partial application preserves its exact plan type. Recover that type + # after the heterogeneous application index before constructing its rows. + application = compiled.applications_by_id[partial_application.id]::typeof(partial_application) + for object_id in partial_application.target_ids + key = (application.id, object_id) + status_view = _compile_model_status_view( + runtime_model(context), partial_application, object_id, + get(targeted_input_bindings, key, ()), compiled.applications_by_id, + targeted_runtime.application_positions, compiled.distributed_outputs, + ) + outputs = _runtime_model_output_streams( + status_view.status, application, object_id, context.temporal_streams, + context.output_retention, true, + ) + output_targets = _runtime_model_output_targets(compiled, application, object_id) + environment_binding = _environment_binding_for(environment_bindings, application.id, object_id) + cache = get!(targeted_runtime.call_context_caches, key) do + CallContextCache(nothing) + end + push!(targets, _targeted_newborn_call_target( + context, application, object_id, _application_model(application, object_id), + status_view, outputs, output_targets, environment_bindings, environment_binding, cache, + )) + end + return targets +end + +# Status views, publication tuples and handles leave heterogeneous assembly at +# this boundary. Reuse one concrete payload constructor for each actual schema. +function _targeted_newborn_call_target( + context::RunContext, + application::CompiledModelApplication, + object_id::ObjectId, + model, + status_view::CompiledModelStatusView, + outputs::Tuple, + output_targets::NamedTuple, + environment_bindings::CompiledEnvironmentBindings, + environment_binding, + cache::CallContextCache, +) + execution_target = ( + model=model, + status=status_view.status, + canonical_status=status_view.canonical_status, + input_bindings=status_view.temporal_inputs, + output_bindings=outputs, + bound_inputs=status_view.bound_inputs, + output_targets=output_targets, + environment_binding=environment_binding, + # Reaccessing a newborn retains its evaluation execution stamps. + call_context_cache=cache, + ) + return CallTarget( + execution_target, context.compiled, environment_bindings, application, + object_id, (), context.temporal_streams, context.output_retention, + context.time, context.constants, context.publication_allowed, context.environment, + ) +end + function _current_topology_call_targets( context::RunContext, name::Symbol, @@ -7634,9 +7177,6 @@ function _refresh_simulation_runtime!(simulation::Simulation) changed_execution_application_ids, ) simulation.execution_plan = execution_refresh.plan - if !simulation.compiled.status_view_refresh_is_pure_addition - _retire_scheduled_cohort_targets!(simulation.execution_plan.cohorts, simulation.compiled) - end _runtime_performance_finish!( simulation.performance, :execution_plan_compile, @@ -7899,16 +7439,13 @@ function _run_model_execution_step!(simulation::Simulation, step::Integer) completed_schedule_entry = 0 for entry_index in due_entry_indices schedule_entry = schedule_plan.entries[entry_index] - group = simulation.execution_plan.groups_by_application_slot[ - schedule_entry.application_slot - ] - isnothing(group) && continue - _run_model_execution_group!( - group, - simulation, - step, - simulation.performance, - ) + _run_execution_slot!(simulation.execution_plan.groups_by_application_slot, + schedule_entry.application_slot, simulation, step) || continue + + if simulation.execution_plan.topology isa FixedExecution + _refresh_timeline!(simulation, simulation.execution_plan.topology) + continue + end if !isnothing(completed_applications) _mark_schedule_prefix_completed!( @@ -7966,19 +7503,19 @@ function _incremental_output_request_object_ids(delta) end function _continue_scene!(simulation::Simulation, steps::Integer) - steps >= 0 || error("`steps` must be non-negative, got $(steps).") - start_step = simulation.current_step + 1 - final_step = simulation.current_step + steps + steps >= 0 || throw(ArgumentError("`steps` must be non-negative, got $(steps).")) + if iszero(steps) + _refresh_timeline!(simulation, simulation.execution_plan.topology) + return simulation + end + final_step = Base.Checked.checked_add(simulation.current_step, Int(steps)) + start_step = Base.Checked.checked_add(simulation.current_step, 1) for step in start_step:final_step - lifecycle = _pending_output_request_lifecycle_delta(simulation.model) - _refresh_simulation_runtime!(simulation) - _refresh_output_request_targets!(simulation, lifecycle) + _refresh_timeline!(simulation, simulation.execution_plan.topology) _run_model_execution_step!(simulation, step) simulation.current_step = step end - lifecycle = _pending_output_request_lifecycle_delta(simulation.model) - _refresh_simulation_runtime!(simulation) - _refresh_output_request_targets!(simulation, lifecycle) + _refresh_timeline!(simulation, simulation.execution_plan.topology) return simulation end diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index b9f7a4bbd..e49485546 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -6,11 +6,13 @@ include("composite_model/registry_topology.jl") include("composite_model/selectors.jl") include("composite_model/execution_cohorts.jl") include("composite_model/execution_storage.jl") +include("composite_model/execution_cohort_refresh.jl") include("composite_model/compilation.jl") include("composite_model/bound_many.jl") include("composite_model/output_targets.jl") include("composite_model/environment_bindings.jl") include("composite_model/runtime_outputs.jl") +include("composite_model/execution_dispatch.jl") include("composite_model/call_evaluations.jl") include("composite_model/source_compilation.jl") include("composite_model/scenario_dsl.jl") diff --git a/src/native_compilation.jl b/src/native_compilation.jl index d2a8c9353..138e98eed 100644 --- a/src/native_compilation.jl +++ b/src/native_compilation.jl @@ -10,9 +10,8 @@ import ..PlantSimEngine as PSE export prepare, compile -struct PreparedSimulation{S,E,ST} +struct PreparedSimulation{S,ST} simulation::S - scheduled_targets::E status::ST end @@ -55,7 +54,7 @@ function _has_scalar_status(status) end end -function _prepare_scheduled_target(application, target) +function _check_target(application, target) isbits(target.model) || _unsupported(application.id, "model parameters must have an isbits type") isempty(target.input_bindings) || @@ -64,14 +63,13 @@ function _prepare_scheduled_target(application, target) _unsupported(application.id, "collection-valued inputs are unsupported") _has_scalar_status(target.status) || _unsupported(application.id, "status values must have concrete scalar numeric types") - # The ordinary sampler handles raw rows and field remapping. A singleton - # row is independent of the step, so the native loop can reuse its value. + # Validate the same environment row that the canonical batch sampler uses. binding = target.environment_binding environment = isnothing(binding) ? nothing : PSE._sample_compiled_global_environment(binding, application, 1) isbits(environment) || _unsupported(application.id, "sampled environment must be an immutable bits-valued row") - return (; application, target, environment) + return nothing end """ @@ -108,47 +106,20 @@ function prepare(model::PSE.CompositeModel; constants=PSE.Constants()) prepared = PSE._prepare_scenario_plan(owned) _check_scenario(owned, prepared.plan) simulation = PSE._prepare_simulation!(owned; steps=0, outputs=:none, constants) - scheduled_targets = Tuple(_prepare_scheduled_target(group.application, target) - for group in simulation.execution_plan.groups - for batch in group.batches for target in batch.targets) - isempty(scheduled_targets) && + isempty(simulation.execution_plan.groups) && throw(ArgumentError("Compilation requires at least one scheduled application.")) + for group in simulation.execution_plan.groups, batch in group.batches, target in batch.targets + _check_target(group.application, target) + end status = only(PSE.model_objects(owned)).status _has_scalar_status(status) || throw(ArgumentError("Compilation requires concrete scalar numeric object status values.")) - return PreparedSimulation(simulation, scheduled_targets, status) -end - -@inline function _check_static_runtime(simulation) - PSE._simulation_runtime_dirty(simulation, nothing) && - throw(ArgumentError("Compiled simulation topology and bindings must stay fixed.")) - return nothing + plan = PSE._fixed_execution_plan(simulation.execution_plan) + return PreparedSimulation(PSE._simulation_with_execution_plan(simulation, plan), status) end -@inline function _run_scheduled_targets!(simulation, scheduled_targets::Tuple, time::Float64) - (; application, target, environment) = first(scheduled_targets) - PSE._run_model_execution_target_without_calls!( - simulation.compiled, simulation.environment_bindings, application, target, - time, simulation.constants, simulation.temporal_streams, - simulation.output_retention, environment, false, - ) - _check_static_runtime(simulation) - return _run_scheduled_targets!(simulation, Base.tail(scheduled_targets), time) -end - -@inline _run_scheduled_targets!(simulation, ::Tuple{}, time::Float64) = nothing - function PSE.continue!(program::PreparedSimulation; steps::Integer=1) - steps >= 0 || throw(ArgumentError("`steps` must be non-negative.")) - simulation = program.simulation - _check_static_runtime(simulation) - iszero(steps) && return program - final_step = Base.Checked.checked_add(simulation.current_step, Int(steps)) - for step in (simulation.current_step + 1):final_step - simulation.compiled.execution_generation += UInt64(1) - _run_scheduled_targets!(simulation, program.scheduled_targets, Float64(step)) - simulation.current_step = step - end + PSE.continue!(program.simulation; steps) return program end diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index f3085445b..30f4511b7 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -255,6 +255,7 @@ function _model_graph_fallback_application(model, raw_spec, timeline, slot) application_id = something(application_name(spec), process(spec)) target_matcher = _compile_selector_matcher(model, selector) target_ids = _resolve_object_ids(model, selector, target_matcher) + output_names, canonical_output_names = _compiled_output_names(spec) return CompiledModelApplication( CompiledApplicationPlan( slot, @@ -267,6 +268,8 @@ function _model_graph_fallback_application(model, raw_spec, timeline, slot) timestep(spec), _model_application_clock(model, spec, target_ids, timeline), _compiled_object_model_overrides(spec, target_ids, application_id), + output_names, + canonical_output_names, ), target_ids, ) diff --git a/test/runtests.jl b/test/runtests.jl index a0b42bcbf..c07aa72bb 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -47,6 +47,7 @@ else @testset "Persistent typed execution cohorts" begin include("test-execution-cohorts.jl") + include("test-execution-cohort-refresh.jl") include("test-model-canonical-cohorts.jl") end @@ -76,6 +77,7 @@ else @testset "Reusable scenario plans" begin include("test-model-prepared-scenario.jl") + include("test-compilation-metadata.jl") end @testset "Isolated model diagnostics" begin diff --git a/test/test-compilation-metadata.jl b/test/test-compilation-metadata.jl new file mode 100644 index 000000000..b7621f843 --- /dev/null +++ b/test/test-compilation-metadata.jl @@ -0,0 +1,60 @@ +module CompilationMetadataChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "compiled_port_metadata" verbose=false +struct PortProbe{C} <: AbstractCompiled_Port_MetadataModel + declarations::C +end +function PSE.outputs_(model::PortProbe) + model.declarations[] += 1 + return (value=0.0, scratch=zeros(3)) +end +PSE.run!(::PortProbe, status, environment, constants, context) = nothing + +@testset "writer matching uses the prepared port schema" begin + declarations = Ref(0) + model = CompositeModel(Object(:leaf; scale=:Leaf); + applications=(ModelSpec(PortProbe(declarations); name=:probe, + on=Many(scale=:Leaf), output_routing=(scratch=:stream_only,)),)) + simulation = run!(model; steps=0, outputs=:none) + application = only(simulation.compiled.applications) + prepared_count = declarations[] + @test PSE._model_output_names(application) === (:value, :scratch) + @test PSE._model_canonical_output_names(application) === (:value,) + for _ in 1:20 + @test PSE._application_writes_object_variable( + PSE.NoCompiledDistributedOutputs(), application, ObjectId(:leaf), :value) + @test !PSE._application_writes_object_variable( + PSE.NoCompiledDistributedOutputs(), application, ObjectId(:missing), :value) + @test PSE._model_canonical_output_names(application) === (:value,) + end + @test declarations[] == prepared_count +end + +@testset "shared point queries preserve ownership and cardinality checks" begin + model = CompositeModel( + Object(:plant; scale=:Plant), + Object(:leaf_a; scale=:Leaf, parent=:plant), + Object(:leaf_b; scale=:Leaf, parent=:plant)) + cache = Dict{Any,Vector{ObjectId}}() + point = One(Ancestor(scale=:Plant); scale=:Plant) + matcher = PSE._compile_selector_matcher(model, point) + first_ids = PSE._cached_dependency_object_ids(cache, model, point, matcher, ObjectId(:leaf_a)) + @test first_ids == [ObjectId(:plant)] + empty!(first_ids) + next_ids = PSE._cached_dependency_object_ids(cache, model, point, matcher, ObjectId(:leaf_a)) + @test next_ids == [ObjectId(:plant)] + @test next_ids !== only(values(cache)) + many = Many(SceneScope(); scale=:Leaf) + ids = PSE._cached_dependency_object_ids(cache, model, many, + PSE._compile_selector_matcher(model, many), ObjectId(:plant)) + @test ids == [ObjectId(:leaf_a), ObjectId(:leaf_b)] + for selector in (One(SceneScope(); scale=:Leaf), OptionalOne(SceneScope(); scale=:Leaf)) + @test_throws Exception PSE._cached_dependency_object_ids(cache, model, selector, + PSE._compile_selector_matcher(model, selector), ObjectId(:plant)) + end +end + +end diff --git a/test/test-execution-cohort-refresh.jl b/test/test-execution-cohort-refresh.jl new file mode 100644 index 000000000..047246d49 --- /dev/null +++ b/test/test-execution-cohort-refresh.jl @@ -0,0 +1,330 @@ +using PlantSimEngine +using Test + +mutable struct ExecutionRefreshTestTarget{I,S,C} + object_id::I + status::S + context::C +end + +execution_refresh_test_target(id, value) = + ExecutionRefreshTestTarget(ObjectId(id), Status(value=value), Ref(0)) +execution_refresh_test_ids(ids) = ObjectId[ObjectId(id) for id in ids] +execution_refresh_test_targets(membership) = + [target for rows in membership.runs for target in rows] + +@testset "Cohort refresh constructs only changed payloads in canonical order" begin + store = PlantSimEngine.ExecutionCohortStore() + first = execution_refresh_test_target(1, 1.0) + middle = execution_refresh_test_target(2, 2.0f0) + last = execution_refresh_test_target(3, 3.0) + targets = Dict{ObjectId,Any}(target.object_id => target for target in (first, middle, last)) + checked = ObjectId[] + build_target = (object_id, previous) -> begin + push!(checked, object_id) + targets[object_id] + end + initial = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids(1:3), nothing, + ) + membership = initial.membership + @test initial.targets_constructed == 3 + @test initial.targets_reused == initial.targets_removed == 0 + @test initial.membership_changed + @test checked == execution_refresh_test_ids(1:3) + @test length(membership.runs) == 3 + @test membership.runs[1].cohort === membership.runs[3].cohort + @test membership.runs[1].cohort !== membership.runs[2].cohort + @test all(rows -> isconcretetype(eltype(rows)), membership.runs) + @test all(rows -> rows.store === store, membership.runs) + @test execution_refresh_test_targets(membership) == [first, middle, last] + first_location = PlantSimEngine.cohort_location(store, :growth, first.object_id) + last_location = PlantSimEngine.cohort_location(store, :growth, last.object_id) + last_context = last.context + last_ref = PlantSimEngine.refvalue(last.status, :value) + original_ids = membership.object_ids + original_locations = membership.locations + original_runs = copy(membership.runs) + original_starts = membership.run_starts + + earlier = execution_refresh_test_target(0, 0.0) + later = execution_refresh_test_target(4, 4.0f0) + targets[earlier.object_id] = earlier + targets[later.object_id] = later + empty!(checked) + added = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids(0:4), + execution_refresh_test_ids((0, 4)); previous=membership, + ) + @test checked == execution_refresh_test_ids((0, 4)) + @test added.targets_constructed == 2 + @test added.targets_reused == 3 + @test added.targets_removed == 0 + @test added.membership_changed + @test added.membership === membership + @test membership.object_ids === original_ids + @test membership.locations === original_locations + @test membership.run_starts === original_starts + @test all(index -> membership.runs[index] === original_runs[index], 1:3) + @test membership.run_starts == [1, 3, 4, 5] + @test getproperty.(execution_refresh_test_targets(added.membership), :object_id) == + execution_refresh_test_ids(0:4) + @test execution_refresh_test_targets(added.membership)[2] === first + @test execution_refresh_test_targets(added.membership)[4] === last + @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location + @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location + @test last.context === last_context + @test PlantSimEngine.refvalue(last.status, :value) === last_ref + + replacement = execution_refresh_test_target(1, 10.0) + targets[first.object_id] = replacement + empty!(checked) + replaced = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids(0:4), + execution_refresh_test_ids((1,)); previous=added.membership, + ) + @test checked == execution_refresh_test_ids((1,)) + @test replaced.targets_constructed == 1 + @test replaced.targets_reused == 4 + @test !replaced.membership_changed + @test replaced.membership === added.membership + @test execution_refresh_test_targets(replaced.membership)[2] === replacement + @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location + @test execution_refresh_test_targets(replaced.membership)[4] === last + + empty!(checked) + unchanged = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids(0:4), + ObjectId[]; previous=replaced.membership, + ) + @test isempty(checked) + @test unchanged.membership === replaced.membership + @test unchanged.targets_constructed == 0 + @test unchanged.targets_reused == 5 + + empty!(checked) + validated = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids(0:4), + nothing; previous=unchanged.membership, + ) + @test checked == execution_refresh_test_ids(0:4) + @test validated.membership === unchanged.membership + @test validated.targets_constructed == 0 + @test validated.targets_reused == 5 +end + +@testset "Schema extension, removal and empty groups use the same refresh" begin + store = PlantSimEngine.ExecutionCohortStore() + first = execution_refresh_test_target(1, 1.0) + last = execution_refresh_test_target(3, 3.0) + targets = Dict{ObjectId,Any}(target.object_id => target for target in (first, last)) + checked = ObjectId[] + build_target = (object_id, previous) -> begin + push!(checked, object_id) + targets[object_id] + end + initial = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids((1, 3)), nothing, + ).membership + first_location = PlantSimEngine.cohort_location(store, :growth, first.object_id) + last_location = PlantSimEngine.cohort_location(store, :growth, last.object_id) + changed = ExecutionRefreshTestTarget(ObjectId(1), Status(value=2.0f0, extra=7), Ref(0)) + targets[changed.object_id] = changed + empty!(checked) + extended = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids((1, 3)), + execution_refresh_test_ids((1,)); previous=initial, + ) + @test checked == execution_refresh_test_ids((1,)) + @test extended.membership_changed + @test extended.targets_constructed == 1 + @test length(store.cohorts) == 2 + @test execution_refresh_test_targets(extended.membership)[1] === changed + @test execution_refresh_test_targets(extended.membership)[2] === last + @test isnothing(first_location.cohort.rows[first_location.row]) + @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location + + empty!(checked) + removed = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids((3,)), + execution_refresh_test_ids((1,)); previous=extended.membership, + ) + @test isempty(checked) + @test removed.targets_constructed == 0 + @test removed.targets_removed == 1 + @test execution_refresh_test_targets(removed.membership) == [last] + @test isnothing(PlantSimEngine.cohort_location(store, :growth, ObjectId(1))) + @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location + + empty_group = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, ObjectId[], execution_refresh_test_ids((3,)); + previous=removed.membership, + ) + @test isempty(empty_group.membership.runs) + @test empty_group.targets_removed == 1 + @test isempty(store.locations) + targets[first.object_id] = first + reborn = PlantSimEngine.refresh_cohort_membership!( + build_target, store, :growth, execution_refresh_test_ids((1,)), + execution_refresh_test_ids((1,)); previous=empty_group.membership, + ) + @test execution_refresh_test_targets(reborn.membership) == [first] + @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location +end + +@testset "Refresh stages failing construction and isolates execution owners" begin + store = PlantSimEngine.ExecutionCohortStore() + first = execution_refresh_test_target(1, 1.0) + root = PlantSimEngine.refresh_cohort_membership!( + (id, previous) -> first, store, :growth, execution_refresh_test_ids((1,)), nothing, + ).membership + owner = (:controller, ObjectId(:plant), :growth_call, :manual) + called = execution_refresh_test_target(1, 1.0) + call = PlantSimEngine.refresh_cohort_membership!( + (id, previous) -> called, store, :growth, execution_refresh_test_ids((1,)), nothing; + owner, + ).membership + @test root.runs[1].store === call.runs[1].store + @test root.runs[1].cohort !== call.runs[1].cohort + @test root.runs[1][1] === first + @test call.runs[1][1] === called + old_location = PlantSimEngine.cohort_location(store, :growth, ObjectId(1)) + changed = execution_refresh_test_target(1, 1.0f0) + @test_throws ErrorException PlantSimEngine.refresh_cohort_membership!( + (id, previous) -> id == ObjectId(1) ? changed : error("construction fails"), + store, :growth, execution_refresh_test_ids((1, 2)), + execution_refresh_test_ids((1, 2)); previous=root, + ) + @test PlantSimEngine.cohort_location(store, :growth, ObjectId(1)) === old_location + @test root.runs[1][1] === first + @test call.runs[1][1] === called + @test length(store.cohorts) == 2 + @test_throws ArgumentError PlantSimEngine.refresh_cohort_membership!( + (id, previous) -> first, store, :growth, execution_refresh_test_ids((1,)), + ObjectId[]; previous=root, owner, + ) + @test_throws ArgumentError PlantSimEngine.refresh_cohort_membership!( + (id, previous) -> execution_refresh_test_target(99, 1.0), + store, :growth, execution_refresh_test_ids((1,)), nothing; previous=root, + ) + @test root.runs[1][1] === first +end + +@testset "Membership merges distinguish identities with equal display strings" begin + store = PlantSimEngine.ExecutionCohortStore() + numeric = execution_refresh_test_target(1, 1.0) + symbolic = execution_refresh_test_target(Symbol("1"), 2.0) + targets = Dict{ObjectId,Any}(target.object_id => target for target in (numeric, symbolic)) + builder = (id, previous) -> targets[id] + initial = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, ObjectId[numeric.object_id], nothing, + ).membership + mixed_ids = ObjectId[numeric.object_id, symbolic.object_id] + PlantSimEngine._sort_object_ids!(mixed_ids) + added = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, mixed_ids, ObjectId[symbolic.object_id]; previous=initial, + ) + @test getproperty.(execution_refresh_test_targets(added.membership), :object_id) == mixed_ids + @test added.targets_constructed == 1 + @test length(added.membership.runs) == 2 + @test added.membership.runs[1][1] === numeric + @test added.membership.runs[2][1] === symbolic + replacement = execution_refresh_test_target(2, 3.0) + targets[replacement.object_id] = replacement + new_ids = ObjectId[replacement.object_id, symbolic.object_id] + PlantSimEngine._sort_object_ids!(new_ids) + changed_ids = ObjectId[numeric.object_id, replacement.object_id] + PlantSimEngine._sort_object_ids!(changed_ids) + changed = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, new_ids, changed_ids; previous=added.membership, + ) + @test changed.targets_constructed == 1 + @test changed.targets_removed == 1 + @test getproperty.(execution_refresh_test_targets(changed.membership), :object_id) == new_ids + @test isnothing(PlantSimEngine.cohort_location(store, :growth, numeric.object_id)) + @test changed.membership.runs[2][1] === symbolic +end + +@testset "In-place run splices preserve recurring families and unaffected views" begin + store = PlantSimEngine.ExecutionCohortStore() + targets = Dict{ObjectId,Any}( + ObjectId(id) => execution_refresh_test_target(id, Float64(id)) for id in (1, 3, 5) + ) + builder = (id, previous) -> targets[id] + membership = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, execution_refresh_test_ids((1, 3, 5)), nothing, + ).membership + original_run = only(membership.runs) + original_indices = original_run.indices + original_locations = copy(membership.locations) + targets[ObjectId(3)] = execution_refresh_test_target(3, 3.0f0) + split = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, execution_refresh_test_ids((1, 3, 5)), + execution_refresh_test_ids((3,)); previous=membership, + ) + @test split.membership === membership + @test membership.run_starts == [1, 2, 3] + @test length(membership.runs) == 3 + @test membership.runs[1] === original_run + @test membership.runs[1].indices === original_indices + @test membership.runs[1].cohort === membership.runs[3].cohort + @test membership.locations[1] === original_locations[1] + @test membership.locations[3] === original_locations[3] + @test getproperty.(execution_refresh_test_targets(membership), :object_id) == + execution_refresh_test_ids((1, 3, 5)) + right_run = membership.runs[3] + + # A new leading occurrence cannot consume the existing later view. + targets[ObjectId(0)] = execution_refresh_test_target(0, 0.0f0) + leading = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, execution_refresh_test_ids((0, 1, 3, 5)), + execution_refresh_test_ids((0,)); previous=membership, + ) + @test membership.run_starts == [1, 2, 3, 4] + @test membership.runs[2] === original_run + @test membership.runs[4] === right_run + @test getproperty.(execution_refresh_test_targets(leading.membership), :object_id) == + execution_refresh_test_ids((0, 1, 3, 5)) + + targets[ObjectId(3)] = execution_refresh_test_target(3, 3.0) + restored = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, execution_refresh_test_ids((0, 1, 3, 5)), + execution_refresh_test_ids((3,)); previous=membership, + ) + @test restored.membership === membership + @test membership.run_starts == [1, 2] + @test membership.runs[2] === original_run + @test getproperty.(membership.runs[2], :object_id) == execution_refresh_test_ids((1, 3, 5)) + @test only(right_run).object_id == ObjectId(5) + + removed = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, execution_refresh_test_ids((1, 5)), + execution_refresh_test_ids((0, 3)); previous=membership, + ) + @test removed.targets_removed == 2 + @test membership.run_starts == [1] + @test only(membership.runs) === original_run + @test getproperty.(execution_refresh_test_targets(membership), :object_id) == + execution_refresh_test_ids((1, 5)) +end + +function execution_refresh_append_allocations(count) + store = PlantSimEngine.ExecutionCohortStore() + builder = (id, previous) -> execution_refresh_test_target(id.value, Float64(id.value)) + ids = execution_refresh_test_ids(1:count) + membership = PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, ids, nothing, + ).membership + push!(ids, ObjectId(count + 1)) + changed = ObjectId[ObjectId(count + 1)] + return @allocated PlantSimEngine.refresh_cohort_membership!( + builder, store, :growth, ids, changed; previous=membership, + ) +end + +@testset "Appending a row does not copy live membership arrays" begin + execution_refresh_append_allocations(8) + small = minimum(execution_refresh_append_allocations(8) for _ in 1:2) + large = minimum(execution_refresh_append_allocations(4096) for _ in 1:2) + @test large <= small + 4096 +end diff --git a/test/test-execution-cohorts.jl b/test/test-execution-cohorts.jl index 12abe8844..9359584f8 100644 --- a/test/test-execution-cohorts.jl +++ b/test/test-execution-cohorts.jl @@ -16,6 +16,9 @@ end right = PlantSimEngine.cohort_rows!(store, :growth, [last]) @test left isa AbstractVector{typeof(first)} + @test keytype(left.cohort.indices) === typeof(first.object_id) + @test isconcretetype(fieldtype(typeof(left), :cohort)) + @test (@inferred left[1]) === first @test eltype(center) === typeof(middle) @test left.cohort === right.cohort @test left.cohort !== center.cohort diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 3fb203875..915900f9b 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -2749,7 +2749,7 @@ end @test float32_target.context.time == Float64(float32_time) end -@testset "execution plan addition falls back when a group is created" begin +@testset "execution plan creates an initially empty application group" begin model = CompositeModel( Object(:scene; scale=:Scene); applications=( @@ -2786,7 +2786,7 @@ end @test model_object(model, :leaf_1).status.signal == 1.0 end -@testset "execution plan pure-addition staging is transactional" begin +@testset "execution plan extends only the affected concrete runs" begin context_models = PlantSimEngine.ObjectModelOverrides( StabilizationContextModel(), Dict( @@ -2818,6 +2818,14 @@ end if group.application.id == :leaf_source ) original_source_batch = only(original_source_group.batches) + original_targets = Dict( + (batch.application.id, target.object_id) => target + for batch in original_batches for target in batch.targets + ) + original_locations = Dict( + key => PlantSimEngine.cohort_location(simulation.execution_plan.cohorts, key...) + for key in keys(original_targets) + ) original_context_group = only( group for group in original_groups if group.application.id == :leaf_context @@ -2833,11 +2841,10 @@ end ) continue!(simulation) - # The first application was append-compatible, but the second needed a - # new concrete batch. Global staging must leave both old groups untouched - # before the general fallback replaces the plan. + # The source keeps its group and batch. The context family recurs after + # the override, so only that additional ordered run needs a new wrapper. @test [target.object_id for target in original_source_batch.targets] == - ObjectId.([:leaf_a, :leaf_z]) + ObjectId.([:leaf_a, :leaf_z, :leaf_zz]) @test [ [target.object_id for target in batch.targets] for batch in original_context_group.batches @@ -2853,6 +2860,22 @@ end group for group in simulation.execution_plan.groups if group.application.id == :leaf_context ) + @test refreshed_source_group === original_source_group + @test only(refreshed_source_group.batches) === original_source_batch + @test refreshed_context_group.batches[1] === original_context_group.batches[1] + @test refreshed_context_group.batches[2] === original_context_group.batches[2] + @test refreshed_context_group.batches[3].targets.cohort === + original_context_group.batches[1].targets.cohort + for batch in simulation.execution_plan.batches, target in batch.targets + key = (batch.application.id, target.object_id) + haskey(original_targets, key) || continue + previous_target = original_targets[key] + @test target === previous_target + @test target.context === previous_target.context + location = PlantSimEngine.cohort_location(simulation.execution_plan.cohorts, key...) + @test location.cohort === original_locations[key].cohort + @test location.row == original_locations[key].row + end @test [ target.object_id for batch in refreshed_source_group.batches for target in batch.targets @@ -2867,13 +2890,89 @@ end ] performance = Advanced.runtime_performance(simulation) @test performance.counts[:execution_targets_constructed] == 2 - @test performance.counts[:execution_batches_constructed] == 4 + @test performance.counts[:execution_batches_constructed] == 1 @test get( performance.counts, :execution_groups_updated_in_place, 0, - ) == 0 + ) == 1 @test model_object(model, :leaf_zz).status.signal == 1.0 + @test model_object(model, :leaf_a).status.signal == 2.0 + @test model_object(model, :leaf_z).status.signal == 2.0 +end + +@testset "a newborn payload family preserves unrelated groups and row owners" begin + model = CompositeModel( + Object(:scene; scale=:Scene), + Object(:leaf_1; scale=:Leaf, parent=:scene); + applications=( + ModelSpec(StabilizationSourceModel(); name=:leaf_source, on=Many(scale=:Leaf)), + ModelSpec(StabilizationSourceModel(); name=:scene_source, on=One(scale=:Scene)), + ), + ) + simulation = run!(model; outputs=:none, performance=true) + old_leaf_group = only(group for group in simulation.execution_plan.groups + if group.application.id == :leaf_source) + old_scene_group = only(group for group in simulation.execution_plan.groups + if group.application.id == :scene_source) + old_leaf_batch = only(old_leaf_group.batches) + old_scene_batch = only(old_scene_group.batches) + old_leaf_target = only(old_leaf_batch.targets) + old_scene_target = only(old_scene_batch.targets) + old_leaf_location = PlantSimEngine.cohort_location( + simulation.execution_plan.cohorts, :leaf_source, ObjectId(:leaf_1), + ) + register_object!(model, Object( + :leaf_2; scale=:Leaf, parent=:scene, status=Status(signal=0.0f0), + )) + continue!(simulation) + leaf_group = only(group for group in simulation.execution_plan.groups + if group.application.id == :leaf_source) + scene_group = only(group for group in simulation.execution_plan.groups + if group.application.id == :scene_source) + @test scene_group === old_scene_group + @test only(scene_group.batches) === old_scene_batch + @test only(old_scene_batch.targets) === old_scene_target + @test length(leaf_group.batches) == 2 + @test first(leaf_group.batches) === old_leaf_batch + @test only(first(leaf_group.batches).targets) === old_leaf_target + @test last(leaf_group.batches).targets.cohort !== old_leaf_batch.targets.cohort + @test PlantSimEngine.cohort_location( + simulation.execution_plan.cohorts, :leaf_source, ObjectId(:leaf_1), + ) === old_leaf_location + @test model_object(model, :leaf_1).status.signal == 2.0 + @test model_object(model, :leaf_2).status.signal === 1.0f0 + @test model_object(model, :scene).status.signal == 2.0 + performance = Advanced.runtime_performance(simulation) + @test performance.counts[:execution_targets_constructed] == 1 + @test performance.counts[:execution_batches_constructed] == 1 + @test performance.counts[:execution_groups_reused] == 1 + + # The new family now occurs before and after the surviving first family. + # Its later view must remain reserved for its existing batch. + later_float32_batch = last(leaf_group.batches) + later_float32_target = only(later_float32_batch.targets) + register_object!(model, Object( + :leaf_0; scale=:Leaf, parent=:scene, status=Status(signal=0.0f0), + )) + continue!(simulation) + recurring_group = only(group for group in simulation.execution_plan.groups + if group.application.id == :leaf_source) + @test length(recurring_group.batches) == 3 + @test recurring_group.batches[2] === old_leaf_batch + @test recurring_group.batches[3] === later_float32_batch + @test only(recurring_group.batches[3].targets) === later_float32_target + @test recurring_group.batches[1].targets !== later_float32_batch.targets + @test recurring_group.batches[1].targets.cohort === later_float32_batch.targets.cohort + @test [target.object_id for batch in recurring_group.batches for target in batch.targets] == + ObjectId.([:leaf_0, :leaf_1, :leaf_2]) + @test model_object(model, :leaf_0).status.signal === 1.0f0 + @test model_object(model, :leaf_1).status.signal == 3.0 + @test model_object(model, :leaf_2).status.signal === 2.0f0 + @test model_object(model, :scene).status.signal == 3.0 + performance = Advanced.runtime_performance(simulation) + @test performance.counts[:execution_targets_constructed] == 2 + @test performance.counts[:execution_batches_constructed] == 2 end function stabilization_lifecycle_scene(nleaves_per_plant) diff --git a/test/test-model-hard-calls.jl b/test/test-model-hard-calls.jl index 0ccbb1d2f..56c8e40c7 100644 --- a/test/test-model-hard-calls.jl +++ b/test/test-model-hard-calls.jl @@ -1204,6 +1204,23 @@ end ObjectId(:leaf_keep), ObjectId(:leaf_z_after_observation), ] + # A later explicit selection is only a view over this call's membership. + # It must leave the other retained target available in the complete view. + run_call!( + LAZY_MANY_CALL_CONTEXT[], + :children; + objects=(:leaf_keep,), + ) + @test getproperty.(collect(full_call_view), :object_id) == + ObjectId[ObjectId(:leaf_keep), ObjectId(:leaf_z_after_observation)] + other_target = only(call_targets( + LAZY_MANY_CALL_CONTEXT[], + :children; + objects=(:leaf_z_after_observation,), + )) + @test other_target.object_id == ObjectId(:leaf_z_after_observation) + @test getproperty.(collect(full_call_view), :object_id) == + ObjectId[ObjectId(:leaf_keep), ObjectId(:leaf_z_after_observation)] @test Advanced.runtime_performance(simulation).counts[ :selector_call_binding_candidates ] == 1 diff --git a/test/test-model-input-plan-output-metadata.jl b/test/test-model-input-plan-output-metadata.jl index 6d50f3c39..1ea011521 100644 --- a/test/test-model-input-plan-output-metadata.jl +++ b/test/test-model-input-plan-output-metadata.jl @@ -106,16 +106,17 @@ plan_signature(plans) = [(plan.application_id, plan.input, plan.origin, @test length(plans) == count @test all(plan -> plan.potential_source_application_ids == (:source,), plans) @test all(plan -> plan.origin == (explicit ? :model_spec : :inferred_same_object), plans) - # One name snapshot and one contract validation per application; every - # real binding still compares the validated endpoint contracts. - @test queries.source == 2 - @test all(==(2), queries.readers) + # Names already belong to the prepared application. Only contract + # validation reads declarations again, once per application; every real + # binding still compares the validated endpoint contracts. + @test queries.source == 1 + @test all(==(1), queries.readers) @test queries.source_contracts == 1 @test all(==(1), queries.reader_contracts) repeated, fresh_queries = planner_pass(data, applications, destinations) @test plan_signature(repeated) == plan_signature(plans) - @test fresh_queries.source == 2 - @test all(==(2), fresh_queries.readers) + @test fresh_queries.source == 1 + @test all(==(1), fresh_queries.readers) @test fresh_queries.source_contracts == 1 @test all(==(1), fresh_queries.reader_contracts) diff --git a/test/test-native-compilation.jl b/test/test-native-compilation.jl index e41806460..9965c07e8 100644 --- a/test/test-native-compilation.jl +++ b/test/test-native-compilation.jl @@ -85,6 +85,13 @@ end before = NamedTuple(authored_status) split = Compilation.prepare(authored; constants) continuous = Compilation.prepare(authored; constants) + plan = split.simulation.execution_plan + @test plan.topology isa PlantSimEngine.FixedExecution + @test plan.groups isa Tuple + @test plan.batches isa Tuple + @test plan.groups_by_application_slot isa Tuple + @test all(group -> group.batches isa Tuple, plan.groups) + @test plan.cohorts === split.simulation.temporal_streams.cohorts expected = run!(native_compilation_scene(); steps=5, constants) @test current_step(split) == current_step(continuous) == 0 @@ -104,6 +111,8 @@ end continue!(split; steps=4) continue!(continuous; steps=5) @test current_step(split) == current_step(continuous) == current_step(expected) == 5 + @test plan.schedule.last_step == current_step(split) + @test continuous.simulation.execution_plan.schedule.last_step == current_step(continuous) @test final_state(split) == final_state(continuous) == final_state(expected) @test final_state(split).observed === 41.0f0 @test NamedTuple(model_status(authored, :sample)) == before From 31ad422af659a250ae86aa46eadcec8e41a0ca86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 12:25:32 +0100 Subject: [PATCH 003/324] Use typed object families and shared status construction recipes --- src/composite_model/compilation.jl | 99 +++----- src/composite_model/object_families.jl | 203 +++++++++++++++ src/composite_model/registry_topology.jl | 78 +++--- src/composite_model/status_construction.jl | 46 ++++ src/composite_model_api.jl | 1 + test/runtests.jl | 2 + test/test-object-families.jl | 276 +++++++++++++++++++++ test/test-status-construction.jl | 210 ++++++++++++++++ 8 files changed, 803 insertions(+), 112 deletions(-) create mode 100644 src/composite_model/object_families.jl create mode 100644 src/composite_model/status_construction.jl create mode 100644 test/test-object-families.jl create mode 100644 test/test-status-construction.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index d6cec5165..311c9d70a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5270,69 +5270,43 @@ function _ref_vector_carrier(refs) end """ -Mutable, storage-neutral recipe used to assemble one canonical object status. +Sparse reference edits staged before committing one canonical object status. -The recipe keeps existing field order and reference identity, stages additions -or replacements in place, then materializes at most one new `Status`. Keeping -the logical names separate from the current `Ref` backing also leaves a -small seam for a future columnar status-storage experiment. +Unchanged fields remain in the original status. A model-owned construction +recipe supplies their order when the staged edits are committed. """ mutable struct _CanonicalStatusRecipe original::Union{Nothing,Status} - names::Vector{Symbol} - references::Union{Vector{Base.RefValue},Vector{Ref}} - positions::Union{Nothing,Dict{Symbol,Int}} + edit_names::Vector{Symbol} + edit_references::Vector{Ref} changed::Bool field_changes::Int end -_status_recipe_references(references::Tuple{Vararg{Base.RefValue}}) = - Base.RefValue[references...] -_status_recipe_references(references) = Ref[references...] - function _CanonicalStatusRecipe(status::Union{Nothing,Status}) - names = isnothing(status) ? Symbol[] : collect(propertynames(status)) - references = if isnothing(status) - Base.RefValue[] - else - _status_recipe_references(refvalues(status)) - end - positions = if length(names) > 1 - index = Dict{Symbol,Int}() - sizehint!(index, length(names)) - for (position, name) in pairs(names) - index[name] = position - end - index - else - nothing - end return _CanonicalStatusRecipe( status, - names, - references, - positions, + Symbol[], + Ref[], isnothing(status), 0, ) end -@inline function _status_recipe_position(recipe::_CanonicalStatusRecipe, variable::Symbol) - positions = recipe.positions - isnothing(positions) || return get(positions, variable, 0) - return !isempty(recipe.names) && first(recipe.names) === variable ? 1 : 0 +@inline function _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) + variable in recipe.edit_names && return true + return !isnothing(recipe.original) && variable in propertynames(recipe.original) end -@inline _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) = - !iszero(_status_recipe_position(recipe, variable)) - function _status_recipe_reference( recipe::_CanonicalStatusRecipe, variable::Symbol, ) - position = _status_recipe_position(recipe, variable) - iszero(position) && throw(KeyError(variable)) - return recipe.references[position] + position = findfirst(isequal(variable), recipe.edit_names) + isnothing(position) || return recipe.edit_references[position] + isnothing(recipe.original) && throw(KeyError(variable)) + variable in propertynames(recipe.original) || throw(KeyError(variable)) + return refvalue(recipe.original, variable) end function _status_recipe_set_reference!( @@ -5340,23 +5314,18 @@ function _status_recipe_set_reference!( variable::Symbol, reference::Ref, ) - position = _status_recipe_position(recipe, variable) - if iszero(position) - push!(recipe.names, variable) - push!(recipe.references, reference) - if isnothing(recipe.positions) - # Zero/one-field recipes need no lookup table. Once a second field - # is added, use the same indexed path as wider status schemas. - if length(recipe.names) == 2 - recipe.positions = Dict(first(recipe.names) => 1, variable => 2) - end - else - recipe.positions[variable] = length(recipe.names) + position = findfirst(isequal(variable), recipe.edit_names) + if isnothing(position) + original = recipe.original + if !isnothing(original) && variable in propertynames(original) && + refvalue(original, variable) === reference + return false end - elseif recipe.references[position] === reference - return false + push!(recipe.edit_names, variable) + push!(recipe.edit_references, reference) else - recipe.references[position] = reference + recipe.edit_references[position] === reference && return false + recipe.edit_references[position] = reference end recipe.changed = true recipe.field_changes += 1 @@ -5387,18 +5356,24 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end -function _finish_status_recipe(recipe::_CanonicalStatusRecipe) +function _finish_status_recipe(model::CompositeModel, recipe::_CanonicalStatusRecipe) recipe.changed || return recipe.original - names = Tuple(recipe.names) - references = Tuple(recipe.references) - return Status(NamedTuple{names}(references)) + original = recipe.original + existing_names = isnothing(original) ? () : propertynames(original) + existing_references = isnothing(original) ? () : refvalues(original) + construction = _status_construction_recipe!( + model.registry.objects.layout_cache, + existing_names, + Tuple(recipe.edit_names), + ) + return _construct_status(construction, existing_references, Tuple(recipe.edit_references)) end function _model_object_status_for_preparation( model::CompositeModel, object_id::ObjectId, ) - status = _model_object(model, object_id).status + status = model_status(model, object_id) (isnothing(status) || status isa Status) || error( "Model object `$(object_id.value)` uses model applications but its status has type " * "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." @@ -5446,7 +5421,7 @@ function _apply_status_recipes!( _replace_model_object_status!( model, object_id, - _finish_status_recipe(recipe), + _finish_status_recipe(model, recipe), ) _runtime_performance_count!( performance, diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl new file mode 100644 index 000000000..897492b0e --- /dev/null +++ b/src/composite_model/object_families.jl @@ -0,0 +1,203 @@ +abstract type AbstractObjectFamily end + +struct ObjectFamilyRow{I<:ObjectId,S} + id::I + status::S +end + +mutable struct ObjectFamily{I<:ObjectId,S} <: AbstractObjectFamily + rows::Vector{Union{Nothing,ObjectFamilyRow{I,S}}} +end + +struct ObjectFamilyLocation + family::Int + row::Int + object::Object +end + +mutable struct OpenObjectFamilyCatalog + families::Vector{AbstractObjectFamily} + slots::Dict{Tuple{DataType,DataType},Int} +end + +OpenObjectFamilyCatalog() = OpenObjectFamilyCatalog( + AbstractObjectFamily[], Dict{Tuple{DataType,DataType},Int}(), +) + +struct ClosedObjectFamilyCatalog{F<:Tuple} + families::F +end + +"""Canonical object identities and typed status families behind the object dictionary.""" +struct ObjectFamilyStore{I<:ObjectId,C} <: AbstractDict{I,Object} + catalog::C + locations::Dict{I,ObjectFamilyLocation} + status_owners::IdDict{Base.RefValue{Nothing},I} + layout_cache::Dict{Tuple{Tuple,Tuple},Any} +end + +ObjectFamilyStore{I}() where {I<:ObjectId} = ObjectFamilyStore( + OpenObjectFamilyCatalog(), Dict{I,ObjectFamilyLocation}(), + IdDict{Base.RefValue{Nothing},I}(), + Dict{Tuple{Tuple,Tuple},Any}(), +) +ObjectFamilyStore() = ObjectFamilyStore{ObjectId}() + +Base.length(store::ObjectFamilyStore) = length(store.locations) +Base.haskey(store::ObjectFamilyStore, id) = haskey(store.locations, id) +Base.getindex(store::ObjectFamilyStore, id) = store.locations[id].object + +function Base.get(store::ObjectFamilyStore, id, default) + location = get(store.locations, id, nothing) + return isnothing(location) ? default : location.object +end + +function Base.iterate(store::ObjectFamilyStore, state...) + item = iterate(store.locations, state...) + isnothing(item) && return nothing + (id, location), next = item + return id => location.object, next +end + +# A dictionary copy exposes the same mutable Object facades, as an ordinary +# shallow Dict copy does. It does not create a second writable family owner. +Base.copy(store::ObjectFamilyStore) = Dict(store) +Base.empty(::ObjectFamilyStore{I}) where {I} = ObjectFamilyStore{I}() + +function _object_family_for_write!(catalog::OpenObjectFamilyCatalog, ::Type{I}, ::Type{S}) where {I,S} + slot = get!(catalog.slots, (I, S)) do + push!(catalog.families, ObjectFamily{I,S}(Union{Nothing,ObjectFamilyRow{I,S}}[])) + length(catalog.families) + end + return slot, catalog.families[slot]::ObjectFamily{I,S} +end + +@generated function _object_family_for_write!(catalog::ClosedObjectFamilyCatalog{F}, ::Type{I}, ::Type{S}) where {F,I,S} + for (slot, family_type) in enumerate(fieldtypes(F)) + family_type === ObjectFamily{I,S} || continue + return :($slot, getfield(catalog.families, $slot)) + end + return :(throw(ArgumentError("The object identity/status schema is outside the prepared family catalog."))) +end + +function _object_family_status_at(catalog::OpenObjectFamilyCatalog, location::ObjectFamilyLocation) + return _object_family_status_at(catalog.families[location.family], location.row) +end + +@inline function _object_family_status_at(family::ObjectFamily{I,S}, row::Int) where {I,S} + entry = family.rows[row] + isnothing(entry) && throw(ArgumentError("The object family row is no longer registered.")) + return entry.status::S +end + +# A finite union retains the concrete Status families across a runtime slot. +# Object counts, IDs and row positions are deliberately absent from the type. +@generated function _object_family_status_at(catalog::ClosedObjectFamilyCatalog{F}, location::ObjectFamilyLocation) where {F} + # Extract the family parameters directly; rows also admit tombstones. + status_types = [family.parameters[2] for family in fieldtypes(F)] + result_type = Union{status_types...} + branch = :(throw(BoundsError(catalog.families, location.family))) + for slot in reverse(1:fieldcount(F)) + value = :(_object_family_status_at(getfield(catalog.families, $slot), location.row)) + branch = Expr(:if, :(location.family == $slot), value, branch) + end + return Expr(:(::), branch, result_type) +end + +_object_family_status(store::ObjectFamilyStore, id) = + _object_family_status_at(store.catalog, store.locations[id]) + +function _validate_object_family_status_owner!(store::ObjectFamilyStore, status, id) + status isa Status || return nothing + existing = get(store.status_owners, _status_identity(status), nothing) + if !isnothing(existing) && existing != id + throw(ArgumentError( + "The same Status instance cannot be owned by model objects " * + "`$(existing.value)` and `$(id.value)`. Give each Object its own Status instance.", + )) + end + return nothing +end + +function _forget_object_family_status!(store::ObjectFamilyStore, status, id) + status isa Status || return nothing + identity = _status_identity(status) + get(store.status_owners, identity, nothing) == id && delete!(store.status_owners, identity) + return nothing +end + +function _clear_object_family_row!(catalog, location::ObjectFamilyLocation) + catalog.families[location.family].rows[location.row] = nothing + return nothing +end + +function _store_object_family_row!(store::ObjectFamilyStore{K}, object::Object, id::I, status::S) where {K,I<:ObjectId,S} + id isa K || throw(ArgumentError("The object identity type is outside the prepared family catalog.")) + previous = get(store.locations, id, nothing) + if !isnothing(previous) && previous.object !== object + throw(ArgumentError("Remove the registered Object before reusing its identity for another Object.")) + end + _validate_object_family_status_owner!(store, status, id) + slot, family = _object_family_for_write!(store.catalog, I, S) + if !isnothing(previous) + _forget_object_family_status!(store, _object_family_status_at(store.catalog, previous), id) + end + entry = ObjectFamilyRow(id, status) + row = if !isnothing(previous) && previous.family == slot + family.rows[previous.row] = entry + previous.row + else + push!(family.rows, entry) + isnothing(previous) || _clear_object_family_row!(store.catalog, previous) + length(family.rows) + end + store.locations[id] = ObjectFamilyLocation(slot, row, object) + status isa Status && (store.status_owners[_status_identity(status)] = id) + return status +end + +function Base.setindex!(store::ObjectFamilyStore, object::Object, id) + isequal(object.id, id) || throw(ArgumentError("The dictionary key must match the Object identity.")) + _store_object_family_row!(store, object, object.id, object.status) + return store +end + +function Base.delete!(store::ObjectFamilyStore, id) + location = get(store.locations, id, nothing) + isnothing(location) && return store + _forget_object_family_status!(store, _object_family_status_at(store.catalog, location), id) + _clear_object_family_row!(store.catalog, location) + delete!(store.locations, id) + return store +end + +function Base.empty!(store::ObjectFamilyStore) + empty!(store.locations) + empty!(store.status_owners) + empty!(store.layout_cache) + for family in store.catalog.families + empty!(family.rows) + end + return store +end + +"""Close active families of a private model before execution; replace its old store.""" +function _closed_object_family_store(store::ObjectFamilyStore) + # Preparation may have replaced an object's status several times. Empty + # historical schemas are not promises about future newborn construction. + slots = sort!(unique([location.family for location in values(store.locations)])) + families = Tuple(store.catalog.families[slot] for slot in slots) + id_types = unique([typeof(family).parameters[1] for family in families]) + isempty(id_types) && throw(ArgumentError("A closed object family store requires an identity schema.")) + I = Union{id_types...} + closed_slots = Dict(slot => index for (index, slot) in enumerate(slots)) + locations = Dict{I,ObjectFamilyLocation}( + id => ObjectFamilyLocation(closed_slots[location.family], location.row, location.object) + for (id, location) in store.locations + ) + return ObjectFamilyStore( + ClosedObjectFamilyCatalog(families), locations, + IdDict{Base.RefValue{Nothing},I}(store.status_owners), + copy(store.layout_cache), + ) +end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 6f98adb82..11ce07d7f 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -214,9 +214,10 @@ function Object( ) end -mutable struct ObjectRegistry - objects::Dict{ObjectId,Any} - object_ids_by_status::IdDict{Base.RefValue{Nothing},ObjectId} +include("object_families.jl") + +mutable struct ObjectRegistry{O} + objects::O by_scale::Dict{Symbol,Set{ObjectId}} by_kind::Dict{Symbol,Set{ObjectId}} by_species::Dict{Symbol,Set{ObjectId}} @@ -224,8 +225,7 @@ mutable struct ObjectRegistry end ObjectRegistry() = ObjectRegistry( - Dict{ObjectId,Any}(), - IdDict{Base.RefValue{Nothing},ObjectId}(), + ObjectFamilyStore(), Dict{Symbol,Set{ObjectId}}(), Dict{Symbol,Set{ObjectId}}(), Dict{Symbol,Set{ObjectId}}(), @@ -244,7 +244,7 @@ struct MTGObjectAccessors{I,S,K,SP,N,G,ST} status::ST end -struct MTGObjectAdapter{R,I,S,K,SP,N,G,ST} +struct MTGObjectAdapter{R,I,S,K,SP,N,G,ST,FI,RI} root::R id::I scale::S @@ -254,8 +254,21 @@ struct MTGObjectAdapter{R,I,S,K,SP,N,G,ST} geometry::G status::ST max_node_id::Base.RefValue{Int} - object_ids_by_node::IdDict{Any,ObjectId} - nodes_by_object_id::Dict{ObjectId,Any} + object_ids_by_node::FI + nodes_by_object_id::RI +end + +# Close only identity carrier types, preserving the source tree and every +# accessor. A closed execution schema can still create arbitrary numbers of +# nodes and call the same registration/removal operations. +function _closed_mtg_object_adapter(adapter::MTGObjectAdapter, ::Type{I}) where {I<:ObjectId} + R = typeof(adapter.root) + return MTGObjectAdapter( + adapter.root, adapter.id, adapter.scale, adapter.kind, adapter.species, + adapter.name, adapter.geometry, adapter.status, adapter.max_node_id, + IdDict{R,I}(adapter.object_ids_by_node), + Dict{I,R}(adapter.nodes_by_object_id), + ) end function _register_mtg_object_identity!(adapter::MTGObjectAdapter, node) @@ -822,8 +835,8 @@ function CompositeModel( geometry, status, Ref(MultiScaleTreeGraph.new_id(root) - 1), - IdDict{Any,ObjectId}(), - Dict{ObjectId,Any}(), + IdDict{typeof(root),ObjectId}(), + Dict{ObjectId,typeof(root)}(), ) objects = _objects_from_mtg(root, adapter) return CompositeModel( @@ -973,8 +986,6 @@ function _index_object!(registry::ObjectRegistry, object::Object) _push_index!(registry.by_scale, object.scale, object.id) _push_index!(registry.by_kind, object.kind, object.id) _push_index!(registry.by_species, object.species, object.id) - object.status isa Status && - (registry.object_ids_by_status[_status_identity(object.status)] = object.id) return nothing end @@ -982,14 +993,6 @@ function _deindex_object!(registry::ObjectRegistry, object::Object) _delete_index!(registry.by_scale, object.scale, object.id) _delete_index!(registry.by_kind, object.kind, object.id) _delete_index!(registry.by_species, object.species, object.id) - if object.status isa Status && - get( - registry.object_ids_by_status, - _status_identity(object.status), - nothing, - ) == object.id - delete!(registry.object_ids_by_status, _status_identity(object.status)) - end return nothing end @@ -998,22 +1001,7 @@ function _validate_status_identity_available!( status, object_id::ObjectId, ) - status isa Status || return nothing - existing = get( - registry.object_ids_by_status, - _status_identity(status), - nothing, - ) - if !isnothing(existing) && existing != object_id - throw( - ArgumentError( - "The same Status instance cannot be owned by model objects " * - "`$(existing.value)` and `$(object_id.value)`. Give each Object " * - "its own Status instance.", - ), - ) - end - return nothing + return _validate_object_family_status_owner!(registry.objects, status, object_id) end function _validate_status_source_identity_available!( @@ -1077,19 +1065,8 @@ function _replace_model_object_status!( "got `$(typeof(status))`.", ) object.status === status && return status - registry = model.registry - _validate_status_identity_available!(registry, status, object.id) - if object.status isa Status && - get( - registry.object_ids_by_status, - _status_identity(object.status), - nothing, - ) == object.id - delete!(registry.object_ids_by_status, _status_identity(object.status)) - end + _store_object_family_row!(model.registry.objects, object, object.id, status) setfield!(object, :status, status) - status isa Status && - (registry.object_ids_by_status[_status_identity(status)] = object.id) _set_status_source_identity!(model, object.id, status) return status end @@ -1150,7 +1127,7 @@ function object_id(model::CompositeModel, object::Object) end function object_id(model::CompositeModel, status::Status) - index = model.registry.object_ids_by_status + index = model.registry.objects.status_owners identity = _status_identity(status) haskey(index, identity) || throw( ArgumentError("The supplied Status instance is not registered by this model."), @@ -1189,7 +1166,8 @@ represented by `source`. `source` accepts the same identities as [`object_id`](@ref), including an exact MTG node. Runtime status belongs to the model registry and is not stored in MTG attributes. """ -model_status(model::CompositeModel, source) = model_object(model, source).status +model_status(model::CompositeModel, source) = + _object_family_status(model.registry.objects, object_id(model, source)) """ source_node(model::CompositeModel, source) -> MultiScaleTreeGraph.Node diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl new file mode 100644 index 000000000..b30aa9d78 --- /dev/null +++ b/src/composite_model/status_construction.jl @@ -0,0 +1,46 @@ +struct ExistingStatusReference{I} end +struct EditedStatusReference{I} end + +"""Ordered reference selections for a status schema, without object state or defaults.""" +struct StatusConstructionRecipe{Names,A<:Tuple} + actions::A +end + +function StatusConstructionRecipe(existing_names::Tuple, edit_names::Tuple) + names = collect(Symbol, existing_names) + actions = Any[ExistingStatusReference{index}() for index in eachindex(names)] + for (index, name) in pairs(edit_names) + position = findfirst(isequal(name), names) + action = EditedStatusReference{index}() + if isnothing(position) + push!(names, name) + push!(actions, action) + else + actions[position] = action + end + end + selections = Tuple(actions) + return StatusConstructionRecipe{Tuple(names),typeof(selections)}(selections) +end + +@inline _status_construction_reference(::ExistingStatusReference{I}, existing, edited) where {I} = + getfield(existing, I) +@inline _status_construction_reference(::EditedStatusReference{I}, existing, edited) where {I} = + getfield(edited, I) + +function _construct_status( + recipe::StatusConstructionRecipe{Names}, + existing::Tuple, + edited::Tuple, +) where {Names} + references = map(recipe.actions) do action + _status_construction_reference(action, existing, edited) + end + return Status(NamedTuple{Names}(references)) +end + +function _status_construction_recipe!(cache, existing_names::Tuple, edit_names::Tuple) + return get!(cache, (existing_names, edit_names)) do + StatusConstructionRecipe(existing_names, edit_names) + end +end diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index e49485546..f5f93ab49 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -3,6 +3,7 @@ # abstraction boundary. include("composite_model/status_conversion.jl") include("composite_model/registry_topology.jl") +include("composite_model/status_construction.jl") include("composite_model/selectors.jl") include("composite_model/execution_cohorts.jl") include("composite_model/execution_storage.jl") diff --git a/test/runtests.jl b/test/runtests.jl index c07aa72bb..471668c1a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -39,6 +39,7 @@ else @testset "Registered object identity" begin include("test-model-object-id.jl") + include("test-object-families.jl") end @testset "Concrete runtime object identities" begin @@ -65,6 +66,7 @@ else @testset "Organ status assembly" begin include("test-organ-status-assembly.jl") + include("test-status-construction.jl") end @testset "CompositeModel display" begin diff --git a/test/test-object-families.jl b/test/test-object-families.jl new file mode 100644 index 000000000..5c15e3503 --- /dev/null +++ b/test/test-object-families.jl @@ -0,0 +1,276 @@ +module CanonicalObjectFamilyChecks + +using Test +using PlantSimEngine +using MultiScaleTreeGraph + +const PSE = PlantSimEngine + +@testset "ordinary registry owns typed status families and exact object facades" begin + supplied = Status(value=1f0) + reference = PSE.refvalue(supplied, :value) + first = Object(1; scale=:Leaf, status=supplied) + second = Object(:leaf; scale=:Leaf, status=Status(value=2.0)) + empty = Object((:plant, 3); scale=:Leaf) + model = CompositeModel(first, second, empty) + store = model.registry.objects + + @test store isa PSE.ObjectFamilyStore + @test store.catalog isa PSE.OpenObjectFamilyCatalog + @test length(store.catalog.families) == 3 + @test model_object(model, 1) === first + @test model_status(model, 1) === supplied + @test PSE.refvalue(model_status(model, supplied), :value) === reference + @test isnothing(model_status(model, (:plant, 3))) + @test Set(keys(store)) == Set((ObjectId(1), ObjectId(:leaf), ObjectId((:plant, 3)))) + @test Set(values(store)) == Set((first, second, empty)) + @test Dict(store)[ObjectId(1)] === first + @test copy(store)[ObjectId(:leaf)] === second + @test get(store, ObjectId(:absent), nothing) === nothing + @test object_id(model, supplied) === ObjectId(1) + + model_status(model, 1).value = 4f0 + @test supplied.value === first.status.value === 4f0 + location = store.locations[ObjectId(1)] + family = store.catalog.families[location.family] + @test family isa PSE.ObjectFamily{ObjectId{Int},typeof(supplied)} + @test family.rows[location.row].status === supplied +end + +@testset "status replacement moves family membership and exclusive ownership" begin + original = Status(value=1f0) + first = Object(:first; status=original) + occupied = Status(value=9.0) + second = Object(:second; status=occupied) + model = CompositeModel(first, second) + store = model.registry.objects + previous = store.locations[first.id] + replacement = Status(value=3.0, counter=2) + + @test PSE._replace_model_object_status!(model, first, replacement) === replacement + current = store.locations[first.id] + @test current.family != previous.family + @test isnothing(store.catalog.families[previous.family].rows[previous.row]) + @test model_object(model, :first) === first + @test first.status === model_status(model, :first) === replacement + @test object_id(model, replacement) === first.id + @test_throws ArgumentError object_id(model, original) + @test original.value === 1f0 + + @test_throws ArgumentError PSE._replace_model_object_status!(model, first, occupied) + @test first.status === model_status(model, :first) === replacement + @test model_status(model, :second) === occupied + @test store.locations[first.id] == current + @test_throws ArgumentError PSE._replace_model_object_status!( + model, Object(:first; status=Status(value=0.0)), Status(value=12.0)) + @test model_object(model, :first) === first + @test model_status(model, :first) === replacement + + @test isnothing(PSE._replace_model_object_status!(model, first, nothing)) + @test isnothing(model_status(model, :first)) + @test_throws ArgumentError object_id(model, replacement) + @test PSE._replace_model_object_status!(model, first, original) === original + @test object_id(model, original) === first.id +end + +PSE.@process "canonical_family_increment" verbose = false +struct FamilyIncrement <: AbstractCanonical_Family_IncrementModel end +PSE.inputs_(::FamilyIncrement) = NamedTuple() +PSE.outputs_(::FamilyIncrement) = (value=0.0,) +function PSE.run!(::FamilyIncrement, status, environment, constants, context) + status.value += one(status.value) + return nothing +end + +@testset "conversion and normal execution read canonical family state" begin + source = Status(value=2.0) + first = Object(:leaf; scale=:Leaf, status=source) + model = CompositeModel(first; + applications=(ModelSpec(FamilyIncrement(); name=:increment, on=Many(scale=:Leaf)),), + type_promotion=Dict(Float64 => Float32)) + converted = model_status(model, :leaf) + @test converted !== source + @test converted.value === 2f0 + @test first.status === converted + @test object_id(model, converted) === first.id + @test_throws ArgumentError object_id(model, source) + @test_throws ArgumentError register_object!(model, Object(:duplicate; status=source)) + + simulation = run!(model; outputs=:all) + @test model_status(model, :leaf) === converted + @test converted.value === 3f0 + late_source = Status(value=4.5) + late = Object(:late; scale=:Leaf, status=late_source) + register_object!(model, late) + @test late.status.value === 4.5f0 + @test model_status(model, :late) === late.status + continue!(simulation) + @test converted.value === 4f0 + @test model_status(model, :late).value === 5.5f0 + @test outputs(simulation)[(:increment, ObjectId(:late), :value)] == [(2.0, 5.5f0)] + + removed_status = model_status(model, :late) + removed_location = model.registry.objects.locations[late.id] + remove_object!(model, late.id) + @test_throws ArgumentError object_id(model, removed_status) + @test_throws ErrorException model_status(model, late.id) + replacement = Object(:late; scale=:Leaf, status=Status(value=10.0)) + register_object!(model, replacement) + @test model_object(model, :late) === replacement + @test model_status(model, :late).value === 10f0 + @test model.registry.objects.locations[late.id].row != removed_location.row + @test_throws ArgumentError object_id(model, late) + continue!(simulation) + @test model_status(model, :late).value === 11f0 + @test removed_status.value === 5.5f0 +end + +@testset "typed MTG identities preserve exact nodes through growth and removal" begin + root = Node(MultiScaleTreeGraph.NodeMTG(:/, :Scene, 1, 0)) + leaf = Node(root, MultiScaleTreeGraph.NodeMTG(:+, :Leaf, 1, 1)) + model = CompositeModel(root; + status=node -> MultiScaleTreeGraph.symbol(node) === :Leaf ? Status(value=1f0) : nothing) + adapter = model.source_adapter + @test keytype(adapter.object_ids_by_node) === typeof(root) + @test valtype(adapter.nodes_by_object_id) === typeof(root) + @test source_node(model, leaf) === leaf + @test isnothing(model_status(model, root)) + @test_throws ArgumentError object_id(model, deepcopy(leaf)) + @test_throws ArgumentError source_node(model, deepcopy(leaf)) + + born = add_organ!(root, model, :+, :Leaf, 1; initial_status=(value=7f0,)) + id = object_id(model, born) + node = source_node(model, born) + @test model_status(model, node) === born + @test born.node === node + @test source_node(model, id) === node + @test object_id(model, node) === id + @test born.value === 7f0 + + closed_adapter = PSE._closed_mtg_object_adapter(adapter, ObjectId{Int}) + @test closed_adapter.root === root + @test closed_adapter.status === adapter.status + @test keytype(closed_adapter.nodes_by_object_id) === ObjectId{Int} + @test closed_adapter.nodes_by_object_id[id] === node + @test closed_adapter.object_ids_by_node[node] === id + + remove_object!(model, id) + @test_throws ArgumentError object_id(model, born) + @test_throws ArgumentError object_id(model, node) + @test !haskey(adapter.nodes_by_object_id, id) + @test !haskey(adapter.object_ids_by_node, node) + MultiScaleTreeGraph.delete_node!(node) + reused = add_organ!(root, model, :+, :Leaf, 1; id=id.value, initial_status=(value=9f0,)) + @test object_id(model, reused) === id + @test source_node(model, reused) !== node + @test model_status(model, id) === reused + @test_throws ArgumentError object_id(model, node) +end + +@testset "different node attribute schemas preserve one exact MTG node family" begin + root = Node(MultiScaleTreeGraph.NodeMTG(:/, :Scene, 1, 0), (label="scene",)) + leaf = Node(root, MultiScaleTreeGraph.NodeMTG(:+, :Leaf, 1, 1), + (area=2f0, state=:active)) + tip = Node(leaf, MultiScaleTreeGraph.NodeMTG(:+, :Tip, 1, 2), + Dict{Symbol,Any}(:rate => 3.0, :history => Float32[1, 2])) + model = CompositeModel(root) + @test typeof(root) === typeof(leaf) === typeof(tip) + @test source_node(model, object_id(model, leaf)) === leaf + @test source_node(model, object_id(model, tip)) === tip + @test leaf[:area] === 2f0 + @test tip[:history] == Float32[1, 2] + + grown = add_organ!(tip, model, :+, :Tip, 2; attributes=(new_field=4,)) + @test typeof(source_node(model, grown)) === typeof(root) + @test grown.new_field === 4 + + # Explicit raw construction can create a different detached node family, + # but cannot attach it to the homogeneous children vector of this tree. + encoding = MultiScaleTreeGraph.NodeMTG(:+, :Leaf, 1, 1) + attrs = (foreign=true,) + N = Node{typeof(encoding),typeof(attrs)} + foreign = N(MultiScaleTreeGraph.node_id(leaf), nothing, N[], encoding, attrs, nothing) + @test typeof(foreign) !== typeof(root) + @test_throws ArgumentError object_id(model, foreign) + @test_throws ArgumentError source_node(model, foreign) +end + +@testset "deepcopy preserves private canonical family aliases" begin + original = Status(value=1f0) + object = Object(:leaf; status=original) + model = CompositeModel(object) + copied = deepcopy(model) + copied_object = model_object(copied, :leaf) + copied_status = model_status(copied, :leaf) + @test copied_object !== object + @test copied_status !== original + @test copied_object.status === copied_status + @test object_id(copied, copied_status) === ObjectId(:leaf) + @test_throws ArgumentError object_id(copied, original) + @test_throws ArgumentError object_id(model, copied_status) + location = copied.registry.objects.locations[ObjectId(:leaf)] + family = copied.registry.objects.catalog.families[location.family] + @test family.rows[location.row].status === copied_status + copied_status.value = 6f0 + @test copied_object.status.value === 6f0 + @test original.value === 1f0 +end + +@testset "closed family catalog keeps runtime membership and shared payloads" begin + first_status = Status(value=1f0) + first = Object(1; status=first_status) + model = CompositeModel(first) + closed = PSE._closed_object_family_store(model.registry.objects) + @test closed.catalog isa PSE.ClosedObjectFamilyCatalog + @test closed.catalog.families isa Tuple + @test keytype(closed.locations) === ObjectId{Int} + @test closed[first.id] === first + @test (@inferred PSE._object_family_status(closed, first.id)) === first_status + store_type = typeof(closed) + + born = Object(2; status=Status(value=2f0)) + closed[born.id] = born + @test typeof(closed) === store_type + @test length(closed) == 2 + @test PSE._object_family_status(closed, born.id) === born.status + @test closed.status_owners[PSE._status_identity(born.status)] === born.id + @test_throws ArgumentError setindex!(closed, Object(3; status=Status(value=3.0)), ObjectId(3)) + @test !haskey(closed, ObjectId(3)) + @test length(closed) == 2 + + delete!(closed, born.id) + @test length(closed) == 1 + @test !haskey(closed.status_owners, PSE._status_identity(born.status)) + replacement = Object(2; status=Status(value=8f0)) + closed[replacement.id] = replacement + @test closed[replacement.id] === replacement + @test PSE._object_family_status(closed, replacement.id).value === 8f0 + + mixed = CompositeModel(Object(1; status=Status(value=1f0)), Object(:leaf; status=nothing)) + mixed_closed = PSE._closed_object_family_store(mixed.registry.objects) + @test keytype(mixed_closed.locations) === Union{ObjectId{Int},ObjectId{Symbol}} + @test PSE._object_family_status(mixed_closed, ObjectId(1)).value === 1f0 + @test isnothing(PSE._object_family_status(mixed_closed, ObjectId(:leaf))) + + historical = CompositeModel(Object(:leaf; status=Status(value=1f0))) + PSE._replace_model_object_status!(historical, :leaf, Status(value=2.0, count=1)) + @test length(historical.registry.objects.catalog.families) == 2 + active = PSE._closed_object_family_store(historical.registry.objects) + @test length(active.catalog.families) == 1 + @test PSE._object_family_status(active, ObjectId(:leaf)).value === 2.0 + @test_throws ArgumentError setindex!(active, + Object(:newborn; status=Status(value=3f0)), ObjectId(:newborn)) + + statuses = [Status(value=Float32(index), payload=ntuple(identity, index)) for index in 1:8] + eight = CompositeModel((Object(index; status=status) for (index, status) in enumerate(statuses))...) + eight_closed = PSE._closed_object_family_store(eight.registry.objects) + allowed = Union{typeof.(statuses)...} + inferred = Core.Compiler.return_type(PSE._object_family_status, + Tuple{typeof(eight_closed),ObjectId{Int}}) + @test inferred === allowed + for (index, status) in enumerate(statuses) + @test PSE._object_family_status(eight_closed, ObjectId(index)) === status + end +end + +end diff --git a/test/test-status-construction.jl b/test/test-status-construction.jl new file mode 100644 index 000000000..f52de5bb6 --- /dev/null +++ b/test/test-status-construction.jl @@ -0,0 +1,210 @@ +module StatusConstructionChecks + +using Dates +using PlantSimEngine +using Test + +const PSE = PlantSimEngine + +@testset "cached layouts preserve order and use the actual reference types" begin + model = CompositeModel(Object(:object; status=Status())) + original = Status(keep=1, replace=2.0) + keep = PSE.refvalue(original, :keep) + replacement = Ref(3.0f0) + tail = Ref([4.0]) + edits = PSE._CanonicalStatusRecipe(original) + @test isempty(edits.edit_names) + @test isempty(edits.edit_references) + @test !PSE._status_recipe_set_reference!(edits, :keep, keep) + @test PSE._status_recipe_set_reference!(edits, :replace, replacement) + @test PSE._status_recipe_set_reference!(edits, :tail, tail) + @test !PSE._status_recipe_set_reference!(edits, :tail, tail) + constructed = PSE._finish_status_recipe(model, edits) + @test propertynames(constructed) == (:keep, :replace, :tail) + @test PSE.refvalue(constructed, :keep) === keep + @test PSE.refvalue(constructed, :replace) === replacement + @test PSE.refvalue(constructed, :tail) === tail + @test PSE._status_recipe_reference(edits, :keep) === keep + @test PSE._status_recipe_reference(edits, :replace) === replacement + @test_throws KeyError PSE._status_recipe_reference(edits, :absent) + @test PSE._finish_status_recipe(model, PSE._CanonicalStatusRecipe(original)) === original + + cache = model.registry.objects.layout_cache + layout = only(values(cache)) + same_shape = PSE._CanonicalStatusRecipe(Status(keep=8, replace=9.0)) + PSE._status_recipe_set_reference!(same_shape, :replace, Ref(big"10.0")) + PSE._status_recipe_set_reference!(same_shape, :tail, Ref([11.0f0])) + another = PSE._finish_status_recipe(model, same_shape) + @test typeof(another) !== typeof(constructed) + @test another.replace isa BigFloat + @test another.tail isa Vector{Float32} + @test length(cache) == 1 + @test only(values(cache)) === layout + @test all(isbits, values(cache)) + @test all(key -> key isa Tuple{Tuple{Vararg{Symbol}},Tuple{Vararg{Symbol}}}, keys(cache)) + + storage = [12.0] + external = Ref(storage, 1) + external_edit = PSE._CanonicalStatusRecipe(Status(keep=1)) + PSE._status_recipe_set_reference!(external_edit, :external, external) + external_status = PSE._finish_status_recipe(model, external_edit) + @test PSE.refvalue(external_status, :external) === external + storage[1] = 13.0 + @test external_status.external == 13.0 + + empty_a = PSE._finish_status_recipe(model, PSE._CanonicalStatusRecipe(nothing)) + empty_b = PSE._finish_status_recipe(model, PSE._CanonicalStatusRecipe(nothing)) + @test propertynames(empty_a) == () + @test getfield(empty_a, :identity) !== getfield(empty_b, :identity) + @test all(isbits, values(cache)) + projected = PSE._closed_object_family_store(model.registry.objects) + @test projected.layout_cache == cache + @test projected.layout_cache !== cache + @test isempty(CompositeModel(Object(:other)).registry.objects.layout_cache) + discarded = PSE.ObjectFamilyStore() + merge!(discarded.layout_cache, cache) + empty!(discarded) + @test isempty(discarded.layout_cache) + @test !isempty(cache) +end + +PSE.@process "status_construction_defaults" verbose=false +struct MutableDefaults{T} <: AbstractStatus_Construction_DefaultsModel + initial::T +end +PSE.outputs_(model::MutableDefaults) = (items=model.initial[],) +PSE.run!(::MutableDefaults, status, environment, constants, context) = nothing + +@testset "ordinary preparation keeps mutable defaults fresh and object-private" begin + initial = Ref([1.0]) + model = CompositeModel( + Object(:first; scale=:Leaf), Object(:second; scale=:Leaf); + applications=(ModelSpec(MutableDefaults(initial); name=:defaults, + on=Many(scale=:Leaf)),), + environment=(duration=Hour(1),), type_promotion=Dict(Float64 => Float32)) + simulation = run!(model; steps=0, outputs=:none) + first = model_status(model, :first).items + second = model_status(model, :second).items + @test first == second == Float32[1] + @test first !== second + @test first !== initial[] + @test eltype(first) === Float32 + initial[][1] = 9.0 + register_object!(model, Object(:third; scale=:Leaf)) + continue!(simulation; steps=1) + third = model_status(model, :third).items + @test third == Float32[9] + @test first == second == Float32[1] + first[1] = 20f0 + @test second == Float32[1] + @test third == Float32[9] + @test initial[] == [9.0] + @test all(isbits, values(model.registry.objects.layout_cache)) +end + +PSE.@process "status_construction_producer" verbose=false +PSE.@process "status_construction_consumer" verbose=false +struct Producer <: AbstractStatus_Construction_ProducerModel end +struct Consumer <: AbstractStatus_Construction_ConsumerModel end +PSE.outputs_(::Producer) = (value=7.0,) +PSE.inputs_(::Consumer) = (input=Default(0.0),) +PSE.run!(::Producer, status, environment, constants, context) = nothing +PSE.run!(::Consumer, status, environment, constants, context) = nothing + +@testset "resolved input aliases still validate their declared defaults" begin + converted = Pair{Symbol,Any}[] + transform(variable, value) = begin + push!(converted, variable => value) + variable === :input ? value + 1000 : value + end + model = CompositeModel( + Object(:source; status=Status(value=7.0)), + Object(:reader; status=Status()); + applications=( + ModelSpec(Producer(); name=:producer, on=One(id=:source)), + ModelSpec(Consumer(); name=:consumer, on=One(id=:reader), + inputs=(input=One(SceneScope(); id=:source, application=:producer, var=:value),)), + ), environment=(duration=Hour(1),), status_transform=transform) + empty!(converted) + run!(model; steps=0, outputs=:none) + @test converted == [:input => 0.0] + @test model_status(model, :reader).input == 7.0 + @test PSE.refvalue(model_status(model, :reader), :input) === + PSE.refvalue(model_status(model, :source), :value) + @test haskey(model.status_conversion_records, + (:model_input_default, :consumer, ObjectId(:reader), :input)) +end + +PSE.@process "status_construction_transaction" verbose=false +struct TransactionDefault{T} <: AbstractStatus_Construction_TransactionModel + initial::T +end +PSE.outputs_(model::TransactionDefault) = (pending=model.initial,) +PSE.run!(::TransactionDefault, status, environment, constants, context) = nothing + +@testset "conversion failure leaves every staged object unchanged" begin + converted = Float64[] + transform(variable, value) = begin + if variable === :pending + push!(converted, value) + value == 2.0 && error("intentional later-object conversion failure") + end + value + end + model = CompositeModel( + Object(:first; status=Status(keep=11.0)), + Object(:second; status=Status(keep=12.0)); + applications=( + ModelSpec(TransactionDefault(1.0); name=:first_default, on=One(id=:first)), + ModelSpec(TransactionDefault(2.0); name=:second_default, on=One(id=:second)), + ), environment=(duration=Hour(1),), status_transform=transform) + first = model_status(model, :first) + second = model_status(model, :second) + records = copy(model.status_conversion_records) + @test_throws ErrorException run!(model; steps=0, outputs=:none) + @test converted == [1.0, 2.0] + @test model_status(model, :first) === first + @test model_status(model, :second) === second + @test propertynames(first) == propertynames(second) == (:keep,) + @test first.keep == 11.0 + @test second.keep == 12.0 + @test model.status_conversion_records == records +end + +PSE.@process "status_construction_distributed" verbose=false +struct DistributedDefaults{T} <: AbstractStatus_Construction_DistributedModel + initial::T +end +PSE.outputs_(model::DistributedDefaults) = (flow=Distributed(Default(model.initial[])),) +PSE.run!(::DistributedDefaults, status, environment, constants, context) = nothing + +@testset "shared layouts retain fresh effective override defaults" begin + initial = Ref([1.0]) + overridden = Ref([2.0]) + template = CompositeModelTemplate(( + ModelSpec(DistributedDefaults(initial); name=:writer, on=Many(scale=:Plant), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree())),)), + )) + model = CompositeModel( + ObjectInstance(:left, template; root=Object(:left_root; scale=:Plant), + objects=(Object(:left_leaf; scale=:Leaf, parent=:left_root),)), + ObjectInstance(:right, template; root=Object(:right_root; scale=:Plant), + objects=(Object(:right_leaf; scale=:Leaf, parent=:right_root),), + overrides=(writer=DistributedDefaults(overridden),)); + environment=(duration=Hour(1),), type_promotion=Dict(Float64 => Float32)) + simulation = run!(model; steps=0, outputs=:none) + @test model_status(model, :left_leaf).flow == Float32[1] + @test model_status(model, :right_leaf).flow == Float32[2] + initial[][1] = 3.0 + overridden[][1] = 4.0 + register_object!(model, Object(:left_new; scale=:Leaf, parent=:left_root)) + register_object!(model, Object(:right_new; scale=:Leaf, parent=:right_root)) + continue!(simulation; steps=1) + @test model_status(model, :left_new).flow == Float32[3] + @test model_status(model, :right_new).flow == Float32[4] + @test model_status(model, :left_leaf).flow == Float32[1] + @test model_status(model, :right_leaf).flow == Float32[2] + @test all(isbits, values(model.registry.objects.layout_cache)) +end + +end From 6db3d2f24dd08a97e85e6e353ee170ee6c50b060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 14:44:15 +0100 Subject: [PATCH 004/324] Prepare shared input recipes and preserve canonical status ownership Resolve input routes through one prepared recipe for initial objects and newborns, preserve typed identities and live references, and reuse cached output declarations. Avoid reboxing open-family statuses and suppress unused inferred constructors for Julia 1.10. --- src/composite_model/compilation.jl | 282 +++++++++++---------- src/composite_model/execution_cohorts.jl | 4 + src/composite_model/object_families.jl | 11 +- src/composite_model/runtime_outputs.jl | 2 +- src/visualization/model_graph_view.jl | 4 +- test/runtests.jl | 1 + test/test-compilation-metadata.jl | 25 +- test/test-model-adaptive-selectors.jl | 28 +- test/test-model-input-recipes.jl | 231 +++++++++++++++++ test/test-model-previous-timestep-views.jl | 15 +- test/test-object-families.jl | 45 ++++ 11 files changed, 495 insertions(+), 153 deletions(-) create mode 100644 test/test-model-input-recipes.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 311c9d70a..495a52008 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -48,8 +48,15 @@ end Base.propertynames(application::CompiledModelApplication) = (:plan, :target_ids, propertynames(application.plan)...) -"""Immutable authored input declaration for one application.""" -struct CompiledModelInputPlan{SEL,M,OA,PSA,W} +struct InputRouteTag{INPUT,SOURCE,FROM_STATUS} end + +_input_route_input(::InputRouteTag{INPUT}) where {INPUT} = INPUT +_input_route_source(::InputRouteTag{INPUT,SOURCE}) where {INPUT,SOURCE} = Val(SOURCE) +_input_route_from_status(::InputRouteTag{INPUT,SOURCE,FROM_STATUS}) where {INPUT,SOURCE,FROM_STATUS} = FROM_STATUS + +"""Immutable authored input declaration and reference-access recipe.""" +struct CompiledModelInputPlan{TAG,SEL,M,OA,PSA,W} + route::TAG slot::Int application_slot::Int application_id::Symbol @@ -67,6 +74,54 @@ struct CompiledModelInputPlan{SEL,M,OA,PSA,W} window::W end +"""Prepared application input order and query sharing; no live object state.""" +struct CompiledApplicationInputRecipe{E,G,Q} + explicit::E + inferred::G + query_slots::Q + query_count::Int +end + +function _input_query_key(plan::CompiledModelInputPlan) + matcher = plan.matcher + return ( + plan.multiplicity, + matcher.scope, matcher.relation, matcher.scale, matcher.kind, + matcher.species, matcher.id, matcher.defaults_to_context, + ) +end + +function _compiled_application_input_recipe(plans) + explicit = Tuple(plan for plan in plans if plan.origin != :inferred_same_object) + inferred_names = Symbol[] + inferred = Dict{Symbol,Vector{CompiledModelInputPlan}}() + for plan in plans + plan.origin == :inferred_same_object || continue + if !haskey(inferred, plan.input) + push!(inferred_names, plan.input) + inferred[plan.input] = CompiledModelInputPlan[] + end + push!(inferred[plan.input], plan) + end + groups = Tuple(Tuple(inferred[name]) for name in inferred_names) + keys = map(_input_query_key, explicit) + counts = Dict{Any,Int}() + for key in keys + counts[key] = get(counts, key, 0) + 1 + end + shared_slots = Dict{Any,Int}() + query_slots = map(keys) do key + counts[key] > 1 || return 0 + get!(shared_slots, key) do + length(shared_slots) + 1 + end + end + return CompiledApplicationInputRecipe(explicit, groups, query_slots, length(shared_slots)) +end + +_compiled_application_input_recipes(plans_by_application) = + map(_compiled_application_input_recipe, plans_by_application) + """Immutable authored hard-call declaration for one application.""" struct CompiledModelCallPlan{NAME,MODE,SEL,M,PCA} slot::Int @@ -576,12 +631,13 @@ end Immutable application, dependency-declaration, and timeline metadata shared by every lifecycle refresh of a compiled scenario. """ -struct CompiledScenarioPlan{AP,AI,ATI,IP,IPI,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL} +struct CompiledScenarioPlan{AP,AI,ATI,IP,IPI,IR,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL} applications::AP applications_by_id::AI application_target_candidates::ATI input_plans::IP input_plans_by_application::IPI + input_recipes_by_application::IR call_plans::CP call_plans_by_application::CPI distributed_output_plans::DOP @@ -1144,12 +1200,14 @@ function _compiled_scenario_plan( application_order, manual_application_ids, ) + input_plans_by_application = _plans_by_application(applications, input_plans) return CompiledScenarioPlan( application_plans, application_plans_by_id, _application_target_candidate_index(model, application_plans), Tuple(input_plans), - _plans_by_application(applications, input_plans), + input_plans_by_application, + _compiled_application_input_recipes(input_plans_by_application), Tuple(call_plans), _plans_by_application(applications, call_plans), distributed_output_plans, @@ -1166,10 +1224,10 @@ function _compiled_scenario_plan( ) end -struct CompiledModelInputBinding{PL,P,C} +struct CompiledModelInputBinding{PL,P,C,I<:ObjectId,SI<:AbstractVector{<:ObjectId}} plan::PL - consumer_id::ObjectId - source_ids::Vector{ObjectId} + consumer_id::I + source_ids::SI source_application_ids::Vector{Symbol} policy::P carrier_hint::Symbol @@ -1892,7 +1950,7 @@ function _compile_scene( model, applications, scenario_plan.manual_application_ids, - scenario_plan.input_plans_by_application, + scenario_plan.input_recipes_by_application, distributed_outputs, ) many_input_binding_cache = @@ -2147,12 +2205,12 @@ function _insert_sorted_object_ids!(ids, added_ids) return ids end -Base.@nospecializeinfer function _compile_added_consumer_bindings!( +function _compile_added_consumer_bindings!( bindings, model, application, consumer_id, - input_plans, + recipe::CompiledApplicationInputRecipe, manual_application_ids, applications_by_object, applications_by_id, @@ -2160,88 +2218,50 @@ Base.@nospecializeinfer function _compile_added_consumer_bindings!( many_binding_cache=nothing, performance=nothing, ) - # Cold assembly must not specialize on each application × input-plan tuple. - @nospecialize application input_plans - # One consumer's inputs often select the same objects for different - # variables/producers. Keep this cache local to this invocation so neither - # scene identity nor lifecycle invalidation needs persistent cache state. - share_object_queries = count( - plan -> plan.origin != :inferred_same_object, - input_plans, - ) > 1 - object_query_cache = share_object_queries ? Dict{Any,Vector{ObjectId}}() : nothing - for plan in input_plans - plan.origin == :inferred_same_object && continue + query_cache = _input_query_cache(model.registry.objects, recipe.query_count) + foreach(recipe.explicit, recipe.query_slots) do plan, query_slot if !isnothing(many_binding_cache) shared_binding = _shared_many_input_binding( - many_binding_cache, - model, - plan, - consumer_id, + many_binding_cache, model, plan, consumer_id, ) if !isnothing(shared_binding) push!(bindings, shared_binding) - _runtime_performance_count!( - performance, - :many_input_binding_precompile_reuses, - ) - continue + _runtime_performance_count!(performance, :many_input_binding_precompile_reuses) + return nothing end end - _push_model_input_binding!( - bindings, - model, - application, - consumer_id, - plan, - applications_by_object, - applications_by_id, - nothing, - distributed_outputs, - ; object_query_cache, + _resolve_materialize_input_route!( + bindings, model, application, consumer_id, plan, + applications_by_object, applications_by_id, nothing, distributed_outputs; + query_cache, query_slot, ) end application.id in manual_application_ids && return bindings - processed_inputs = Set{Symbol}() - for plan in input_plans - plan.origin == :inferred_same_object || continue - plan.input in processed_inputs && continue - push!(processed_inputs, plan.input) + foreach(recipe.inferred) do group + plan = first(group) matches = CompiledModelInputPlan[ - candidate for candidate in input_plans - if candidate.origin == :inferred_same_object && - candidate.input == plan.input && - _application_writes_object_variable( - distributed_outputs, - applications_by_id[candidate.application], - consumer_id, - candidate.source_var, - ) + candidate for candidate in group + if _application_writes_object_variable( + distributed_outputs, + applications_by_id[candidate.application], + consumer_id, + candidate.source_var, + ) ] matches = _final_inferred_output_plans( - distributed_outputs, - consumer_id, - plan.source_var, - matches, + distributed_outputs, consumer_id, plan.source_var, matches, ) - isempty(matches) && continue + isempty(matches) && return nothing if length(matches) > 1 error( - "Input `$(plan.input)` on application `$(application.id)` for object `$(consumer_id.value)` ", - "has ambiguous same-object producers: `$([match.application for match in matches])`. ", + "Input `$(plan.input)` on application `$(application.id)` for object `$(consumer_id.value)` " * + "has ambiguous same-object producers: `$([match.application for match in matches])`. " * "Add `inputs=(:$(plan.input) => One(...),)` to disambiguate." ) end - _push_model_input_binding!( - bindings, - model, - application, - consumer_id, - only(matches), - applications_by_object, - applications_by_id, - ObjectId[consumer_id], - distributed_outputs, + _resolve_materialize_input_route!( + bindings, model, application, consumer_id, only(matches), + applications_by_object, applications_by_id, [consumer_id], distributed_outputs, ) end return bindings @@ -2571,7 +2591,7 @@ function _append_added_many_sources!( performance, ) && return true - new_carrier = _input_carrier(model, binding.selector, new_source_ids, binding.source_var) + new_carrier = _input_carrier(model, binding.selector, new_source_ids, _input_route_source(binding.plan.route)) isnothing(new_carrier) && return false existing_refs = parent(binding.carrier) new_refs = parent(new_carrier) @@ -3836,7 +3856,7 @@ function _extend_compiled_scene( end application = applications_by_id[binding.application_id] replacement = CompiledModelInputBinding[] - _push_model_input_binding!( + _resolve_materialize_input_route!( replacement, model, application, @@ -3884,7 +3904,7 @@ function _extend_compiled_scene( application, consumer_id, _application_plans( - compiled.scenario_plan.input_plans_by_application, + compiled.scenario_plan.input_recipes_by_application, application.slot, ), manual_application_ids, @@ -5132,27 +5152,36 @@ function _dependency_object_ids( ) end -function _cached_dependency_object_ids( - cache, - model::CompositeModel, - selector::AbstractObjectMultiplicity, - matcher::CompiledSelectorMatcher, - context::ObjectId, -) - isnothing(cache) && - return _dependency_object_ids(model, selector, matcher, context) - key = ( - multiplicity(selector), - matcher.scope, matcher.relation, matcher.scale, matcher.kind, - matcher.species, matcher.id, matcher.defaults_to_context, - ) - cached_ids = get(cache, key, nothing) - isnothing(cached_ids) || return copy(cached_ids) - ids = _dependency_object_ids(model, selector, matcher, context) - # Writer filtering and lifecycle carriers own mutable vectors. The cache - # retains an unfiltered snapshot and never lends it to a binding. - cache[key] = copy(ids) - return ids +_input_binding_source_ids(::ObjectFamilyStore, source_ids) = source_ids + +function _input_binding_source_ids(::ObjectFamilyStore{I,<:ClosedObjectFamilyCatalog}, source_ids) where {I<:ObjectId} + source_ids isa Vector{I} && return source_ids + narrowed = Vector{I}(undef, length(source_ids)) + for index in eachindex(source_ids) + source_id = source_ids[index] + source_id isa I || throw(ArgumentError("Input source identity is outside the prepared object schema.")) + narrowed[index] = source_id::I + end + return narrowed +end + +function _input_query_cache(store::ObjectFamilyStore{I}, count::Int) where {I} + iszero(count) && return nothing + return fill!(Vector{Union{Nothing,Vector{I}}}(undef, count), nothing) +end + +function _input_route_source_ids(cache, query_slot, model, plan, consumer_id) + if !isnothing(cache) && !iszero(query_slot) + cached_ids = cache[query_slot] + isnothing(cached_ids) || return copy(cached_ids) + end + source_ids = _input_binding_source_ids(model.registry.objects, + _dependency_object_ids(model, plan.selector, plan.matcher, consumer_id)) + # Each binding still owns mutable IDs; cached queries remain unfiltered. + if !isnothing(cache) && !iszero(query_slot) + cache[query_slot] = copy(source_ids) + end + return source_ids end function _carrier_hint(selector::AbstractObjectMultiplicity, policy, window) @@ -5162,18 +5191,21 @@ function _carrier_hint(selector::AbstractObjectMultiplicity, policy, window) return :shared_ref end -function _status_ref_or_nothing(status, var::Symbol) +_input_reference_name(variable::Symbol) = variable +_input_reference_name(::Val{VARIABLE}) where {VARIABLE} = VARIABLE + +function _status_ref_or_nothing(status::S, variable) where {S} status isa Status || return nothing - var in propertynames(status) || return nothing - return refvalue(status, var) + name = _input_reference_name(variable) + name in propertynames(status) || return nothing + return refvalue(status, name) end -function _input_carrier(model::CompositeModel, selector::AbstractObjectMultiplicity, source_ids::Vector{ObjectId}, source_var::Symbol) +function _input_carrier(model::CompositeModel, selector::AbstractObjectMultiplicity, source_ids::AbstractVector{<:ObjectId}, source_var) refs = Base.RefValue[] selector isa Many && sizehint!(refs, length(source_ids) + 1) for source_id in source_ids - object = _model_object(model, source_id) - source_ref = _status_ref_or_nothing(object.status, source_var) + source_ref = _status_ref_or_nothing(model_status(model, source_id), source_var) isnothing(source_ref) && return nothing push!(refs, source_ref) end @@ -7145,7 +7177,9 @@ Base.@nospecializeinfer function _compiled_model_input_plan( "`PreviousTimeStep(:$(input))`." ) end + route = InputRouteTag{input,source_var,_selector_from_status(selector)}() return CompiledModelInputPlan( + route, length(plans) + 1, application.plan.slot, application.id, @@ -7439,14 +7473,13 @@ function _compile_model_input_bindings( model::CompositeModel, applications, manual_application_ids=Set{Symbol}(), - plans_by_application=nothing, + input_recipes_by_application=nothing, distributed_outputs=NoCompiledDistributedOutputs(), ) - if isnothing(plans_by_application) - plans_by_application = _plans_by_application( - applications, - _compile_model_input_plans(model, applications), - ) + if isnothing(input_recipes_by_application) + plans = _compile_model_input_plans(model, applications) + input_recipes_by_application = _compiled_application_input_recipes( + _plans_by_application(applications, plans)) end bindings = CompiledModelInputBinding[] by_object = _applications_by_object(applications) @@ -7458,7 +7491,7 @@ function _compile_model_input_bindings( model, application, consumer_id, - _application_plans(plans_by_application, application.slot), + _application_plans(input_recipes_by_application, application.slot), manual_application_ids, by_object, by_id, @@ -7469,7 +7502,7 @@ function _compile_model_input_bindings( return bindings end -Base.@nospecializeinfer function _push_model_input_binding!( +function _resolve_materialize_input_route!( bindings, model::CompositeModel, application::CompiledModelApplication, @@ -7479,22 +7512,17 @@ Base.@nospecializeinfer function _push_model_input_binding!( applications_by_id, source_ids_override=nothing, distributed_outputs=NoCompiledDistributedOutputs(), - ; object_query_cache=nothing, + ; query_cache=nothing, query_slot::Int=0, ) - @nospecialize application plan - input_sym = plan.input + input_sym = _input_route_input(plan.route) selector = plan.selector - source_var = plan.source_var + source_var_tag = _input_route_source(plan.route) + source_var = _input_reference_name(source_var_tag) process_filter = plan.process application_filter = plan.application source_ids = isnothing(source_ids_override) ? - _cached_dependency_object_ids( - object_query_cache, - model, - selector, - plan.matcher, - consumer_id, - ) : source_ids_override + _input_route_source_ids(query_cache, query_slot, model, plan, consumer_id) : + _input_binding_source_ids(model.registry.objects, source_ids_override) _filter_many_input_sources_by_writer!( source_ids, selector, @@ -7506,7 +7534,7 @@ Base.@nospecializeinfer function _push_model_input_binding!( applications_by_object, ) selector isa Many && sizehint!(source_ids, length(source_ids) + 1) - source_application_ids = if _selector_from_status(selector) + source_application_ids = if _input_route_from_status(plan.route) Symbol[] else _matching_input_source_applications( @@ -7569,7 +7597,7 @@ Base.@nospecializeinfer function _push_model_input_binding!( if selector isa OptionalOne && (!isnothing(process_filter) || !isnothing(application_filter)) && isempty(source_application_ids) - source_ids = ObjectId[] + source_ids = empty(source_ids) end policy = _model_selector_policy(selector, applications_by_id, source_application_ids, source_var) if policy isa PreviousTimeStep @@ -7601,7 +7629,7 @@ Base.@nospecializeinfer function _push_model_input_binding!( applications_by_id, ) else - _input_carrier(model, selector, source_ids, source_var) + _input_carrier(model, selector, source_ids, source_var_tag) end carrier_hint = if isempty(source_ids) && selector isa OptionalOne :optional_default @@ -7722,7 +7750,7 @@ function _matches_input_source_writer( local_writer = any(get(applications_by_object, source_id, ())) do application isnothing(process_filter) || application.process == process_filter || return false isnothing(application_filter) || application.id == application_filter || return false - return haskey(_local_output_schema(application.spec), source_var) + return source_var in _model_output_names(application) end local_writer && return true return _has_matching_distributed_input_writer( @@ -7768,7 +7796,7 @@ function _validate_model_input_source!( consumer_id::ObjectId, input_sym::Symbol, source_var::Symbol, - source_ids::Vector{ObjectId}, + source_ids::AbstractVector{<:ObjectId}, carrier, carrier_hint::Symbol, ) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 332556ee2..2ffff5656 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -5,6 +5,10 @@ mutable struct ExecutionCohort{T,I<:ObjectId} <: AbstractExecutionCohort application_id::Symbol rows::Vector{Union{Nothing,T}} indices::Dict{I,Int} + + ExecutionCohort{T,I}(owner, application_id::Symbol, rows::Vector{Union{Nothing,T}}, + indices::Dict{I,Int}) where {T,I<:ObjectId} = + new{T,I}(owner, application_id, rows, indices) end struct ExecutionCohortLocation diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 897492b0e..eec0af20b 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -7,6 +7,9 @@ end mutable struct ObjectFamily{I<:ObjectId,S} <: AbstractObjectFamily rows::Vector{Union{Nothing,ObjectFamilyRow{I,S}}} + + ObjectFamily{I,S}(rows::Vector{Union{Nothing,ObjectFamilyRow{I,S}}}) where {I<:ObjectId,S} = + new{I,S}(rows) end struct ObjectFamilyLocation @@ -80,8 +83,12 @@ end return :(throw(ArgumentError("The object identity/status schema is outside the prepared family catalog."))) end -function _object_family_status_at(catalog::OpenObjectFamilyCatalog, location::ObjectFamilyLocation) - return _object_family_status_at(catalog.families[location.family], location.row) +function _object_family_status_at(::OpenObjectFamilyCatalog, location::ObjectFamilyLocation) + # The registered facade owns the existing boxed Status; family rows retain + # its concrete reference payload. Canonical writes update both together. + # Reuse that box across this open dispatch boundary instead of reboxing the + # immutable Status. No scientific values or reference carriers are copied. + return getfield(location.object, :status) end @inline function _object_family_status_at(family::ObjectFamily{I,S}, row::Int) where {I,S} diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 114879647..670044ebf 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6044,7 +6044,7 @@ function _prepare_targeted_newborn_targets( application, object_id, _application_plans( - compiled.scenario_plan.input_plans_by_application, + compiled.scenario_plan.input_recipes_by_application, application.slot, ), targeted_runtime.manual_application_ids, diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 30f4511b7..b6652867b 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -471,7 +471,9 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) model, applications, manual_application_ids, - _plans_by_application(applications, input_plans), + _compiled_application_input_recipes( + _plans_by_application(applications, input_plans), + ), distributed_outputs, ) end diff --git a/test/runtests.jl b/test/runtests.jl index 471668c1a..653f47887 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -80,6 +80,7 @@ else @testset "Reusable scenario plans" begin include("test-model-prepared-scenario.jl") include("test-compilation-metadata.jl") + include("test-model-input-recipes.jl") end @testset "Isolated model diagnostics" begin diff --git a/test/test-compilation-metadata.jl b/test/test-compilation-metadata.jl index b7621f843..f9b015e60 100644 --- a/test/test-compilation-metadata.jl +++ b/test/test-compilation-metadata.jl @@ -29,6 +29,12 @@ PSE.run!(::PortProbe, status, environment, constants, context) = nothing @test !PSE._application_writes_object_variable( PSE.NoCompiledDistributedOutputs(), application, ObjectId(:missing), :value) @test PSE._model_canonical_output_names(application) === (:value,) + for variable in (:value, :scratch) + @test PSE._matches_input_source_writer(ObjectId(:leaf), variable, + nothing, :probe, simulation.compiled.applications_by_id, + simulation.compiled.distributed_outputs, + simulation.compiled.applications_by_object) + end end @test declarations[] == prepared_count end @@ -38,22 +44,23 @@ end Object(:plant; scale=:Plant), Object(:leaf_a; scale=:Leaf, parent=:plant), Object(:leaf_b; scale=:Leaf, parent=:plant)) - cache = Dict{Any,Vector{ObjectId}}() + cache = PSE._input_query_cache(model.registry.objects, 2) point = One(Ancestor(scale=:Plant); scale=:Plant) - matcher = PSE._compile_selector_matcher(model, point) - first_ids = PSE._cached_dependency_object_ids(cache, model, point, matcher, ObjectId(:leaf_a)) + plan = (selector=point, matcher=PSE._compile_selector_matcher(model, point)) + first_ids = PSE._input_route_source_ids(cache, 1, model, plan, ObjectId(:leaf_a)) @test first_ids == [ObjectId(:plant)] empty!(first_ids) - next_ids = PSE._cached_dependency_object_ids(cache, model, point, matcher, ObjectId(:leaf_a)) + next_ids = PSE._input_route_source_ids(cache, 1, model, plan, ObjectId(:leaf_a)) @test next_ids == [ObjectId(:plant)] - @test next_ids !== only(values(cache)) + @test next_ids !== cache[1] many = Many(SceneScope(); scale=:Leaf) - ids = PSE._cached_dependency_object_ids(cache, model, many, - PSE._compile_selector_matcher(model, many), ObjectId(:plant)) + many_plan = (selector=many, matcher=PSE._compile_selector_matcher(model, many)) + ids = PSE._input_route_source_ids(cache, 2, model, many_plan, ObjectId(:plant)) @test ids == [ObjectId(:leaf_a), ObjectId(:leaf_b)] for selector in (One(SceneScope(); scale=:Leaf), OptionalOne(SceneScope(); scale=:Leaf)) - @test_throws Exception PSE._cached_dependency_object_ids(cache, model, selector, - PSE._compile_selector_matcher(model, selector), ObjectId(:plant)) + invalid_plan = (selector=selector, matcher=PSE._compile_selector_matcher(model, selector)) + @test_throws Exception PSE._input_route_source_ids(nothing, 0, model, + invalid_plan, ObjectId(:plant)) end end diff --git a/test/test-model-adaptive-selectors.jl b/test/test-model-adaptive-selectors.jl index 952f5243d..659b73f44 100644 --- a/test/test-model-adaptive-selectors.jl +++ b/test/test-model-adaptive-selectors.jl @@ -626,23 +626,29 @@ end # The cache is deliberately scoped to one consumer assembly. A cached # unfiltered result must remain owned separately from every returned # vector, because writer filtering mutates those returned vectors. - cache = Dict{Any,Vector{ObjectId}}() - selectors = (bindings[:active_values].selector, bindings[:dormant_values].selector, - bindings[:supplied_values].selector) + application = simulation.compiled.applications_by_id[:partition] + recipe = PlantSimEngine._application_plans( + simulation.compiled.scenario_plan.input_recipes_by_application, application.slot) + cache = PlantSimEngine._input_query_cache(model.registry.objects, recipe.query_count) + routes = Dict(plan.input => (plan, slot) for (plan, slot) in + zip(recipe.explicit, recipe.query_slots)) expected = adaptive_reference_ids(model; root=:plant, scale=:Leaf) - first_ids = PlantSimEngine._cached_dependency_object_ids(cache, model, - selectors[1], PlantSimEngine._compile_selector_matcher(model, selectors[1]), ObjectId(:plant)) + first_plan, first_slot = routes[:active_values] + first_ids = PlantSimEngine._input_route_source_ids(cache, first_slot, + model, first_plan, ObjectId(:plant)) @test first_ids == expected empty!(first_ids) - second_ids = PlantSimEngine._cached_dependency_object_ids(cache, model, - selectors[2], PlantSimEngine._compile_selector_matcher(model, selectors[2]), ObjectId(:plant)) + second_plan, second_slot = routes[:dormant_values] + second_ids = PlantSimEngine._input_route_source_ids(cache, second_slot, + model, second_plan, ObjectId(:plant)) @test second_ids == expected pop!(second_ids) - third_ids = PlantSimEngine._cached_dependency_object_ids(cache, model, - selectors[3], PlantSimEngine._compile_selector_matcher(model, selectors[3]), ObjectId(:plant)) + third_plan, third_slot = routes[:supplied_values] + third_ids = PlantSimEngine._input_route_source_ids(cache, third_slot, + model, third_plan, ObjectId(:plant)) @test third_ids == expected @test length(cache) == 1 - @test only(values(cache)) == expected - @test only(values(cache)) !== third_ids + @test only(cache) == expected + @test only(cache) !== third_ids end end diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl new file mode 100644 index 000000000..635abb26e --- /dev/null +++ b/test/test-model-input-recipes.jl @@ -0,0 +1,231 @@ +module SharedInputRecipeChecks + +using Dates, PlantSimEngine, Test +using PlantSimEngine.Diagnostics +const PSE = PlantSimEngine + +PSE.@process "input_recipe_writer" verbose=false +PSE.@process "input_recipe_pair_reader" verbose=false +PSE.@process "input_recipe_aggregate" verbose=false +PSE.@process "input_recipe_empty" verbose=false + +struct Writer{T,P} <: AbstractInput_Recipe_WriterModel + value::T + policy::P +end +Writer(value) = Writer(value, nothing) +PSE.inputs_(::Writer) = NamedTuple() +PSE.outputs_(::Writer{T}) where {T} = (x=zero(T), y=zero(T)) +PSE.output_policy(model::Writer) = isnothing(model.policy) ? NamedTuple() : + (x=model.policy[], y=model.policy[]) +function PSE.run!(model::Writer, status, environment, constants, context) + status.x = model.value + status.y = 2 * model.value + return nothing +end + +struct PairReader{T} <: AbstractInput_Recipe_Pair_ReaderModel end +PSE.inputs_(::PairReader{T}) where {T} = (left=Required(T), right=Required(T)) +PSE.outputs_(::PairReader{T}) where {T} = (total=zero(T),) +function PSE.run!(::PairReader, status, environment, constants, context) + status.total = status.left + status.right + return nothing +end + +struct InferredReader <: AbstractInput_Recipe_Pair_ReaderModel end +PSE.inputs_(::InferredReader) = (x=Required(Float32), y=Required(Float32)) +PSE.outputs_(::InferredReader) = (total=0f0,) +function PSE.run!(::InferredReader, status, environment, constants, context) + status.total = status.x + status.y + return nothing +end + +struct AggregateReader <: AbstractInput_Recipe_AggregateModel end +PSE.inputs_(::AggregateReader) = (values=Default(Float64[]),) +PSE.outputs_(::AggregateReader) = (total=0.0,) +function PSE.run!(::AggregateReader, status, environment, constants, context) + status.total = sum(bound_input(context, :values); init=0.0) + return nothing +end + +struct EmptyModel <: AbstractInput_Recipe_EmptyModel end +PSE.inputs_(::EmptyModel) = NamedTuple() +PSE.outputs_(::EmptyModel) = NamedTuple() +PSE.run!(::EmptyModel, status, environment, constants, context) = nothing + +function pair_model(; policy=nothing) + return CompositeModel(Object(0; scale=:Scene), Object(1; scale=:Leaf), + Object(2; scale=:Reader), Object(3; scale=:Other); + applications=( + ModelSpec(EmptyModel(); name=:empty_a, on=One(id=0)), + ModelSpec(Writer(2f0, policy); name=:source, on=One(id=1)), + ModelSpec(EmptyModel(); name=:empty_b, on=One(id=0)), + ModelSpec(PairReader{Float32}(); name=:reader, on=One(id=2), + inputs=(left=One(SceneScope(); id=1, var=:x), + right=One(SceneScope(); id=1, var=:y))), + ModelSpec(Writer(9f0); name=:other_source, on=One(id=3)), + ), environment=(duration=Hour(1),)) +end + +function binding_signature(bindings) + return [(binding.application_id, binding.input, binding.source_ids, + binding.source_application_ids, typeof(binding.policy), binding.carrier_hint) + for binding in bindings] +end + +function reader_recipe(compiled) + application = compiled.applications_by_id[:reader] + recipe = PSE._application_plans(compiled.scenario_plan.input_recipes_by_application, + application.slot) + return application, recipe +end + +@testset "canonical input recipes preserve named application slots and shared live refs" begin + model = pair_model() + simulation = run!(model; outputs=:all) + compiled = simulation.compiled + scenario = compiled.scenario_plan + application, recipe = reader_recipe(compiled) + @test keys(scenario.input_recipes_by_application) == keys(scenario.input_plans_by_application) + @test keys(scenario.input_recipes_by_application) == + (:empty_a, :source, :empty_b, :reader, :other_source) + @test application.slot == 4 + @test compiled.applications_by_id[:source].slot == 2 + @test compiled.applications_by_id[:other_source].slot == 5 + @test recipe.query_count == 1 + @test recipe.query_slots == (1, 1) + @test isempty(recipe.inferred) + @test Tuple(plan.input for plan in recipe.explicit) == (:left, :right) + @test model_status(model, 2).total === 6f0 + bindings = compiled.input_bindings_by_target[(:reader, ObjectId(2))] + for binding in bindings + source = binding.input === :left ? :x : :y + @test input_carrier(binding) === PSE.refvalue(model_status(model, 1), source) + @test fieldtype(typeof(binding), :consumer_id) === ObjectId{Int} + end + # Exercise the canonical default preparation entry, without supplying the + # prebuilt recipe table. It must derive the same routes and exact carriers. + fresh = PSE._compile_model_input_bindings(model, compiled.applications) + @test binding_signature(fresh) == binding_signature(compiled.input_bindings) + @test all(input_carrier(binding) === PSE.refvalue(model_status(model, 1), + binding.input === :left ? :x : :y) for binding in fresh) +end + +@testset "inferred input groups drive initial and newborn execution in dependency order" begin + model = CompositeModel(Object(1; scale=:Leaf); + applications=( + ModelSpec(InferredReader(); name=:inferred, on=Many(scale=:Leaf)), + ModelSpec(Writer(3f0); name=:source, on=Many(scale=:Leaf)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; outputs=:all) + recipe = simulation.compiled.scenario_plan.input_recipes_by_application.inferred + @test isempty(recipe.explicit) + @test Tuple(first(group).input for group in recipe.inferred) == (:x, :y) + @test model_status(model, 1).total === 9f0 + initial = Status(x=1f0, y=2f0) + x_reference = PSE.refvalue(initial, :x) + y_reference = PSE.refvalue(initial, :y) + register_object!(model, Object(2; scale=:Leaf, status=initial)) + continue!(simulation) + @test model_status(model, 2).total === 9f0 + @test PSE.refvalue(model_status(model, 2), :x) === x_reference + @test PSE.refvalue(model_status(model, 2), :y) === y_reference + bindings = simulation.compiled.input_bindings_by_target[(:inferred, ObjectId(2))] + @test Tuple(binding.input for binding in bindings) == (:x, :y) + @test all(input_carrier(binding) === PSE.refvalue(model_status(model, 2), binding.input) + for binding in bindings) + @test outputs(simulation)[(:inferred, ObjectId(2), :total)] == [(2.0, 9f0)] +end + +@testset "one recipe resolves new source families without copying values or refs" begin + first = Status(x=2f0) + model = CompositeModel(Object(:plant; scale=:Plant), + Object(1; scale=:Leaf, parent=:plant, status=first); + applications=(ModelSpec(AggregateReader(); name=:aggregate, on=One(id=:plant), + inputs=(values=Many(scale=:Leaf, within=Subtree(), var=:x, from_status=true),)),), + environment=(duration=Hour(1),)) + simulation = run!(model; outputs=:all) + recipe = only(values(simulation.compiled.scenario_plan.input_recipes_by_application)) + @test model_status(model, :plant).total === 2.0 + old_binding = only(simulation.compiled.input_bindings) + old_carrier = input_carrier(old_binding) + first_ref = PSE.refvalue(first, :x) + @test only(parent(old_carrier)) === first_ref + + second = Status(x=9.0) + register_object!(model, Object(:new_leaf; scale=:Leaf, parent=:plant, status=second)) + continue!(simulation) + @test only(values(simulation.compiled.scenario_plan.input_recipes_by_application)) === recipe + @test model_status(model, :plant).total === 11.0 + binding = only(simulation.compiled.input_bindings) + carrier = input_carrier(binding) + @test carrier isa PSE.ObjectRefVector + @test Set(binding.source_ids) == Set((ObjectId(1), ObjectId(:new_leaf))) + @test isempty(binding.source_application_ids) + for (id, reference) in zip(binding.source_ids, parent(carrier)) + @test reference === PSE.refvalue(model_status(model, id), :x) + end + @test first_ref[] isa Float32 + @test PSE.refvalue(second, :x)[] isa Float64 + first_ref[] = 7f0 + @test first.x === 7f0 + @test only(old_carrier) === 7f0 + continue!(simulation) + @test model_status(model, :plant).total === 16.0 + @test outputs(simulation)[(:aggregate, ObjectId(:plant), :total)] == + [(1.0, 2.0), (2.0, 11.0), (3.0, 16.0)] +end + +function materialize_reader(model, compiled, application, recipe) + bindings = PSE.CompiledModelInputBinding[] + PSE._compile_added_consumer_bindings!(bindings, model, application, ObjectId(2), + recipe, compiled.scenario_plan.manual_application_ids, + compiled.applications_by_object, compiled.applications_by_id, + compiled.distributed_outputs) + return bindings +end + +function closed_registry_model(model) + previous = model.registry + registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), + previous.by_scale, previous.by_kind, previous.by_species, + previous.ancestor_ids_by_object) + return PSE.CompositeModel(registry, model.applications, model.environment, + model.instances, model.source_adapter, model.status_conversion, + model.status_conversion_records, model.status_source_owners, + model.status_source_identities, model.scenario_plan_cache, + model.binding_cache, model.environment_binding_cache, model.bindings_dirty, + model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, + model.revision, model.environment_revision) +end + +@testset "prepared routes retain fresh producer policies and closed identity types" begin + policy = Ref{PSE.SchedulePolicy}(HoldLast()) + model = pair_model(; policy) + simulation = run!(model; outputs=:none) + compiled = simulation.compiled + application, recipe = reader_recipe(compiled) + first = materialize_reader(model, compiled, application, recipe) + @test all(binding.policy isa HoldLast for binding in first) + policy[] = Aggregate() + next = materialize_reader(model, compiled, application, recipe) + @test all(binding.policy isa Aggregate for binding in next) + @test all(binding.carrier_hint === :temporal_stream for binding in next) + @test all(binding.policy isa HoldLast for binding in first) + @test all(input_carrier(old) === input_carrier(new) for (old, new) in zip(first, next)) + + closed = closed_registry_model(model) + bindings = materialize_reader(closed, compiled, application, recipe) + @test all(binding.source_ids isa Vector{ObjectId{Int}} for binding in bindings) + @test all(binding.consumer_id isa ObjectId{Int} for binding in bindings) + @test all(binding.source_ids == [ObjectId(1)] for binding in bindings) + for binding in bindings + source = binding.input === :left ? :x : :y + @test input_carrier(binding) === PSE.refvalue(model_status(closed, 1), source) + end + @test_throws ArgumentError PSE._input_binding_source_ids(closed.registry.objects, + [ObjectId(:unadmitted_identity_type)]) +end + +end diff --git a/test/test-model-previous-timestep-views.jl b/test/test-model-previous-timestep-views.jl index 67ca36b88..fe90b607b 100644 --- a/test/test-model-previous-timestep-views.jl +++ b/test/test-model-previous-timestep-views.jl @@ -770,6 +770,10 @@ end ) initial_target = only(only(initial_call_view.execution_batches).targets) initial_temporal_inputs = initial_target.input_bindings + initial_source_streams = only(initial_temporal_inputs).source_streams + initial_source_stream = only(initial_source_streams) + initial_private_values = initial_target.status.signals + initial_context = initial_target.context @test final_state(simulation, :scene).signal_total == 1.0 @test final_state(simulation, :scene).source_count == 1 @@ -787,8 +791,15 @@ end refreshed_target = only(only(refreshed_call_view.execution_batches).targets) @test refreshed_call_view !== initial_call_view - @test refreshed_target !== initial_target - @test refreshed_target.input_bindings !== initial_temporal_inputs + # The caller metadata belongs to the refreshed call wrapper. Its callee + # owner and private temporal storage extend without replacing their schema. + @test refreshed_target === initial_target + @test refreshed_target.input_bindings === initial_temporal_inputs + @test refreshed_target.context === initial_context + @test only(refreshed_target.input_bindings).source_streams === initial_source_streams + @test first(initial_source_streams) === initial_source_stream + @test length(initial_source_streams) == 2 + @test refreshed_target.status.signals === initial_private_values @test length(refreshed_target.status.signals) == 2 @test outputs(simulation)[ (:manual_controller, ObjectId(:scene), :signal_total) diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 5c15e3503..f519b0465 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -37,6 +37,51 @@ const PSE = PlantSimEngine @test family.rows[location.row].status === supplied end +@noinline function escape_registered_status!(sink, model, id, count) + for _ in 1:count + sink[] = model_status(model, id) + end + return nothing +end + +registered_status_allocations(sink, model, id, count) = + @allocated escape_registered_status!(sink, model, id, count) + +@testset "escaping open-family lookups reuse the canonical Status box" begin + supplied = Status(value=1f0, items=Float32[2], counter=0, label=:leaf, active=true) + object = Object(:leaf; status=supplied) + model = CompositeModel(object) + sink = Ref{Any}() + for _ in 1:2 + escape_registered_status!(sink, model, object.id, 1000) + registered_status_allocations(sink, model, object.id, 1000) + end + @test registered_status_allocations(sink, model, object.id, 1) == 0 + @test registered_status_allocations(sink, model, object.id, 1000) == 0 + @test sink[] === supplied === object.status + @test all(index -> PSE.refvalues(sink[])[index] === PSE.refvalues(supplied)[index], + eachindex(PSE.refvalues(supplied))) + location = model.registry.objects.locations[object.id] + family = model.registry.objects.catalog.families[location.family] + @test family.rows[location.row].status === sink[] + sink[].items[1] = 3f0 + @test supplied.items === object.status.items + @test supplied.items == Float32[3] + + replacement = Status(value=4.0, items=[5.0], counter=1, label=:updated, active=false) + PSE._replace_model_object_status!(model, object, replacement) + for _ in 1:2 + escape_registered_status!(sink, model, object.id, 1000) + registered_status_allocations(sink, model, object.id, 1000) + end + @test registered_status_allocations(sink, model, object.id, 1000) == 0 + @test sink[] === replacement === object.status + @test PSE.refvalue(sink[], :items) === PSE.refvalue(replacement, :items) + @test object_id(model, replacement) === object.id + @test_throws ArgumentError object_id(model, supplied) + @test supplied.items == Float32[3] +end + @testset "status replacement moves family membership and exclusive ownership" begin original = Status(value=1f0) first = Object(:first; status=original) From 64089f8a324d63208dce885d752a6297da87faad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 16:29:02 +0100 Subject: [PATCH 005/324] Share execution owners across scheduled and newborn model calls Share immutable status headers and environment snapshots through stable owners, remove the alternate newborn payload and kernel branch, and resolve runtime call names through declared targets. Reuse status construction for private views, normalize empty output requests, and fix source imports for local model modules. --- src/composite_model/compilation.jl | 68 ++--- src/composite_model/runtime_outputs.jl | 262 ++++++++---------- src/composite_model/source_compilation.jl | 19 +- src/native_compilation.jl | 2 +- test/runtests.jl | 4 + test/test-model-api-stabilization.jl | 2 +- test/test-model-canonical-cohorts.jl | 10 +- test/test-model-empty-output-requests.jl | 42 +++ ...test-model-environment-binding-identity.jl | 145 ++++++++++ test/test-model-newborn-execution-owner.jl | 102 +++++++ test/test-model-previous-timestep-views.jl | 27 +- test/test-model-runtime-call-names.jl | 237 ++++++++++++++++ 12 files changed, 702 insertions(+), 218 deletions(-) create mode 100644 test/test-model-empty-output-requests.jl create mode 100644 test/test-model-environment-binding-identity.jl create mode 100644 test/test-model-newborn-execution-owner.jl create mode 100644 test/test-model-runtime-call-names.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 495a52008..4927b63fb 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1286,12 +1286,15 @@ struct CompiledTemporalInput{B,S,I,R} reference::R end -struct CompiledModelStatusView{S,C,T,P,BI} - status::S - canonical_status::C - temporal_inputs::T - private_outputs::P - bound_inputs::BI +# One reference-backed owner keeps the immutable Status headers shared by +# compiled bindings and every execution owner. Numerical state remains in the +# existing reference carriers; only those carriers' values may change in place. +mutable struct CompiledModelStatusView{S,C,T,P,BI} + const status::S + const canonical_status::C + const temporal_inputs::T + const private_outputs::P + const bound_inputs::BI end struct CompiledModelCallBinding{P} @@ -1460,18 +1463,20 @@ Base.propertynames(binding::CompiledEnvironmentBinding) = ( propertynames(binding.plan)..., ) -struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C} - model::SC - application_plans::AP - application_plans_by_id::API - bindings::B - by_target::I - positions_by_target::PI - targets_by_object::OI - sample_cache::C - model_revision::Int - environment_revision::Int - applications_identity::UInt +# Share one heap identity across typed simulation fields and context caches. +# Providers and cache contents keep their existing live sampling semantics. +mutable struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C} + const model::SC + const application_plans::AP + const application_plans_by_id::API + const bindings::B + const by_target::I + const positions_by_target::PI + const targets_by_object::OI + const sample_cache::C + const model_revision::Int + const environment_revision::Int + const applications_identity::UInt end # Keep a stable heap identity at dynamic execution-batch boundaries. The @@ -6728,10 +6733,6 @@ Base.@nospecializeinfer function _compile_model_status_view( Ref(_private_temporal_storage(binding, initial)), )) end - temporal_by_name = Dict( - temporal_input.binding.input => temporal_input - for temporal_input in temporal_inputs - ) private_references = Ref[] for name in private_output_names initial, _, _ = _materialize_status_value( @@ -6747,27 +6748,14 @@ Base.@nospecializeinfer function _compile_model_status_view( push!(private_references, Ref(initial)) end private_outputs = NamedTuple{Tuple(private_output_names)}(Tuple(private_references)) - names = collect(Symbol, propertynames(canonical_status)) - for name in private_output_names - name in names || push!(names, name) + recipe = _CanonicalStatusRecipe(canonical_status) + for (name, reference) in pairs(private_outputs) + _status_recipe_set_reference!(recipe, name, reference) end for input in temporal_inputs - name = input.binding.input - name in names || push!(names, name) - end - references = Ref[] - for name in names - temporal_input = get(temporal_by_name, name, nothing) - reference = if !isnothing(temporal_input) - temporal_input.reference - elseif hasproperty(private_outputs, name) - getproperty(private_outputs, name) - else - refvalue(canonical_status, name) - end - push!(references, reference) + _status_recipe_set_reference!(recipe, input.binding.input, input.reference) end - status = Status(NamedTuple{Tuple(names)}(Tuple(references))) + status = _finish_status_recipe(model, recipe) return CompiledModelStatusView( status, canonical_status, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 670044ebf..6afa21afb 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -516,8 +516,8 @@ end @inline function Base.getproperty(target::CallTarget, name::Symbol) name === :model && return getfield(getfield(target, :execution_target), :model) - name === :status && return getfield(getfield(target, :execution_target), :status) - name === :canonical_status && return getfield(getfield(target, :execution_target), :canonical_status) + name === :status && return getfield(getfield(getfield(target, :execution_target), :status_view), :status) + name === :canonical_status && return getfield(getfield(getfield(target, :execution_target), :status_view), :canonical_status) name === :temporal_inputs && return getfield(getfield(target, :execution_target), :input_bindings) name === :output_bindings && return getfield(getfield(target, :execution_target), :output_bindings) name === :bound_inputs && return getfield(getfield(target, :execution_target), :bound_inputs) @@ -1012,11 +1012,10 @@ struct CachedGlobalModelEnvironment{B} binding::B end -mutable struct CompiledExecutionTarget{M,S,CS,IB,BI,OT,OB,CB,EB,RC,I<:ObjectId} +mutable struct CompiledExecutionTarget{M,V<:CompiledModelStatusView,IB,BI,OT,OB,CB,EB,RC,I<:ObjectId} object_id::I model::M - status::S - canonical_status::CS + const status_view::V input_bindings::IB bound_inputs::BI output_targets::OT @@ -1048,6 +1047,30 @@ function _call_bindings_signature(call_bindings) return signature end +# Fully specified payload construction shared by scheduled, manual, and +# pre-barrier newborn execution. Binding resolution and cache ownership stay +# with their callers; this factory neither interns targets nor refreshes time. +function _compiled_execution_target( + object_id::ObjectId, + model, + status_view::CompiledModelStatusView, + input_bindings, + bound_inputs, + output_targets, + output_bindings, + call_bindings, + environment_binding, + context, + call_context_cache::CallContextCache, +) + return CompiledExecutionTarget( + object_id, model, status_view, input_bindings, bound_inputs, + output_targets, output_bindings, call_bindings, + _call_bindings_signature(call_bindings), environment_binding, + context, call_context_cache, + ) +end + mutable struct ExecutionBatchContextState # Scheduled root batches always use the default publication/environment # state. Hard-call batches deliberately bypass this synchronization cache. @@ -2808,9 +2831,9 @@ end publish_outputs::Bool, ) status = isempty(target.input_bindings) ? - target.status : + target.status_view.status : _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, compiled, application, @@ -2877,9 +2900,9 @@ end publish_outputs, ) status = isempty(target.input_bindings) ? - target.status : + target.status_view.status : _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, compiled, application, @@ -3013,9 +3036,9 @@ end end for target in batch.targets status = isempty(target.input_bindings) ? - target.status : + target.status_view.status : _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, compiled, batch.application, @@ -3117,9 +3140,9 @@ function _run_model_execution_batch_profiled!( for target in batch.targets started_at = _runtime_performance_start(performance) status = isempty(target.input_bindings) ? - target.status : + target.status_view.status : _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, compiled, batch.application, @@ -3672,11 +3695,10 @@ function _new_model_execution_target( local_output_bindings..., distributed_output_bindings..., ) - return CompiledExecutionTarget( + return _compiled_execution_target( object_id, model, - status_view.status, - status_view.canonical_status, + status_view, _runtime_model_temporal_inputs( status_view.temporal_inputs, temporal_streams, @@ -3685,7 +3707,6 @@ function _new_model_execution_target( distributed_targets, output_bindings, call_bindings, - _call_bindings_signature(call_bindings), environment_binding, context, CallContextCache(context), @@ -4135,8 +4156,8 @@ function _model_execution_target_change_reason( isnothing(status_view) && return :missing_status_view target.model === _application_model(application, object_id) || return :model - target.status === status_view.status || return :status_view - target.canonical_status === status_view.canonical_status || + target.status_view.status === status_view.status || return :status_view + target.status_view.canonical_status === status_view.canonical_status || return :canonical_status target.bound_inputs === status_view.bound_inputs || return :bound_inputs @@ -4691,7 +4712,7 @@ function explain_execution_plan(plan::CompiledExecutionPlan) cohort_schema=eltype(batch.targets), target_type=eltype(batch.targets), model_type=fieldtype(eltype(batch.targets), :model), - status_type=fieldtype(eltype(batch.targets), :status), + status_type=fieldtype(fieldtype(eltype(batch.targets), :status_view), :status), input_bindings_type=fieldtype(eltype(batch.targets), :input_bindings), call_bindings_type=fieldtype(eltype(batch.targets), :call_bindings), call_capability=isempty(first(batch.targets).call_bindings) ? @@ -5015,58 +5036,28 @@ end return targets end -@inline _find_call_targets(::Tuple{}, ::Val, ::RunContext) = nothing +@inline _with_named_call(operation, ::Tuple{}, name::Symbol, context::RunContext, args...) = + _missing_named_call(context, name) -@inline function _find_call_targets( - calls::Tuple, - ::Val{name}, - context::RunContext, -) where {name} +# The declared call tuple supplies the finite branches. Keep the operation in +# the selected concrete branch without constructing Val from a runtime name. +@inline function _with_named_call(operation, calls::Tuple, name::Symbol, context::RunContext, args...) targets = first(calls) if _compiled_call_name(targets.binding) === name - targets.time == context.time && - targets.publication_allowed == context.publication_allowed && - targets.environment === context.environment && - return targets - return _synchronize_call_targets_slow!(targets, context) + return operation(targets, context, name, args...) end - return _find_call_targets(Base.tail(calls), Val(name), context) + return _with_named_call(operation, Base.tail(calls), name, context, args...) end -@inline _find_manual_call_targets(::Tuple{}, ::Val, ::RunContext) = nothing - -@inline function _find_manual_call_targets( - calls::Tuple, - ::Val{name}, - context::RunContext, -) where {name} - targets = first(calls) - if _compiled_call_name(targets.binding) === name - _compiled_call_mode(targets.binding) === :manual || - _initializer_requires_dedicated_api(context, name) - targets.time == context.time && - targets.publication_allowed == context.publication_allowed && - targets.environment === context.environment && - return targets - return _synchronize_call_targets_slow!(targets, context) - end - return _find_manual_call_targets(Base.tail(calls), Val(name), context) +@inline function _synchronized_named_call(targets, context::RunContext, name::Symbol) + targets.time == context.time && + targets.publication_allowed == context.publication_allowed && + targets.environment === context.environment && return targets + return _synchronize_call_targets_slow!(targets, context) end -Base.@constprop :aggressive function _model_call_targets( - context::RunContext, - name::Symbol, -) - found = _find_call_targets(context.calls, Val(name), context) - if isnothing(found) - available = Symbol[targets.binding.call for targets in context.calls] - error( - "Application `$(context.application.id)` on object ", - "`$(context.object_id.value)` did not declare call `$(name)`. ", - "Declared calls: $(available).", - ) - end - return found +Base.@constprop :aggressive function _model_call_targets(context::RunContext, name::Symbol) + return _with_named_call(_synchronized_named_call, context.calls, name, context) end @noinline function _initializer_requires_dedicated_api(context, name) @@ -5079,20 +5070,15 @@ end ) end -@inline Base.@constprop :aggressive function _manual_call_targets( - context::RunContext, - name::Symbol, -) - found = _find_manual_call_targets(context.calls, Val(name), context) - if isnothing(found) - available = Symbol[targets.binding.call for targets in context.calls] - error( - "Application `$(context.application.id)` on object ", - "`$(context.object_id.value)` did not declare call `$(name)`. ", - "Declared calls: $(available).", - ) +@inline function _selected_call_targets(targets, context::RunContext, name::Symbol, requested_ids) + if isnothing(requested_ids) + _compiled_call_mode(targets.binding) === :manual || + _initializer_requires_dedicated_api(context, name) + return _synchronized_named_call(targets, context, name) end - return found + return _current_topology_call_targets( + _synchronized_named_call(targets, context, name), context, name, requested_ids, + ) end _call_target_matches(targets::CallTargets, application, object_id::ObjectId) = @@ -5548,9 +5534,9 @@ Base.@constprop :aggressive function call_targets( ; objects=nothing, ) - return isnothing(objects) ? - _manual_call_targets(context, name) : - _current_topology_call_targets(context, name, objects) + requested_ids = isnothing(objects) ? nothing : + _call_target_object_ids(runtime_model(context), objects) + return _with_named_call(_selected_call_targets, context.calls, name, context, requested_ids) end @inline function _single_call_model(batches::Tuple{B}) where {B} @@ -5580,7 +5566,7 @@ execution target and remains valid until a lifecycle refresh barrier. ) end -@noinline function _call_model_missing_error(context, name) +@noinline function _missing_named_call(context, name) available = Symbol[targets.binding.call for targets in context.calls] error( "Application `$(context.application.id)` on object ", @@ -5589,26 +5575,16 @@ end ) end -@inline function _call_model( - context::RunContext, - ::Val{name}, -) where {name} - targets = _find_call_targets(context.calls, Val(name), context) - isnothing(targets) && _call_model_missing_error(context, name) +@inline function _selected_call_model(targets, context::RunContext, name::Symbol) + targets = _synchronized_named_call(targets, context, name) _compiled_call_mode(targets.binding) === :manual || _initializer_requires_dedicated_api(context, name) length(targets) == 1 || _call_model_target_count_error(name, targets) - return _single_call_model( - _materialize_call_execution_batches!(targets), - ) + return _single_call_model(_materialize_call_execution_batches!(targets)) end - -@inline Base.@constprop :aggressive function call_model( - context::RunContext, - name::Symbol, -) - return _call_model(context, Val(name)) +@inline Base.@constprop :aggressive function call_model(context::RunContext, name::Symbol) + return _with_named_call(_selected_call_model, context.calls, name, context) end function call_model(context, name::Symbol) @@ -5884,11 +5860,11 @@ function _targeted_new_object_call_targets( context::RunContext, name::Symbol, requested_ids, + cached_targets::CallTargets, ; initializer::Bool=false, ) model = runtime_model(context) - cached_targets = _model_call_targets(context, name) binding = cached_targets.binding expected_mode = initializer ? :initializer : :manual _compiled_call_mode(binding) === expected_mode || error( @@ -6167,17 +6143,12 @@ function _targeted_newborn_call_target( environment_binding, cache::CallContextCache, ) - execution_target = ( - model=model, - status=status_view.status, - canonical_status=status_view.canonical_status, - input_bindings=status_view.temporal_inputs, - output_bindings=outputs, - bound_inputs=status_view.bound_inputs, - output_targets=output_targets, - environment_binding=environment_binding, - # Reaccessing a newborn retains its evaluation execution stamps. - call_context_cache=cache, + # Keep the targeted runtime's cache and partial binding shell. In + # particular, do not intern this owner into the post-barrier cohort store. + execution_target = _compiled_execution_target( + object_id, model, status_view, status_view.temporal_inputs, + status_view.bound_inputs, output_targets, outputs, (), + environment_binding, cache.default, cache, ) return CallTarget( execution_target, context.compiled, environment_bindings, application, @@ -6187,16 +6158,17 @@ function _targeted_newborn_call_target( end function _current_topology_call_targets( + cached_targets::CallTargets, context::RunContext, name::Symbol, - objects, + requested_ids, ) model = runtime_model(context) - requested_ids = _call_target_object_ids(model, objects) targeted = _targeted_new_object_call_targets( context, name, requested_ids, + cached_targets, ) isnothing(targeted) || return targeted compiled = refresh_bindings!(model) @@ -6502,11 +6474,11 @@ end # here instead of boxing model/status/output tuples as dispatch arguments. if frame === nothing _run_call_kernel!( - owner.model, owner.status, environment, context, owner.output_bindings, + owner.model, owner.status_view.status, environment, context, owner.output_bindings, ) else _run_evaluated_call_kernel!( - owner.model, owner.status, environment, context, owner.output_bindings, frame, + owner.model, owner.status_view.status, environment, context, owner.output_bindings, frame, ) end return nothing @@ -6520,7 +6492,7 @@ end ) cache = target.context_cache frame = _record_call_execution!(cache) - status = _materialize_model_inputs!( + _materialize_model_inputs!( target.status, target.temporal_inputs, target.compiled, @@ -6546,22 +6518,9 @@ end target.output_targets, target.temporal_streams, target.output_retention, target.time, target.constants, publication_allowed, environment, ) - if target.execution_target isa CompiledExecutionTarget - # Input materialization above updates this owner's references and - # returns the same Status. Targeted newborns have a distinct payload - # and retain the original dispatch path below. - _run_owned_call_kernel!( - target.execution_target, environment_value, context, frame, - ) - elseif frame === nothing - _run_call_kernel!( - target.model, status, environment_value, context, target.output_bindings, - ) - else - _run_evaluated_call_kernel!( - target.model, status, environment_value, context, target.output_bindings, frame, - ) - end + _run_owned_call_kernel!( + target.execution_target, environment_value, context, frame, + ) finally acquired && (cache.in_use = false) end @@ -6648,7 +6607,7 @@ end cache = target.call_context_cache _record_call_execution!(cache, frame) _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, targets.compiled, application, @@ -6823,21 +6782,19 @@ object, is an error. The application/object pair is reserved before model code runs, so a failed attempt remains marked and cannot be retried in the same lifecycle event after an unknown partial mutation. """ -function run_initializer!( - context::RunContext, - name::Symbol, - object, -) +function run_initializer!(context::RunContext, name::Symbol, object) context.publication_allowed || error( "Initializer `$(name)` cannot run inside a non-publishing hard call. " * "Keep its creator application root-scheduled.", ) + requested_ids = _call_target_object_ids(runtime_model(context), object) + return _with_named_call(_selected_run_initializer!, context.calls, name, context, requested_ids) +end + +function _selected_run_initializer!(cached_targets, context::RunContext, name::Symbol, requested_ids) model = runtime_model(context) - requested_ids = _call_target_object_ids(model, object) targets = _targeted_new_object_call_targets( - context, - name, - requested_ids; + context, name, requested_ids, _synchronized_named_call(cached_targets, context, name); initializer=true, ) target = only(targets) @@ -6905,18 +6862,18 @@ function run_call!( ), ) end - targets = isnothing(objects) ? - call_targets(context, name) : - call_targets(context, name; objects=objects) + requested_ids = isnothing(objects) ? nothing : + _call_target_object_ids(runtime_model(context), objects) + return _with_named_call(_selected_run_call!, context.calls, name, context, + requested_ids, publish, sampled_environment, environment) +end + +@inline function _selected_run_call!(cached_targets, context::RunContext, name::Symbol, + requested_ids, publish, sampled_environment, environment) + targets = _selected_call_targets(cached_targets, context, name, requested_ids) selected_environment = environment isa NoEnvironmentOverride ? - context.environment : - environment - return _run_call_targets!( - targets, - publish, - sampled_environment, - selected_environment, - ) + context.environment : environment + return _run_call_targets!(targets, publish, sampled_environment, selected_environment) end function run_call!( @@ -6935,12 +6892,13 @@ function run_call!( end function _model_output_selection(outputs) - outputs === :all && return (OutputRequest[], true) - outputs === :none && return (OutputRequest[], false) + outputs === :all && return ((), true) + outputs === :none && return ((), false) outputs isa Symbol && error( "Unsupported output selection `$(outputs)`. Use `:all`, `:none`, an `OutputRequest`, or a vector of requests.", ) requests = _normalize_output_requests(outputs) + isempty(requests) && return ((), false) return requests, false end diff --git a/src/composite_model/source_compilation.jl b/src/composite_model/source_compilation.jl index 4aa195172..28ed885fa 100644 --- a/src/composite_model/source_compilation.jl +++ b/src/composite_model/source_compilation.jl @@ -589,6 +589,7 @@ function _compiled_source_module_path(source_module::Module) parent === current && break current = parent end + current === Main && pushfirst!(names, :Main) return join(string.(names), ".") end @@ -944,9 +945,9 @@ function _compiled_source_prepare_target!( shared_environment, ) status = isempty(target.input_bindings) ? - target.status : + target.status_view.status : _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, simulation.compiled, application, @@ -1029,7 +1030,7 @@ function _compiled_source_run_call_target!( ) _record_call_execution!(target.call_context_cache, frame) status = _materialize_model_inputs!( - target.status, + target.status_view.status, target.input_bindings, targets.compiled, application, @@ -1214,12 +1215,16 @@ function _compiled_source_run_initializer!( "Initializer `$(name)` cannot run inside a non-publishing hard call. " * "Keep its creator application root-scheduled.", ) + requested_ids = _call_target_object_ids(runtime_model(context), object) + return _with_named_call(_selected_source_initializer!, context.calls, name, context, + source_id, requested_ids) +end + +function _selected_source_initializer!(cached_targets, context::RunContext, + name::Symbol, source_id::Val, requested_ids) model = runtime_model(context) - requested_ids = _call_target_object_ids(model, object) targets = _targeted_new_object_call_targets( - context, - name, - requested_ids; + context, name, requested_ids, _synchronized_named_call(cached_targets, context, name); initializer=true, ) target = only(targets) diff --git a/src/native_compilation.jl b/src/native_compilation.jl index 138e98eed..c1773e128 100644 --- a/src/native_compilation.jl +++ b/src/native_compilation.jl @@ -61,7 +61,7 @@ function _check_target(application, target) _unsupported(application.id, "temporal input bindings are unsupported") isempty(target.bound_inputs) || _unsupported(application.id, "collection-valued inputs are unsupported") - _has_scalar_status(target.status) || + _has_scalar_status(target.status_view.status) || _unsupported(application.id, "status values must have concrete scalar numeric types") # Validate the same environment row that the canonical batch sampler uses. binding = target.environment_binding diff --git a/test/runtests.jl b/test/runtests.jl index 653f47887..5f99c54a6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -182,6 +182,8 @@ else @testset "Scheduled newborn initializers" begin include("test-model-initializers.jl") + include("test-model-newborn-execution-owner.jl") + include("test-model-runtime-call-names.jl") end @testset "Composite model numerical parity" begin @@ -230,6 +232,7 @@ else @testset "Composite model output boundaries" begin include("test-model-output-boundaries.jl") + include("test-model-empty-output-requests.jl") end @testset "Composite model output datetimes" begin @@ -246,6 +249,7 @@ else @testset "Composite model environment sampling" begin include("test-model-environment-sampling.jl") + include("test-model-environment-binding-identity.jl") end @testset "Composite model temporal reducers" begin diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 915900f9b..31a60a0d6 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -2745,7 +2745,7 @@ end simulation.output_retention, nothing, false, - ) === float32_target.status + ) === float32_target.status_view.status @test float32_target.context.time == Float64(float32_time) end diff --git a/test/test-model-canonical-cohorts.jl b/test/test-model-canonical-cohorts.jl index be0abdf08..ab0194dc3 100644 --- a/test/test-model-canonical-cohorts.jl +++ b/test/test-model-canonical-cohorts.jl @@ -86,7 +86,9 @@ function assert_canonical_storage(simulation) location = PSE.cohort_location(store, batch.application.id, target.object_id) @test location.cohort === view.cohort @test location.row == view.indices[index] - @test target.canonical_status === model_status(simulation.model, target.object_id) + @test target.status_view === simulation.compiled.status_views_by_target[ + (batch.application.id, target.object_id)] + @test target.status_view.canonical_status === model_status(simulation.model, target.object_id) end end return store @@ -118,8 +120,8 @@ end @test override_target.model isa ScaledAccumulator{Float64} @test PSE.cohort_location(store, :plant__accumulate, ObjectId(:leaf_default)).cohort !== PSE.cohort_location(store, :plant__accumulate, ObjectId(:leaf_override)).cohort - @test default_target.canonical_status === default_status - @test override_target.canonical_status === override_status + @test default_target.status_view.canonical_status === default_status + @test override_target.status_view.canonical_status === override_status continue!(simulation; steps=2) @test assert_canonical_storage(simulation) === store @@ -139,7 +141,7 @@ end @test restarted_store !== store @test restarted_target !== default_target @test restarted_target.context !== default_target.context - @test restarted_target.canonical_status === default_status + @test restarted_target.status_view.canonical_status === default_status @test current_step(restarted) == 0 step!(restarted) @test default_status.value === 16.0f0 diff --git a/test/test-model-empty-output-requests.jl b/test/test-model-empty-output-requests.jl new file mode 100644 index 000000000..be7b1be01 --- /dev/null +++ b/test/test-model-empty-output-requests.jl @@ -0,0 +1,42 @@ +module EmptyOutputRequestChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "empty_request_counter" verbose=false +struct Counter <: AbstractEmpty_Request_CounterModel end +PSE.outputs_(::Counter) = (counter=0,) +PSE.run!(::Counter, status, environment, constants, context) = (status.counter += 1; nothing) + +@testset "empty output requests have one concrete schema through growth" begin + for selection in (:none, :all, nothing, OutputRequest[]) + model = CompositeModel(Object(:first; scale=:Leaf); + applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=1, outputs=selection) + @test simulation.output_requests === () + @test isempty(simulation.output_request_matchers) + @test isempty(simulation.output_request_targets) + register_object!(model, Object(:second; scale=:Leaf)) + continue!(simulation) + @test current_step(simulation) == 2 + @test model_status(model, :first).counter == 2 + @test model_status(model, :second).counter == 1 + @test simulation.output_request_model_revision == model.revision + if selection === :all + @test outputs(simulation)[(:counter, ObjectId(:first), :counter)] == [(1.0, 1), (2.0, 2)] + @test outputs(simulation)[(:counter, ObjectId(:second), :counter)] == [(2.0, 1)] + else + @test isempty(outputs(simulation)) + end + end +end + +@testset "requested output selection remains explicit" begin + request = OutputRequest(:Leaf, :counter) + model = CompositeModel(Object(:first; scale=:Leaf); + applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=2, outputs=request) + @test only(simulation.output_requests) === request + @test outputs(simulation)[(:counter, ObjectId(:first), :counter)] == [(1.0, 1), (2.0, 2)] + @test length(collect_outputs(simulation, :counter; sink=nothing)) == 2 + @test_throws ErrorException PSE._model_output_selection(:unsupported) +end +end diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl new file mode 100644 index 000000000..3f5035737 --- /dev/null +++ b/test/test-model-environment-binding-identity.jl @@ -0,0 +1,145 @@ +module EnvironmentBindingsIdentityChecks +using PlantSimEngine +using Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +mutable struct Backend{T} <: EA.AbstractEnvironmentBackend + values::Dict{Symbol,T} + samples::Int +end +mutable struct Trial{T} + values::Dict{Symbol,T} +end +EA.base_step_seconds(::Backend) = 3600.0 +EA.get_nsteps(::Backend) = 8 +EA.environment_variables(::Backend) = Set((:T,)) +EA.bind_environment(::Backend, object::Object, context, config) = + (cell=isnothing(geometry(object)) ? :a : geometry(object).cell,) +function EA.sample(backend::Backend, handle, ::Symbol, time) + backend.samples += 1 + return backend.values[handle.cell] +end +function EA.sample(backend::Backend, handle, trial::Trial, ::Symbol, time) + backend.samples += 1 + return trial.values[handle.cell] +end + +PSE.@process "environment_shell_owner" verbose=false +PSE.@process "environment_shell_leaf" verbose=false +struct Owner{C} <: AbstractEnvironment_Shell_OwnerModel + capture::C +end +PSE.inputs_(::Owner) = NamedTuple() +PSE.outputs_(::Owner) = (visits=0,) +function PSE.run!(model::Owner, status, environment, constants, context) + model.capture[] = context + status.visits += 1 + return nothing +end +struct Leaf{T} <: AbstractEnvironment_Shell_LeafModel + initial::T +end +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(model::Leaf) = (seen=model.initial, calls=0) +PSE.environment_inputs_(model::Leaf) = (T=model.initial,) +function PSE.run!(::Leaf, status, environment, constants, context) + status.seen = environment.T + status.calls += 1 + return nothing +end + +function fixture(::Type{T}) where {T} + capture = Ref{Any}() + backend = Backend(Dict(:a => T(10), :b => T(20)), 0) + model = CompositeModel( + Object(:scene; scale=:Scene), + Object(:scheduled_keep; scale=:Leaf, kind=:scheduled, parent=:scene, geometry=(cell=:a,)), + Object(:scheduled_move; scale=:Leaf, kind=:scheduled, parent=:scene, geometry=(cell=:a,)), + Object(:manual; scale=:Leaf, kind=:manual, parent=:scene, geometry=(cell=:a,)); + applications=( + ModelSpec(Owner(capture); name=:owner, on=One(id=:scene), + calls=(leaves=Many(kind=:manual, within=Subtree(), application=:manual_probe),)), + ModelSpec(Leaf(zero(T)); name=:scheduled_probe, on=Many(kind=:scheduled), + environment=Environment(provider=:shell_probe)), + ModelSpec(Leaf(zero(T)); name=:manual_probe, on=Many(kind=:manual), + environment=Environment(provider=:shell_probe)), + ), environment=backend) + simulation = run!(model; steps=1, outputs=:all) + batch = only(batch for batch in simulation.execution_plan.batches + if batch.application.id == :scheduled_probe) + kept = only(target for target in batch.targets if target.object_id == ObjectId(:scheduled_keep)) + return (; model, simulation, capture, backend, batch, kept) +end + +@testset "clean and dirty environment shells preserve live backend and trial sampling" begin + for T in (Float32, Float64) + data = fixture(T) + original_environment = data.simulation.environment_bindings + original_context = data.kept.context + targets = call_targets(data.capture[], :leaves) + first_target = only(targets) + original_batches = PSE._cached_call_execution_batches(targets) + trial = Trial(Dict(:a => T(30), :b => T(40))) + run_call!(first_target; environment=trial, publish=false) + original_transient = first_target.context_cache.transient + trial.values[:a] = T(31) + run_call!(first_target; environment=trial, publish=false) + @test first_target.status.seen === T(31) + @test first_target.context_cache.transient === original_transient + @test first_target.environment_binding.backend === data.backend + + # A clean public refresh keeps the shell, cached membership, and view. + @test PSE.Advanced.refresh_environment_bindings!(data.model, data.simulation.compiled) === + original_environment + @test only(targets) === first_target + @test PSE._cached_call_execution_batches(targets) === original_batches + + data.backend.values[:a] = T(11) + move_object!(data.model, :scheduled_move, (cell=:b,)) + move_object!(data.model, :manual, (cell=:b,)) + continue!(data.simulation) + current_environment = data.simulation.environment_bindings + @test current_environment !== original_environment + @test current_environment.environment_revision > original_environment.environment_revision + @test current_environment.bindings === original_environment.bindings + @test current_environment.by_target === original_environment.by_target + @test all(binding -> binding.backend === data.backend, + current_environment.bindings) + @test model_status(data.model, :scheduled_keep).seen === T(11) + @test model_status(data.model, :scheduled_move).seen === T(20) + kept = only(target for target in data.batch.targets + if target.object_id == ObjectId(:scheduled_keep)) + @test kept === data.kept + @test kept.context === original_context + @test kept.context.environment_bindings === current_environment + @test data.batch.context_state.environment_bindings === current_environment + + refreshed_targets = call_targets(data.capture[], :leaves) + refreshed_target = only(refreshed_targets) + @test refreshed_targets.environment_bindings === current_environment + @test refreshed_target.environment_binding.backend === data.backend + @test refreshed_target.environment_binding.handle.cell === :b + @test PSE._cached_call_execution_batches(refreshed_targets) !== original_batches + samples = data.backend.samples + run_call!(refreshed_target; environment=trial, publish=false) + @test refreshed_target.status.seen === T(40) + transient = refreshed_target.context_cache.transient + trial.values[:b] = T(41) + run_call!(refreshed_target; environment=trial, publish=false) + @test refreshed_target.status.seen === T(41) + @test refreshed_target.context_cache.transient === transient + @test data.backend.samples == samples + 2 + @test data.backend.values == Dict(:a => T(11), :b => T(20)) + @test PSE.Advanced.refresh_environment_bindings!(data.model, data.simulation.compiled) === + current_environment + @test only(refreshed_targets) === refreshed_target + samples = data.backend.samples + PSE._synchronize_model_execution_batch_contexts!(data.batch, + data.simulation.compiled, current_environment, + data.simulation.temporal_streams, data.simulation.output_retention, + current_step(data.simulation), data.simulation.constants) + @test data.backend.samples == samples + end +end +end diff --git a/test/test-model-newborn-execution-owner.jl b/test/test-model-newborn-execution-owner.jl new file mode 100644 index 000000000..48497d822 --- /dev/null +++ b/test/test-model-newborn-execution-owner.jl @@ -0,0 +1,102 @@ +module CanonicalNewbornExecutionOwnerChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine + +PSE.@process "canonical_newborn_state" verbose=false +PSE.@process "canonical_newborn_creator" verbose=false + +struct Leaf{H,C} <: AbstractCanonical_Newborn_StateModel + hook::H + contexts::C +end +PSE.inputs_(::Leaf) = (driver=Required(Float64),) +PSE.outputs_(::Leaf) = (value=0.0, calls=0) +function PSE.run!(model::Leaf, status, environment, constants, context) + push!(model.contexts, context) + status.calls += 1 + status.value = status.driver + context.time + hook = model.hook[] + if !isnothing(hook) + model.hook[] = nothing + hook() + end + return nothing +end + +struct Creator{C,H} <: AbstractCanonical_Newborn_CreatorModel + capture::C + hook::H +end +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (created=false, value=0.0) +function PSE.run!(model::Creator, status, environment, constants, context) + status.created && return nothing + runtime = runtime_model(context) + born = register_object!(runtime, Object(:born; scale=:Leaf, parent=:scene, + status=Status(driver=2.0, value=0.0, calls=0))) + first = only(call_targets(context, :leaf; objects=born)) + second = only(call_targets(context, :leaf; objects=born)) + binding = PSE._model_call_targets(context, :leaf).binding + location = PSE.cohort_location(context.temporal_streams.cohorts, :newborn_state, + born.id; owner=PSE._execution_call_owner(binding)) + lease_checks = Bool[] + model.hook[] = () -> begin + push!(lease_checks, first.context_cache.in_use) + run_call!(second; publish=false) + push!(lease_checks, first.context_cache.in_use) + end + run_call!(first; publish=true) + model.capture[] = (; first, second, born, lease_checks, + dirty=PSE.bindings_dirty(runtime), prebarrier_location=location) + status.value = first.status.value + status.created = true + return nothing +end + +@testset "newborn calls use canonical owners without changing pre-barrier leases" begin + capture = Ref{Any}() + hook = Ref{Any}(nothing) + contexts = Any[] + model = CompositeModel(Object(:scene; scale=:Scene); + applications=( + ModelSpec(Creator(capture, hook); name=:creator, on=One(id=:scene), + calls=(leaf=Many(scale=:Leaf, within=Subtree(), application=:newborn_state),)), + ModelSpec(Leaf(hook, contexts); name=:newborn_state, on=Many(scale=:Leaf)), + )) + simulation = run!(model; outputs=:all) + data = capture[] + @test data.first.execution_target isa PSE.CompiledExecutionTarget + @test data.second.execution_target isa PSE.CompiledExecutionTarget + @test data.first.execution_target !== data.second.execution_target + @test data.first.status === data.second.status === model_status(model, :born) + @test data.first.execution_target.status_view.status === data.first.status + @test data.first.context_cache === data.second.context_cache + @test data.first.execution_target.context === nothing + @test data.first.context_cache.default === nothing + @test data.first.context_cache.execution_revision == 2 + @test !data.first.context_cache.in_use + @test data.lease_checks == [true, true] + @test length(contexts) == 2 + @test contexts[1] !== contexts[2] + @test data.dirty + @test isnothing(data.prebarrier_location) + @test !PSE.bindings_dirty(model) + @test model_status(model, :scene).value == 3.0 + @test model_status(model, :born).calls == 2 + @test outputs(simulation)[(:newborn_state, ObjectId(:born), :value)] == [(1.0, 3.0)] + @test outputs(simulation)[(:newborn_state, ObjectId(:born), :calls)] == [(1.0, 2)] + + # Retained trial views keep their captured metadata and shared execution + # stamps after the ordinary lifecycle barrier installs current bindings. + run_call!(data.first; publish=false) + @test data.first.time == 1.0 + @test data.first.context_cache.execution_revision == 3 + @test model_status(model, :born).calls == 3 + @test outputs(simulation)[(:newborn_state, ObjectId(:born), :calls)] == [(1.0, 2)] + continue!(simulation) + @test model_status(model, :born).calls == 3 + @test outputs(simulation)[(:newborn_state, ObjectId(:born), :calls)] == [(1.0, 2)] +end +end diff --git a/test/test-model-previous-timestep-views.jl b/test/test-model-previous-timestep-views.jl index fe90b607b..3e4b62aa3 100644 --- a/test/test-model-previous-timestep-views.jl +++ b/test/test-model-previous-timestep-views.jl @@ -292,7 +292,8 @@ end if batch.application.id == :lagged_consumer ), ) - @test execution_target.status === status_view.status + @test execution_target.status_view === status_view + @test execution_target.status_view.status === status_view.status runtime_temporal_input = only(execution_target.input_bindings) @test runtime_temporal_input isa PlantSimEngine.RuntimeTemporalInput @test runtime_temporal_input.compiled === only(status_view.temporal_inputs) @@ -306,7 +307,7 @@ end @test consumer_runtime_output.reference === PlantSimEngine.refvalue(canonical_status, :observed_signal) PlantSimEngine._materialize_model_inputs!( - execution_target.status, + execution_target.status_view.status, execution_target.input_bindings, simulation.compiled, simulation.compiled.applications_by_id[:lagged_consumer], @@ -314,7 +315,7 @@ end 4, ) @test _runtime_materialization_allocations( - execution_target.status, + execution_target.status_view.status, execution_target.input_bindings, simulation.compiled, simulation.compiled.applications_by_id[:lagged_consumer], @@ -513,7 +514,7 @@ end ), ) PlantSimEngine._materialize_model_inputs!( - many_execution_target.status, + many_execution_target.status_view.status, many_execution_target.input_bindings, many_simulation.compiled, many_simulation.compiled.applications_by_id[:many_consumer], @@ -522,7 +523,7 @@ end ) @test @allocated( PlantSimEngine._materialize_model_inputs!( - many_execution_target.status, + many_execution_target.status_view.status, many_execution_target.input_bindings, many_simulation.compiled, many_simulation.compiled.applications_by_id[:many_consumer], @@ -627,7 +628,7 @@ end batch.targets for batch in dynamic_simulation.execution_plan.batches if batch.application.id == :many_consumer ), - ).status === dynamic_view.status + ).status_view.status === dynamic_view.status dynamic_same_step = CompositeModel( Object(:scene; scale=:Scene); @@ -772,7 +773,7 @@ end initial_temporal_inputs = initial_target.input_bindings initial_source_streams = only(initial_temporal_inputs).source_streams initial_source_stream = only(initial_source_streams) - initial_private_values = initial_target.status.signals + initial_private_values = initial_target.status_view.status.signals initial_context = initial_target.context @test final_state(simulation, :scene).signal_total == 1.0 @test final_state(simulation, :scene).source_count == 1 @@ -799,8 +800,8 @@ end @test only(refreshed_target.input_bindings).source_streams === initial_source_streams @test first(initial_source_streams) === initial_source_stream @test length(initial_source_streams) == 2 - @test refreshed_target.status.signals === initial_private_values - @test length(refreshed_target.status.signals) == 2 + @test refreshed_target.status_view.status.signals === initial_private_values + @test length(refreshed_target.status_view.status.signals) == 2 @test outputs(simulation)[ (:manual_controller, ObjectId(:scene), :signal_total) ] == [(1.0, 1.0), (2.0, 12.0), (3.0, 14.0)] @@ -854,7 +855,7 @@ end ), ) materialize_mixed!() = PlantSimEngine._materialize_model_inputs!( - mixed_execution_target.status, + mixed_execution_target.status_view.status, mixed_execution_target.input_bindings, mixed_simulation.compiled, mixed_application, @@ -863,10 +864,10 @@ end ) materialize_mixed!() - @test mixed_execution_target.status.scalar == 12.0 - @test collect(mixed_execution_target.status.signals) == [3.0, 4.0] + @test mixed_execution_target.status_view.status.scalar == 12.0 + @test collect(mixed_execution_target.status_view.status.signals) == [3.0, 4.0] @test _runtime_materialization_allocations( - mixed_execution_target.status, + mixed_execution_target.status_view.status, mixed_execution_target.input_bindings, mixed_simulation.compiled, mixed_application, diff --git a/test/test-model-runtime-call-names.jl b/test/test-model-runtime-call-names.jl new file mode 100644 index 000000000..66ebb29f7 --- /dev/null +++ b/test/test-model-runtime-call-names.jl @@ -0,0 +1,237 @@ +module RuntimeCallNameChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "runtime_name_owner" verbose=false +PSE.@process "runtime_name_target" verbose=false +PSE.@process "runtime_name_creator" verbose=false + +struct TargetA <: AbstractRuntime_Name_TargetModel end +struct TargetB <: AbstractRuntime_Name_TargetModel end +PSE.inputs_(::Union{TargetA,TargetB}) = NamedTuple() +PSE.outputs_(::TargetA) = (value=0f0, visits=0) +PSE.outputs_(::TargetB) = (value=0.0, visits=0, flag=false) +function PSE.run!(::TargetA, status, environment, constants, context) + status.value += 2f0 + status.visits += 1 + return nothing +end +function PSE.run!(::TargetB, status, environment, constants, context) + status.value += 7.0 + status.visits += 1 + status.flag = true + return nothing +end + +struct CaptureOwner{C} <: AbstractRuntime_Name_OwnerModel + capture::C +end +PSE.outputs_(::CaptureOwner) = (visits=0,) +function PSE.run!(model::CaptureOwner, status, environment, constants, context) + model.capture[] = context + status.visits += 1 + return nothing +end + +@noinline cli_name(args::Vector{String}) = Symbol(only(args)) +cli_targets(context, args) = call_targets(context, cli_name(args)) +cli_model(context, args) = call_model(context, cli_name(args)) +cli_run(context, args; publish=false, objects=nothing) = + run_call!(context, cli_name(args); publish, objects) +@inline literal_model(context::C) where {C} = call_model(context, :a) +function literal_model_allocations(context::C) where {C} + literal_model(context) + return @allocated literal_model(context) +end +function runtime_lookup_allocations(context::C, args) where {C} + cli_targets(context, args) + return @allocated cli_targets(context, args) +end + +function manual_fixture() + capture = Ref{Any}(nothing) + model = CompositeModel(Object(:owner; scale=:Scene), + Object(:first; scale=:LeafA, parent=:owner), + Object(:second; scale=:LeafB, parent=:owner); + applications=( + ModelSpec(CaptureOwner(capture); name=:owner, on=One(id=:owner), + calls=( + a=One(id=:first, within=SceneScope(), application=:target_a), + b=Many(id=:second, within=SceneScope(), application=:target_b), + empty=Many(id=:absent, within=SceneScope(), application=:target_a), + )), + ModelSpec(TargetA(); name=:target_a, on=Many(scale=:LeafA)), + ModelSpec(TargetB(); name=:target_b, on=Many(scale=:LeafB)), + )) + return (; model, capture) +end + +@testset "runtime Symbol calls keep finite heterogeneous target branches" begin + fixture = manual_fixture() + simulation = run!(fixture.model; outputs=:all) + context = fixture.capture[] + a_args, b_args = ["a"], ["b"] + a = cli_targets(context, a_args) + b = cli_targets(context, b_args) + @test a === call_targets(context, :a) + @test b === call_targets(context, :b) + @test length(a) == length(b) == 1 + @test cli_model(context, a_args) isa TargetA + @test cli_model(context, b_args) isa TargetB + @test typeof(only(a)) !== typeof(only(b)) + @test cli_run(context, a_args; publish=true) === a + @test cli_run(context, b_args; publish=true) === b + @test model_status(fixture.model, :first).value === 2f0 + @test model_status(fixture.model, :second).value === 7.0 + @test model_status(fixture.model, :second).flag + @test cli_run(context, b_args; publish=false) === b + @test model_status(fixture.model, :second).value === 14.0 + @test outputs(simulation)[(:target_b, ObjectId(:second), :value)] == [(1.0, 7.0)] + @test isempty(cli_run(context, ["empty"]; publish=true)) + @test_throws ArgumentError cli_model(context, ["empty"]) + @test_throws ErrorException cli_targets(context, ["missing"]) + @test_throws ErrorException cli_model(context, ["missing"]) + @test_throws ErrorException cli_run(context, ["missing"]) + @test_throws ErrorException cli_run(context, a_args; objects=:second) + identity_error = try + call_targets(context, cli_name(["missing"]); objects=:unregistered) + nothing + catch error + error + end + @test identity_error isa ErrorException + @test occursin("No model object", sprint(showerror, identity_error)) + previous_permission = context.publication_allowed + permission_error = try + context.publication_allowed = false + run_initializer!(context, cli_name(["missing"]), :unregistered) + nothing + catch error + error + finally + context.publication_allowed = previous_permission + end + @test permission_error isa ErrorException + @test occursin("non-publishing hard call", sprint(showerror, permission_error)) + @test (@inferred literal_model(context)) isa TargetA + @test literal_model_allocations(context) == 0 + @test runtime_lookup_allocations(context, a_args) == 0 + @test runtime_lookup_allocations(context, b_args) == 0 +end + +struct DynamicInitializerCreator{C} <: AbstractRuntime_Name_CreatorModel + names::Vector{String} + capture::C +end +PSE.outputs_(::DynamicInitializerCreator) = ( + observed_a=0f0, observed_b=0.0, created=false, + manual_guard=false, unknown_guard=false, duplicate_guard=false, +) +function PSE.run!(model::DynamicInitializerCreator, status, environment, constants, context) + status.created && return nothing + status.created = true + model.capture[] = context + a = register_object!(runtime_model(context), + Object(:born_a; scale=:LeafA, parent=:owner, + status=Status(value=0f0, visits=0))) + b = register_object!(runtime_model(context), + Object(:born_b; scale=:LeafB, parent=:owner, + status=Status(value=0.0, visits=0, flag=false))) + status.manual_guard = try + call_targets(context, cli_name(model.names[1:1])) + false + catch error + error isa ArgumentError + end + status.unknown_guard = try + run_initializer!(context, cli_name(["missing"]), a) + false + catch error + error isa ErrorException + end + first_status = run_initializer!(context, cli_name(model.names[1:1]), a) + status.duplicate_guard = try + run_initializer!(context, cli_name(model.names[1:1]), a) + false + catch error + error isa ErrorException + end + second_status = run_initializer!(context, cli_name(model.names[2:2]), b) + status.observed_a = first_status.value + status.observed_b = second_status.value + return nothing +end + +function initializer_fixture() + capture = Ref{Any}(nothing) + model = CompositeModel(Object(:owner; scale=:Scene); + applications=( + ModelSpec(DynamicInitializerCreator(["init_a", "init_b"], capture); + name=:creator, on=One(id=:owner), + calls=( + init_a=Initializer(One(scale=:LeafA, within=SceneScope(), application=:target_a)), + init_b=Initializer(One(scale=:LeafB, within=SceneScope(), application=:target_b)), + )), + ModelSpec(TargetA(); name=:target_a, on=Many(scale=:LeafA)), + ModelSpec(TargetB(); name=:target_b, on=Many(scale=:LeafB)), + )) + return (; model, capture) +end + +@testset "runtime Symbol initializers preserve one-shot mode and publication" begin + fixture = initializer_fixture() + model, capture = fixture.model, fixture.capture + simulation = run!(model; outputs=:all) + creator = model_status(model, :owner) + @test creator.manual_guard + @test creator.unknown_guard + @test creator.duplicate_guard + @test creator.observed_a === 2f0 + @test creator.observed_b === 7.0 + @test model_status(model, :born_a).value === 2f0 + @test model_status(model, :born_b).value === 7.0 + @test model_status(model, :born_a).visits == 1 + @test model_status(model, :born_b).visits == 1 + @test isempty(get(outputs(simulation), (:target_a, ObjectId(:born_a), :value), [])) + @test isempty(get(outputs(simulation), (:target_b, ObjectId(:born_b), :value), [])) + continue!(simulation) + @test model_status(model, :born_a).value === 4f0 + @test model_status(model, :born_b).value === 14.0 + @test model_status(model, :born_a).visits == 2 + @test model_status(model, :born_b).visits == 2 + @test outputs(simulation)[(:target_a, ObjectId(:born_a), :value)] == [(2.0, 4f0)] + @test outputs(simulation)[(:target_b, ObjectId(:born_b), :value)] == [(2.0, 14.0)] + @test_throws ArgumentError cli_targets(capture[], ["init_a"]) + @test_throws ArgumentError cli_model(capture[], ["init_b"]) + @test_throws ArgumentError cli_run(capture[], ["init_a"]) +end + +@testset "readable source preserves runtime-named newborn initializers" begin + @test PSE._compiled_source_module_path(@__MODULE__) == "Main.RuntimeCallNameChecks" + @test PSE._compiled_source_module_path(PSE) == "PlantSimEngine" + fixture = initializer_fixture() + source = PSE.Authoring.compiled_model_source(fixture.model; + function_name=:runtime_named_initializers!) + @test occursin("_compiled_source_run_initializer!", source) + mktempdir() do directory + path = joinpath(directory, "RuntimeNamedInitializers.jl") + write(path, source) + generated_module = Module(gensym(:RuntimeNamedInitializers)) + Base.include(generated_module, path) + generated_run = getfield(generated_module, :runtime_named_initializers!) + generated = Base.invokelatest(generated_run, fixture.model; steps=1, outputs=:all) + @test model_status(runtime_model(generated), :born_a).value === 2f0 + @test model_status(runtime_model(generated), :born_b).value === 7.0 + @test isempty(get(outputs(generated), (:target_a, ObjectId(:born_a), :value), [])) + @test isempty(get(outputs(generated), (:target_b, ObjectId(:born_b), :value), [])) + Base.invokelatest(generated_run, generated; steps=1) + ordinary = run!(initializer_fixture().model; steps=2, outputs=:all) + @test isequal(collect_outputs(generated; sink=nothing), + collect_outputs(ordinary; sink=nothing)) + @test model_status(runtime_model(generated), :born_a).value === 4f0 + @test model_status(runtime_model(generated), :born_b).value === 14.0 + end +end + +end From 0d4e1a4cbba53fd30f1aabb96f0e75a7911c0238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 17:11:56 +0100 Subject: [PATCH 006/324] Reuse resolved inputs and prepared call contexts across invocations Resolve producer ownership once before constructing typed live carriers. Clone current call preparations with independent leases and generation checks; preserve stale OptionalOne rebuilds. Track evaluation owners by identity and retain a concrete raw singleton environment schema without extra sampling. Validation: 1246 focused assertions through Kaimon on Julia 1.13.1. Full native growth and final benchmark acceptance remain pending. --- src/composite_model/call_evaluation_types.jl | 8 +- src/composite_model/call_evaluations.jl | 15 +- src/composite_model/compilation.jl | 247 +++++++++--- src/composite_model/environment_bindings.jl | 24 +- src/composite_model/runtime_outputs.jl | 268 +++++++++++-- test/runtests.jl | 3 + test/test-model-call-context-cloning.jl | 374 ++++++++++++++++++ test/test-model-call-evaluations.jl | 79 ++++ ...-model-global-environment-sample-schema.jl | 336 ++++++++++++++++ test/test-resolved-input-materialization.jl | 274 +++++++++++++ 10 files changed, 1532 insertions(+), 96 deletions(-) create mode 100644 test/test-model-call-context-cloning.jl create mode 100644 test/test-model-global-environment-sample-schema.jl create mode 100644 test/test-resolved-input-materialization.jl diff --git a/src/composite_model/call_evaluation_types.jl b/src/composite_model/call_evaluation_types.jl index 89169c97a..44c9b7142 100644 --- a/src/composite_model/call_evaluation_types.jl +++ b/src/composite_model/call_evaluation_types.jl @@ -26,7 +26,7 @@ mutable struct CallEvaluationTaskIdentity end mutable struct CallEvaluationFrame events::Vector{AbstractCallPublicationEvent} - executions::Dict{Any,UInt64} + executions::IdDict{Any,UInt64} generation::UInt64 pending::Bool in_use::Bool @@ -46,9 +46,9 @@ mutable struct CallEvaluationFrame end CallEvaluationFrame() = CallEvaluationFrame( - # Cache keys are mutable objects with identity equality. Dict keeps its - # storage when emptied and stores revision values without boxing. - AbstractCallPublicationEvent[], Dict{Any,UInt64}(), UInt64(0), false, + # Execution stamps belong to mutable cache identities. Their contents and + # transient leases may change while a candidate is pending. + AbstractCallPublicationEvent[], IdDict{Any,UInt64}(), UInt64(0), false, false, nothing, nothing, 0, 0, 0, nothing, UInt64(0), (false, false), UInt64(0), 0.0, nothing, UInt64(0), false, ) diff --git a/src/composite_model/call_evaluations.jl b/src/composite_model/call_evaluations.jl index 08225f1e6..faa017729 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -110,12 +110,19 @@ function _evaluate_call_targets!(targets::AbstractVector{<:CallTarget}, sampled_ return nothing end +# Base.empty!(IdDict) allocates a fresh table. Its one-pass filter removes +# current identities in place; insertion handles eventual tombstone cleanup. +function _clear_call_execution_stamps!(frame::CallEvaluationFrame) + filter!(_ -> false, frame.executions) + return nothing +end + function _begin_call_evaluation!(frame, compiled, time, permission) frame.generation += UInt64(1) frame.pending = false frame.in_use = true empty!(frame.events) - empty!(frame.executions) + _clear_call_execution_stamps!(frame) frame.task_identity = _call_evaluation_task_identity!() frame.compiled = compiled frame.model_revision = compiled.model.revision @@ -142,7 +149,7 @@ function _with_call_evaluation(f, frame) return result catch empty!(frame.events) - empty!(frame.executions) + _clear_call_execution_stamps!(frame) frame.task_identity = nothing frame.parent = nothing rethrow() @@ -241,7 +248,7 @@ call_targets(evaluation::CallEvaluation) = evaluation.targets return nothing end -@noinline _call_execution_matches(cache::CallContextCache, executions::Dict{Any,UInt64}) = +@noinline _call_execution_matches(cache::CallContextCache, executions::IdDict{Any,UInt64}) = cache.execution_revision == executions[cache] function _validate_call_evaluation(evaluation::CallEvaluation) @@ -310,7 +317,7 @@ function accept_call!(evaluation::CallEvaluation) # Keep prepared capacity, but release consumed snapshots. Published # streams or the parent journal now own the captured values. empty!(frame.events) - empty!(frame.executions) + _clear_call_execution_stamps!(frame) frame.task_identity = nothing frame.parent = nothing end diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 4927b63fb..3d8cae59e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1402,7 +1402,12 @@ struct CompiledEnvironmentSamplingRule{T,S} end CompiledEnvironmentSamplingRule(target::Symbol, source::Symbol) = CompiledEnvironmentSamplingRule{target,source}() -struct CompiledEnvironmentApplicationPlan{B,C,RI,SI,PO,R,CR,S,P} +# A value-type witness narrows the existing shared Any-valued sample memo. +# It carries no sampled state and does not change cache ownership or resets. +struct GlobalEnvironmentSampleSchema{R} end +@inline _global_environment_sample_value(::GlobalEnvironmentSampleSchema{R}, value) where {R} = value::R + +struct CompiledEnvironmentApplicationPlan{B,C,RI,SI,PO,R,CR,S,P,GS} application_id::Symbol backend::B config::C @@ -1414,6 +1419,7 @@ struct CompiledEnvironmentApplicationPlan{B,C,RI,SI,PO,R,CR,S,P} sampler::S prepared_source::P uses_raw_global_source::Bool + sample_schema::GS end struct CompiledEnvironmentBinding{P,H,C} @@ -2222,6 +2228,27 @@ function _compile_added_consumer_bindings!( distributed_outputs=NoCompiledDistributedOutputs(), many_binding_cache=nothing, performance=nothing, +) + return _compile_consumer_input_recipe!( + bindings, model, application.id, application.process, consumer_id, recipe, + manual_application_ids, applications_by_object, applications_by_id, + distributed_outputs, many_binding_cache, performance, + ) +end + +function _compile_consumer_input_recipe!( + bindings, + model, + application_id::Symbol, + application_process::Symbol, + consumer_id, + recipe::CompiledApplicationInputRecipe, + manual_application_ids, + applications_by_object, + applications_by_id, + distributed_outputs=NoCompiledDistributedOutputs(), + many_binding_cache=nothing, + performance=nothing, ) query_cache = _input_query_cache(model.registry.objects, recipe.query_count) foreach(recipe.explicit, recipe.query_slots) do plan, query_slot @@ -2236,12 +2263,12 @@ function _compile_added_consumer_bindings!( end end _resolve_materialize_input_route!( - bindings, model, application, consumer_id, plan, + bindings, model, application_id, application_process, consumer_id, plan, applications_by_object, applications_by_id, nothing, distributed_outputs; query_cache, query_slot, ) end - application.id in manual_application_ids && return bindings + application_id in manual_application_ids && return bindings foreach(recipe.inferred) do group plan = first(group) matches = CompiledModelInputPlan[ @@ -2259,15 +2286,20 @@ function _compile_added_consumer_bindings!( isempty(matches) && return nothing if length(matches) > 1 error( - "Input `$(plan.input)` on application `$(application.id)` for object `$(consumer_id.value)` " * + "Input `$(plan.input)` on application `$(application_id)` for object `$(consumer_id.value)` " * "has ambiguous same-object producers: `$([match.application for match in matches])`. " * "Add `inputs=(:$(plan.input) => One(...),)` to disambiguate." ) end - _resolve_materialize_input_route!( - bindings, model, application, consumer_id, only(matches), - applications_by_object, applications_by_id, [consumer_id], distributed_outputs, + selected = only(matches) + sources = ResolvedInputSources( + _input_binding_source_ids(model.registry.objects, [consumer_id]), + Symbol[selected.application], ) + push!(bindings, _materialize_input_route( + model, application_id, application_process, consumer_id, selected, + sources, applications_by_id, + )) end return bindings end @@ -3864,7 +3896,8 @@ function _extend_compiled_scene( _resolve_materialize_input_route!( replacement, model, - application, + application.id, + application.process, binding.consumer_id, binding.plan, applications_by_object, @@ -5206,19 +5239,92 @@ function _status_ref_or_nothing(status::S, variable) where {S} return refvalue(status, name) end -function _input_carrier(model::CompositeModel, selector::AbstractObjectMultiplicity, source_ids::AbstractVector{<:ObjectId}, source_var) - refs = Base.RefValue[] - selector isa Many && sizehint!(refs, length(source_ids) + 1) - for source_id in source_ids - source_ref = _status_ref_or_nothing(model_status(model, source_id), source_var) - isnothing(source_ref) && return nothing - push!(refs, source_ref) +@inline function _checked_input_reference(reference) + isnothing(reference) && return nothing + reference isa Base.RefValue || throw(ArgumentError( + "Input reference carriers require Base.RefValue storage; got `$(typeof(reference))`.", + )) + return reference +end + +function _input_reference_carrier( + ::Union{One,OptionalOne}, source_ids, reference_for, +) + isempty(source_ids) && return nothing + return _checked_input_reference(reference_for(only(source_ids))) +end + +function _input_reference_carrier(::Many, source_ids, reference_for) + first_source = iterate(source_ids) + isnothing(first_source) && return RefVector{Any}() + source_id, iteration_state = first_source + reference = _checked_input_reference(reference_for(source_id)) + isnothing(reference) && return nothing + return _many_input_reference_carrier( + source_ids, reference_for, reference, typeof(reference[]), iteration_state, + ) +end + +function _many_input_reference_carrier( + source_ids, reference_for, first_reference::Base.RefValue{T}, ::Type{T}, + iteration_state, +) where {T} + references = Base.RefValue{T}[] + sizehint!(references, length(source_ids) + 1) + push!(references, first_reference) + while true + next_source = iterate(source_ids, iteration_state) + isnothing(next_source) && break + source_id, iteration_state = next_source + reference = _checked_input_reference(reference_for(source_id)) + isnothing(reference) && return nothing + if reference isa Base.RefValue{T} + push!(references, reference) + else + heterogeneous = Base.RefValue[references...] + push!(heterogeneous, reference) + return _heterogeneous_input_reference_carrier( + source_ids, reference_for, heterogeneous, iteration_state, + ) + end end - if selector isa Many - isempty(refs) && return RefVector{Any}() - return _ref_vector_carrier(refs) + return RefVector(references) +end + +# An abstract Ref payload must retain the previous ObjectRefVector contract, +# even when its current value happens to have the same type as another source. +function _many_input_reference_carrier( + source_ids, reference_for, first_reference::Base.RefValue, ::Type, + iteration_state, +) + references = Base.RefValue[first_reference] + sizehint!(references, length(source_ids) + 1) + return _heterogeneous_input_reference_carrier( + source_ids, reference_for, references, iteration_state, + ) +end + +function _heterogeneous_input_reference_carrier( + source_ids, reference_for, references, iteration_state, +) + while true + next_source = iterate(source_ids, iteration_state) + isnothing(next_source) && break + source_id, iteration_state = next_source + reference = _checked_input_reference(reference_for(source_id)) + isnothing(reference) && return nothing + push!(references, reference) end - return isempty(refs) ? nothing : only(refs) + return ObjectRefVector(references) +end + +function _input_carrier( + model::CompositeModel, selector::AbstractObjectMultiplicity, + source_ids::AbstractVector{<:ObjectId}, source_var, +) + reference_for = source_id -> + _status_ref_or_nothing(model_status(model, source_id), source_var) + return _input_reference_carrier(selector, source_ids, reference_for) end function _has_stream_only_input_source( @@ -5276,23 +5382,10 @@ function _stream_only_initial_carrier( source_var::Symbol, applications_by_id, ) - references = Base.RefValue[] - for source_id in source_ids - reference = _stream_only_initial_reference( - model, - source_id, - source_application_ids, - source_var, - applications_by_id, - ) - isnothing(reference) && return nothing - push!(references, reference) - end - if selector isa Many - isempty(references) && return RefVector{Any}() - return _ref_vector_carrier(references) - end - return isempty(references) ? nothing : only(references) + reference_for = source_id -> _stream_only_initial_reference( + model, source_id, source_application_ids, source_var, applications_by_id, + ) + return _input_reference_carrier(selector, source_ids, reference_for) end function _ref_vector_carrier(refs) @@ -7490,17 +7583,21 @@ function _compile_model_input_bindings( return bindings end -function _resolve_materialize_input_route!( - bindings, +"""Resolved live object membership and validated producer ownership for one input.""" +struct ResolvedInputSources{I<:AbstractVector{<:ObjectId}} + source_ids::I + source_application_ids::Vector{Symbol} +end + +function _resolve_input_sources( model::CompositeModel, - application::CompiledModelApplication, consumer_id::ObjectId, plan::CompiledModelInputPlan, applications_by_object, applications_by_id, source_ids_override=nothing, - distributed_outputs=NoCompiledDistributedOutputs(), - ; query_cache=nothing, query_slot::Int=0, + distributed_outputs=NoCompiledDistributedOutputs(); + query_cache=nothing, query_slot::Int=0, ) input_sym = _input_route_input(plan.route) selector = plan.selector @@ -7577,7 +7674,7 @@ function _resolve_materialize_input_route!( end if !(selector isa Many) && length(source_application_ids) > 1 error( - "Input `$(input_sym)` on application `$(application.id)` matched several " * + "Input `$(input_sym)` on application `$(plan.application_id)` matched several " * "source applications `$(source_application_ids)`. Add one of those canonical " * "identifiers as `application=...` to the `inputs=...` selector.", ) @@ -7587,17 +7684,35 @@ function _resolve_materialize_input_route!( isempty(source_application_ids) source_ids = empty(source_ids) end + return ResolvedInputSources(source_ids, source_application_ids) +end + +function _materialize_input_route( + model::CompositeModel, + application_id::Symbol, + application_process::Symbol, + consumer_id::ObjectId, + plan::CompiledModelInputPlan, + sources::ResolvedInputSources, + applications_by_id, +) + input_sym = _input_route_input(plan.route) + selector = plan.selector + source_var_tag = _input_route_source(plan.route) + source_var = _input_reference_name(source_var_tag) + source_ids = sources.source_ids + source_application_ids = sources.source_application_ids policy = _model_selector_policy(selector, applications_by_id, source_application_ids, source_var) if policy isa PreviousTimeStep policy.variable == input_sym || error( "PreviousTimeStep marker for input `$(input_sym)` on application ", - "`$(application.id)` names `$(policy.variable)`. Use ", + "`$(application_id)` names `$(policy.variable)`. Use ", "`PreviousTimeStep(:$(input_sym))`." ) else _validate_policy_instance( something(_model_object(model, consumer_id).scale, :Default), - application.process, + application_process, input_sym, policy, ) @@ -7628,7 +7743,7 @@ function _resolve_materialize_input_route!( end _validate_model_input_source!( model, - application, + application_id, consumer_id, input_sym, source_var, @@ -7636,18 +7751,34 @@ function _resolve_materialize_input_route!( carrier, carrier_hint, ) - push!( - bindings, - CompiledModelInputBinding( - plan, - consumer_id, - source_ids, - source_application_ids, - policy, - carrier_hint, - carrier, - ), + return CompiledModelInputBinding( + plan, consumer_id, source_ids, source_application_ids, + policy, carrier_hint, carrier, + ) +end + + +function _resolve_materialize_input_route!( + bindings, + model::CompositeModel, + application_id::Symbol, + application_process::Symbol, + consumer_id::ObjectId, + plan::CompiledModelInputPlan, + applications_by_object, + applications_by_id, + source_ids_override=nothing, + distributed_outputs=NoCompiledDistributedOutputs(); + query_cache=nothing, query_slot::Int=0, +) + sources = _resolve_input_sources( + model, consumer_id, plan, applications_by_object, applications_by_id, + source_ids_override, distributed_outputs; query_cache, query_slot, ) + push!(bindings, _materialize_input_route( + model, application_id, application_process, consumer_id, plan, + sources, applications_by_id, + )) return bindings end @@ -7780,7 +7911,7 @@ end function _validate_model_input_source!( model::CompositeModel, - application::CompiledModelApplication, + application_id::Symbol, consumer_id::ObjectId, input_sym::Symbol, source_var::Symbol, @@ -7795,7 +7926,7 @@ function _validate_model_input_source!( ] isempty(status_source_ids) && return nothing error( - "Input binding `$(input_sym)` on application `$(application.id)` for object ", + "Input binding `$(input_sym)` on application `$(application_id)` for object ", "`$(consumer_id.value)` reads `$(source_var)` from objects ", "`$([id.value for id in status_source_ids])`, but no source `Status` reference is available." ) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 62055da86..1dba832d3 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -168,6 +168,16 @@ function _environment_source_variable_names(sampling_rules) return Tuple(Symbol(source) for (_, source) in sampling_rules) end +# Raw singleton sampling returns the source itself. Other sampling recipes +# retain Any until their result schema is known; preparation never samples a +# custom source merely to discover its return type. +function _global_environment_sample_schema(backend, source, sampler, uses_raw::Bool, prepare_runtime::Bool) + R = prepare_runtime && isnothing(sampler) && uses_raw && + backend isa GlobalConstant && + DataFormat(environment_source(backend)) isa SingletonAlike ? typeof(source) : Any + return GlobalEnvironmentSampleSchema{R}() +end + function _compile_environment_application_plans( model::CompositeModel, applications; @@ -216,6 +226,9 @@ function _compile_environment_application_plans( has_bindings = bindings isa NamedTuple && !isempty(keys(bindings)) has_source_overrides = !isempty(keys(_environment_source_overrides(application.spec))) + uses_raw_global_source = backend isa GlobalConstant && + isnothing(sampler) && + !has_bindings && !has_source_overrides plan = CompiledEnvironmentApplicationPlan( application.id, backend, @@ -227,10 +240,10 @@ function _compile_environment_application_plans( compiled_sampling_rules, sampler, prepared_source, - backend isa GlobalConstant && - isnothing(sampler) && - !has_bindings && - !has_source_overrides, + uses_raw_global_source, + _global_environment_sample_schema( + backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, + ), ) push!(plans, plan) haskey(plans_by_id, application.id) && error( @@ -463,7 +476,8 @@ function _same_environment_application_plan(a, b) typeof(b.compiled_sampling_rules) && a.sampler === b.sampler && a.prepared_source === b.prepared_source && - a.uses_raw_global_source == b.uses_raw_global_source + a.uses_raw_global_source == b.uses_raw_global_source && + typeof(a.sample_schema) === typeof(b.sample_schema) end function _reconciled_environment_application_plans( diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 6afa21afb..154963577 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -582,6 +582,34 @@ mutable struct _CallTargetBufferCache second::Any end +# A wrapper's invocation metadata can be synchronized while its execution +# batches remain a retained snapshot. Capture preparation independently so a +# leased old owner cannot share an obsolete One/OptionalOne tuple after growth. +struct CallTargetsPreparation{CS,EB,TS,OR,C} + compiled::CS + environment_bindings::EB + temporal_streams::TS + output_retention::OR + constants::C + model_revision::Int + environment_revision::Int + applications_identity::UInt + membership_reference::Base.RefValue{UInt64} + membership_generation::UInt64 +end + +function _call_targets_preparation( + compiled, environment_bindings, binding, temporal_streams, output_retention, constants, +) + return CallTargetsPreparation( + compiled, environment_bindings, temporal_streams, output_retention, constants, + compiled.revision, environment_bindings.environment_revision, + environment_bindings.applications_identity, + getfield(binding, :membership_generation), + _compiled_call_membership_generation(binding), + ) +end + """ CallTargets <: AbstractVector{CallTarget} @@ -611,6 +639,7 @@ mutable struct CallTargets{CS,EB,B,TS,OR,C,BT} <: AbstractVector{CallTarget} # may legitimately change its concrete type between invocations. environment::Any execution_batches::BT + preparation::CallTargetsPreparation{CS,EB,TS,OR,C} evaluation::Union{Nothing,CallEvaluationFrame} target_buffer_cache::Union{Nothing,_CallTargetBufferCache} # One singular snapshot or transient slot; numerical state stays in its owner. @@ -667,7 +696,7 @@ Base.@nospecializeinfer function CallTargets( constants, ) end - targets = CallTargets( + return _prepared_call_targets( compiled, environment_bindings, binding, @@ -678,15 +707,91 @@ Base.@nospecializeinfer function CallTargets( publication_allowed, environment, execution_batches, - nothing, - nothing, - nothing, + ) +end + +# Both graph preparation and a leased context's clone use this fully specified +# shell constructor. Execution owners and scientific reference carriers belong +# to the prepared batches; mutable views and their borrowing caches do not. +@inline function _prepared_call_targets( + compiled, environment_bindings, binding, temporal_streams, output_retention, + time, constants, publication_allowed, environment, execution_batches, +) + targets = CallTargets( + compiled, environment_bindings, binding, temporal_streams, output_retention, + float(time), constants, publication_allowed, environment, execution_batches, + _call_targets_preparation( + compiled, environment_bindings, binding, temporal_streams, output_retention, constants, + ), + nothing, nothing, nothing, ) execution_batches isa LazyCallExecutionBatches && (execution_batches.owner = targets) return targets end +@inline function _call_targets_preparation_is_current( + targets::CallTargets, compiled, environment_bindings, temporal_streams, + output_retention, constants, +) + prepared = targets.preparation + return prepared.compiled === compiled && + prepared.environment_bindings === environment_bindings && + prepared.temporal_streams === temporal_streams && + prepared.output_retention === output_retention && + prepared.constants === constants && + prepared.model_revision == compiled.revision && + prepared.environment_revision == environment_bindings.environment_revision && + prepared.applications_identity == environment_bindings.applications_identity && + prepared.membership_reference === getfield(targets.binding, :membership_generation) && + prepared.membership_generation == _compiled_call_membership_generation(targets.binding) +end + +@inline _call_context_preparation_is_current(::Tuple{}, args...) = true + +@inline function _call_context_preparation_is_current( + calls::Tuple, compiled, environment_bindings, temporal_streams, + output_retention, constants, +) + _call_targets_preparation_is_current( + first(calls), compiled, environment_bindings, temporal_streams, + output_retention, constants, + ) || return false + return _call_context_preparation_is_current( + Base.tail(calls), compiled, environment_bindings, temporal_streams, + output_retention, constants, + ) +end + +@inline _clone_call_execution_batches(batches::Tuple) = batches + +@inline function _clone_call_execution_batches(batches::LazyCallExecutionBatches) + # A lazy wrapper points at its owning CallTargets. Share its prepared state, + # never its owner link; cloning must leave a cold Many membership cold. + return LazyCallExecutionBatches( + nothing, batches.batches, batches.tracks_full_membership, + ) +end + +@inline _clone_runtime_call_targets(::Tuple{}, args...) = () + +@inline function _clone_runtime_call_targets( + calls::Tuple, compiled, environment_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, +) + prototype = first(calls) + targets = _prepared_call_targets( + compiled, environment_bindings, prototype.binding, temporal_streams, + output_retention, time, constants, publication_allowed, environment, + _clone_call_execution_batches(prototype.execution_batches), + ) + remaining = _clone_runtime_call_targets( + Base.tail(calls), compiled, environment_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, + ) + return (targets, remaining...) +end + function _current_call_binding_for_retained_view( compiled::CompiledCompositeModel, binding::CompiledModelCallBinding, @@ -833,6 +938,10 @@ function _record_call_execution_batch_cache!( else batches end + targets.preparation = _call_targets_preparation( + targets.compiled, targets.environment_bindings, targets.binding, + targets.temporal_streams, targets.output_retention, targets.constants, + ) # Explicit `objects=` selections share the call owner's payloads with its # complete cached view. Only that complete membership can retire rows; # absence from one selection does not remove a target from the call. @@ -849,6 +958,10 @@ function _record_extended_call_execution_batch_cache!( binding::CompiledModelCallBinding, ) targets.last_single_snapshot = nothing + targets.preparation = _call_targets_preparation( + compiled, environment_bindings, binding, targets.temporal_streams, + targets.output_retention, targets.constants, + ) cached = targets.execution_batches cached isa LazyCallExecutionBatches || return targets cached.tracks_full_membership || return targets @@ -2585,14 +2698,16 @@ function _model_environment_for_binding( step = Int(round(time)) key = (application.id, step) haskey(env_bindings.sample_cache, key) && - return env_bindings.sample_cache[key] + return _global_environment_sample_value( + binding.plan.sample_schema, env_bindings.sample_cache[key], + ) sampled = _sample_compiled_global_environment( binding, application, step, ) env_bindings.sample_cache[key] = sampled - return sampled + return _global_environment_sample_value(binding.plan.sample_schema, sampled) end return sample_environment( binding.backend, @@ -2654,9 +2769,7 @@ end context.output_retention = output_retention context.constants = constants end - context.time = float(time) - context.publication_allowed = publication_allowed - context.environment = environment + _synchronize_current_call_context!(context, time, publication_allowed, environment) if runtime_changed _prepare_runtime_call_targets!( context.calls, @@ -5115,19 +5228,39 @@ end environment = isconcretetype(V) ? (targets.environment::fieldtype(V, :environment)) : targets.environment context = target.context - calls = if context isa RunContext && !target.call_context_cache.in_use - _prepare_runtime_call_targets!( - context.calls, - targets.compiled, - targets.environment_bindings, - targets.temporal_streams, - targets.output_retention, - targets.time, - targets.constants, - targets.publication_allowed, - environment, - ) - context.calls + calls = if context isa RunContext + if target.call_context_cache.in_use + if _call_context_clone_is_current( + context, targets.compiled, targets.environment_bindings, + application, target.object_id, target.bound_inputs, target.output_targets, + targets.temporal_streams, targets.output_retention, targets.constants, + ) + _clone_runtime_call_targets( + context.calls, targets.compiled, targets.environment_bindings, + targets.temporal_streams, targets.output_retention, targets.time, + targets.constants, targets.publication_allowed, environment, + ) + else + _runtime_call_targets( + targets.compiled, targets.environment_bindings, target.call_bindings, + targets.temporal_streams, targets.output_retention, targets.time, + targets.constants, targets.publication_allowed, environment, + ) + end + else + _prepare_runtime_call_targets!( + context.calls, + targets.compiled, + targets.environment_bindings, + targets.temporal_streams, + targets.output_retention, + targets.time, + targets.constants, + targets.publication_allowed, + environment, + ) + context.calls + end else _runtime_call_targets( targets.compiled, @@ -6371,6 +6504,18 @@ end ) where {CS,A,CT,BI,OT,TS,OR,C,OldE,I,E} = RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I} @inline _call_context_type(::Nothing, environment) = RunContext +# Metadata already proved current needs only invocation values synchronized. +# Keep this small boundary usable when a stale owner's new descendant tuple +# differs from its original default type, without reboxing all owner metadata. +@inline function _synchronize_current_call_context!( + context::RunContext, time, publication_allowed::Bool, environment, +) + context.time = float(time) + context.publication_allowed = publication_allowed + context.environment = environment + return context +end + @inline function _call_context_matches( context::RunContext, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, temporal_streams, output_retention, constants, @@ -6386,6 +6531,57 @@ end end @inline _call_context_matches(::Nothing, args...) = false +@inline function _call_context_clone_is_current( + context::RunContext, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, constants, +) + # The context identity guard also protects an empty descendant template: + # no per-child stamp exists to prove it still describes another generation. + return _call_context_matches( + context, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, constants, + context.environment, + ) && _call_context_preparation_is_current( + context.calls, compiled, environment_bindings, temporal_streams, + output_retention, constants, + ) +end + +# A typed default already contains the resolved descendant schema. Reentry or +# another environment specialization needs fresh mutable call wrappers, not a +# second graph lookup. Each child execution owner retains its own lease. +@inline function _clone_model_execution_context( + prototype::RunContext, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, time, + constants, publication_allowed, environment, +) + if !_call_context_clone_is_current( + prototype, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, constants, + ) + return _prepare_model_execution_context!( + nothing, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, + time, constants, publication_allowed, environment, + ) + end + calls = _clone_runtime_call_targets( + prototype.calls, compiled, environment_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, + ) + return RunContext( + compiled, environment_bindings, application, object_id, calls, + bound_inputs, output_targets, temporal_streams, output_retention, + float(time), constants, publication_allowed, environment, + ) +end + +# Truly cold owners still require canonical graph preparation. In particular, +# Nothing does not imply that the application has no declared descendants. +@inline function _clone_model_execution_context(::Nothing, args...) + return _prepare_model_execution_context!(nothing, args...) +end + @inline function _prepare_cached_call_context!( cache::CallContextCache, reuse::Bool, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, temporal_streams, @@ -6397,20 +6593,42 @@ end context, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, temporal_streams, output_retention, constants, environment, + ) && _call_context_preparation_is_current( + context.calls, compiled, environment_bindings, temporal_streams, + output_retention, constants, )) context = reuse ? cache.transient : nothing + if context isa RunContext && !(context isa Context) && + _call_context_matches( + context, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, + constants, environment, + ) && _call_context_clone_is_current( + context, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, temporal_streams, output_retention, constants, + ) + # A stale OptionalOne can have acquired a different descendant tuple + # type. Reuse that current transient rather than forcing the old + # default's Context type and rebuilding it on every invocation. + return _synchronize_current_call_context!( + context, time, publication_allowed, environment, + ) + end if !(context isa Context && _call_context_matches( context, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, temporal_streams, output_retention, constants, environment, + ) && _call_context_preparation_is_current( + context.calls, compiled, environment_bindings, temporal_streams, + output_retention, constants, )) # A reentrant call needs its own descendants as well as its shell: # child CallTargets carry mutable time, environment and permission. - context = _prepare_model_execution_context!( - nothing, compiled, environment_bindings, application, object_id, + context = _clone_model_execution_context( + cache.default, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, temporal_streams, output_retention, time, constants, publication_allowed, environment, - )::Context + ) reuse && (cache.transient = context) return context end diff --git a/test/runtests.jl b/test/runtests.jl index 5f99c54a6..4177844a8 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -81,6 +81,7 @@ else include("test-model-prepared-scenario.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") + include("test-resolved-input-materialization.jl") end @testset "Isolated model diagnostics" begin @@ -138,6 +139,7 @@ else @testset "Transient manual-call context reuse" begin include("test-model-call-context-cache.jl") + include("test-model-call-context-cloning.jl") end @testset "Lightweight manual-call target views" begin @@ -250,6 +252,7 @@ else @testset "Composite model environment sampling" begin include("test-model-environment-sampling.jl") include("test-model-environment-binding-identity.jl") + include("test-model-global-environment-sample-schema.jl") end @testset "Composite model temporal reducers" begin diff --git a/test/test-model-call-context-cloning.jl b/test/test-model-call-context-cloning.jl new file mode 100644 index 000000000..389d008fc --- /dev/null +++ b/test/test-model-call-context-cloning.jl @@ -0,0 +1,374 @@ +module TypedCallContextCloningChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +PSE.@process "typed_context_clone_owner" verbose=false +PSE.@process "typed_context_clone_middle" verbose=false +PSE.@process "typed_context_clone_leaf" verbose=false + +mutable struct Trial{T} + values::NTuple{2,T} +end +struct AlternateTrial{T} + values::NTuple{2,T} +end +mutable struct Backend{T} <: EA.AbstractEnvironmentBackend + values::NTuple{2,T} + samples::Int + commits::Vector{T} +end +EA.base_step_seconds(::Backend) = 3600.0 +EA.get_nsteps(::Backend) = 8 +EA.environment_variables(::Backend) = Set((:T,)) +EA.bind_environment(::Backend, object::Object, context, config) = + (cell=isnothing(geometry(object)) ? 1 : geometry(object).cell,) +function EA.sample(backend::Backend, handle, ::Symbol, time) + backend.samples += 1 + return backend.values[handle.cell] +end +function EA.sample(backend::Backend, handle, trial::Union{Trial,AlternateTrial}, ::Symbol, time) + backend.samples += 1 + return trial.values[handle.cell] +end +function EA.commit_environment!(backend::Backend, handle, state, time) + push!(backend.commits, state.T) + return nothing +end + +struct Owner{C} <: AbstractTyped_Context_Clone_OwnerModel + capture::C +end +PSE.outputs_(::Owner) = (visits=0,) +function PSE.run!(model::Owner, status, environment, constants, context) + model.capture[] = context + status.visits += 1 + return nothing +end +struct Leaf{T} <: AbstractTyped_Context_Clone_LeafModel + initial::T +end +PSE.outputs_(model::Leaf) = (seen=model.initial, visits=0) +PSE.environment_inputs_(model::Leaf) = (T=model.initial,) +PSE.environment_outputs_(model::Leaf) = (T=model.initial,) +function PSE.run!(::Leaf, status, environment, constants, context) + status.seen = environment.T + status.visits += 1 + commit_environment!(context, (T=environment.T,)) + return nothing +end +struct Middle{T,C,H} <: AbstractTyped_Context_Clone_MiddleModel + initial::T + capture::C + hook::H +end +PSE.outputs_(model::Middle) = (sampled=model.initial, seen=model.initial, visits=0) +PSE.environment_inputs_(model::Middle) = (T=model.initial,) +function PSE.run!(model::Middle, status, environment, constants, context) + child = only(call_targets(context, :one)) + hook = model.hook[] + if !isnothing(hook) + model.hook[] = nothing + hook() + end + run_call!(child; publish=true) + model.capture[] = (; context, child) + status.sampled = environment.T + status.seen = child.status.seen + status.visits += 1 + return nothing +end + +function fixture(::Type{T}) where {T} + owner_capture, middle_capture, hook = Ref{Any}(), Ref{Any}(), Ref{Any}(nothing) + backend = Backend((T(10), T(20)), 0, T[]) + model = CompositeModel( + Object(:owner; scale=:Scene), + Object(:middle; scale=:Branch, parent=:owner, geometry=(cell=1,)), + Object(:leaf; scale=:Leaf, parent=:middle, geometry=(cell=2,)); + applications=( + ModelSpec(Owner(owner_capture); name=:owner, on=One(id=:owner), + calls=(middle=One(id=:middle, within=Subtree(), application=:middle),)), + ModelSpec(Middle(zero(T), middle_capture, hook); name=:middle, + on=One(id=:middle), calls=( + one=One(id=:leaf, within=Subtree(), application=:leaf), + optional=OptionalOne(id=:leaf, within=Subtree(), application=:leaf), + many=Many(id=:leaf, within=Subtree(), application=:leaf)), + environment=Environment(provider=:context_clone)), + ModelSpec(Leaf(zero(T)); name=:leaf, on=One(id=:leaf), + environment=Environment(provider=:context_clone)), + ), environment=backend) + simulation = run!(model; steps=1, outputs=:all) + parent = only(call_targets(owner_capture[], :middle)) + return (; model, simulation, parent, backend, owner_capture, middle_capture, hook) +end + +@noinline function prepare_context(target, environment; reuse=true, time=target.time, publish=false) + return PSE._prepare_cached_call_context!( + target.context_cache, reuse, target.compiled, target.environment_bindings, + target.application, target.object_id, target.bound_inputs, target.output_targets, + target.temporal_streams, target.output_retention, time, target.constants, + publish, environment, + ) +end + +@testset "typed context clones isolate shells and preserve execution owners" begin + data = fixture(Float64) + prototype = data.parent.context_cache.default + @test prototype isa PSE.RunContext + one = call_targets(prototype, :one) + many = call_targets(prototype, :many) + @test many.execution_batches isa PSE.LazyCallExecutionBatches + @test isnothing(many.execution_batches.batches) + evaluation = PSE.CallEvaluationFrame() + buffers = PSE._CallTargetBufferCache(nothing, nothing) + snapshot = (:prepared_snapshot,) + one.evaluation = evaluation + one.target_buffer_cache = buffers + one.last_single_snapshot = snapshot + + trial = Trial((30.0, 40.0)) + typed_calls = @inferred PSE._clone_runtime_call_targets( + prototype.calls, data.parent.compiled, data.parent.environment_bindings, + data.parent.temporal_streams, data.parent.output_retention, 2.0, + data.parent.constants, false, trial, + ) + @test typeof(typed_calls) === typeof(prototype.calls) + context = prepare_context(data.parent, trial; time=2.0, publish=false) + @test context !== prototype + @test context === data.parent.context_cache.transient + @test typeof(context.calls) === typeof(prototype.calls) + @test context.time == 2.0 && !context.publication_allowed + @test context.environment === trial + @test context.compiled === prototype.compiled + @test context.bound_inputs === prototype.bound_inputs + @test context.output_targets === prototype.output_targets + @test data.backend.samples == 0 + @test one.evaluation === evaluation + @test one.target_buffer_cache === buffers + @test one.last_single_snapshot === snapshot + for cloned in context.calls + @test isnothing(cloned.evaluation) + @test isnothing(cloned.target_buffer_cache) + @test isnothing(cloned.last_single_snapshot) + end + # Subsequent materialization may populate the original borrowing caches; + # restoration here keeps that activity separate from clone isolation. + one.evaluation = nothing + one.target_buffer_cache = nothing + one.last_single_snapshot = nothing + for (original, cloned) in zip(prototype.calls, context.calls) + @test cloned !== original + @test cloned.binding === original.binding + @test cloned.time == 2.0 && !cloned.publication_allowed + @test cloned.environment === trial + if original.execution_batches isa Tuple + @test cloned.execution_batches === original.execution_batches + old_target, new_target = only(original), only(cloned) + @test new_target.execution_target === old_target.execution_target + @test new_target.status === old_target.status + @test new_target.context_cache === old_target.context_cache + else + @test cloned.execution_batches !== original.execution_batches + @test cloned.execution_batches.owner === cloned + @test original.execution_batches.owner === original + @test cloned.execution_batches.tracks_full_membership + @test isnothing(cloned.execution_batches.batches) + end + end + cloned_many = call_targets(context, :many) + @test length(cloned_many) == 1 + @test isnothing(many.execution_batches.batches) # cloning did not warm the prototype + @test !isnothing(cloned_many.execution_batches.batches) + + # A warm Many shares prepared scientific owners but has an independent owner + # link and snapshot/borrowing metadata on every newly leased context shell. + @test length(many) == 1 + reentrant = prepare_context(data.parent, trial; reuse=false, publish=true) + @test reentrant !== prototype && reentrant !== context + @test data.parent.context_cache.transient === context + warm_many = call_targets(reentrant, :many) + @test warm_many.execution_batches !== many.execution_batches + @test warm_many.execution_batches.owner === warm_many + @test warm_many.execution_batches.batches === many.execution_batches.batches + @test only(warm_many).execution_target === only(many).execution_target + @test data.backend.samples == 0 +end + +@testset "reentry preserves outer descendants, fresh trial sampling and publication masks" begin + for T in (Float32, Float64) + data = fixture(T) + trial = Trial((T(30), T(40))) + inner_trial = AlternateTrial((T(50), T(60))) + inner_capture, inner_parent_capture = Ref{Any}(), Ref{Any}() + lease_checks = Bool[] + data.hook[] = () -> begin + push!(lease_checks, data.parent.context_cache.in_use) + inner_parent = only(call_targets(data.owner_capture[], :middle)) + inner_parent_capture[] = inner_parent + run_call!(inner_parent; environment=inner_trial, publish=false) + inner_capture[] = data.middle_capture[] + push!(lease_checks, data.parent.context_cache.in_use) + end + run_call!(data.parent; environment=trial, publish=true) + outer, inner = data.middle_capture[], inner_capture[] + @test lease_checks == [true, true] + @test !data.parent.context_cache.in_use + @test outer.context !== inner.context + @test outer.context.calls !== inner.context.calls + @test inner_parent_capture[].calls !== data.parent.calls + @test outer.child.execution_target === inner.child.execution_target + @test outer.child.context_cache === inner.child.context_cache + @test outer.child.status === inner.child.status === model_status(data.model, :leaf) + @test outer.child.environment === trial + @test inner.child.environment === inner_trial + @test outer.child.publication_allowed && !inner.child.publication_allowed + @test model_status(data.model, :middle).sampled === T(30) + @test model_status(data.model, :middle).seen === T(40) + @test data.backend.samples == 4 + @test data.backend.commits == T[40] + @test outputs(data.simulation)[(:leaf, ObjectId(:leaf), :seen)] == [(1.0, T(40))] + transient = data.parent.context_cache.transient + + # Reusing the same mutable override and shell must sample its new values. + trial.values = (T(31), T(41)) + run_call!(data.parent; environment=trial, publish=false) + @test data.parent.context_cache.transient === transient + @test model_status(data.model, :middle).sampled === T(31) + @test model_status(data.model, :leaf).seen === T(41) + @test data.backend.samples == 6 + @test data.backend.commits == T[40] + @test outputs(data.simulation)[(:leaf, ObjectId(:leaf), :seen)] == [(1.0, T(40))] + + data.backend.values = (T(11), T(21)) + run_call!(data.parent; publish=false) + @test model_status(data.model, :middle).sampled === T(11) + @test model_status(data.model, :leaf).seen === T(21) + @test data.backend.samples == 8 + @test data.backend.commits == T[40] + end +end + +@noinline function repeat_contexts(target, environment, count) + for _ in 1:count + prepare_context(target, environment) + end + return nothing +end +context_reuse_allocations(target, environment, count) = + @allocated repeat_contexts(target, environment, count) + +struct OptionalMiddle{T} <: AbstractTyped_Context_Clone_MiddleModel + initial::T +end +PSE.outputs_(model::OptionalMiddle) = (seen=model.initial, visits=0) +function PSE.run!(::OptionalMiddle, status, environment, constants, context) + children = call_targets(context, :child) + if !isempty(children) + child = only(children) + run_call!(child; publish=true) + status.seen = child.status.seen + end + status.visits += 1 + return nothing +end + +@testset "stale leased OptionalOne clones rebuild the current descendant schema" begin + for T in (Float32, Float64) + capture = Ref{Any}() + backend = Backend((T(10), T(20)), 0, T[]) + model = CompositeModel(Object(:owner; scale=:Scene), + Object(:middle; scale=:Branch, parent=:owner); applications=( + ModelSpec(Owner(capture); name=:owner, on=One(id=:owner), + calls=(middle=One(id=:middle, within=Subtree(), application=:middle),)), + ModelSpec(OptionalMiddle(zero(T)); name=:middle, on=One(id=:middle), + calls=(child=OptionalOne(id=:newborn, within=Subtree(), application=:leaf),)), + ModelSpec(Leaf(zero(T)); name=:leaf, on=Many(scale=:Leaf), + environment=Environment(provider=:context_clone)), + ), environment=backend) + # This fixture explicitly bypasses the Simulation lifecycle barrier to + # test a leased context's schema. Retention is covered by the public + # call scenarios above; this private refresh creates no output streams. + simulation = run!(model; steps=1, outputs=:none) + parents = call_targets(capture[], :middle) + parent = only(parents) + cache = parent.context_cache + active = prepare_context(parent, parent.environment; publish=true) + old_calls = active.calls + old_optional = call_targets(active, :child) + @test isempty(old_optional) + @test old_optional.execution_batches === () + cache.in_use = true + inner = nothing + try + register_object!(model, Object(:newborn; scale=:Leaf, parent=:middle, + geometry=(cell=2,))) + refreshed = PSE.Advanced.refresh_bindings!(model) + environments = PSE.refresh_environment_bindings!(model, refreshed) + # Synchronization can replace wrapper metadata without rebuilding + # its eager tuple. The captured preparation generation must still + # identify this old empty OptionalOne as stale. + PSE._prepare_runtime_call_targets!((parents,), refreshed, + environments, parent.temporal_streams, parent.output_retention, + parent.time, parent.constants, true, parent.environment) + PSE._prepare_model_execution_context!(active, refreshed, environments, + parent.application, parent.object_id, parent.bound_inputs, parent.output_targets, + parent.temporal_streams, parent.output_retention, parent.time, + parent.constants, true, parent.environment) + @test active.compiled === refreshed + @test active.environment_bindings === environments + @test old_optional.compiled === refreshed + @test old_optional.environment_bindings === environments + @test old_optional.binding.callee_object_ids == ObjectId[ObjectId(:newborn)] + inner = only(parents) + @test inner.execution_target === parent.execution_target + @test inner.context_cache === cache + @test inner.calls !== old_calls + @test typeof(inner.calls) !== typeof(old_calls) + @test active.calls === old_calls + @test isempty(old_optional) + fresh_optional = only(inner.calls) + @test fresh_optional.binding === old_optional.binding + @test length(fresh_optional) == 1 + @test only(fresh_optional).object_id == ObjectId(:newborn) + + # The context-cache path also needs a new schema, not an assertion + # forcing the old default's empty descendant tuple type. + fresh_context = prepare_context(inner, inner.environment; reuse=false) + @test typeof(fresh_context.calls) !== typeof(old_calls) + @test length(only(fresh_context.calls)) == 1 + run_call!(inner; publish=false) + @test model_status(model, :newborn).seen === T(20) + @test model_status(model, :newborn).visits == 1 + @test isempty(backend.commits) + @test isempty(old_optional) + @test cache.in_use + finally + cache.in_use = false + end + # Once the old owner is no longer leased, preserve the freshly rebuilt + # CT specialization and its caches instead of rebuilding it indefinitely. + current_transient = prepare_context(inner, inner.environment) + @test cache.transient === current_transient + @test typeof(current_transient.calls) !== typeof(old_calls) + for time in (1.0, 2.0, 3.0) + repeated = prepare_context(inner, inner.environment; time, publish=true) + @test repeated === current_transient + @test repeated.calls === current_transient.calls + @test repeated.time == time && repeated.publication_allowed + end + # The companion TMP probe measures this dynamic old-owner path without + # conflating identity reuse with an unmeasured zero-allocation claim. + repeat_contexts(inner, inner.environment, 10) + @test cache.transient === current_transient + step!(simulation) + current = only(call_targets(capture[], :middle)) + run_call!(current; publish=false) + @test model_status(model, :newborn).visits == 2 + @test current.status.seen === T(20) + end +end + +end # module TypedCallContextCloningChecks diff --git a/test/test-model-call-evaluations.jl b/test/test-model-call-evaluations.jl index b9b1d7606..dff74ff15 100644 --- a/test/test-model-call-evaluations.jl +++ b/test/test-model-call-evaluations.jl @@ -625,4 +625,83 @@ end end end +@testset "execution stamps track mutable cache identities independently" begin + left = PSE.CallContextCache(nothing) + right = PSE.CallContextCache(nothing) + frame = PSE.CallEvaluationFrame() + @test frame.executions isa IdDict{Any,UInt64} + @test left !== right + @test left.default === right.default === nothing + PSE._record_call_execution!(left, frame) + PSE._record_call_execution!(right, frame) + @test length(frame.executions) == 2 + @test frame.executions[left] == frame.executions[right] == UInt64(1) + left.transient = (candidate=:changed,) + left.in_use = true + PSE._record_call_execution!(left, frame) + @test frame.executions[left] == UInt64(2) + @test frame.executions[right] == UInt64(1) + @test PSE._call_execution_matches(left, frame.executions) + @test PSE._call_execution_matches(right, frame.executions) + left.execution_revision += UInt64(1) + @test !PSE._call_execution_matches(left, frame.executions) + @test PSE._call_execution_matches(right, frame.executions) + PSE._clear_call_execution_stamps!(frame) + @test isempty(frame.executions) + PSE._clear_call_execution_stamps!(frame) + @test isempty(frame.executions) +end + +@testset "a different execution owner does not stale a disjoint candidate" begin + fixture = basic_scene() + simulation = run!(fixture.model; steps=1, outputs=:all) + context = fixture.capture[] + left = only(call_targets(context, :one)) + right = only(call_targets(context, :many; objects=(:leaf_b,))) + @test left.context_cache !== right.context_cache + pending_left = evaluate_call!(left) + pending_right = evaluate_call!(right) + @test length(pending_left.frame.executions) == 1 + @test haskey(pending_left.frame.executions, left.context_cache) + @test !haskey(pending_left.frame.executions, right.context_cache) + run_call!(right; publish=false) + @test accept_call!(pending_left) === pending_left + @test_throws ArgumentError accept_call!(pending_right) + @test model_status(fixture.model, :leaf_a).calls == 1 + @test model_status(fixture.model, :leaf_b).calls == 2 + @test raw(simulation, :leaf, :leaf_a, :seen) == [(1.0, 10.0)] + @test isempty(raw(simulation, :leaf, :leaf_b, :seen)) + @test isempty(pending_left.frame.executions) +end + +@testset "nested accepted child stamps survive in the parent by identity" begin + fixture = nested_scene(; evaluate_child=true) + simulation = run!(fixture.model; steps=1, outputs=:all) + context = fixture.capture[] + middle = only(call_targets(context, :middle)) + outer = evaluate_call!(context, :middle) + leaf = only(call_targets(middle.context_cache.default, :leaf)) + @test length(outer.frame.executions) == 2 + @test haskey(outer.frame.executions, middle.context_cache) + @test haskey(outer.frame.executions, leaf.context_cache) + @test isempty(leaf.context_cache.evaluation.executions) + @test isempty(raw(simulation, :leaf, :leaf, :seen)) + @test accept_call!(outer) === outer + @test model_status(fixture.model, :middle).middle_calls == 1 + @test model_status(fixture.model, :leaf).calls == 2 + @test raw(simulation, :middle, :middle, :middle_seen) == [(1.0, 12.0)] + @test raw(simulation, :leaf, :leaf, :calls) == [(1.0, 2)] + @test isempty(outer.frame.executions) + + # A later descendant execution invalidates the whole pending parent, + # while retaining the already accepted sample and avoiding kernel replay. + pending = evaluate_call!(context, :middle) + leaf = only(call_targets(middle.context_cache.default, :leaf)) + run_call!(leaf; publish=false) + @test_throws ArgumentError accept_call!(pending) + @test model_status(fixture.model, :middle).middle_calls == 2 + @test model_status(fixture.model, :leaf).calls == 5 + @test raw(simulation, :leaf, :leaf, :calls) == [(1.0, 2)] +end + end # module CallEvaluationChecks diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl new file mode 100644 index 000000000..232aeaadd --- /dev/null +++ b/test/test-model-global-environment-sample-schema.jl @@ -0,0 +1,336 @@ +module GlobalEnvironmentSampleSchemaChecks + +using Dates +using DataFrames +using PlantSimEngine +using Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +PSE.@process "global_sample_schema_none" verbose=false +PSE.@process "global_sample_schema_probe" verbose=false +PSE.@process "global_sample_schema_owner" verbose=false + +struct NoEnvironmentProbe <: AbstractGlobal_Sample_Schema_NoneModel end +PSE.outputs_(::NoEnvironmentProbe) = (visits=0,) +function PSE.run!(::NoEnvironmentProbe, status, environment, constants, context) + isnothing(environment) || error("Expected the default Nothing environment") + status.visits += 1 + return nothing +end +struct Probe{T} <: AbstractGlobal_Sample_Schema_ProbeModel + initial::T +end +PSE.outputs_(model::Probe) = (seen=model.initial, visits=0) +PSE.environment_inputs_(model::Probe) = (T=model.initial,) +function PSE.run!(::Probe, status, environment, constants, context) + status.seen = environment.T + status.visits += 1 + return nothing +end +struct Owner{C} <: AbstractGlobal_Sample_Schema_OwnerModel + capture::C +end +PSE.outputs_(::Owner) = (visits=0,) +function PSE.run!(model::Owner, status, environment, constants, context) + model.capture[] = context + status.visits += 1 + return nothing +end + +# Sampling instrumentation only: the singleton contract still returns exactly +# the authored row. Preparing the schema must never invoke this method. +mutable struct CountedRow{T} + T::T + duration::Hour + reads::Dict{Int,Int} +end +PSE.DataFormat(::Type{<:CountedRow}) = PSE.SingletonAlike() +function PSE._environment_row_at_step(row::CountedRow, step::Int) + row.reads[step] = get(row.reads, step, 0) + 1 + return row +end + +function prepared(source; remap=false, shared=false) + objects = shared ? ( + Object(:a; scale=:Leaf, kind=:shared), + Object(:b; scale=:Leaf, kind=:shared), + Object(:c; scale=:Leaf, kind=:other), + ) : (Object(:a; scale=:Leaf, kind=:shared),) + config = remap ? Environment(sources=(T=:T,)) : Environment() + applications = shared ? ( + ModelSpec(Probe(0f0); name=:probe, on=Many(kind=:shared), environment=config), + ModelSpec(Probe(0f0); name=:other, on=One(id=:c), environment=config), + ) : (ModelSpec(Probe(0f0); name=:probe, on=One(id=:a), environment=config),) + model = CompositeModel(objects...; applications, environment=source) + simulation = run!(model; steps=0, outputs=:none) + application = simulation.compiled.applications_by_id[:probe] + binding = simulation.environment_bindings.by_target[(:probe, ObjectId(:a))] + return (; model, simulation, application, binding) +end + +sample(data, time; environment=PSE._NO_ENVIRONMENT_OVERRIDE) = + PSE._model_environment_for_binding(data.simulation.environment_bindings, + data.application, data.binding, time, environment) + +@noinline function cached_temperature(data, count) + total = 0f0 + for _ in 1:count + total += sample(data, 1).T + end + return total +end +cache_hit_allocations(data, count) = @allocated cached_temperature(data, count) + +@testset "raw singleton schemas narrow the shared memo without sampling" begin + model = CompositeModel(Object(:a; scale=:Leaf); applications=( + ModelSpec(NoEnvironmentProbe(); name=:probe, on=One(id=:a)),)) + simulation = run!(model; steps=0, outputs=:none) + application = simulation.compiled.applications_by_id[:probe] + binding = simulation.environment_bindings.by_target[(:probe, ObjectId(:a))] + @test binding.plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Nothing} + @test sizeof(binding.plan.sample_schema) == 0 + @test (@inferred PSE._model_environment_for_binding( + simulation.environment_bindings, application, binding, 1)) === nothing + @test (@inferred PSE._model_environment_for_binding( + simulation.environment_bindings, application, binding, 1)) === nothing + @test haskey(simulation.environment_bindings.sample_cache, (:probe, 1)) + continue!(simulation; steps=1) + @test final_state(simulation).visits == 1 + + source = (T=11.5f0, duration=Hour(1)) + data = prepared(source) + @test data.binding.plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{typeof(source)} + @test (@inferred sample(data, 1)) === source + @test (@inferred sample(data, 1)) === source + @test data.simulation.environment_bindings.sample_cache isa Dict{Tuple{Symbol,Int},Any} + for _ in 1:3 + cached_temperature(data, 1000) + cache_hit_allocations(data, 1000) + end + @test cached_temperature(data, 1000) === 11500f0 + @test cache_hit_allocations(data, 1000) == 0 + # A raw default schema must not constrain an explicit override to that + # source's type or cache its mutable values. + raw_trial = CountedRow(40.0, Hour(1), Dict{Int,Int}()) + @test sample(data, 1; environment=raw_trial) === raw_trial + raw_trial.T = 41.0 + @test sample(data, 1; environment=raw_trial).T === 41.0 + @test raw_trial.reads == Dict(1 => 2) + @test sample(data, 1) === source + + counted = CountedRow(10f0, Hour(1), Dict{Int,Int}()) + shared = prepared(counted; shared=true) + @test isempty(counted.reads) + @test shared.binding.plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{typeof(counted)} + @test sample(shared, 1) === counted + @test sample(shared, 1) === counted + sibling = shared.simulation.environment_bindings.by_target[(:probe, ObjectId(:b))] + @test PSE._model_environment_for_binding(shared.simulation.environment_bindings, + shared.application, sibling, 1) === counted + @test counted.reads == Dict(1 => 1) + other = shared.simulation.compiled.applications_by_id[:other] + other_binding = shared.simulation.environment_bindings.by_target[(:other, ObjectId(:c))] + @test PSE._model_environment_for_binding(shared.simulation.environment_bindings, + other, other_binding, 1) === counted + @test counted.reads == Dict(1 => 2) + @test Set(keys(shared.simulation.environment_bindings.sample_cache)) == + Set(((:probe, 1), (:other, 1))) + plans, _ = PSE._compile_environment_application_plans(shared.model, + shared.simulation.compiled.applications; prepare_runtime=false) + @test all(plan -> plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any}, plans) + @test counted.reads == Dict(1 => 2) +end + +@testset "projected histories, resets and explicit trials retain existing memo semantics" begin + source = CountedRow(10f0, Hour(1), Dict{Int,Int}()) + data = prepared(source; remap=true) + @test data.binding.plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any} + @test isempty(source.reads) + @test sample(data, 1).T === 10f0 + source.T = 20f0 + @test sample(data, 3).T === 20f0 + source.T = 30f0 + @test sample(data, 1).T === 10f0 + @test sample(data, 3).T === 20f0 + @test source.reads == Dict(1 => 1, 3 => 1) + memo = data.simulation.environment_bindings.sample_cache + @test Set(keys(memo)) == Set(((:probe, 1), (:probe, 3))) + + trial = CountedRow(40f0, Hour(1), Dict{Int,Int}()) + @test sample(data, 1; environment=trial).T === 40f0 + trial.T = 41f0 + @test sample(data, 1; environment=trial).T === 41f0 + @test trial.reads == Dict(1 => 2) + @test source.reads == Dict(1 => 1, 3 => 1) + @test memo[(:probe, 1)].T === 10f0 + empty!(memo) + @test isempty(memo) + @test sample(data, 1).T === 30f0 + @test source.reads == Dict(1 => 2, 3 => 1) +end + +@testset "retained call views preserve captured times across the same shared reset" begin + capture = Ref{Any}() + source = CountedRow(10f0, Hour(1), Dict{Int,Int}()) + model = CompositeModel(Object(:owner; scale=:Scene), + Object(:leaf; scale=:Leaf, parent=:owner); applications=( + ModelSpec(Owner(capture); name=:owner, on=One(id=:owner), + calls=(leaf=One(id=:leaf, within=Subtree(), application=:leaf),)), + ModelSpec(Probe(0f0); name=:leaf, on=One(id=:leaf), + environment=Environment(sources=(T=:T,))), + ), environment=source) + simulation = run!(model; steps=1, outputs=:all) + first_view = only(call_targets(capture[], :leaf)) + run_call!(first_view; publish=false) + @test first_view.status.seen === 10f0 + source.T = 20f0 + step!(simulation) + second_view = only(call_targets(capture[], :leaf)) + run_call!(second_view; publish=false) + @test second_view.status.seen === 20f0 + source.T = 30f0 + run_call!(first_view; publish=false) + @test first_view.status.seen === 30f0 + source.T = 40f0 + run_call!(second_view; publish=false) + @test second_view.status.seen === 20f0 + run_call!(first_view; publish=false) + @test first_view.status.seen === 30f0 + @test first_view.time == 1 && second_view.time == 2 + @test first_view.environment_bindings.sample_cache === + second_view.environment_bindings.sample_cache === simulation.environment_bindings.sample_cache + step!(simulation) + run_call!(first_view; publish=false) + @test first_view.status.seen === 40f0 + @test isempty(outputs(simulation)[(:leaf, ObjectId(:leaf), :seen)]) +end + +mutable struct SpatialBackend{T} <: EA.AbstractEnvironmentBackend + values::Dict{Symbol,T} + samples::Int +end +mutable struct SpatialTrial{T} + values::Dict{Symbol,T} +end +EA.base_step_seconds(::SpatialBackend) = 3600.0 +EA.get_nsteps(::SpatialBackend) = 8 +EA.environment_variables(::SpatialBackend) = Set((:T,)) +EA.bind_environment(::SpatialBackend, object::Object, context, config) = + (cell=geometry(object).cell,) +function EA.sample(backend::SpatialBackend, handle, ::Symbol, time) + backend.samples += 1 + return backend.values[handle.cell] +end +function EA.sample(backend::SpatialBackend, handle, trial::SpatialTrial, ::Symbol, time) + backend.samples += 1 + return trial.values[handle.cell] +end + +@testset "spatial and mutable trial sampling bypass the global schema memo" begin + backend = SpatialBackend(Dict(:a => 10f0, :b => 20f0), 0) + model = CompositeModel(Object(:leaf; scale=:Leaf, geometry=(cell=:a,)); + applications=(ModelSpec(Probe(0f0); name=:probe, on=One(id=:leaf), + environment=Environment(provider=:schema_spatial)),), environment=backend) + simulation = run!(model; steps=0, outputs=:none) + application = simulation.compiled.applications_by_id[:probe] + bindings = simulation.environment_bindings + binding = bindings.by_target[(:probe, ObjectId(:leaf))] + @test binding.plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any} + read(env=PSE._NO_ENVIRONMENT_OVERRIDE) = + PSE._model_environment_for_binding(bindings, application, binding, 1, env).T + @test read() === 10f0 + backend.values[:a] = 11f0 + @test read() === 11f0 + trial = SpatialTrial(Dict(:a => 30f0, :b => 40f0)) + @test read(trial) === 30f0 + trial.values[:a] = 31f0 + @test read(trial) === 31f0 + @test backend.samples == 4 + @test isempty(bindings.sample_cache) + move_object!(model, :leaf, (cell=:b,)) + refreshed = PSE.Advanced.refresh_environment_bindings!(model, simulation.compiled) + moved = refreshed.by_target[(:probe, ObjectId(:leaf))] + @test moved.handle.cell === :b + @test moved.plan === binding.plan + @test PSE._model_environment_for_binding(refreshed, application, moved, 1).T === 20f0 + @test PSE._model_environment_for_binding(refreshed, application, moved, 1, trial).T === 40f0 + trial.values[:b] = 41f0 + @test PSE._model_environment_for_binding(refreshed, application, moved, 1, trial).T === 41f0 + @test backend.samples == 7 + @test refreshed.sample_cache === bindings.sample_cache + @test isempty(refreshed.sample_cache) +end + +function table_probe(source; remap=false) + config = remap ? Environment(sources=(T=:temperature,)) : Environment() + model = CompositeModel(Object(:a; scale=:Leaf); applications=( + ModelSpec(Probe(0f0); name=:probe, on=One(id=:a), environment=config),), + environment=source) + return run!(model; steps=3, outputs=:all) +end + +@testset "DataFrame preparation keeps table samples Any and preserves every Float32 row" begin + temperatures = Float32[1.25, 2.5, 4] + unused = Int32[11, 22, 33] + durations = fill(Hour(1), 3) + expected = [(1.0, 1.25f0), (2.0, 2.5f0), (3.0, 4f0)] + for remap in (false, true) + frame = remap ? + DataFrame(temperature=copy(temperatures), unused=copy(unused), duration=copy(durations)) : + DataFrame(T=copy(temperatures), unused=copy(unused), duration=copy(durations)) + rows = remap ? + [(temperature=temperatures[i], unused=unused[i], duration=durations[i]) for i in 1:3] : + [(T=temperatures[i], unused=unused[i], duration=durations[i]) for i in 1:3] + simulation = table_probe(frame; remap) + control = table_probe(rows; remap) + plan = simulation.environment_bindings.application_plans_by_id[:probe] + @test plan.prepared_source isa PSE.PreparedGlobalEnvironmentRows + @test plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any} + @test current_step(simulation) == current_step(control) == 3 + @test final_state(simulation) == final_state(control) == (seen=4f0, visits=3) + @test outputs(simulation)[(:probe, ObjectId(:a), :seen)] == + outputs(control)[(:probe, ObjectId(:a), :seen)] == expected + @test all(sample -> sample[2] isa Float32, + outputs(simulation)[(:probe, ObjectId(:a), :seen)]) + application = simulation.compiled.applications_by_id[:probe] + binding = simulation.environment_bindings.by_target[(:probe, ObjectId(:a))] + sampled = PSE._model_environment_for_binding( + simulation.environment_bindings, application, binding, 2, + ) + @test sampled.T === 2.5f0 + if !remap + @test sampled.unused === Int32(22) + @test sampled.duration == Hour(1) + end + end +end + +struct ColumnProbe{C} <: AbstractGlobal_Sample_Schema_ProbeModel + capture::C +end +PSE.outputs_(::ColumnProbe) = (seen=0f0, visits=0) +PSE.environment_inputs_(::ColumnProbe) = (T=Float32[],) +function PSE.run!(model::ColumnProbe, status, environment, constants, context) + model.capture[] = environment + status.seen = sum(environment.T) + status.visits += 1 + return nothing +end + +@testset "NamedTuple columns preserve the existing raw singleton contract" begin + source = (T=Float32[1.25, 2.5, 4], unused=Int32[11, 22, 33], duration=Hour(1)) + capture = Ref{Any}() + model = CompositeModel(Object(:a; scale=:Leaf); applications=( + ModelSpec(ColumnProbe(capture); name=:probe, on=One(id=:a)),), environment=source) + simulation = run!(model; outputs=:all) + plan = simulation.environment_bindings.application_plans_by_id[:probe] + @test PSE.DataFormat(source) isa PSE.SingletonAlike + @test plan.prepared_source === source + @test plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{typeof(source)} + @test capture[] === source + @test current_step(simulation) == 1 + @test final_state(simulation) == (seen=7.75f0, visits=1) +end + +end # module GlobalEnvironmentSampleSchemaChecks diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl new file mode 100644 index 000000000..d3fdf76ef --- /dev/null +++ b/test/test-resolved-input-materialization.jl @@ -0,0 +1,274 @@ +module ResolvedInputMaterializationChecks + +using Dates, PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "resolved_endpoint_source" verbose=false +PSE.@process "resolved_endpoint_reader" verbose=false +PSE.@process "resolved_endpoint_distributor" verbose=false + +struct Source{T,P} <: AbstractResolved_Endpoint_SourceModel + value::T + policy::P +end +Source(value) = Source(value, nothing) +PSE.outputs_(model::Source{T}) where {T} = (x=zero(T),) +PSE.output_policy(model::Source) = isnothing(model.policy) ? NamedTuple() : (x=model.policy[],) +function PSE.run!(model::Source, status, environment, constants, context) + status.x = model.value * oftype(model.value, context.time) + return nothing +end + +struct Reader{T} <: AbstractResolved_Endpoint_ReaderModel end +PSE.inputs_(::Reader{T}) where {T} = (x=Required(T),) +PSE.outputs_(::Reader{T}) where {T} = (seen=zero(T),) +PSE.run!(::Reader, status, environment, constants, context) = (status.seen=status.x; nothing) + +struct Distributor{T} <: AbstractResolved_Endpoint_DistributorModel + value::T +end +PSE.outputs_(model::Distributor{T}) where {T} = (x=Distributed(Default(zero(T))),) +function PSE.run!(model::Distributor, status, environment, constants, context) + destinations = output_targets(context, (:x,)) + for index in eachindex(destinations.columns.x) + destinations.columns.x[index] = model.value + end + return nothing +end + +function point_scene(::Type{T}; policy=nothing, stream_only=false) where {T} + return CompositeModel(Object(:source; scale=:Leaf), Object(:reader; scale=:Reader); + applications=( + ModelSpec(Source(T(2.5), policy); name=:source, on=One(id=:source), + output_routing=stream_only ? (x=:stream_only,) : NamedTuple()), + ModelSpec(Reader{T}(); name=:reader, on=One(id=:reader), + inputs=(x=One(SceneScope(); id=:source, application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) +end + +@testset "resolved point endpoints keep live identity and fresh policy reads" begin + for T in (Float32, Float64) + policy = Ref{PSE.SchedulePolicy}(HoldLast()) + model = point_scene(T; policy) + simulation = run!(model; steps=0, outputs=:none) + compiled = simulation.compiled + application = compiled.applications_by_id[:reader] + plan = only(compiled.scenario_plan.input_plans_by_application.reader) + sources = PSE._resolve_input_sources(model, ObjectId(:reader), plan, + compiled.applications_by_object, compiled.applications_by_id, + nothing, compiled.distributed_outputs) + @test sources.source_ids == [ObjectId(:source)] + @test sources.source_application_ids == [:source] + first = PSE._materialize_input_route(model, :reader, application.process, + ObjectId(:reader), plan, sources, compiled.applications_by_id) + source_ref = PSE.refvalue(model_status(model, :source), :x) + @test first.carrier === source_ref + @test first.policy isa HoldLast + policy[] = Aggregate() + next = PSE._materialize_input_route(model, :reader, application.process, + ObjectId(:reader), plan, sources, compiled.applications_by_id) + @test next.carrier === source_ref + @test next.policy isa Aggregate + @test next.carrier_hint === :temporal_stream + @test first.policy isa HoldLast + source_ref[] = T(9) + @test next.carrier[] === T(9) + end +end + +struct CountWriterChecks + count::Base.RefValue{Int} +end +function PSE._application_writes_object_variable(counter::CountWriterChecks, application, id, variable) + counter.count[] += 1 + return PSE._application_writes_object_variable(PSE.NoCompiledDistributedOutputs(), application, id, variable) +end +PSE._final_inferred_output_plans(::CountWriterChecks, id, variable, matches) = matches + +@testset "inferred endpoints reuse the writer already validated for that object" begin + model = CompositeModel(Object(:leaf; scale=:Leaf); + applications=( + ModelSpec(Reader{Float32}(); name=:reader, on=Many(scale=:Leaf)), + ModelSpec(Source(3f0); name=:source, on=Many(scale=:Leaf)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; outputs=:all) + compiled = simulation.compiled + application = compiled.applications_by_id[:reader] + recipe = compiled.scenario_plan.input_recipes_by_application.reader + counter = CountWriterChecks(Ref(0)) + bindings = PSE.CompiledModelInputBinding[] + PSE._compile_added_consumer_bindings!(bindings, model, application, ObjectId(:leaf), + recipe, compiled.scenario_plan.manual_application_ids, + compiled.applications_by_object, compiled.applications_by_id, counter) + @test counter.count[] == 1 + @test only(bindings).source_application_ids == [:source] + @test only(bindings).carrier === PSE.refvalue(model_status(model, :leaf), :x) + @test model_status(model, :leaf).seen === 3f0 +end + +@testset "point, homogeneous and heterogeneous carriers visit sources once" begin + ids = [ObjectId(1), ObjectId(2), ObjectId(3)] + cells = [Ref(1.0), Ref(2.0), Ref(3.0)] + visited = Int[] + reference_for(id) = (push!(visited, id.value); cells[id.value]) + @test PSE._input_reference_carrier(One(), ids[1:1], reference_for) === cells[1] + @test visited == [1] + empty!(visited) + @test isnothing(PSE._input_reference_carrier(OptionalOne(), ObjectId{Int}[], reference_for)) + @test isempty(visited) + homogeneous = PSE._input_reference_carrier(Many(), ids, reference_for) + @test homogeneous isa PSE.RefVector{Float64} + @test visited == [1, 2, 3] + @test all(parent(homogeneous)[index] === cells[index] for index in eachindex(cells)) + cells[2][] = 8.0 + @test homogeneous[2] === 8.0 + + mixed = Base.RefValue[Ref(1f0), Ref(2.0), Ref(3)] + empty!(visited) + mixed_for(id) = (push!(visited, id.value); mixed[id.value]) + heterogeneous = PSE._input_reference_carrier(Many(), ids, mixed_for) + @test heterogeneous isa PSE.ObjectRefVector + @test visited == [1, 2, 3] + @test all(parent(heterogeneous)[index] === mixed[index] for index in eachindex(mixed)) + @test typeof.(collect(heterogeneous)) == [Float32, Float64, Int] + mixed[1][] = 7f0 + @test heterogeneous[1] === 7f0 + + abstract = Ref{Real}(1.0) + @test PSE._input_reference_carrier(Many(), ids[1:1], _ -> abstract) isa PSE.ObjectRefVector + @test PSE._input_reference_carrier(Many(), ObjectId{Int}[], reference_for) isa PSE.RefVector{Any} + @test isnothing(PSE._input_reference_carrier(One(), ids[1:1], _ -> nothing)) + empty!(visited) + missing_for(id) = (push!(visited, id.value); id.value == 2 ? nothing : cells[id.value]) + @test isnothing(PSE._input_reference_carrier(Many(), ids, missing_for)) + @test visited == [1, 2] + external = Ref([4.0], 1) + @test_throws ArgumentError PSE._input_reference_carrier(One(), ids[1:1], _ -> external) + @test_throws ArgumentError PSE._input_reference_carrier(Many(), ids[1:1], _ -> external) +end + +struct OffsetSourceIds{T} <: AbstractVector{T} + values::Vector{T} + offset::Int + reads::Vector{Int} +end +OffsetSourceIds(values::Vector{T}, offset::Int) where {T} = + OffsetSourceIds{T}(values, offset, Int[]) +Base.size(ids::OffsetSourceIds) = size(ids.values) +Base.axes(ids::OffsetSourceIds) = + (Base.IdentityUnitRange(ids.offset:(ids.offset + length(ids.values) - 1)),) +Base.firstindex(ids::OffsetSourceIds) = ids.offset +Base.lastindex(ids::OffsetSourceIds) = ids.offset + length(ids.values) - 1 +function Base.getindex(ids::OffsetSourceIds, index::Int) + checkbounds(ids, index) + push!(ids.reads, index) + return ids.values[index - ids.offset + 1] +end +function Base.iterate(ids::OffsetSourceIds, state::Int=firstindex(ids)) + state > lastindex(ids) && return nothing + return ids[state], state + 1 +end + +@testset "source collection preserves arbitrary vector axes and iteration state" begin + for cells in ( + Base.RefValue[Ref(1f0), Ref(2f0), Ref(3f0), Ref(4f0)], + Base.RefValue[Ref(1f0), Ref(2f0), Ref(3.0), Ref(4f0)], + Base.RefValue[Ref{Real}(1.0), Ref(2.0), Ref(3.0), Ref(4.0)], + ) + ids = OffsetSourceIds(ObjectId.(1:4), -3) + visited = Int[] + getter(id) = (push!(visited, id.value); cells[id.value]) + carrier = PSE._input_reference_carrier(Many(), ids, getter) + @test ids.reads == [-3, -2, -1, 0] + @test visited == [1, 2, 3, 4] + @test all(parent(carrier)[index] === cells[index] for index in eachindex(cells)) + @test typeof.(collect(carrier)) == typeof.([cell[] for cell in cells]) + if all(cell -> cell isa Base.RefValue{Float32}, cells) + @test carrier isa PSE.RefVector{Float32} + else + @test carrier isa PSE.ObjectRefVector + end + end + empty_ids = OffsetSourceIds(ObjectId{Int}[], 9) + @test PSE._input_reference_carrier(Many(), empty_ids, _ -> error("empty source visited")) isa PSE.RefVector{Any} + @test isempty(empty_ids.reads) + for selector in (One(), OptionalOne()) + ids = OffsetSourceIds([ObjectId(1)], 7) + cell = Ref(5.0) + @test PSE._input_reference_carrier(selector, ids, _ -> cell) === cell + @test ids.reads == [7] + end +end + +@noinline function repeat_point_carrier(model, selector, ids, expected, repetitions) + same = true + for _ in 1:repetitions + same &= PSE._input_carrier(model, selector, ids, Val(:x)) === expected + end + return same +end +@noinline point_allocations(model, selector, ids, expected, repetitions) = + @allocated repeat_point_carrier(model, selector, ids, expected, repetitions) +@noinline many_allocations(ids, getter) = + @allocated PSE._input_reference_carrier(Many(), ids, getter) + +@testset "point materialization has no allocation per source and Many builds one vector" begin + status = Status(x=1.0) + model = CompositeModel(Object(1; status)) + ids = [ObjectId(1)] + expected = PSE.refvalue(status, :x) + for selector in (One(), OptionalOne()) + @test repeat_point_carrier(model, selector, ids, expected, 2) + point_allocations(model, selector, ids, expected, 1000) + allocated = minimum(point_allocations(model, selector, ids, expected, 1000) for _ in 1:3) + # A small fixed allowance accommodates instrumentation on the Kaimon + # task; the former temporary vector per call exceeds this by far. + @test allocated <= 4096 + end + count = 1024 + many_ids = ObjectId.(1:count) + cells = [Ref(Float64(index)) for index in 1:count] + getter = id -> cells[id.value] + many_allocations(many_ids, getter) + allocated = minimum(many_allocations(many_ids, getter) for _ in 1:3) + @test allocated <= sizeof(Int) * count + 4096 +end + +@testset "shared materialization preserves Updates, distributed ownership and stream-only values" begin + ordered = CompositeModel(Object(:leaf; scale=:Leaf); + applications=( + ModelSpec(Source(2.0); name=:first, on=Many(scale=:Leaf)), + ModelSpec(Source(5.0); name=:second, on=Many(scale=:Leaf), updates=Updates(:x; after=:first)), + ModelSpec(Reader{Float64}(); name=:reader, on=Many(scale=:Leaf), + inputs=(x=One(within=Self(), var=:x),)), + ), environment=(duration=Hour(1),)) + simulation = run!(ordered; outputs=:all) + @test model_status(ordered, :leaf).seen === 5.0 + @test only(filter(binding -> binding.application_id === :reader, + simulation.compiled.input_bindings)).source_application_ids == [:second] + + distributed = CompositeModel(Object(:plant; scale=:Plant), + Object(:leaf; scale=:Leaf, parent=:plant); + applications=( + ModelSpec(Distributor(4f0); name=:distributor, on=Many(scale=:Plant), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree())),)), + ModelSpec(Reader{Float32}(); name=:reader, on=Many(scale=:Leaf)), + ), environment=(duration=Hour(1),)) + simulation = run!(distributed; outputs=:all) + @test model_status(distributed, :leaf).seen === 4f0 + register_object!(distributed, Object(:new_leaf; scale=:Leaf, parent=:plant)) + continue!(simulation) + @test model_status(distributed, :new_leaf).seen === 4f0 + newborn = only(binding for binding in simulation.compiled.input_bindings + if binding.application_id === :reader && binding.consumer_id == ObjectId(:new_leaf)) + @test newborn.source_application_ids == [:distributor] + @test newborn.carrier === PSE.refvalue(model_status(distributed, :new_leaf), :x) + + streamed = point_scene(Float64; stream_only=true) + simulation = run!(streamed; steps=2, outputs=:all) + @test !(:x in propertynames(model_status(streamed, :source))) + @test model_status(streamed, :reader).seen === 5.0 + @test outputs(simulation)[(:source, ObjectId(:source), :x)] == [(1.0, 2.5), (2.0, 5.0)] +end + +end From 4056ff6eb45de3452bedf269e7f647f5fdf7da06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 18:09:06 +0100 Subject: [PATCH 007/324] Share application binding loops and pass resolved calls to context preparation Use the same application-level input binder for initial preparation, lifecycle additions and targeted newborns. Reuse the ordered batch list when provider and publication metadata still match. Replace the four context preparation variants with one factory consuming the current payload binding tuple; retain captured source-call shells and stale/reentrant ownership semantics. No cold context graph lookup remains. Validation: 3367 assertions through serial Kaimon runs on Julia 1.13.1, including multirate, global/spatial/transient environments, distributed outputs, source compilation and allocation contracts. Full native growth and final matched performance qualification remain pending. --- src/composite_model/compilation.jl | 127 +++--- src/composite_model/runtime_outputs.jl | 367 ++++++------------ src/composite_model/source_compilation.jl | 4 + test/test-model-call-context-cache.jl | 4 +- test/test-model-call-context-cloning.jl | 60 ++- test/test-model-canonical-cohorts.jl | 72 +++- test/test-model-input-recipes.jl | 2 +- test/test-model-materialized-call-dispatch.jl | 4 +- test/test-resolved-input-materialization.jl | 2 +- 9 files changed, 324 insertions(+), 318 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 3d8cae59e..3f20105a4 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2216,24 +2216,54 @@ function _insert_sorted_object_ids!(ids, added_ids) return ids end -function _compile_added_consumer_bindings!( - bindings, - model, - application, - consumer_id, - recipe::CompiledApplicationInputRecipe, - manual_application_ids, - applications_by_object, - applications_by_id, - distributed_outputs=NoCompiledDistributedOutputs(), - many_binding_cache=nothing, - performance=nothing, +# One coarse application boundary recovers the authored recipe before walking +# real consumers. Initial binding, normal growth and targeted newborns share +# this loop and the same per-consumer resolver/materializer below. +function _compile_application_consumer_bindings!( + bindings, model, application, recipe::CompiledApplicationInputRecipe, + manual_application_ids, applications_by_object, applications_by_id, + distributed_outputs=NoCompiledDistributedOutputs(), many_binding_cache=nothing, + performance=nothing, recorder=nothing, +) + application_id, application_process = application.id, application.process + for consumer_id in application.target_ids + first_new_binding = length(bindings) + 1 + _compile_consumer_input_recipe!( + bindings, model, application_id, application_process, consumer_id, recipe, + manual_application_ids, applications_by_object, applications_by_id, + distributed_outputs, many_binding_cache, performance, + ) + _record_consumer_input_bindings!( + recorder, bindings, application, consumer_id, + first_new_binding, length(bindings), + ) + end + return bindings +end + +_record_consumer_input_bindings!(::Nothing, args...) = nothing + +struct _AddedConsumerInputBindings{M,C,B,I} + model::M + many_binding_cache::C + changed_bindings::B + input_bindings_by_target::I +end + +function _record_consumer_input_bindings!( + recorder::_AddedConsumerInputBindings, bindings, application, consumer_id, + first_new_binding, last_new_binding, ) - return _compile_consumer_input_recipe!( - bindings, model, application.id, application.process, consumer_id, recipe, - manual_application_ids, applications_by_object, applications_by_id, - distributed_outputs, many_binding_cache, performance, - ) + first_new_binding <= last_new_binding || return nothing + for binding_index in first_new_binding:last_new_binding + bindings[binding_index] = _share_many_input_binding!( + recorder.many_binding_cache, recorder.model, bindings[binding_index], + ) + end + new_bindings = bindings[first_new_binding:last_new_binding] + append!(recorder.changed_bindings, new_bindings) + recorder.input_bindings_by_target[(application.id, consumer_id)] = Tuple(new_bindings) + return nothing end function _compile_consumer_input_recipe!( @@ -3933,39 +3963,19 @@ function _extend_compiled_scene( ) end previous_binding_count = length(input_bindings) + recorder = _AddedConsumerInputBindings( + model, many_binding_cache, changed_bindings, input_bindings_by_target, + ) for application in added_applications - for consumer_id in application.target_ids - first_new_binding = length(input_bindings) + 1 - _compile_added_consumer_bindings!( - input_bindings, - model, - application, - consumer_id, - _application_plans( - compiled.scenario_plan.input_recipes_by_application, - application.slot, - ), - manual_application_ids, - applications_by_object, - applications_by_id, - distributed_outputs, - many_binding_cache, - performance, - ) - last_new_binding = length(input_bindings) - if first_new_binding <= last_new_binding - for binding_index in first_new_binding:last_new_binding - input_bindings[binding_index] = _share_many_input_binding!( - many_binding_cache, - model, - input_bindings[binding_index], - ) - end - new_bindings = input_bindings[first_new_binding:last_new_binding] - append!(changed_bindings, new_bindings) - input_bindings_by_target[(application.id, consumer_id)] = Tuple(new_bindings) - end - end + isempty(application.target_ids) && continue + recipe = _application_plans( + compiled.scenario_plan.input_recipes_by_application, application.slot, + ) + _compile_application_consumer_bindings!( + input_bindings, model, application, recipe, manual_application_ids, + applications_by_object, applications_by_id, distributed_outputs, + many_binding_cache, performance, recorder, + ) end dynamic_input_binding_indices = if rebuild_dynamic_input_index many_binding_cache = @@ -7566,19 +7576,12 @@ function _compile_model_input_bindings( by_object = _applications_by_object(applications) by_id = Dict(application.id => application for application in applications) for application in applications - for consumer_id in application.target_ids - _compile_added_consumer_bindings!( - bindings, - model, - application, - consumer_id, - _application_plans(input_recipes_by_application, application.slot), - manual_application_ids, - by_object, - by_id, - distributed_outputs, - ) - end + isempty(application.target_ids) && continue + recipe = _application_plans(input_recipes_by_application, application.slot) + _compile_application_consumer_bindings!( + bindings, model, application, recipe, manual_application_ids, + by_object, by_id, distributed_outputs, + ) end return bindings end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 154963577..2086c2613 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2740,21 +2740,48 @@ end ) end +# The execution payload owns the already resolved current call bindings. +# Context creation never rediscovers that dependency schema through a global map. +# A fresh shell either clones a current prototype or rebuilds from those bindings; +# updating an existing shell retains its leased descendant views. @inline function _prepare_model_execution_context!( - context::RunContext, + context::Union{Nothing,RunContext}, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, + call_bindings::Tuple, temporal_streams, output_retention, time, constants, publication_allowed::Bool, - environment, + environment; + fresh::Bool=false, ) + if isnothing(context) || fresh + calls = if context isa RunContext && _call_context_clone_is_current( + context, compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, + ) + _clone_runtime_call_targets( + context.calls, compiled, environment_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, + ) + else + _runtime_call_targets( + compiled, environment_bindings, call_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, + ) + end + return RunContext( + compiled, environment_bindings, application, object_id, calls, + bound_inputs, output_targets, temporal_streams, output_retention, + float(time), constants, publication_allowed, environment, + ) + end runtime_changed = context.compiled !== compiled || context.environment_bindings !== environment_bindings @@ -2772,128 +2799,13 @@ end _synchronize_current_call_context!(context, time, publication_allowed, environment) if runtime_changed _prepare_runtime_call_targets!( - context.calls, - compiled, - environment_bindings, - temporal_streams, - output_retention, - time, - constants, - publication_allowed, - environment, + context.calls, compiled, environment_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, ) end return context end -@inline function _prepare_model_execution_context!( - context::RunContext, - compiled, - environment_bindings, - application, - object_id, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - time, - constants, -) - return _prepare_model_execution_context!( - context, - compiled, - environment_bindings, - application, - object_id, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - time, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, - ) -end - -@inline function _prepare_model_execution_context!( - ::Nothing, - compiled, - environment_bindings, - application, - object_id, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - time, - constants, - publication_allowed::Bool, - environment, -) - call_bindings = get( - compiled.call_bindings_by_target, - (application.id, object_id), - (), - ) - calls = _runtime_call_targets( - compiled, - environment_bindings, - call_bindings, - temporal_streams, - output_retention, - time, - constants, - publication_allowed, - environment, - ) - return RunContext( - compiled, - environment_bindings, - application, - object_id, - calls, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - float(time), - constants, - publication_allowed, - environment, - ) -end - -@inline function _prepare_model_execution_context!( - context::Nothing, - compiled, - environment_bindings, - application, - object_id, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - time, - constants, -) - return _prepare_model_execution_context!( - context, - compiled, - environment_bindings, - application, - object_id, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - time, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, - ) -end - function _synchronize_model_execution_batch_contexts!( batch::CompiledExecutionBatch, compiled, @@ -2917,10 +2829,13 @@ function _synchronize_model_execution_batch_contexts!( target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, temporal_streams, output_retention, time, constants, + true, + _NO_ENVIRONMENT_OVERRIDE, ) end # Mark the batch current only after every retained context has been @@ -2964,20 +2879,11 @@ end target.context.time = time target.context else - RunContext( - compiled, - env_bindings, - application, - target.object_id, - (), - target.bound_inputs, - target.output_targets, - temporal_streams, - output_retention, - time, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, + _prepare_model_execution_context!( + nothing, compiled, env_bindings, application, target.object_id, + target.bound_inputs, target.output_targets, target.call_bindings, + temporal_streams, output_retention, time, constants, + true, _NO_ENVIRONMENT_OVERRIDE, ) end run!(target.model, status, environment_value, constants, context) @@ -3041,10 +2947,13 @@ end target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, temporal_streams, output_retention, time, constants, + true, + _NO_ENVIRONMENT_OVERRIDE, ) end run!(target.model, status, environment_value, constants, context) @@ -3177,10 +3086,13 @@ end target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, temporal_streams, output_retention, batch_time, constants, + true, + _NO_ENVIRONMENT_OVERRIDE, ) end run!( @@ -3295,10 +3207,13 @@ function _run_model_execution_batch_profiled!( target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, temporal_streams, output_retention, batch_time, constants, + true, + _NO_ENVIRONMENT_OVERRIDE, ) end started_at = _runtime_performance_start(performance) @@ -3678,47 +3593,6 @@ _runtime_model_output_targets(compiled, application, object_id) = compiled.distributed_outputs, ) -function _compiled_model_execution_context( - compiled, - env_bindings, - application, - object_id, - bound_inputs, - output_targets, - call_bindings, - temporal_streams, - output_retention, - constants, -) - isnothing(temporal_streams) && isempty(output_targets) && return nothing - calls = _runtime_call_targets( - compiled, - env_bindings, - call_bindings, - temporal_streams, - output_retention, - 0.0, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, - ) - return RunContext( - compiled, - env_bindings, - application, - object_id, - calls, - bound_inputs, - output_targets, - temporal_streams, - output_retention, - 0.0, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, - ) -end - function _compiled_model_execution_target( compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, @@ -3777,18 +3651,15 @@ function _new_model_execution_target( application.id, object_id, ) - context = _compiled_model_execution_context( - compiled, - env_bindings, - application, - object_id, - bound_inputs, - distributed_targets, - call_bindings, - temporal_streams, - output_retention, - constants, - ) + context = if isnothing(temporal_streams) && isempty(distributed_targets) + nothing + else + _prepare_model_execution_context!( + nothing, compiled, env_bindings, application, object_id, + bound_inputs, distributed_targets, call_bindings, temporal_streams, + output_retention, 0.0, constants, true, _NO_ENVIRONMENT_OVERRIDE, + ) + end local_output_bindings = _runtime_model_output_streams( status_view.status, application, @@ -3866,6 +3737,28 @@ function _execution_batch_matches( batch.output_publication.enabled == output_publication.enabled end +# Retained ordered views already describe the current concrete payloads. Check +# their providers and publication contract before allocating reconciliation +# indexes; an unchanged layout needs no new batch-list owner. +function _execution_batches_match_membership( + env_bindings, application, membership, output_publication, previous_group, +) + isnothing(previous_group) && return false + previous_group.application === application || return false + batches = previous_group.batches + length(batches) == length(membership.runs) || return false + for index in eachindex(membership.runs) + rows = membership.runs[index] + batch = batches[index] + batch.targets === rows || return false + provider = _compiled_model_execution_environment_provider( + env_bindings, application, first(rows), + ) + _execution_batch_matches(batch, application, provider, output_publication) || return false + end + return true +end + function _model_execution_batches( env_bindings::CompiledEnvironmentBindings, application::CompiledModelApplication, @@ -3874,6 +3767,11 @@ function _model_execution_batches( previous_group=nothing, ) output_publication = _compiled_output_publication(output_retention, application) + if _execution_batches_match_membership( + env_bindings, application, membership, output_publication, previous_group, + ) + return (batches=previous_group.batches, batches_constructed=0) + end live_views = IdDict{ExecutionCohortRows,Nothing}(rows => nothing for rows in membership.runs) previous_by_view = IdDict{ExecutionCohortRows,Any}() spare_by_cohort = IdDict{AbstractExecutionCohort,Vector{Any}}() @@ -5233,6 +5131,7 @@ end if _call_context_clone_is_current( context, targets.compiled, targets.environment_bindings, application, target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, targets.temporal_streams, targets.output_retention, targets.constants, ) _clone_runtime_call_targets( @@ -6146,22 +6045,15 @@ function _prepare_targeted_newborn_targets( end input_bindings = CompiledModelInputBinding[] for application in callee_applications - for object_id in application.target_ids - _compile_added_consumer_bindings!( - input_bindings, - model, - application, - object_id, - _application_plans( - compiled.scenario_plan.input_recipes_by_application, - application.slot, - ), - targeted_runtime.manual_application_ids, - applications_by_object, - compiled.applications_by_id, - compiled.distributed_outputs, - ) - end + isempty(application.target_ids) && continue + recipe = _application_plans( + compiled.scenario_plan.input_recipes_by_application, application.slot, + ) + _compile_application_consumer_bindings!( + input_bindings, model, application, recipe, + targeted_runtime.manual_application_ids, applications_by_object, + compiled.applications_by_id, compiled.distributed_outputs, + ) end final_input_references = _model_input_status_references(input_bindings) _prepare_model_input_statuses_batched!( @@ -6516,9 +6408,16 @@ end return context end +@inline function _call_context_bindings_match(calls::Tuple, bindings::Tuple) + length(calls) == length(bindings) || return false + isempty(calls) && return true + first(calls).binding === first(bindings) || return false + return _call_context_bindings_match(Base.tail(calls), Base.tail(bindings)) +end + @inline function _call_context_matches( context::RunContext, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, environment, ) return context.compiled === compiled && @@ -6527,19 +6426,20 @@ end context.bound_inputs === bound_inputs && context.output_targets === output_targets && context.temporal_streams === temporal_streams && context.output_retention === output_retention && context.constants === constants && + _call_context_bindings_match(context.calls, call_bindings) && typeof(context.environment) === typeof(environment) end @inline _call_context_matches(::Nothing, args...) = false @inline function _call_context_clone_is_current( context::RunContext, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, ) # The context identity guard also protects an empty descendant template: # no per-child stamp exists to prove it still describes another generation. return _call_context_matches( context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, context.environment, ) && _call_context_preparation_is_current( context.calls, compiled, environment_bindings, temporal_streams, @@ -6547,51 +6447,16 @@ end ) end -# A typed default already contains the resolved descendant schema. Reentry or -# another environment specialization needs fresh mutable call wrappers, not a -# second graph lookup. Each child execution owner retains its own lease. -@inline function _clone_model_execution_context( - prototype::RunContext, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, time, - constants, publication_allowed, environment, -) - if !_call_context_clone_is_current( - prototype, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, - ) - return _prepare_model_execution_context!( - nothing, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, - time, constants, publication_allowed, environment, - ) - end - calls = _clone_runtime_call_targets( - prototype.calls, compiled, environment_bindings, temporal_streams, - output_retention, time, constants, publication_allowed, environment, - ) - return RunContext( - compiled, environment_bindings, application, object_id, calls, - bound_inputs, output_targets, temporal_streams, output_retention, - float(time), constants, publication_allowed, environment, - ) -end - -# Truly cold owners still require canonical graph preparation. In particular, -# Nothing does not imply that the application has no declared descendants. -@inline function _clone_model_execution_context(::Nothing, args...) - return _prepare_model_execution_context!(nothing, args...) -end - @inline function _prepare_cached_call_context!( cache::CallContextCache, reuse::Bool, compiled, environment_bindings, - application, object_id, bound_inputs, output_targets, temporal_streams, + application, object_id, bound_inputs, output_targets, call_bindings::Tuple, temporal_streams, output_retention, time, constants, publication_allowed, environment, ) Context = _call_context_type(cache.default, environment) context = reuse ? cache.default : nothing if !(context isa Context && _call_context_matches( context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, environment, ) && _call_context_preparation_is_current( context.calls, compiled, environment_bindings, temporal_streams, @@ -6601,11 +6466,11 @@ end if context isa RunContext && !(context isa Context) && _call_context_matches( context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, environment, ) && _call_context_clone_is_current( context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, ) # A stale OptionalOne can have acquired a different descendant tuple # type. Reuse that current transient rather than forcing the old @@ -6616,7 +6481,7 @@ end end if !(context isa Context && _call_context_matches( context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, environment, ) && _call_context_preparation_is_current( context.calls, compiled, environment_bindings, temporal_streams, @@ -6624,10 +6489,10 @@ end )) # A reentrant call needs its own descendants as well as its shell: # child CallTargets carry mutable time, environment and permission. - context = _clone_model_execution_context( + context = _prepare_model_execution_context!( cache.default, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, - time, constants, publication_allowed, environment, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, + time, constants, publication_allowed, environment; fresh=true, ) reuse && (cache.transient = context) return context @@ -6635,7 +6500,7 @@ end end return _prepare_model_execution_context!( context::Context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, + bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, time, constants, publication_allowed, environment, ) end @@ -6733,7 +6598,7 @@ end context = _prepare_cached_call_context!( cache, acquired, target.compiled, target.environment_bindings, target.application, target.object_id, target.bound_inputs, - target.output_targets, target.temporal_streams, target.output_retention, + target.output_targets, target.execution_target.call_bindings, target.temporal_streams, target.output_retention, target.time, target.constants, publication_allowed, environment, ) _run_owned_call_kernel!( @@ -6852,6 +6717,7 @@ end _prepare_model_execution_context!( target.context, targets.compiled, targets.environment_bindings, application, target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, targets.temporal_streams, targets.output_retention, targets.time, targets.constants, publication_allowed, environment, ) @@ -6859,6 +6725,7 @@ end _prepare_cached_call_context!( cache, acquired, targets.compiled, targets.environment_bindings, application, target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, targets.temporal_streams, targets.output_retention, targets.time, targets.constants, publication_allowed, environment, ) diff --git a/src/composite_model/source_compilation.jl b/src/composite_model/source_compilation.jl index 28ed885fa..e039b5abd 100644 --- a/src/composite_model/source_compilation.jl +++ b/src/composite_model/source_compilation.jl @@ -969,10 +969,13 @@ function _compiled_source_prepare_target!( target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, simulation.temporal_streams, simulation.output_retention, time, simulation.constants, + true, + _NO_ENVIRONMENT_OVERRIDE, ) return status, environment, context end @@ -1057,6 +1060,7 @@ function _compiled_source_run_call_target!( target.object_id, target.bound_inputs, target.output_targets, + target.call_bindings, targets.temporal_streams, targets.output_retention, targets.time, diff --git a/test/test-model-call-context-cache.jl b/test/test-model-call-context-cache.jl index 920bc7630..e598fe6c7 100644 --- a/test/test-model-call-context-cache.jl +++ b/test/test-model-call-context-cache.jl @@ -324,8 +324,10 @@ function prepare_test_cache(cache, target, environment; time=target.time, publis return PSE._prepare_cached_call_context!( cache, true, target.compiled, target.environment_bindings, target.application, target.object_id, target.bound_inputs, target.output_targets, + target.execution_target.call_bindings, target.temporal_streams, target.output_retention, time, target.constants, - publish, environment) + publish, environment, + ) end @testset "materialization preserves descendants of an actively leased default context" begin diff --git a/test/test-model-call-context-cloning.jl b/test/test-model-call-context-cloning.jl index 389d008fc..2d998939e 100644 --- a/test/test-model-call-context-cloning.jl +++ b/test/test-model-call-context-cloning.jl @@ -109,6 +109,7 @@ end return PSE._prepare_cached_call_context!( target.context_cache, reuse, target.compiled, target.environment_bindings, target.application, target.object_id, target.bound_inputs, target.output_targets, + target.execution_target.call_bindings, target.temporal_streams, target.output_retention, time, target.constants, publish, environment, ) @@ -315,8 +316,10 @@ end parent.time, parent.constants, true, parent.environment) PSE._prepare_model_execution_context!(active, refreshed, environments, parent.application, parent.object_id, parent.bound_inputs, parent.output_targets, + parent.execution_target.call_bindings, parent.temporal_streams, parent.output_retention, parent.time, - parent.constants, true, parent.environment) + parent.constants, true, parent.environment, + ) @test active.compiled === refreshed @test active.environment_bindings === environments @test old_optional.compiled === refreshed @@ -371,4 +374,59 @@ end end end +@testset "one context factory consumes the payload's already resolved bindings" begin + data = fixture(Float64) + parent = data.parent + bindings = parent.execution_target.call_bindings + @test length(bindings) == 3 + key = (parent.application.id,parent.object_id) + saved = pop!(parent.compiled.call_bindings_by_target,key) + context = nothing + try + # A target payload already owns these validated bindings. Context + # construction must not silently rediscover a different/empty schema. + context = PSE._prepare_model_execution_context!( + nothing,parent.compiled,parent.environment_bindings,parent.application, + parent.object_id,parent.bound_inputs,parent.output_targets,bindings, + parent.temporal_streams,parent.output_retention,2.0,parent.constants, + false,parent.environment, + ) + @test !haskey(parent.compiled.call_bindings_by_target,key) + @test context isa PSE.RunContext + @test Tuple(PSE._compiled_call_name(target.binding) for target in context.calls) == + Tuple(PSE._compiled_call_name(binding) for binding in bindings) + @test all(target.binding === binding for (target,binding) in zip(context.calls,bindings)) + @test context.time == 2.0 && !context.publication_allowed + @test PSE.refvalue(only(call_targets(context,:one)).status,:seen) === + PSE.refvalue(model_status(data.model,:leaf),:seen) + @test data.backend.samples == 0 + finally + parent.compiled.call_bindings_by_target[key] = saved + end + @test parent.compiled.call_bindings_by_target[key] === saved +end + +@testset "same-shaped replacement bindings do not reuse a stale prototype" begin + data = fixture(Float64) + parent = data.parent + original = parent.execution_target.call_bindings + replacement = map(original) do binding + PSE.CompiledModelCallBinding(binding.plan, binding.consumer_id, + copy(binding.callee_object_ids), copy(binding.callee_application_ids)) + end + prototype = parent.context_cache.default + @test PSE._call_context_bindings_match(prototype.calls, original) + @test !PSE._call_context_bindings_match(prototype.calls, replacement) + context = PSE._prepare_model_execution_context!( + prototype,parent.compiled,parent.environment_bindings,parent.application, + parent.object_id,parent.bound_inputs,parent.output_targets,replacement, + parent.temporal_streams,parent.output_retention,2.0,parent.constants, + false,parent.environment; fresh=true, + ) + @test context !== prototype + @test all(target.binding === binding for (target,binding) in zip(context.calls,replacement)) + @test all(target.binding === binding for (target,binding) in zip(prototype.calls,original)) + @test data.backend.samples == 0 +end + end # module TypedCallContextCloningChecks diff --git a/test/test-model-canonical-cohorts.jl b/test/test-model-canonical-cohorts.jl index ab0194dc3..091567351 100644 --- a/test/test-model-canonical-cohorts.jl +++ b/test/test-model-canonical-cohorts.jl @@ -1,6 +1,6 @@ module CanonicalCohortChecks -using PlantSimEngine, Random, Test +using PlantSimEngine, Dates, Random, Test using PlantSimEngine.Diagnostics const PSE = PlantSimEngine @@ -354,4 +354,74 @@ end @test model_status(model, :d).value == 11 end + +@testset "unchanged ordered batches reuse their list through same-schema growth" begin + model = CompositeModel( + Object(1; scale=:Leaf, status=Status(value=0f0, visits=0)), + Object(2; scale=:Leaf, status=Status(value=0.0, visits=0)), + Object(3; scale=:Leaf, status=Status(value=0f0, visits=0)); + applications=(ModelSpec(Accumulator(1f0); name=:sum, on=Many(scale=:Leaf)),), + environment=(T=1f0, duration=Day(1)), + ) + simulation = run!(model; steps=0, outputs=:none) + group = only(simulation.execution_plan.groups) + original_batches = group.batches + @test length(original_batches) == 3 # Preserve A/B/A execution order. + assembled = PSE._model_execution_batches(simulation.environment_bindings, + group.application, group.membership, simulation.output_retention, group) + @test assembled.batches === original_batches + @test assembled.batches_constructed == 0 + + # The fast reuse check must still reject changed sampling/publication + # metadata. This compiler-only probe does not run an inconsistent batch. + batch = first(original_batches) + publication = batch.output_publication + try + original_batches[1] = PSE.CompiledExecutionBatch(batch.application, batch.targets, + PSE.RawGlobalModelEnvironment((T=2f0, duration=Day(1))), publication) + changed = PSE._model_execution_batches(simulation.environment_bindings, + group.application, group.membership, simulation.output_retention, group) + @test changed.batches !== original_batches + @test changed.batches_constructed == 1 + @test first(changed.batches) !== batch + @test changed.batches[2] === original_batches[2] + @test changed.batches[3] === original_batches[3] + finally + original_batches[1] = batch + end + try + original_batches[1] = PSE.CompiledExecutionBatch(batch.application, batch.targets, + batch.environment_provider, + PSE.CompiledOutputPublication(publication.variables, !publication.enabled)) + changed = PSE._model_execution_batches(simulation.environment_bindings, + group.application, group.membership, simulation.output_retention, group) + @test changed.batches !== original_batches + @test changed.batches_constructed == 1 + @test first(changed.batches) !== batch + finally + original_batches[1] = batch + end + + continue!(simulation) + register_object!(model, Object(4; scale=:Leaf, status=Status(value=0f0, visits=0))) + continue!(simulation) + @test only(simulation.execution_plan.groups) === group + @test group.batches === original_batches + @test [target.object_id for rows in group.membership.runs for target in rows] == ObjectId.([1, 2, 3, 4]) + @test model_status(model, 1).value === 2f0 + @test model_status(model, 2).value === 2.0 + @test model_status(model, 3).value === 2f0 + @test model_status(model, 4).value === 1f0 + + remove_object!(model, 2) + continue!(simulation) + current = only(simulation.execution_plan.groups) + @test length(current.batches) == 1 + @test current.batches !== original_batches + @test [target.object_id for target in only(current.batches).targets] == ObjectId.([1, 3, 4]) + @test model_status(model, 1).value === 3f0 + @test model_status(model, 3).value === 3f0 + @test model_status(model, 4).value === 2f0 +end + end # module CanonicalCohortChecks diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 635abb26e..7b7ba0399 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -178,7 +178,7 @@ end function materialize_reader(model, compiled, application, recipe) bindings = PSE.CompiledModelInputBinding[] - PSE._compile_added_consumer_bindings!(bindings, model, application, ObjectId(2), + PSE._compile_consumer_input_recipe!(bindings, model, application.id, application.process, ObjectId(2), recipe, compiled.scenario_plan.manual_application_ids, compiled.applications_by_object, compiled.applications_by_id, compiled.distributed_outputs) diff --git a/test/test-model-materialized-call-dispatch.jl b/test/test-model-materialized-call-dispatch.jl index 4e1ed7b51..27a1cf491 100644 --- a/test/test-model-materialized-call-dispatch.jl +++ b/test/test-model-materialized-call-dispatch.jl @@ -344,8 +344,10 @@ end active = PSE._prepare_cached_call_context!(cache, true, parent.compiled, parent.environment_bindings, parent.application, parent.object_id, parent.bound_inputs, parent.output_targets, + parent.execution_target.call_bindings, parent.temporal_streams, parent.output_retention, parent.time, - parent.constants, true, parent.environment) + parent.constants, true, parent.environment, + ) @test active === cache.default old_optional = call_targets(active, :child) old_calls = active.calls diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index d3fdf76ef..553a20273 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -97,7 +97,7 @@ PSE._final_inferred_output_plans(::CountWriterChecks, id, variable, matches) = m recipe = compiled.scenario_plan.input_recipes_by_application.reader counter = CountWriterChecks(Ref(0)) bindings = PSE.CompiledModelInputBinding[] - PSE._compile_added_consumer_bindings!(bindings, model, application, ObjectId(:leaf), + PSE._compile_consumer_input_recipe!(bindings, model, application.id, application.process, ObjectId(:leaf), recipe, compiled.scenario_plan.manual_application_ids, compiled.applications_by_object, compiled.applications_by_id, counter) @test counter.count[] == 1 From f5f386277eb3e5c16241c293c1f4716782e188f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 19:21:55 +0100 Subject: [PATCH 008/324] Prepare authored scenario declarations when constructing CompositeModel --- docs/src/journeys/modelers/basic_model.md | 6 + docs/src/model_execution.md | 48 ++- src/composite_model/compilation.jl | 222 ++++++++++---- src/composite_model/registry_topology.jl | 42 ++- src/composite_model/runtime_outputs.jl | 4 +- src/composite_model/selectors.jl | 18 +- src/visualization/model_graph_editor_api.jl | 11 +- test/runtests.jl | 1 + test/test-model-scenario-authoring.jl | 322 ++++++++++++++++++++ 9 files changed, 589 insertions(+), 85 deletions(-) create mode 100644 test/test-model-scenario-authoring.jl diff --git a/docs/src/journeys/modelers/basic_model.md b/docs/src/journeys/modelers/basic_model.md index 073147780..9a4dc7403 100644 --- a/docs/src/journeys/modelers/basic_model.md +++ b/docs/src/journeys/modelers/basic_model.md @@ -53,6 +53,12 @@ Main.DocsSources.section( ) ``` +PlantSimEngine can read these declarations while constructing or inspecting a +simulation. They should describe the model without drawing random numbers or +changing its scientific state. Put those calculations in `run!` or an explicit +initializer. A fresh vector used as a default is fine: each object receives +private initial storage. + A `VariableContract` describes a variable's units and meaning. It records, for example, whether a value is per plant or per square metre, and whether it is a rate or a daily total. This helps check that two connected models diff --git a/docs/src/model_execution.md b/docs/src/model_execution.md index 87a364bf0..762c0441e 100644 --- a/docs/src/model_execution.md +++ b/docs/src/model_execution.md @@ -68,8 +68,12 @@ other simulations with different choices. ## Compilation Before Runtime -Before the first time step, PlantSimEngine prepares the simulation. This -preparation is called **compilation**. It: +`CompositeModel` prepares the application declarations when you construct it: +application identifiers, selector rules, output-port names, and environment +hints. It registers the objects you supplied without running their equations. + +Starting a simulation resolves those declarations against the current objects +and environment. This preparation is called **compilation**. It: 1. finds the objects selected by each application's `on` rule; 2. finds where each input value will come from; @@ -84,12 +88,40 @@ preparation is called **compilation**. It: 8. groups objects with matching model, status, and environment types so Julia can run them efficiently. -The scenario plan records the selected objects, connections, and execution -order. PlantSimEngine can reuse it while those declarations and the topology -still match. Live status references and time histories belong to the -simulation. When a model creates or removes an object during a run, -PlantSimEngine refreshes the affected connections before later applications -use them. Use `continue!` or `step!` to advance with the same history. +The model reuses its application declarations and dependency metadata. Target +membership, reference carriers, clocks, and sampling handles are resolved from +the real objects and environment. You can register objects or change the +weather duration before the first run; preparation uses their current values. +Run length, requested outputs, and temporal storage are supplied for each +simulation. + +Canonical object statuses belong to the model's registry. A `Simulation` uses +those live references and keeps its own progress and output history. `run!` +starts a new timeline from the model's current state. For independent repeats, +construct a fresh model or call `deepcopy(initial_model)` before the first run. Use +`continue!` or `step!` to advance the same timeline. + +When a model creates, removes, or reparents an object, the same preparation +operators refresh the affected membership and connections before later +applications use them. Unaffected targets, references, and compatible execution +batches are retained. + +### Declaration methods describe the model + +Treat `inputs_`, `outputs_`, environment declarations, `dep`, `timespec`, +`environment_hint`, and variable contracts as descriptions derived from model +parameters. PlantSimEngine may query them during construction, preparation, or +inspection. Do not draw random numbers, advance a scientific state, or depend +on their call count. Put those operations in `run!` or an explicit real-object +initializer. Creating a fresh mutable default, such as an empty vector, is +supported; object preparation keeps defaults private to each object. + +Keep declaration names and layouts stable while a prepared model is in use. +Graph-editor configuration changes prepare the declarations again. When redefining +layout methods interactively, explicitly refresh with +`PlantSimEngine.Advanced.refresh_bindings!(model; force=true)` before starting a +new simulation. Environment changes resolve clocks and bindings while retaining +unchanged application declarations. Useful inspection helpers: diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 3f20105a4..760cdd048 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -650,6 +650,135 @@ struct CompiledScenarioPlan{AP,AI,ATI,IP,IPI,IR,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL timeline::TL end +# Authoring records contain declarations, never current target identities, +# status values, resolved overrides, clocks, or simulation-owned storage. +struct AuthoredApplicationRecipe{S,M,H,ON,CN} + slot::Int + id::Symbol + spec::S + process::Symbol + name::Union{Nothing,Symbol} + target_matcher::M + environment_hint::H + output_names::ON + canonical_output_names::CN +end + +struct ScenarioPreparationFailure{E,B} + phase::Symbol + application_id::Union{Nothing,Symbol} + error::E + backtrace::B +end + +# Exceptions and interpreter frames are diagnostic metadata, and may reference +# Modules or methods that cannot be deep-copied. Preserve the original exception +# for rethrowing; give the copied model a separate trace vector. Scientific +# models, statuses and defaults are copied through their ordinary owners. +function Base.deepcopy_internal(failure::ScenarioPreparationFailure, stack::IdDict) + return get!(stack, failure) do + ScenarioPreparationFailure(failure.phase, failure.application_id, + failure.error, copy(failure.backtrace)) + end +end + +mutable struct ScenarioPreparation{M,S,A,F} + const owner::M + const source_specs::S + const authored::A + const failure::F + resolved::Any +end + +function _authored_specs_match(source_specs, specs) + length(source_specs) == length(specs) || return false + return all(pair -> pair[1] === pair[2], zip(source_specs, specs)) +end + +function _prepare_authored_scenario(model::CompositeModel, raw_specs) + source_specs = Tuple(raw_specs) + authored = Any[] + phase = :model_specs + application_id = nothing + try + specs = map(as_model_spec, source_specs) + phase = :application_identifiers + counts = Dict{Symbol,Int}() + for spec in specs + proc = process(spec) + counts[proc] = get(counts, proc, 0) + 1 + end + ids = Set{Symbol}() + for (slot, spec) in pairs(specs) + proc = process(spec) + name = application_name(spec) + application_id = isnothing(name) ? proc : name + selector = applies_to(spec) + phase = :application_selector + isnothing(selector) && error( + "Model application for process `$(proc)` has no `ModelSpec(...; on=...)` selector.", + ) + selector isa AbstractObjectMultiplicity || error( + "`ModelSpec(...; on=...)` for process `$(proc)` must use an object selector such as `Many(scale=:Leaf)`.", + ) + phase = :application_identifiers + isnothing(name) && counts[proc] > 1 && error( + "Composite model contains $(counts[proc]) unnamed applications for process `$(proc)`. " * + "Give every repeated application a unique name with `ModelSpec(model; name=:application_name)`.", + ) + application_id in ids && error("Duplicate compiled model application id `$(application_id)`.") + push!(ids, application_id) + phase = :application_selector + matcher = _authored_selector_matcher(selector) + phase = :environment_hint + hint = environment_hint(model_(spec)) + phase = :output_ports + output_names, canonical_output_names = _compiled_output_names(spec) + push!(authored, AuthoredApplicationRecipe( + slot, application_id, spec, proc, name, matcher, hint, + output_names, canonical_output_names, + )) + end + return ScenarioPreparation(model, source_specs, Tuple(authored), nothing, nothing) + catch err + err isa InterruptException && rethrow() + failure = ScenarioPreparationFailure(phase, application_id, err, catch_backtrace()) + return ScenarioPreparation(model, source_specs, Tuple(authored), failure, nothing) + end +end + +function _model_owned_scenario_preparation(model::CompositeModel, preparation::ScenarioPreparation) + preparation.owner === model && return preparation + # Internal reconstruction can share authored metadata, never the mutable + # resolved target snapshot. This check is O(1) on lifecycle invalidation. + owned = ScenarioPreparation(model, preparation.source_specs, + preparation.authored, preparation.failure, nothing) + model.scenario_plan_cache = owned + return owned +end + +function _scenario_preparation(model::CompositeModel; force::Bool=false) + preparation = model.scenario_plan_cache + if force || isnothing(preparation) || + !_authored_specs_match(preparation.source_specs, model.applications) + preparation = _prepare_authored_scenario(model, model.applications) + model.scenario_plan_cache = preparation + end + return _model_owned_scenario_preparation(model, preparation) +end + +function _authored_application_recipes(preparation::ScenarioPreparation) + isnothing(preparation.failure) || throw(preparation.failure.error) + return preparation.authored +end + +function _authored_application_recipes(model::CompositeModel, raw_specs) + if _authored_specs_match(model.applications, raw_specs) + return _authored_application_recipes(_scenario_preparation(model)) + end + return _authored_application_recipes(_prepare_authored_scenario(model, raw_specs)) +end + # The snapshot owns its target lists. Runtime application membership can # change during growth, so each binding compilation takes a private copy. struct PreparedScenario{P} @@ -1895,8 +2024,12 @@ function _prepare_scenario_plan( model::CompositeModel, timeline; force::Bool=false, performance=nothing, ) + # Snapshot forcing resolves membership and cadence again. Explicit + # refresh_bindings!(force=true) owns the separate authored-metadata refresh. + preparation = _scenario_preparation(model) + _authored_application_recipes(preparation) if !force - prepared = model.scenario_plan_cache + prepared = preparation.resolved if !isnothing(prepared) && prepared.plan.timeline.base_step_seconds == timeline.base_step_seconds return prepared end @@ -1904,7 +2037,8 @@ function _prepare_scenario_plan( if !isnothing(compiled) && compiled.scenario_plan.timeline.base_step_seconds == timeline.base_step_seconds prepared = PreparedScenario(compiled.scenario_plan, Vector{ObjectId}[copy(app.target_ids) for app in compiled.applications]) - return model.scenario_plan_cache = prepared + preparation.resolved = prepared + return prepared end end plan, applications = _build_scenario_plan(model, model.applications, timeline; performance) @@ -1914,7 +2048,8 @@ function _prepare_scenario_plan( if !force && model.bindings_dirty && !isnothing(model.binding_cache) return prepared end - return model.scenario_plan_cache = prepared + preparation.resolved = prepared + return prepared end function _compile_scene( @@ -4573,74 +4708,37 @@ function explain_initialization(model::CompositeModel) end function _compile_model_applications(model::CompositeModel, raw_specs, timeline) - specs = [as_model_spec(raw_spec) for raw_spec in raw_specs] - process_counts = Dict{Symbol,Int}() - for spec in specs - proc = process(spec) - process_counts[proc] = get(process_counts, proc, 0) + 1 - end - ids = Set{Symbol}() + recipes = _authored_application_recipes(model, raw_specs) + return _resolve_application_recipes(model, recipes, timeline) +end + +function _resolve_application_recipes(model::CompositeModel, recipes::Tuple, timeline) applications = CompiledModelApplication[] - for (slot, spec) in pairs(specs) - selector = applies_to(spec) - isnothing(selector) && error( - "Model application for process `$(process(spec))` has no `ModelSpec(...; on=...)` selector." - ) - selector isa AbstractObjectMultiplicity || error( - "`ModelSpec(...; on=...)` for process `$(process(spec))` must use an object selector such as `Many(scale=:Leaf)`." - ) - proc = process(spec) - name = application_name(spec) - if isnothing(name) && process_counts[proc] > 1 - error( - "Composite model contains $(process_counts[proc]) unnamed applications for process `$(proc)`. ", - "Give every repeated application a unique name with `ModelSpec(model; name=:application_name)`.", - ) - end - app_id = isnothing(name) ? proc : name - app_id in ids && error("Duplicate compiled model application id `$(app_id)`.") - push!(ids, app_id) - target_matcher = _compile_selector_matcher(model, selector) + for recipe in recipes + target_matcher = _resolve_selector_matcher(model, recipe.target_matcher) + selector = applies_to(recipe.spec) target_ids = _resolve_object_ids(model, selector, target_matcher) sizehint!(target_ids, length(target_ids) + 1) spec = _model_spec_with_environment_hints( - model, - spec, - _model_application_hint_scale(model, target_ids), - ) - model_overrides = _compiled_object_model_overrides(spec, target_ids, app_id) - output_names, canonical_output_names = _compiled_output_names(spec) - push!( - applications, - CompiledModelApplication( - CompiledApplicationPlan( - slot, - app_id, - spec, - proc, - name, - selector, - target_matcher, - timestep(spec), - _model_application_clock( - model, - spec, - target_ids, - timeline, - ), - model_overrides, - output_names, - canonical_output_names, - ), - target_ids, + model, recipe.spec, _model_application_hint_scale(model, target_ids), + recipe.environment_hint, + ) + model_overrides = _compiled_object_model_overrides(spec, target_ids, recipe.id) + push!(applications, CompiledModelApplication( + CompiledApplicationPlan( + recipe.slot, recipe.id, spec, recipe.process, recipe.name, + selector, target_matcher, timestep(spec), + _model_application_clock(model, spec, target_ids, timeline), + model_overrides, recipe.output_names, recipe.canonical_output_names, ), - ) + target_ids, + )) end return applications end -function _model_spec_with_environment_hints(model::CompositeModel, spec, scale::Symbol) - hint = _normalize_environment_hint(scale, process(spec), environment_hint(model_(spec))) +function _model_spec_with_environment_hints(model::CompositeModel, spec, scale::Symbol, authored_hint) + hint = _normalize_environment_hint(scale, process(spec), authored_hint) current_bindings = environment_bindings(spec) has_explicit_bindings = !(current_bindings isa NamedTuple && isempty(keys(current_bindings))) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 11ce07d7f..6ec8967c4 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -554,6 +554,30 @@ function CompositeModel( _status_conversion=nothing, _status_values_materialized::Bool=false, _status_conversion_records=nothing, +) + model = _assemble_composite_model( + items...; + applications, instances, environment, source_adapter, + type_promotion, status_transform, _status_conversion, + _status_values_materialized, _status_conversion_records, + ) + _scenario_preparation(model) + return model +end + +# Graph-editor transactions also use this assembler, then finalize authored +# preparation once after their last configuration mutation. +function _assemble_composite_model( + items::Union{Object,ObjectInstance}...; + applications=(), + instances=(), + environment=nothing, + source_adapter=nothing, + type_promotion=nothing, + status_transform=nothing, + _status_conversion=nothing, + _status_values_materialized::Bool=false, + _status_conversion_records=nothing, ) objects, mounted_instances = _collect_model_items(items, instances) instance_ids = _prepare_object_instances!(objects, mounted_instances) @@ -597,11 +621,12 @@ function CompositeModel( 0, 0, ) - return _register_model_objects!( + _register_model_objects!( model, objects; status_values_materialized=_status_values_materialized, ) + return model end """ @@ -886,9 +911,13 @@ function _mark_bindings_dirty!( kind in (:addition, :structural, :full) || error( "Unsupported binding dirty kind `$(kind)`.", ) - model.scenario_plan_cache = nothing - delta = model.lifecycle_delta ids = _lifecycle_object_ids(object_ids) + if isnothing(ids) || kind === :full + model.scenario_plan_cache = nothing + elseif !isnothing(model.scenario_plan_cache) + _model_owned_scenario_preparation(model, model.scenario_plan_cache).resolved = nothing + end + delta = model.lifecycle_delta if isnothing(ids) model.binding_cache = nothing delta.structural_kind = :full @@ -1720,11 +1749,10 @@ function refresh_bindings!( performance=performance, ) end - prepared = model.scenario_plan_cache + preparation = _scenario_preparation(model; force) + _authored_application_recipes(preparation) + prepared = preparation.resolved previous = model.binding_cache - if force - prepared = model.scenario_plan_cache = nothing - end plan_changed = !isnothing(prepared) && !isnothing(previous) && prepared.plan !== previous.scenario_plan if force || model.bindings_dirty || isnothing(previous) || plan_changed diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 2086c2613..42903e216 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7816,7 +7816,9 @@ function _prepare_simulation!( started_at = initial_composite_started_at # An existing simulation may have refreshed its environment while retaining # its schedule. Compare the current base step even after that refresh. - prepared = model.scenario_plan_cache + preparation = _scenario_preparation(model) + _authored_application_recipes(preparation) + prepared = preparation.resolved compiled = model.binding_cache if !isnothing(prepared) || !isnothing(compiled) previous = isnothing(prepared) ? compiled.scenario_plan : prepared.plan diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 6db0ba418..bb53208ea 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -690,13 +690,10 @@ _compile_selector_scope(model::CompositeModel, scope::Scope) = _compile_selector_relation(::Nothing) = nothing _compile_selector_relation(relation::Symbol) = Val(relation) -function _compile_selector_matcher( - model::CompositeModel, - selector::AbstractObjectMultiplicity, -) +function _authored_selector_matcher(selector::AbstractObjectMultiplicity) criteria_ = criteria(selector) relation = _criteria_value(criteria_, :relation, Relation) - scope = _compile_selector_scope(model, _criteria_scope(criteria_)) + scope = _criteria_scope(criteria_) scale = _criteria_value(criteria_, :scale) kind = _criteria_value(criteria_, :kind) species = _criteria_value(criteria_, :species) @@ -718,6 +715,17 @@ function _compile_selector_matcher( ) end +function _resolve_selector_matcher(model::CompositeModel, matcher::CompiledSelectorMatcher) + return CompiledSelectorMatcher( + _compile_selector_scope(model, matcher.scope), matcher.relation, + matcher.scale, matcher.kind, matcher.species, matcher.id, + matcher.defaults_to_context, + ) +end + +_compile_selector_matcher(model::CompositeModel, selector::AbstractObjectMultiplicity) = + _resolve_selector_matcher(model, _authored_selector_matcher(selector)) + function _scope_object_ids(model::CompositeModel, scope, context) if isnothing(scope) || scope isa SceneScope return ObjectId[keys(model.registry.objects)...] diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index 07b3052cf..99a2028aa 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -306,8 +306,15 @@ function apply_model_graph_edit( preserve=(), ) candidate = _model_graph_deepcopy(model, preserve) + preparation = candidate.scenario_plan_cache candidate = _apply_model_graph_edit!(candidate, edit) _mark_bindings_dirty!(candidate) + if !isnothing(preparation) && + _authored_specs_match(preparation.source_specs, candidate.applications) + candidate.scenario_plan_cache = preparation + _model_owned_scenario_preparation(candidate, preparation).resolved = nothing + end + _scenario_preparation(candidate) return candidate end @@ -1052,7 +1059,7 @@ function _model_edit_rebuild_instances( for application in model.applications if _model_edit_application_id(application) in mounted_ids ) - rebuilt = CompositeModel( + rebuilt = _assemble_composite_model( (deepcopy(object) for object in model_objects(model))...; applications=global_applications, instances=instances, @@ -1157,7 +1164,7 @@ function _apply_model_graph_edit!(model::CompositeModel, edit::SetCompositeModel application for application in model.applications if _model_edit_application_id(application) ∉ mounted_ids ) - return CompositeModel( + return _assemble_composite_model( (deepcopy(object) for object in model_objects(model))...; applications=global_applications, instances=Tuple(_model_edit_normalize_instance(instance) for instance in model.instances), diff --git a/test/runtests.jl b/test/runtests.jl index 4177844a8..d1eb6e420 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -79,6 +79,7 @@ else @testset "Reusable scenario plans" begin include("test-model-prepared-scenario.jl") + include("test-model-scenario-authoring.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") include("test-resolved-input-materialization.jl") diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl new file mode 100644 index 000000000..d4df6f0be --- /dev/null +++ b/test/test-model-scenario-authoring.jl @@ -0,0 +1,322 @@ +module ScenarioAuthoringChecks + +using Dates, PlantSimEngine, Random, Test +using PlantSimEngine.GraphEditor +const PSE = PlantSimEngine + +PSE.@process "scenario_authoring_probe" verbose=false +PSE.@process "scenario_authoring_constant" verbose=false + +struct Probe{R,C,H} <: AbstractScenario_Authoring_ProbeModel + rng::R + declarations::C + hints::H +end +function PSE.outputs_(model::Probe) + model.declarations[] += 1 + return (value=0.0, scratch=zeros(2), visits=0) +end +function PSE.environment_hint(model::Probe) + model.hints[] += 1 + return NamedTuple() +end +function PSE.run!(model::Probe, status, environment, constants, context) + status.value += rand(model.rng) + status.scratch[1] += 1 + status.visits += 1 + return nothing +end + +struct ConstantProbe <: AbstractScenario_Authoring_ConstantModel + value::Float64 +end +PSE.outputs_(::ConstantProbe) = (value=0.0, visits=0) +function PSE.run!(model::ConstantProbe, status, environment, constants, context) + status.value = model.value + status.visits += 1 + return nothing +end + +@testset "constructor prepares typed authoring metadata without materializing state" begin + declarations, hints = Ref(0), Ref(0) + rng = Xoshiro(71) + expected_rng = copy(rng) + conversions = Symbol[] + transform(variable, value) = (push!(conversions, variable); value) + model = CompositeModel(Object(1; scale=:Leaf, status=Status(seed=1.0)); + applications=(ModelSpec(Probe(rng, declarations, hints); + name=:probe, on=Many(scale=:Leaf)),), status_transform=transform) + preparation = model.scenario_plan_cache + @test preparation isa PSE.ScenarioPreparation + @test isnothing(preparation.failure) + @test isnothing(preparation.resolved) + @test preparation.authored isa Tuple + recipe = only(preparation.authored) + @test recipe isa PSE.AuthoredApplicationRecipe + @test recipe.output_names == (:value, :scratch, :visits) + @test recipe.canonical_output_names == recipe.output_names + @test recipe.spec === only(model.applications) + @test declarations[] == hints[] == 1 + @test conversions == [:seed] + @test NamedTuple(model_status(model, 1)) == (seed=1.0,) + @test isnothing(PSE.Advanced.compiled_bindings(model)) + @test rand(copy(rng)) == rand(copy(expected_rng)) + + # Resolve the existing recipe against real membership and time without + # invoking its moved port/hint declarations a second time. + resolved = PSE._compile_model_applications(model, Tuple(model.applications), PSE._model_timeline(model)) + @test only(resolved).target_ids == [ObjectId(1)] + @test declarations[] == hints[] == 1 + @test conversions == [:seed] + @test model.scenario_plan_cache === preparation + + simulation = run!(model; outputs=:all) + first_draw = rand(expected_rng) + @test model_status(model, 1).value == first_draw + @test model_status(model, 1).visits == 1 + @test hints[] == 1 + original_scratch = model_status(model, 1).scratch + converted_before_birth = length(conversions) + declaration_count = declarations[] + register_object!(model, Object(0; scale=:Leaf, status=Status(seed=2.0))) + @test model.scenario_plan_cache === preparation + @test preparation.authored === (recipe,) + @test conversions[(converted_before_birth + 1):end] == [:seed] + @test declarations[] == declaration_count + @test hints[] == 1 + step!(simulation) + newborn_draw, older_draw = rand(expected_rng), rand(expected_rng) + @test model_status(model, 0).value == newborn_draw + @test model_status(model, 1).value == first_draw + older_draw + @test model_status(model, 0).visits == 1 + @test model_status(model, 1).visits == 2 + @test model_status(model, 0).scratch !== original_scratch + @test model_status(model, 0).scratch == [1.0, 0.0] + @test original_scratch == [2.0, 0.0] + + # Configuration reconstruction retains identical authored specs and only + # refreshes runtime resolution, never preparing an intermediate model. + old_declarations = declarations[] + edited = apply_model_graph_edit(model, + SetCompositeModelEnvironment((duration=Hour(1),))) + edited_probe = PSE.model_(only(edited.applications)) + @test edited_probe.declarations[] == old_declarations + @test edited_probe.hints[] == hints[] + @test declarations[] == old_declarations + @test hints[] == 1 + @test edited.scenario_plan_cache.owner === edited + @test isnothing(edited.scenario_plan_cache.failure) +end + +@testset "structural reconstruction shares recipes but owns its target snapshot" begin + declarations, hints = Ref(0), Ref(0) + spec = ModelSpec(Probe(Xoshiro(17), declarations, hints); + name=:probe, on=Many(scale=:Leaf)) + first_model = CompositeModel(Object(1; scale=:Leaf); applications=(spec,)) + first_snapshot = PSE._prepare_scenario_plan(first_model) + first_owner = first_model.scenario_plan_cache + next_model = CompositeModel(Object(2; scale=:Leaf); applications=(spec,)) + # Internal closed-registry reconstruction passes through this field. Its + # reusable immutable metadata must not share the mutable resolved slot. + next_model.scenario_plan_cache = first_owner + before = declarations[] + next_owner = PSE._scenario_preparation(next_model) + @test next_owner !== first_owner + @test next_owner.owner === next_model + @test next_owner.authored === first_owner.authored + @test isnothing(next_owner.resolved) + @test declarations[] == before + register_object!(next_model, Object(3; scale=:Leaf)) + next_snapshot = PSE._prepare_scenario_plan(next_model) + @test only(next_snapshot.target_ids) == [ObjectId(2), ObjectId(3)] + @test first_owner.resolved === first_snapshot + @test only(first_snapshot.target_ids) == [ObjectId(1)] +end + +@testset "future scopes, targets and overrides resolve only against the first run" begin + models = PSE.ObjectModelOverrides(ConstantProbe(1.0), + Dict(ObjectId(:future_leaf) => ConstantProbe(7.0))) + model = CompositeModel(Object(:root; scale=:Plant); applications=( + ModelSpec(models; name=:probe, + on=One(scale=:Leaf, within=Scope(ObjectId(:future_root))), every=Hour(2)),), + environment=(duration=Hour(1),)) + preparation = model.scenario_plan_cache + @test isnothing(preparation.failure) + @test only(preparation.authored).target_matcher.scope isa Scope + report = PSE.compile_model_report(model) + @test !isempty(report.diagnostics) + @test isnothing(report.compiled) + @test model.scenario_plan_cache === preparation + @test isnothing(preparation.resolved) + @test_throws Exception run!(model; steps=0) + @test isnothing(preparation.failure) # cardinality is not a frozen authoring error + + register_object!(model, Object(:future_leaf; scale=:Leaf, parent=:root)) + register_object!(model, Object(:future_root; scale=:Plant, parent=:root)) + reparent_object!(model, :future_leaf, :future_root) + model.environment = (duration=Hour(2),) + mark_environment_binding_dirty!(model) + simulation = run!(model; steps=3, outputs=:all) + @test model.scenario_plan_cache === preparation + @test only(simulation.compiled.applications).target_ids == [ObjectId(:future_leaf)] + @test only(simulation.compiled.applications).clock.dt == 1.0 + @test model_status(model, :future_leaf).value == 7.0 + @test model_status(model, :future_leaf).visits == 3 +end + +@testset "cadence rebuilding after registration preserves authored metadata" begin + declarations, hints = Ref(0), Ref(0) + model = CompositeModel(Object(1; scale=:Leaf); applications=( + ModelSpec(Probe(Xoshiro(59), declarations, hints); name=:probe, + on=Many(scale=:Leaf), every=Hour(2)),), + environment=(duration=Hour(1),)) + preparation = model.scenario_plan_cache + authored = preparation.authored + first = run!(model; steps=0, outputs=:all) + @test first.compiled.scenario_plan.timeline.base_step_seconds == 3600.0 + @test only(first.compiled.applications).clock.dt == 2.0 + register_object!(model, Object(2; scale=:Leaf)) + @test model.scenario_plan_cache === preparation + @test isnothing(preparation.resolved) + model.environment = (duration=Hour(2),) + mark_environment_binding_dirty!(model) + + # Pure application resolution reuses both moved declaration hooks. Real + # status/default and contract preparation may still read outputs_ later. + declaration_count, hint_count = declarations[], hints[] + applications = PSE._compile_model_applications(model, Tuple(model.applications), + PSE._model_timeline(model)) + @test only(applications).target_ids == [ObjectId(1), ObjectId(2)] + @test only(applications).clock.dt == 1.0 + @test declarations[] == declaration_count + @test hints[] == hint_count + + # Automatic cadence forcing must commit its newly resolved plan even with + # a pending addition, while retaining the constructor's authoring owner. + restarted = run!(model; steps=3, outputs=:all) + @test model.scenario_plan_cache === preparation + @test preparation.authored === authored + @test hints[] == hint_count + @test preparation.resolved.plan === restarted.compiled.scenario_plan + @test restarted.compiled.scenario_plan.timeline.base_step_seconds == 7200.0 + @test only(restarted.compiled.applications).clock.dt == 1.0 + @test first.compiled.scenario_plan.timeline.base_step_seconds == 3600.0 + @test current_step(first) == 0 + @test current_step(restarted) == 3 + @test model_status(model, 1).visits == model_status(model, 2).visits == 3 + @test model_status(model, 1).scratch !== model_status(model, 2).scratch + + # The private snapshot force has the same resolution-only semantics. + previous_snapshot = preparation.resolved + forced_snapshot = PSE._prepare_scenario_plan(model; force=true) + @test forced_snapshot !== previous_snapshot + @test preparation.resolved === forced_snapshot + @test model.scenario_plan_cache === preparation + @test preparation.authored === authored + @test hints[] == hint_count + + # An explicit public compiler force still refreshes authored declarations. + PSE.Advanced.refresh_bindings!(model; force=true) + @test model.scenario_plan_cache !== preparation + @test hints[] == hint_count + 1 +end + +@testset "authoring errors stay structured, inspectable and repairable" begin + invalid = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(ConstantProbe(1.0); name=:missing),)) + preparation = invalid.scenario_plan_cache + @test preparation.failure isa PSE.ScenarioPreparationFailure + @test preparation.failure.phase == :application_selector + @test preparation.failure.application_id == :missing + @test preparation.failure.error isa ErrorException + @test_throws ErrorException run!(invalid; steps=0) + report = PSE.compile_model_report(invalid) + @test !isempty(report.diagnostics) + @test any(row -> occursin("selector", row.message), report.diagnostics) + @test isnothing(PSE.Advanced.compiled_bindings(invalid)) + + repaired = apply_model_graph_edit(invalid, UpdateModelApplication( + GlobalApplicationRef(:missing), ConstantProbe(2.0), :missing, + One(id=:root), nothing, + )) + simulation = run!(repaired) + @test final_state(simulation).value == 2.0 + @test isnothing(repaired.scenario_plan_cache.failure) + @test invalid.scenario_plan_cache === preparation + @test preparation.failure.application_id == :missing +end + +struct BrokenDeclarations <: AbstractScenario_Authoring_ConstantModel + fail::Base.RefValue{Bool} + calls::Base.RefValue{Int} +end +function PSE.outputs_(model::BrokenDeclarations) + model.calls[] += 1 + model.fail[] && throw(ArgumentError("intentional authored declaration failure")) + return (value=0.0, visits=0) +end +PSE.run!(::BrokenDeclarations, status, environment, constants, context) = (status.visits += 1; nothing) + +@testset "a captured declaration error is propagated without re-evaluation" begin + fail, calls = Ref(true), Ref(0) + model = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(BrokenDeclarations(fail, calls); name=:broken, on=One(id=:root)),), + environment=(duration=Hour(1),)) + failure = model.scenario_plan_cache.failure + @test failure.phase == :output_ports + @test failure.application_id == :broken + @test failure.error isa ArgumentError + @test calls[] == 1 + @test_throws ArgumentError run!(model; steps=0) + @test calls[] == 1 + report = PSE.compile_model_report(model) + @test any(row -> occursin("intentional authored declaration failure", row.message), report.diagnostics) + @test calls[] == 1 # diagnostic recovery works on its owned structural copy + fail[] = false + PSE.Advanced.refresh_bindings!(model; force=true) + @test isnothing(model.scenario_plan_cache.failure) + @test final_state(run!(model)).visits == 1 + # A failed force refresh must not let an older compiled cache hide the + # newly recorded declaration error on a later normal run/snapshot query. + fail[] = true + @test_throws ArgumentError PSE.Advanced.refresh_bindings!(model; force=true) + failed_count = calls[] + @test_throws ArgumentError run!(model; steps=0) + @test_throws ArgumentError PSE._prepare_scenario_plan(model) + @test calls[] == failed_count + + # Automatic cadence rebuilding is an ordinary run, not permission to + # reevaluate a declaration already captured by a failed force refresh. + model.environment = (duration=Hour(2),) + mark_environment_binding_dirty!(model) + @test_throws ArgumentError run!(model; steps=0) + @test calls[] == failed_count +end + +struct ModuleDeclarationError <: Exception + owner::Module +end +Base.showerror(io::IO, ::ModuleDeclarationError) = print(io, "invalid module declaration") + +struct ModuleDeclaration <: AbstractScenario_Authoring_ConstantModel end +PSE.outputs_(::ModuleDeclaration) = throw(ModuleDeclarationError(@__MODULE__)) + +@testset "diagnostic copies retain opaque exceptions without copying modules" begin + model = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(ModuleDeclaration(); name=:module_error, on=One(id=:root)),)) + failure = model.scenario_plan_cache.failure + @test failure.error isa ModuleDeclarationError + @test failure.error.owner === @__MODULE__ + owned = deepcopy(model) + @test owned.scenario_plan_cache.owner === owned + @test owned.scenario_plan_cache.failure.error === failure.error + @test owned.scenario_plan_cache.failure.backtrace !== failure.backtrace + @test owned.scenario_plan_cache.failure.backtrace == failure.backtrace + @test_throws ModuleDeclarationError run!(owned; steps=0) + report = PSE.compile_model_report(model) + @test any(row -> occursin("invalid module declaration", row.message), report.diagnostics) + @test model.scenario_plan_cache.failure === failure + @test isnothing(PSE.Advanced.compiled_bindings(model)) +end + +end # module ScenarioAuthoringChecks From 46bd9092f500f1ae6ed127b67289b08e10a856ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 19:35:04 +0100 Subject: [PATCH 009/324] Keep compiled metadata tables behind typed scalar lookup owners --- src/composite_model/compilation.jl | 39 +++++-- test/runtests.jl | 1 + test/test-model-api-stabilization.jl | 8 +- test/test-model-diagnostic-isolation.jl | 2 +- test/test-model-input-recipes.jl | 2 +- test/test-model-prepared-scenario.jl | 8 +- test/test-owned-metadata-tables.jl | 109 ++++++++++++++++++++ test/test-resolved-input-materialization.jl | 2 +- 8 files changed, 151 insertions(+), 20 deletions(-) create mode 100644 test/test-owned-metadata-tables.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 760cdd048..6962040c0 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -74,12 +74,33 @@ struct CompiledModelInputPlan{TAG,SEL,M,OA,PSA,W} window::W end +"""Fixed metadata schema whose scalar lookups stay inside its typed owner.""" +mutable struct CompiledMetadataTable{T<:NamedTuple} + const entries::T +end + +@inline Base.getindex(table::CompiledMetadataTable, key::Union{Symbol,Int}) = + getindex(getfield(table, :entries), key) +@inline Base.get(table::CompiledMetadataTable, key::Symbol, default) = + get(getfield(table, :entries), key, default) +@inline Base.haskey(table::CompiledMetadataTable, key::Symbol) = + haskey(getfield(table, :entries), key) +@inline Base.keys(table::CompiledMetadataTable) = keys(getfield(table, :entries)) +@inline Base.length(table::CompiledMetadataTable) = length(getfield(table, :entries)) +# Iterate through the owner; returning values(entries) would expose the complete +# tuple again at an unspecialized caller boundary. +Base.values(table::CompiledMetadataTable) = table +@inline function Base.iterate(table::CompiledMetadataTable, slot::Int=1) + slot > length(table) && return nothing + return (table[slot], slot + 1) +end + """Prepared application input order and query sharing; no live object state.""" -struct CompiledApplicationInputRecipe{E,G,Q} - explicit::E - inferred::G - query_slots::Q - query_count::Int +mutable struct CompiledApplicationInputRecipe{E,G,Q} + const explicit::E + const inferred::G + const query_slots::Q + const query_count::Int end function _input_query_key(plan::CompiledModelInputPlan) @@ -120,7 +141,7 @@ function _compiled_application_input_recipe(plans) end _compiled_application_input_recipes(plans_by_application) = - map(_compiled_application_input_recipe, plans_by_application) + CompiledMetadataTable(map(_compiled_application_input_recipe, plans_by_application)) """Immutable authored hard-call declaration for one application.""" struct CompiledModelCallPlan{NAME,MODE,SEL,M,PCA} @@ -805,7 +826,7 @@ end function _applications_by_id(applications) application_ids = Tuple(application.id for application in applications) - return NamedTuple{application_ids}(Tuple(applications)) + return CompiledMetadataTable(NamedTuple{application_ids}(Tuple(applications))) end function _scenario_call_owners(applications, call_plans) @@ -1323,7 +1344,7 @@ function _compiled_scenario_plan( applications, application_children, ) - application_plans_by_id = NamedTuple{application_ids}(application_plans) + application_plans_by_id = CompiledMetadataTable(NamedTuple{application_ids}(application_plans)) application_schedule = _compiled_application_schedule( application_plans_by_id, application_order, @@ -7583,7 +7604,7 @@ function _compile_model_output_destination_plans( end _application_plans(plans_by_application, application_slot::Integer) = - getfield(plans_by_application, application_slot) + plans_by_application[application_slot] function _potential_input_source_applications( applications_by_id, diff --git a/test/runtests.jl b/test/runtests.jl index d1eb6e420..02c4a6b40 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -82,6 +82,7 @@ else include("test-model-scenario-authoring.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") + include("test-owned-metadata-tables.jl") include("test-resolved-input-materialization.jl") end diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 31a60a0d6..f0272e8f5 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -814,7 +814,7 @@ end Advanced.refresh_environment_bindings!(model) register_object!(model, Object(:leaf_1; scale=:Leaf, parent=:scene)) first_refresh = Advanced.refresh_bindings!(model) - @test first_refresh.applications_by_id.source.target_ids == + @test first_refresh.applications_by_id[:source].target_ids == ObjectId[ObjectId(:leaf_1)] after_binding_refresh = Advanced.lifecycle_delta(model) @test after_binding_refresh.structural_kind == :clean @@ -829,7 +829,7 @@ end @test Tuple(snapshot.id for snapshot in pending.added) == (ObjectId(:leaf_1), ObjectId(:leaf_2)) Advanced.refresh_environment_bindings!(model) - @test Advanced.compiled_bindings(model).applications_by_id.source.target_ids == + @test Advanced.compiled_bindings(model).applications_by_id[:source].target_ids == ObjectId.([:leaf_1, :leaf_2]) @test Advanced.lifecycle_delta(model).structural_kind == :clean @test isempty(Advanced.lifecycle_delta(model).added) @@ -1676,7 +1676,7 @@ end @test !ismutabletype(typeof(only(application_schedule.entries))) @test ismutabletype(typeof(application)) @test isconst(typeof(application), :plan) - @test compiled.applications_by_id isa NamedTuple + @test compiled.applications_by_id isa PlantSimEngine.CompiledMetadataTable @test scenario_plan.call_owners isa NamedTuple @test scenario_plan.application_children isa NamedTuple @test scenario_plan.manual_application_ids == () @@ -2114,7 +2114,7 @@ end Object(:leaf_2; scale=:Leaf, parent=:plant), ) @test ObjectId(:leaf_2) ∉ - simulation.compiled.applications_by_id.source.target_ids + simulation.compiled.applications_by_id[:source].target_ids pending_delta = Advanced.lifecycle_delta(model) @test pending_delta.structural_kind == :addition @test only(pending_delta.added).id == ObjectId(:leaf_2) diff --git a/test/test-model-diagnostic-isolation.jl b/test/test-model-diagnostic-isolation.jl index 5f7d57f02..f5b394186 100644 --- a/test/test-model-diagnostic-isolation.jl +++ b/test/test-model-diagnostic-isolation.jl @@ -86,7 +86,7 @@ end @test only(explain_bindings(model)).source_ids == [:leaf_a, :leaf_b] @test Advanced.bindings_dirty(model) @test Advanced.environment_bindings_dirty(model) - @test simulation.compiled.applications_by_id.source.target_ids == [ObjectId(:leaf_a)] + @test simulation.compiled.applications_by_id[:source].target_ids == [ObjectId(:leaf_a)] @test binding.source_ids == [ObjectId(:leaf_a)] @test input_carrier(binding) === carrier @test outputs(simulation)[stream_key] === retained diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 7b7ba0399..6d83f4b92 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -118,7 +118,7 @@ end ModelSpec(Writer(3f0); name=:source, on=Many(scale=:Leaf)), ), environment=(duration=Hour(1),)) simulation = run!(model; outputs=:all) - recipe = simulation.compiled.scenario_plan.input_recipes_by_application.inferred + recipe = simulation.compiled.scenario_plan.input_recipes_by_application[:inferred] @test isempty(recipe.explicit) @test Tuple(first(group).input for group in recipe.inferred) == (:x, :y) @test model_status(model, 1).total === 9f0 diff --git a/test/test-model-prepared-scenario.jl b/test/test-model-prepared-scenario.jl index 166c99cdf..621518047 100644 --- a/test/test-model-prepared-scenario.jl +++ b/test/test-model-prepared-scenario.jl @@ -132,7 +132,7 @@ end [ObjectId(:new_sensor)] continue!(cached_sim; steps=1) @test cached_sim.compiled.scenario_plan === removed.plan - @test cached_sim.compiled.applications_by_id.reader_a.target_ids == [ObjectId(:new_sensor)] + @test cached_sim.compiled.applications_by_id[:reader_a].target_ids == [ObjectId(:new_sensor)] @test PlantSimEngine._prepare_scenario_plan(model).plan === cached_sim.compiled.scenario_plan @test haskey(outputs(cached_sim), (:reader_a, ObjectId(:new_sensor), :observed)) end @@ -160,7 +160,7 @@ end @test ongoing.compiled.scenario_plan.timeline.base_step_seconds == 3600.0 restarted = run!(continued_model; steps=0) @test restarted.compiled.scenario_plan.timeline.base_step_seconds == 7200.0 - @test restarted.compiled.scenario_plan.applications_by_id.producer.clock.dt == 1.0 + @test restarted.compiled.scenario_plan.applications_by_id[:producer].clock.dt == 1.0 @test ongoing.compiled.scenario_plan.timeline.base_step_seconds == 3600.0 authored = prepared_scenario_fixture() @@ -176,8 +176,8 @@ end )) changed = PlantSimEngine._prepare_scenario_plan(edited) @test PlantSimEngine._prepare_scenario_plan(authored) === original - @test original.plan.applications_by_id.producer.clock.dt == 2.0 - @test changed.plan.applications_by_id.producer.clock.dt == 3.0 + @test original.plan.applications_by_id[:producer].clock.dt == 2.0 + @test changed.plan.applications_by_id[:producer].clock.dt == 3.0 edited_sim = run!(edited; steps=6, outputs=:all) fresh = prepared_scenario_fixture(; cadence=Hour(3), seed=37, reader_scope=Scope(:plant_b)) @test edited_sim.compiled.scenario_plan === changed.plan diff --git a/test/test-owned-metadata-tables.jl b/test/test-owned-metadata-tables.jl new file mode 100644 index 000000000..975b3d305 --- /dev/null +++ b/test/test-owned-metadata-tables.jl @@ -0,0 +1,109 @@ +module OwnedMetadataTableChecks + +using PlantSimEngine, Random, Test +const PSE = PlantSimEngine + +left_entry(table) = table[:left] +second_entry(table) = table[2] + +@testset "fixed metadata owner preserves order, lookup, and reference identity" begin + left, right = Ref(1), Ref(2f0) + entries = (left=left, right=right) + table = PSE.CompiledMetadataTable(entries) + @test ismutabletype(typeof(table)) + @test isconst(typeof(table), :entries) + @test keys(table) === (:left, :right) + @test length(table) == 2 + @test !isempty(table) + @test values(table) === table + @test (@inferred left_entry(table)) === left + @test (@inferred second_entry(table)) === right + @test_throws MethodError table[Int32(1)] + @test get(table, :left, nothing) === left + @test get(table, :missing, right) === right + @test haskey(table, :left) + @test !haskey(table, :missing) + @test Tuple(values(table)) === (left, right) + @test_throws BoundsError table[0] + @test_throws BoundsError table[3] + @test_throws ErrorException table[:missing] + left[] = 7 + @test table[:left][] == 7 + @test right[] === 2f0 + reserved = PSE.CompiledMetadataTable((entries=left, length=right)) + @test reserved[:entries] === left + @test reserved[:length] === right + empty_table = PSE.CompiledMetadataTable(NamedTuple()) + @test isempty(empty_table) + @test keys(empty_table) === () + @test iterate(empty_table) === nothing + @test Tuple(values(empty_table)) === () +end + +PSE.@process "metadata_owner_source" verbose=false +PSE.@process "metadata_owner_reader" verbose=false + +struct Source{R} <: AbstractMetadata_Owner_SourceModel + rng::R + metadata_calls::Base.RefValue{Int} +end +function PSE.inputs_(model::Source) + model.metadata_calls[] += 1 + return NamedTuple() +end +function PSE.outputs_(model::Source) + model.metadata_calls[] += 1 + return (x=0f0,) +end +PSE.run!(model::Source, status, environment, constants, context) = + (status.x += rand(model.rng, Float32); nothing) + +struct Reader <: AbstractMetadata_Owner_ReaderModel end +PSE.inputs_(::Reader) = (x=Required(Float32),) +PSE.outputs_(::Reader) = (y=0f0,) +PSE.run!(::Reader, status, environment, constants, context) = + (status.y = 2f0 * status.x; nothing) + +function fixture() + rng = Xoshiro(71) + metadata_calls = Ref(0) + model = CompositeModel(Object(1; scale=:Leaf); + applications=( + ModelSpec(Reader(); name=:reader, on=Many(scale=:Leaf)), + ModelSpec(Source(rng, metadata_calls); name=:source, on=Many(scale=:Leaf)), + )) + return model, rng, metadata_calls +end + +@testset "metadata indexes reuse canonical application and recipe identities" begin + model, rng, metadata_calls = fixture() + simulation = run!(model; steps=1, outputs=:all) + compiled = simulation.compiled + source = compiled.applications_by_id[:source] + recipe = compiled.scenario_plan.input_recipes_by_application[:reader] + @test source === compiled.applications[2] + @test compiled.applications_by_id[2] === source + @test compiled.scenario_plan.applications_by_id[:source] === source.plan + @test PSE._application_plans(compiled.scenario_plan.input_recipes_by_application, 1) === recipe + @test recipe isa PSE.CompiledApplicationInputRecipe + @test ismutabletype(typeof(recipe)) + @test all(name -> isconst(typeof(recipe), name), fieldnames(typeof(recipe))) + @test isempty(recipe.explicit) + @test only(only(recipe.inferred)).input === :x + calls_before = metadata_calls[] + rng_before = copy(rng) + by_id = PSE._applications_by_id(compiled.applications) + recipes = PSE._compiled_application_input_recipes(compiled.scenario_plan.input_plans_by_application) + @test by_id[:source] === source + @test recipes[:reader].inferred === recipe.inferred + @test metadata_calls[] == calls_before + @test rand(copy(rng), Float32) === rand(rng_before, Float32) + @test model_status(model, 1).y === 2f0 * model_status(model, 1).x + register_object!(model, Object(2; scale=:Leaf)) + continue!(simulation; steps=1) + @test simulation.compiled.scenario_plan.input_recipes_by_application[:reader] === recipe + @test ObjectId(2) in simulation.compiled.applications_by_id[:source].target_ids + @test model_status(model, 2).y === 2f0 * model_status(model, 2).x +end + +end diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index 553a20273..2d1f21624 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -94,7 +94,7 @@ PSE._final_inferred_output_plans(::CountWriterChecks, id, variable, matches) = m simulation = run!(model; outputs=:all) compiled = simulation.compiled application = compiled.applications_by_id[:reader] - recipe = compiled.scenario_plan.input_recipes_by_application.reader + recipe = compiled.scenario_plan.input_recipes_by_application[:reader] counter = CountWriterChecks(Ref(0)) bindings = PSE.CompiledModelInputBinding[] PSE._compile_consumer_input_recipe!(bindings, model, application.id, application.process, ObjectId(:leaf), From c21f6c6d9f0806f1c67589615ace2b6bd4c339dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 21:24:18 +0100 Subject: [PATCH 010/324] Share typed lifecycle factories and logical execution identities across the canonical engine --- docs/src/model_execution.md | 5 +- src/composite_model/call_evaluation_types.jl | 8 +- src/composite_model/call_evaluations.jl | 8 +- src/composite_model/compilation.jl | 515 +++++++++++++----- src/composite_model/environment_bindings.jl | 47 +- src/composite_model/execution_dispatch.jl | 30 +- src/composite_model/object_families.jl | 21 +- src/composite_model/registry_topology.jl | 49 +- src/composite_model/runtime_outputs.jl | 235 ++++++-- src/composite_model/status_construction.jl | 42 ++ src/input_schema.jl | 18 +- src/visualization/model_graph_editor_api.jl | 2 +- src/visualization/model_graph_view.jl | 59 +- test/runtests.jl | 14 + test/test-application-membership-slots.jl | 124 +++++ test/test-input-default-values.jl | 156 ++++++ test/test-input-source-matching.jl | 145 +++++ test/test-model-adaptive-selectors.jl | 2 +- test/test-model-authored-call-plans.jl | 203 +++++++ test/test-model-call-context-cache.jl | 2 +- test/test-model-call-evaluations.jl | 38 +- test/test-model-call-execution-identity.jl | 256 +++++++++ ...est-model-diagnostic-authoring-recovery.jl | 148 +++++ test/test-model-input-recipes.jl | 2 +- .../test-model-newborn-context-initializer.jl | 75 +++ test/test-model-newborn-context-nested.jl | 93 ++++ test/test-model-newborn-execution-owner.jl | 19 +- test/test-model-persistent-empty-groups.jl | 98 ++++ test/test-model-runtime-call-names.jl | 7 +- test/test-model-slot-group-refresh.jl | 92 ++++ test/test-owned-metadata-tables.jl | 4 +- test/test-registered-status-dispatch.jl | 165 ++++++ test/test-selector-ancestor-index.jl | 73 +++ test/test-selector-query-scope-append.jl | 118 ++++ test/test-selector-query-scope-root.jl | 139 +++++ test/test-status-construction.jl | 12 +- 36 files changed, 2673 insertions(+), 351 deletions(-) create mode 100644 test/test-application-membership-slots.jl create mode 100644 test/test-input-default-values.jl create mode 100644 test/test-input-source-matching.jl create mode 100644 test/test-model-authored-call-plans.jl create mode 100644 test/test-model-call-execution-identity.jl create mode 100644 test/test-model-diagnostic-authoring-recovery.jl create mode 100644 test/test-model-newborn-context-initializer.jl create mode 100644 test/test-model-newborn-context-nested.jl create mode 100644 test/test-model-persistent-empty-groups.jl create mode 100644 test/test-model-slot-group-refresh.jl create mode 100644 test/test-registered-status-dispatch.jl create mode 100644 test/test-selector-ancestor-index.jl create mode 100644 test/test-selector-query-scope-append.jl create mode 100644 test/test-selector-query-scope-root.jl diff --git a/docs/src/model_execution.md b/docs/src/model_execution.md index 762c0441e..ff5344a78 100644 --- a/docs/src/model_execution.md +++ b/docs/src/model_execution.md @@ -69,8 +69,9 @@ other simulations with different choices. ## Compilation Before Runtime `CompositeModel` prepares the application declarations when you construct it: -application identifiers, selector rules, output-port names, and environment -hints. It registers the objects you supplied without running their equations. +application identifiers, selector rules, output-port names, environment hints, +and declared calls between models. It registers the objects you supplied without +running their equations. Starting a simulation resolves those declarations against the current objects and environment. This preparation is called **compilation**. It: diff --git a/src/composite_model/call_evaluation_types.jl b/src/composite_model/call_evaluation_types.jl index 44c9b7142..3056ffa53 100644 --- a/src/composite_model/call_evaluation_types.jl +++ b/src/composite_model/call_evaluation_types.jl @@ -26,7 +26,7 @@ mutable struct CallEvaluationTaskIdentity end mutable struct CallEvaluationFrame events::Vector{AbstractCallPublicationEvent} - executions::IdDict{Any,UInt64} + executions::IdDict{Base.RefValue{UInt64},UInt64} generation::UInt64 pending::Bool in_use::Bool @@ -46,9 +46,9 @@ mutable struct CallEvaluationFrame end CallEvaluationFrame() = CallEvaluationFrame( - # Execution stamps belong to mutable cache identities. Their contents and - # transient leases may change while a candidate is pending. - AbstractCallPublicationEvent[], IdDict{Any,UInt64}(), UInt64(0), false, + # Execution stamps identify logical application/object state. Context-cache + # wrappers and transient leases may be rebuilt while that identity persists. + AbstractCallPublicationEvent[], IdDict{Base.RefValue{UInt64},UInt64}(), UInt64(0), false, false, nothing, nothing, 0, 0, 0, nothing, UInt64(0), (false, false), UInt64(0), 0.0, nothing, UInt64(0), false, ) diff --git a/src/composite_model/call_evaluations.jl b/src/composite_model/call_evaluations.jl index faa017729..d9f08da63 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -248,8 +248,8 @@ call_targets(evaluation::CallEvaluation) = evaluation.targets return nothing end -@noinline _call_execution_matches(cache::CallContextCache, executions::IdDict{Any,UInt64}) = - cache.execution_revision == executions[cache] +@noinline _call_execution_matches(stamp::Base.RefValue{UInt64}, + executions::IdDict{Base.RefValue{UInt64},UInt64}) = stamp[] == executions[stamp] function _validate_call_evaluation(evaluation::CallEvaluation) frame = evaluation.frame @@ -258,8 +258,8 @@ function _validate_call_evaluation(evaluation::CallEvaluation) frame.pending && frame.generation == evaluation.generation || throw(ArgumentError("Call evaluation is stale or has already been accepted.")) _validate_call_model_state(frame, frame.compiled) - for cache in keys(frame.executions) - _call_execution_matches(cache, frame.executions) || + for stamp in keys(frame.executions) + _call_execution_matches(stamp, frame.executions) || throw(ArgumentError("Call evaluation is stale after another execution of its targets.")) end frame.parent === _active_call_evaluation() || diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6962040c0..b93c579c5 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2,7 +2,7 @@ Immutable scenario-level metadata for one model application. Runtime object membership is stored separately in [`CompiledModelApplication`](@ref). """ -struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,ON,CN} +struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,ON,CN,CP} slot::Int id::Symbol spec::S @@ -15,6 +15,7 @@ struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,ON,CN} model_overrides::MO output_names::ON canonical_output_names::CN + call_plans::CP end """ @@ -80,13 +81,13 @@ mutable struct CompiledMetadataTable{T<:NamedTuple} end @inline Base.getindex(table::CompiledMetadataTable, key::Union{Symbol,Int}) = - getindex(getfield(table, :entries), key) + _with_metadata_entry(identity, table, key) @inline Base.get(table::CompiledMetadataTable, key::Symbol, default) = - get(getfield(table, :entries), key, default) -@inline Base.haskey(table::CompiledMetadataTable, key::Symbol) = - haskey(getfield(table, :entries), key) -@inline Base.keys(table::CompiledMetadataTable) = keys(getfield(table, :entries)) -@inline Base.length(table::CompiledMetadataTable) = length(getfield(table, :entries)) + haskey(table, key) ? table[key] : default +@inline Base.haskey(::CompiledMetadataTable{T}, key::Symbol) where {T} = + key in fieldnames(T) +@inline Base.keys(::CompiledMetadataTable{T}) where {T} = fieldnames(T) +@inline Base.length(::CompiledMetadataTable{T}) where {T} = fieldcount(T) # Iterate through the owner; returning values(entries) would expose the complete # tuple again at an unspecialized caller boundary. Base.values(table::CompiledMetadataTable) = table @@ -673,7 +674,7 @@ end # Authoring records contain declarations, never current target identities, # status values, resolved overrides, clocks, or simulation-owned storage. -struct AuthoredApplicationRecipe{S,M,H,ON,CN} +struct AuthoredApplicationRecipe{S,M,H,ON,CN,CP} slot::Int id::Symbol spec::S @@ -683,6 +684,13 @@ struct AuthoredApplicationRecipe{S,M,H,ON,CN} environment_hint::H output_names::ON canonical_output_names::CN + call_plans::CP +end + +function _application_recipe_with_calls(recipe::AuthoredApplicationRecipe, call_plans::Tuple) + return AuthoredApplicationRecipe(recipe.slot, recipe.id, recipe.spec, + recipe.process, recipe.name, recipe.target_matcher, recipe.environment_hint, + recipe.output_names, recipe.canonical_output_names, call_plans) end struct ScenarioPreparationFailure{E,B} @@ -718,20 +726,36 @@ end function _prepare_authored_scenario(model::CompositeModel, raw_specs) source_specs = Tuple(raw_specs) - authored = Any[] - phase = :model_specs - application_id = nothing - try - specs = map(as_model_spec, source_specs) - phase = :application_identifiers - counts = Dict{Symbol,Int}() - for spec in specs + # Capture one declaration result per application. Invalid authoring does + # not hide later valid applications from a read-only diagnostic report. + counts = Dict{Symbol,Int}() + prepared_specs = map(source_specs) do raw_spec + phase = :model_specs + try + spec = as_model_spec(raw_spec) + phase = :application_identifiers proc = process(spec) + proc isa Symbol || throw(ArgumentError( + "A model process identifier must be a Symbol, got `$(typeof(proc))`.", + )) counts[proc] = get(counts, proc, 0) + 1 + (spec, proc) + catch err + err isa InterruptException && rethrow() + ScenarioPreparationFailure(phase, nothing, err, catch_backtrace()) end - ids = Set{Symbol}() - for (slot, spec) in pairs(specs) - proc = process(spec) + end + authored = Any[] + ids = Set{Symbol}() + for (slot, prepared) in pairs(prepared_specs) + if prepared isa ScenarioPreparationFailure + push!(authored, prepared) + continue + end + spec, proc = prepared + phase = :application_identifiers + application_id = nothing + try name = application_name(spec) application_id = isnothing(name) ? proc : name selector = applies_to(spec) @@ -757,15 +781,35 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs) output_names, canonical_output_names = _compiled_output_names(spec) push!(authored, AuthoredApplicationRecipe( slot, application_id, spec, proc, name, matcher, hint, - output_names, canonical_output_names, + output_names, canonical_output_names, (), )) - end - return ScenarioPreparation(model, source_specs, Tuple(authored), nothing, nothing) - catch err - err isa InterruptException && rethrow() - failure = ScenarioPreparationFailure(phase, application_id, err, catch_backtrace()) - return ScenarioPreparation(model, source_specs, Tuple(authored), failure, nothing) - end + catch err + err isa InterruptException && rethrow() + push!(authored, ScenarioPreparationFailure(phase, application_id, err, catch_backtrace())) + end + end + # ModelSpec already owns normalized Call/Initializer declarations. Prepare + # their logical routes after every application identifier is known, without + # replaying dep or resolving any object/scope membership. + declaration_applications = Tuple(record for record in authored + if record isa AuthoredApplicationRecipe) + call_slot = 0 + for index in eachindex(authored) + recipe = authored[index] + recipe isa AuthoredApplicationRecipe || continue + try + call_plans = _prepare_authored_call_plans(recipe, declaration_applications, call_slot) + authored[index] = _application_recipe_with_calls(recipe, call_plans) + call_slot += length(call_plans) + catch err + err isa InterruptException && rethrow() + authored[index] = ScenarioPreparationFailure(:call_declarations, + recipe.id, err, catch_backtrace()) + end + end + failure_index = findfirst(record -> record isa ScenarioPreparationFailure, authored) + failure = isnothing(failure_index) ? nothing : authored[failure_index] + return ScenarioPreparation(model, source_specs, Tuple(authored), failure, nothing) end function _model_owned_scenario_preparation(model::CompositeModel, preparation::ScenarioPreparation) @@ -778,18 +822,26 @@ function _model_owned_scenario_preparation(model::CompositeModel, preparation::S return owned end +_authored_specs_match(preparation::ScenarioPreparation, model::CompositeModel) = + _authored_specs_match(preparation.source_specs, model.applications) + function _scenario_preparation(model::CompositeModel; force::Bool=false) preparation = model.scenario_plan_cache if force || isnothing(preparation) || - !_authored_specs_match(preparation.source_specs, model.applications) + !_authored_specs_match(preparation, model) preparation = _prepare_authored_scenario(model, model.applications) model.scenario_plan_cache = preparation end return _model_owned_scenario_preparation(model, preparation) end -function _authored_application_recipes(preparation::ScenarioPreparation) +function _validate_authored_scenario(preparation::ScenarioPreparation) isnothing(preparation.failure) || throw(preparation.failure.error) + return nothing +end + +function _authored_application_recipes(preparation::ScenarioPreparation) + _validate_authored_scenario(preparation) return preparation.authored end @@ -1209,7 +1261,7 @@ function _application_output_selectors( selectors = Any[] variable in _model_canonical_output_names(application) && push!(selectors, application.applies_to) - for plan in _application_plans(plans.by_application, application.slot) + for plan in _application_plans(plans.by_application, application.id) variable in keys(plan.declarations) || continue push!(selectors, plan.selector) end @@ -1440,6 +1492,9 @@ end # compiled bindings and every execution owner. Numerical state remains in the # existing reference carriers; only those carriers' values may change in place. mutable struct CompiledModelStatusView{S,C,T,P,BI} + # One logical application/object execution identity, shared by all context + # leases and by rebuilt views of the same live scientific state. + const execution_stamp::Base.RefValue{UInt64} const status::S const canonical_status::C const temporal_inputs::T @@ -2048,7 +2103,7 @@ function _prepare_scenario_plan( # Snapshot forcing resolves membership and cadence again. Explicit # refresh_bindings!(force=true) owns the separate authored-metadata refresh. preparation = _scenario_preparation(model) - _authored_application_recipes(preparation) + _validate_authored_scenario(preparation) if !force prepared = preparation.resolved if !isnothing(prepared) && prepared.plan.timeline.base_step_seconds == timeline.base_step_seconds @@ -2178,7 +2233,7 @@ function _compile_scene( applications, applications_by_id, ordered_applications, - _applications_by_object(applications), + _applications_by_object(applications, model.registry.objects), input_bindings, call_bindings, input_bindings_by_target, @@ -2772,19 +2827,28 @@ function _append_added_many_sources!( ) binding.multiplicity == :many || return false default_scope = _default_dependency_scope(model, binding.consumer_id) - new_source_ids = ObjectId[ - object_id for object_id in added_ids if - _selector_matches_object_id( - model, - binding.matcher, - object_id; - context=binding.consumer_id, - default_to_context=true, - default_scope=default_scope, - ) && !first( - _sorted_object_id_position(binding.source_ids, object_id), - ) - ] + matcher = binding.matcher + matching_matcher = matcher + query_prepared = false + new_source_ids = ObjectId[] + for object_id in added_ids + if matcher.defaults_to_context + object_id == binding.consumer_id || continue + else + _selector_matches_object_labels(model, matcher, object_id) || continue + # Preserve point-predicate error order: no topology work until a + # candidate passes labels, then resolve its scope only once. + if !query_prepared + matching_matcher = _query_scope_matcher(model, matcher, + binding.consumer_id, default_scope) + query_prepared = true + end + _selector_matches_object_topology(model, matching_matcher, object_id; + context=binding.consumer_id, default_scope) || continue + end + first(_sorted_object_id_position(binding.source_ids, object_id)) || + push!(new_source_ids, object_id) + end isempty(new_source_ids) && return true _sort_object_ids!(new_source_ids) _filter_many_input_sources_by_writer!( @@ -3049,6 +3113,7 @@ function _preserve_model_status_view_temporal_state!( end status = Status(NamedTuple{names}(references)) return CompiledModelStatusView( + previous.execution_stamp, status, current.canonical_status, temporal_inputs, @@ -3257,7 +3322,8 @@ function _extend_model_status_views( get(input_bindings_by_target, key, ()), applications_by_id, positions, - distributed_outputs, + distributed_outputs; + execution_stamp=_status_view_execution_stamp(model, key, previous_view), ) views[key] = isnothing(previous_view) ? current_view : @@ -4125,7 +4191,7 @@ function _extend_compiled_scene( for application in added_applications isempty(application.target_ids) && continue recipe = _application_plans( - compiled.scenario_plan.input_recipes_by_application, application.slot, + compiled.scenario_plan.input_recipes_by_application, application.id, ) _compile_application_consumer_bindings!( input_bindings, model, application, recipe, manual_application_ids, @@ -4751,6 +4817,7 @@ function _resolve_application_recipes(model::CompositeModel, recipes::Tuple, tim selector, target_matcher, timestep(spec), _model_application_clock(model, spec, target_ids, timeline), model_overrides, recipe.output_names, recipe.canonical_output_names, + recipe.call_plans, ), target_ids, )) @@ -5561,11 +5628,15 @@ function _status_recipe_reference( recipe::_CanonicalStatusRecipe, variable::Symbol, ) - position = findfirst(isequal(variable), recipe.edit_names) - isnothing(position) || return recipe.edit_references[position] - isnothing(recipe.original) && throw(KeyError(variable)) - variable in propertynames(recipe.original) || throw(KeyError(variable)) - return refvalue(recipe.original, variable) + return _status_recipe_reference(recipe.original, recipe.edit_names, recipe.edit_references, variable) +end + +function _status_recipe_reference(original, edit_names, edit_references, variable::Symbol) + position = findfirst(isequal(variable), edit_names) + isnothing(position) || return edit_references[position] + isnothing(original) && throw(KeyError(variable)) + variable in propertynames(original) || throw(KeyError(variable)) + return refvalue(original, variable) end function _status_recipe_set_reference!( @@ -5615,17 +5686,83 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end -function _finish_status_recipe(model::CompositeModel, recipe::_CanonicalStatusRecipe) - recipe.changed || return recipe.original +# Private application views do not become canonical registry rows. Keep their +# construction independent of the canonical ownership/admission catalog. +function _finish_status_recipe(f, cache, recipe::_CanonicalStatusRecipe) + recipe.changed || return f(recipe.original) original = recipe.original existing_names = isnothing(original) ? () : propertynames(original) existing_references = isnothing(original) ? () : refvalues(original) construction = _status_construction_recipe!( - model.registry.objects.layout_cache, + cache, existing_names, Tuple(recipe.edit_names), ) - return _construct_status(construction, existing_references, Tuple(recipe.edit_references)) + return f(_construct_status(construction, existing_references, Tuple(recipe.edit_references))) +end + +function _finish_canonical_status_recipe(f, model::CompositeModel, recipe::_CanonicalStatusRecipe) + return _finish_canonical_status_recipe(f, model.registry.objects.catalog, + model.registry.objects.layout_cache, recipe) +end + +_finish_canonical_status_recipe(f, ::OpenObjectFamilyCatalog, cache, recipe::_CanonicalStatusRecipe) = + _finish_status_recipe(f, cache, recipe) + +function _finish_canonical_status_recipe(f, catalog::ClosedObjectFamilyCatalog, cache, recipe::_CanonicalStatusRecipe) + return _with_registered_status(catalog, recipe.original) do original + recipe.changed || return f(original) + _finish_admitted_status_recipe(f, catalog, original, recipe.edit_names, recipe.edit_references) + end +end + +# Canonical order is the original fields followed by genuinely new fields in +# edit order. Replacements do not move an existing field. +function _status_edit_schema_matches(edit_names, original_names::Tuple, result_names::Tuple) + length(result_names) >= length(original_names) || return false + for index in eachindex(original_names) + result_names[index] === original_names[index] || return false + end + next = length(original_names) + 1 + for name in edit_names + name in original_names && continue + next <= length(result_names) && name === result_names[next] || return false + next += 1 + end + return next == length(result_names) + 1 +end + +# Select and consume actual references in the exact branch. Result schema +# alternatives never escape as a large union before registration/view creation. +@generated function _finish_admitted_status_recipe(f, ::ClosedObjectFamilyCatalog{F}, original::S, edit_names, edit_references) where {F,S} + original_names = _status_schema_names(S) + results = unique(family.parameters[2] for family in fieldtypes(F) if family.parameters[2] <: Status) + branches = Expr[] + for Result in results + names = _status_schema_names(Result) + length(names) >= length(original_names) && names[1:length(original_names)] == original_names || continue + Refs = _status_schema_references(Result) + all(isconcretetype, fieldtypes(Refs)) || continue + factory = ExactReferenceFactory(S, Refs, Result, names) + refs = [gensym(:reference) for _ in names] + reads = [:($(refs[index]) = _status_recipe_reference(original, edit_names, edit_references, $(QuoteNode(name)))) + for (index,name) in enumerate(names)] + checks = [:( $(refs[index]) isa $(fieldtype(Refs,index)) ) for index in eachindex(names)] + matches = isempty(checks) ? true : reduce((left,right)->:($left && $right), checks) + typed = Expr(:tuple, [:( $(refs[index])::$(fieldtype(Refs,index)) ) for index in eachindex(names)]...) + push!(branches, quote + if _status_edit_schema_matches(edit_names, $(QuoteNode(original_names)), $(QuoteNode(names))) + $(reads...) + if $matches + return f(_construct_status($(QuoteNode(factory)), original, $typed)) + end + end + end) + end + return quote + $(branches...) + throw(ArgumentError("The constructed reference schema is outside the prepared object family catalog.")) + end end function _model_object_status_for_preparation( @@ -5677,11 +5814,9 @@ function _apply_status_recipes!( for object_id in recipe_order recipe = recipes[object_id] recipe.changed || continue - _replace_model_object_status!( - model, - object_id, - _finish_status_recipe(model, recipe), - ) + _finish_canonical_status_recipe(model, recipe) do status + _replace_model_object_status!(model, object_id, status) + end _runtime_performance_count!( performance, :lifecycle_binding_refresh_status_recipe_materializations, @@ -6163,7 +6298,7 @@ function _incremental_distributed_output_addition!( for (application_id, object_ids) in new_targets isempty(object_ids) && continue application = applications_by_id[application_id] - isempty(_application_plans(plans.by_application, application.slot)) || + isempty(_application_plans(plans.by_application, application.id)) || return nothing end @@ -6893,7 +7028,8 @@ Base.@nospecializeinfer function _compile_model_status_view( input_bindings, applications_by_id, application_positions, - distributed_outputs=NoCompiledDistributedOutputs(), + distributed_outputs=NoCompiledDistributedOutputs(); + execution_stamp::Base.RefValue{UInt64}, ) # This is cold assembly, not a kernel: avoid inferring the whole view # constructor for every application and heterogeneous binding tuple. @@ -6911,6 +7047,7 @@ Base.@nospecializeinfer function _compile_model_status_view( # temporal/private scratch storage and validating a nonexistent overlap. if !has_temporal_inputs && isempty(output_routing(application.spec)) return CompiledModelStatusView( + execution_stamp, canonical_status, canonical_status, (), @@ -6931,6 +7068,7 @@ Base.@nospecializeinfer function _compile_model_status_view( end if isempty(temporal_bindings) && isempty(private_output_names) return CompiledModelStatusView( + execution_stamp, canonical_status, canonical_status, (), @@ -6977,16 +7115,21 @@ Base.@nospecializeinfer function _compile_model_status_view( for input in temporal_inputs _status_recipe_set_reference!(recipe, input.binding.input, input.reference) end - status = _finish_status_recipe(model, recipe) - return CompiledModelStatusView( - status, - canonical_status, - Tuple(temporal_inputs), - private_outputs, - _compiled_bound_many_inputs(input_bindings, status), - ) + return _finish_status_recipe(model.registry.objects.layout_cache, recipe) do status + CompiledModelStatusView( + execution_stamp, + status, + canonical_status, + Tuple(temporal_inputs), + private_outputs, + _compiled_bound_many_inputs(input_bindings, status), + ) + end end +_status_view_execution_stamp(model, key, previous::CompiledModelStatusView) = previous.execution_stamp +_status_view_execution_stamp(model, key, ::Nothing) = _targeted_call_execution_stamp(model, key) + function _compile_model_status_views( model::CompositeModel, applications, @@ -6996,6 +7139,8 @@ function _compile_model_status_views( distributed_outputs=NoCompiledDistributedOutputs(), ) views = Dict{Tuple{Symbol,ObjectId},Any}() + previous = getfield(model, :binding_cache) + previous_views = previous isa CompiledCompositeModel ? previous.status_views_by_target : nothing positions = Dict( application_id => index for (index, application_id) in pairs(application_order) @@ -7010,7 +7155,9 @@ function _compile_model_status_views( get(input_bindings_by_target, key, ()), applications_by_id, positions, - distributed_outputs, + distributed_outputs; + execution_stamp=_status_view_execution_stamp(model, key, + isnothing(previous_views) ? nothing : get(previous_views, key, nothing)), ) end end @@ -7044,20 +7191,20 @@ function _matching_input_source_applications( haskey(applications_by_id, potential_application_id) matches = if use_planned_singleton application_id = potential_application_id - application = applications_by_id[application_id] - matched = any(source_ids) do source_id - _application_writes_object_variable( - distributed_outputs, - application, - source_id, - source_var, - ) && return true - # Targeted newborn initializers use a partial application overlay - # until the lifecycle barrier extends the compiled application. - # Preserve that path without rescanning unrelated applications. - return any(get(applications_by_object, source_id, ())) do candidate - candidate.id == application_id || return false - return source_var in _model_output_names(candidate) + matched = _with_metadata_entry(applications_by_id, application_id) do application + any(source_ids) do source_id + _application_writes_object_variable( + distributed_outputs, + application, + source_id, + source_var, + ) && return true + # Targeted newborn initializers use a partial application + # overlay until the lifecycle barrier extends the application. + return any(get(applications_by_object, source_id, ())) do candidate + candidate.id == application_id || return false + return source_var in _model_output_names(candidate) + end end end matched ? Symbol[application_id] : Symbol[] @@ -7068,7 +7215,7 @@ function _matching_input_source_applications( source_var in _model_output_names(application) || continue isnothing(process_filter) || application.process == process_filter || continue isnothing(application_filter) || application.id == application_filter || continue - push!(resolved, application.id) + application.id in resolved || push!(resolved, application.id) end _append_distributed_input_source_applications!( resolved, @@ -7080,7 +7227,6 @@ function _matching_input_source_applications( applications_by_id, ) end - unique!(resolved) resolved end if !allow_empty && @@ -7121,13 +7267,16 @@ function _append_distributed_input_source_applications!( isnothing(applications_by_id) && error( "Distributed output producer matching requires the compiled application index.", ) - application = get(applications_by_id, owner.application_id, nothing) - isnothing(application) && continue - isnothing(process_filter) || - application.process == process_filter || continue - isnothing(application_filter) || - application.id == application_filter || continue - push!(matches, application.id) + owner.application_id in matches && continue + haskey(applications_by_id, owner.application_id) || continue + _with_metadata_entry(applications_by_id, owner.application_id) do application + isnothing(process_filter) || + application.process == process_filter || return nothing + isnothing(application_filter) || + application.id == application_filter || return nothing + push!(matches, application.id) + return nothing + end end return matches end @@ -7276,7 +7425,7 @@ function _application_may_output_variable( return any( plan -> variable in keys(plan.declarations) && _selector_labels_may_overlap(source_selector, plan.selector), - _application_plans(plans.by_application, application.slot), + _application_plans(plans.by_application, application.id), ) end @@ -7296,7 +7445,7 @@ function _application_declares_distributed_output( return any( plan -> variable in keys(plan.declarations) && _selector_labels_may_overlap(source_selector, plan.selector), - _application_plans(plans.by_application, application.slot), + _application_plans(plans.by_application, application.id), ) end @@ -7311,7 +7460,7 @@ Base.@nospecializeinfer function _potential_call_application_ids( application.id for application in applications if (isnothing(process_filter) || application.process == process_filter) && (isnothing(application_filter) || application.id == application_filter) && - _selector_labels_may_overlap(selector, application.applies_to) + _selector_labels_may_overlap(selector, applies_to(application.spec)) ) end @@ -7521,39 +7670,47 @@ function _compile_model_input_plans( return plans end +function _prepare_authored_call_plans(application::AuthoredApplicationRecipe, applications, slot_offset::Int) + plans = CompiledModelCallPlan[] + calls = model_calls(application.spec) + calls isa NamedTuple || return () + for (call_name, declaration) in pairs(calls) + call = Symbol(call_name) + selector = _call_binding_selector(declaration) + mode = _call_binding_mode(declaration) + process_filter = _criteria_get(criteria(selector), :process, nothing) + application_filter = _selector_application(selector) + potential_callee_application_ids = _potential_call_application_ids( + applications, selector, process_filter, application_filter) + push!(plans, CompiledModelCallPlan( + slot_offset + length(plans) + 1, application.slot, application.id, call, mode, + selector, _authored_selector_matcher(selector), + get(call_origins(application.spec), call, :model_spec), + process_filter, application_filter, multiplicity(selector), + potential_callee_application_ids, + )) + end + return Tuple(plans) +end + function _compile_model_call_plans(model::CompositeModel, applications) plans = CompiledModelCallPlan[] + visible_applications = Set(application.id for application in applications) for application in applications - calls = model_calls(application.spec) - calls isa NamedTuple || continue - for (call_name, declaration) in pairs(calls) - call = Symbol(call_name) - selector = _call_binding_selector(declaration) - mode = _call_binding_mode(declaration) - potential_callee_application_ids = - _potential_call_application_ids( - applications, - selector, - _criteria_get(criteria(selector), :process, nothing), - _selector_application(selector), - ) - push!( - plans, - CompiledModelCallPlan( - length(plans) + 1, - application.plan.slot, - application.id, - call, - mode, - selector, - _compile_selector_matcher(model, selector), - get(call_origins(application.spec), call, :model_spec), - _criteria_get(criteria(selector), :process, nothing), - _selector_application(selector), - multiplicity(selector), - potential_callee_application_ids, - ), - ) + for authored in application.call_plans + # A partial diagnostic report can omit an invalid application. + # Empty-but-valid applications remain visible, as in the full plan. + potential = all(id -> id in visible_applications, + authored.potential_callee_application_ids) ? + authored.potential_callee_application_ids : + Tuple(id for id in authored.potential_callee_application_ids + if id in visible_applications) + push!(plans, CompiledModelCallPlan( + length(plans) + 1, application.slot, application.id, + authored.call, _compiled_call_mode(authored), authored.selector, + _resolve_selector_matcher(model, authored.matcher), authored.origin, + authored.process, authored.application, authored.multiplicity, potential, + )) end end return plans @@ -7603,8 +7760,8 @@ function _compile_model_output_destination_plans( ) end -_application_plans(plans_by_application, application_slot::Integer) = - plans_by_application[application_slot] +_application_plans(plans_by_application, application_id::Symbol) = + plans_by_application[application_id] function _potential_input_source_applications( applications_by_id, @@ -7692,11 +7849,11 @@ function _compile_model_input_bindings( _plans_by_application(applications, plans)) end bindings = CompiledModelInputBinding[] - by_object = _applications_by_object(applications) - by_id = Dict(application.id => application for application in applications) + by_object = _applications_by_object(applications, model.registry.objects) + by_id = _applications_by_id(applications) for application in applications isempty(application.target_ids) && continue - recipe = _application_plans(input_recipes_by_application, application.slot) + recipe = _application_plans(input_recipes_by_application, application.id) _compile_application_consumer_bindings!( bindings, model, application, recipe, manual_application_ids, by_object, by_id, distributed_outputs, @@ -8121,8 +8278,8 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, i ) end -function _applications_by_object(applications) - by_object = Dict{ObjectId,Vector{Any}}() +function _applications_by_object(applications, ::ObjectFamilyStore{I}) where {I<:ObjectId} + by_object = Dict{I,Vector{Any}}() for application in applications for object_id in application.target_ids push!(get!(by_object, object_id, Any[]), application) @@ -8131,6 +8288,84 @@ function _applications_by_object(applications) return by_object end +# A non-owning position view over the existing reverse-membership index. Its Any +# entries are compared only by identity inside the typed metadata owner. Positions +# belong to this catalog; a partial catalog need not use application.slot values. +struct ApplicationMembershipSlots{A<:CompiledMetadataTable,M} + applications::A + members::M +end + +Base.eltype(::Type{<:ApplicationMembershipSlots}) = Int +Base.IteratorSize(::Type{<:ApplicationMembershipSlots}) = Base.HasLength() +Base.length(slots::ApplicationMembershipSlots) = length(slots.members) +Base.isempty(slots::ApplicationMembershipSlots) = isempty(slots.members) + +@generated function _application_membership_slot(applications::CompiledMetadataTable{T}, member) where {T} + branches = [:(member === getfield(getfield(applications, :entries), $slot) && return $slot) + for slot in 1:fieldcount(T)] + return quote + $(branches...) + throw(ArgumentError("Application membership is outside its compiled catalog.")) + end +end + +function Base.iterate(slots::ApplicationMembershipSlots, state...) + item = iterate(slots.members, state...) + isnothing(item) && return nothing + member, next = item + return _application_membership_slot(slots.applications, member), next +end + +@inline function _application_index_object_id(::AbstractDict{I}, object_id::ObjectId) where {I<:ObjectId} + object_id isa I || throw(ArgumentError( + "The object identity is outside the compiled application index schema.", + )) + return object_id::I +end + +function _application_membership_slots(compiled::CompiledCompositeModel, object_id::ObjectId) + index = compiled.applications_by_object + id = _application_index_object_id(index, object_id) + return ApplicationMembershipSlots(compiled.applications_by_id, get(index, id, ())) +end + +# Consume metadata inside its exact schema branch. Runtime Symbols select +# identities; integer keys select positions local to this owner, never model slots. +@generated function _with_metadata_entry(f, table::CompiledMetadataTable{T}, key::K) where {T,K<:Union{Symbol,Integer}} + entry_keys = K <: Symbol ? fieldnames(T) : ntuple(identity, fieldcount(T)) + branches = [:(key == $(QuoteNode(entry_key)) && + return f(getfield(getfield(table, :entries), $index))) + for (index, entry_key) in enumerate(entry_keys)] + missing = K <: Symbol ? :(throw(KeyError(key))) : :(throw(BoundsError(table, key))) + return quote + $(branches...) + $missing + end +end + +# Execution plans already have a typed tuple boundary; its callback uses the +# same scalar-entry operation as fixed metadata owners. Never unwrap an owner +# into a tuple to enter this method. +@generated function _with_metadata_entry(f, entries::T, key::K) where {T<:Tuple,K<:Integer} + branches = [:(key == $index && return f(getfield(entries, $index))) + for index in 1:fieldcount(T)] + return quote + $(branches...) + throw(BoundsError(entries, key)) + end +end + +@inline _with_metadata_entry(f, entries::AbstractVector, key::Integer) = f(entries[key]) + +function _foreach_object_application(f, compiled::CompiledCompositeModel, object_id::ObjectId) + slots = _application_membership_slots(compiled, object_id) + for slot in slots + _with_metadata_entry(f, slots.applications, slot) + end + return nothing +end + function _matching_callee_applications(applications, object_id::ObjectId, proc, application_name_filter) matches = Symbol[] for application in get(applications, object_id, Any[]) @@ -8255,7 +8490,7 @@ function _compile_model_call_bindings( for consumer_id in application.target_ids for plan in _application_plans( plans_by_application, - application.slot, + application.id, ) call_sym = plan.call selector = plan.selector @@ -8272,7 +8507,7 @@ function _compile_model_call_bindings( ) else isnothing(by_object) && - (by_object = _applications_by_object(lookup_applications)) + (by_object = _applications_by_object(lookup_applications, model.registry.objects)) object_ids = _dependency_object_ids( model, selector, @@ -8462,13 +8697,13 @@ function explain_applications(compiled::CompiledCompositeModel) input_plan_count=length( _application_plans( compiled.scenario_plan.input_plans_by_application, - application.slot, + application.id, ), ), call_plan_count=length( _application_plans( compiled.scenario_plan.call_plans_by_application, - application.slot, + application.id, ), ), output_destination_plan_count= @@ -8478,7 +8713,7 @@ function explain_applications(compiled::CompiledCompositeModel) length( _application_plans( compiled.scenario_plan.distributed_output_plans.by_application, - application.slot, + application.id, ), ), current_target_count=length(application.target_ids), diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 1dba832d3..89b09ea68 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -135,7 +135,7 @@ function _update_model_environment_indices_for_objects!( ) application_ids = Set{Symbol}() for object_id in dirty_object_ids - for application in get(compiled.applications_by_object, object_id, ()) + _foreach_object_application(compiled, object_id) do application push!(application_ids, application.id) end for target in get(cached.targets_by_object, object_id, ()) @@ -601,35 +601,36 @@ function _refresh_environment_bindings_for_objects( stale_targets = Set{Tuple{Symbol,ObjectId}}() replacements = Dict{Tuple{Symbol,ObjectId},CompiledEnvironmentBinding}() for object_id in dirty_ids - current_applications = get( - compiled.applications_by_object, - object_id, - (), - ) + current_applications = _application_membership_slots(compiled, object_id) previous_targets = get(cached.targets_by_object, object_id, ()) isempty(current_applications) && isempty(previous_targets) && continue - current_application_ids = Set( - application.id for application in current_applications - ) + current_application_ids = Set{Symbol}() + for slot in current_applications + _with_metadata_entry(current_applications.applications, slot) do application + push!(current_application_ids, application.id) + end + end for target in previous_targets target[1] in current_application_ids || push!(stale_targets, target) end haskey(model.registry.objects, object_id) || continue - for application in current_applications - partial_application = CompiledModelApplication( - application.plan, - ObjectId[object_id], - ) - for binding in _compile_environment_bindings_for_applications( - model, - (partial_application,), - cached.application_plans_by_id, - ) - replacements[( - binding.application_id, - binding.object_id, - )] = binding + for slot in current_applications + _with_metadata_entry(current_applications.applications, slot) do application + partial_application = CompiledModelApplication( + application.plan, + ObjectId[object_id], + ) + for binding in _compile_environment_bindings_for_applications( + model, + (partial_application,), + cached.application_plans_by_id, + ) + replacements[( + binding.application_id, + binding.object_id, + )] = binding + end end end end diff --git a/src/composite_model/execution_dispatch.jl b/src/composite_model/execution_dispatch.jl index 362179903..a00fb0065 100644 --- a/src/composite_model/execution_dispatch.jl +++ b/src/composite_model/execution_dispatch.jl @@ -2,29 +2,13 @@ abstract type ExecutionTopology end struct DynamicExecution <: ExecutionTopology end struct FixedExecution <: ExecutionTopology end -@inline function _run_execution_slot!(groups::AbstractVector, slot::Int, simulation::Simulation, step::Integer) - group = groups[slot] - isnothing(group) && return false - _run_model_execution_group!(group, simulation, step, simulation.performance) - return true -end - -# Application slots are part of a closed plan's schema. Both representations -# enter the same group/batch executor, while this dispatch keeps tuple members -# concrete when the caller supplies an ordinary runtime slot number. -@generated function _run_execution_slot!(groups::G, slot::Int, simulation::Simulation, step::Integer) where {G<:Tuple} - branches = map(1:fieldcount(G)) do index - body = fieldtype(G, index) === Nothing ? :(return false) : quote - _run_model_execution_group!(getfield(groups, $index), simulation, step, simulation.performance) - return true - end - :(if slot == $index - $body - end) - end - return quote - $(branches...) - throw(BoundsError(groups, slot)) +# Both container representations enter the same group/batch executor. Scalar +# metadata dispatch keeps a closed tuple's group concrete inside the callback. +@inline function _run_execution_slot!(groups::G, slot::Int, simulation::Simulation, step::Integer) where {G<:Union{AbstractVector,Tuple}} + return _with_metadata_entry(groups, slot) do group + isnothing(group) && return false + _run_model_execution_group!(group, simulation, step, simulation.performance) + return true end end diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index eec0af20b..c84a80ab0 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -31,6 +31,20 @@ struct ClosedObjectFamilyCatalog{F<:Tuple} families::F end +# Open registration crosses the ordinary JIT function barrier. Closed +# registration keeps the operation inside the exact admitted Status branch, +# rather than first returning a large union from the Object's Any-valued field. +@inline _with_registered_status(f, ::OpenObjectFamilyCatalog, status) = f(status) + +@generated function _with_registered_status(f, ::ClosedObjectFamilyCatalog{F}, status) where {F} + schemas = unique(family.parameters[2] for family in fieldtypes(F)) + branches = [:(status isa $S && return f(status::$S)) for S in schemas] + return quote + $(branches...) + throw(ArgumentError("The status schema is outside the prepared object family catalog.")) + end +end + """Canonical object identities and typed status families behind the object dictionary.""" struct ObjectFamilyStore{I<:ObjectId,C} <: AbstractDict{I,Object} catalog::C @@ -163,9 +177,12 @@ function _store_object_family_row!(store::ObjectFamilyStore{K}, object::Object, return status end -function Base.setindex!(store::ObjectFamilyStore, object::Object, id) +function Base.setindex!(store::ObjectFamilyStore{I}, object::Object, id) where {I<:ObjectId} isequal(object.id, id) || throw(ArgumentError("The dictionary key must match the Object identity.")) - _store_object_family_row!(store, object, object.id, object.status) + object.id isa I || throw(ArgumentError("The object identity type is outside the prepared family catalog.")) + _with_registered_status(store.catalog, object.status) do status + _store_object_family_row!(store, object, object.id::I, status) + end return store end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 6ec8967c4..9e5802911 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -933,8 +933,9 @@ function _mark_bindings_dirty!( :structural end end - delta.structural_kind === :addition || - (delta.targeted_topology_runtime = nothing) + # Non-addition events cannot use targeted membership preparation. Keep its + # execution stamps reachable until the barrier adopts them into ordinary + # views; consuming the structural delta then releases the runtime. if !model.bindings_dirty model.revision += 1 end @@ -1094,10 +1095,13 @@ function _replace_model_object_status!( "got `$(typeof(status))`.", ) object.status === status && return status - _store_object_family_row!(model.registry.objects, object, object.id, status) - setfield!(object, :status, status) - _set_status_source_identity!(model, object.id, status) - return status + store = model.registry.objects + return _with_registered_status(store.catalog, status) do admitted + _store_object_family_row!(store, object, object.id::keytype(store), admitted) + setfield!(object, :status, admitted) + _set_status_source_identity!(model, object.id, admitted) + return admitted + end end function _replace_model_object_status!(model::CompositeModel, object_id, status) @@ -1337,16 +1341,35 @@ function _register_object_without_lifecycle!( if !isnothing(parent_id) && !haskey(registry.objects, parent_id) error("No model object with id `$(parent_id.value)`.") end - source_status = object.status + return _register_object_status!(model, object, parent_id, object.status, status_values_materialized) +end + +# The same conversion and ownership operations serve both catalog forms. An +# unconverted source need not be a canonical family when conversion is active. +function _register_object_status!(model, object, parent_id, source_status, status_values_materialized) _validate_status_source_identity_available!(model, source_status, object.id) - object.status = status_values_materialized ? - source_status : - _convert_registered_status(model, object.id, source_status) - _validate_status_identity_available!(registry, object.status, object.id) + catalog = model.registry.objects.catalog + if status_values_materialized || _no_status_conversion(model.status_conversion) + return _with_registered_status(catalog, source_status) do status + _register_converted_object!(model, object, parent_id, status, status) + end + end + status = _convert_registered_status(model, object.id, source_status) + return _with_registered_status(catalog, status) do converted + _register_converted_object!(model, object, parent_id, source_status, converted) + end +end + +function _register_converted_object!(model, object, parent_id, source_status, status) + registry = model.registry + _validate_status_identity_available!(registry, status, object.id) + object.status = status instance = isnothing(parent_id) ? nothing : _instance_for_object(model, parent_id) _apply_instance_labels!(object, instance) object.parent = parent_id - registry.objects[object.id] = object + store = registry.objects + id = object.id::keytype(store) + _store_object_family_row!(store, object, id, status) _index_object!(registry, object) _set_status_source_identity!(model, object.id, source_status) ancestors = isnothing(parent_id) ? @@ -1750,7 +1773,7 @@ function refresh_bindings!( ) end preparation = _scenario_preparation(model; force) - _authored_application_recipes(preparation) + _validate_authored_scenario(preparation) prepared = preparation.resolved previous = model.binding_cache plan_changed = !isnothing(prepared) && !isnothing(previous) && diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 42903e216..25db2249a 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -278,14 +278,15 @@ end # A manual target owns its execution shells. Keep the normal typed context and # at most one transient specialization; materialized views share this lease. mutable struct CallContextCache{C} + const execution_stamp::Base.RefValue{UInt64} default::C transient::Any in_use::Bool - execution_revision::UInt64 evaluation::Union{Nothing,CallEvaluationFrame} end -CallContextCache(context) = CallContextCache(context, nothing, false, UInt64(0), nothing) +CallContextCache(context, stamp::Base.RefValue{UInt64}) = + CallContextCache(stamp, context, nothing, false, nothing) function RunContext( compiled, @@ -1235,6 +1236,30 @@ function _compiled_application_execution_group(application, batches, membership) return CompiledApplicationExecutionGroup(application, batches, membership) end +# Host preparation can declare an exact future batch family without creating +# an object, status, model invocation, sample, or a fake execution target. +function _empty_model_execution_group(application, ::Type{B}, cohorts::ExecutionCohortStore) where {B<:CompiledExecutionBatch} + isempty(application.target_ids) || throw(ArgumentError("A future group must start with empty membership.")) + isconcretetype(B) && fieldtype(B, :application) === typeof(application) || + throw(ArgumentError("The batch schema does not match the prepared application.")) + Rows = fieldtype(B, :targets) + Rows <: ExecutionCohortRows || throw(ArgumentError("Prepared batches require canonical cohort rows.")) + _execution_cohort(cohorts, nothing, application.id, eltype(Rows)) + membership = _new_execution_cohort_membership(cohorts, nothing, application.id, 0) + return CompiledApplicationExecutionGroup(application, B[], membership) +end + +# Same-schema metadata refresh keeps the existing owner, including its formerly +# empty slot. A genuinely different open schema keeps the newly compiled group. +_retain_execution_group(::Nothing, current::CompiledApplicationExecutionGroup) = current +_retain_execution_group(previous::CompiledApplicationExecutionGroup, current::CompiledApplicationExecutionGroup) = current +function _retain_execution_group(previous::G, current::G) where {G<:CompiledApplicationExecutionGroup} + previous.application === current.application || return current + previous.batches = current.batches + previous.membership = current.membership + return previous +end + mutable struct RuntimeApplicationSchedule next_due_steps::Vector{Int} heap::Vector{Int} @@ -3693,7 +3718,7 @@ function _new_model_execution_target( call_bindings, environment_binding, context, - CallContextCache(context), + CallContextCache(context, status_view.execution_stamp), ) end @@ -4598,17 +4623,24 @@ function _refresh_model_execution_group!( group_changed = refreshed.membership_changed || refreshed.targets_constructed > 0 || calls_extended[] group = if isempty(assembled.batches) - nothing + if !isnothing(previous_group) && previous_group.application === application && + previous_group.batches isa AbstractVector + empty!(previous_group.batches) + previous_group.membership = refreshed.membership + previous_group + else + nothing + end elseif reused_group previous_group.membership = refreshed.membership - group_changed && _runtime_performance_count!( - performance, :execution_groups_updated_in_place, - ) previous_group else - _compiled_application_execution_group( + _retain_execution_group(previous_group, _compiled_application_execution_group( application, assembled.batches, refreshed.membership, - ) + )) + end + if !isnothing(group) && group === previous_group && group_changed + _runtime_performance_count!(performance, :execution_groups_updated_in_place) end return ( group=group, @@ -4632,6 +4664,30 @@ function _changed_execution_target_ids_by_application(changed_execution_target_i return changed_by_application end +# Prefer the existing authored position without building a Dict of group +# objects. Reordered application metadata still matches the old owner by id. +# Only scalar refresh counts leave the concrete group callback, never a group. +function _with_previous_execution_group(f, slots, application_id::Symbol, + preferred_slot::Int, visited::BitVector, +) + for candidate in 0:length(slots) + slot = iszero(candidate) ? preferred_slot : candidate + (slot < 1 || slot > length(slots) || + (!iszero(candidate) && slot == preferred_slot)) && continue + counts = _with_metadata_entry(slots, slot) do group + if !isnothing(group) && group.application.id === application_id + return f(group)::NTuple{3,Int} + end + return nothing + end + if !isnothing(counts) + visited[slot] = true + return counts + end + end + return f(nothing)::NTuple{3,Int} +end + function _refresh_model_execution_plan( previous::CompiledExecutionPlan, compiled::CompiledCompositeModel, @@ -4643,12 +4699,12 @@ function _refresh_model_execution_plan( changed_application_ids=nothing, changed_execution_target_ids=compiled.changed_execution_target_ids, ) - manual_application_ids = _manual_call_application_ids(compiled) changed_by_application = isnothing(changed_application_ids) ? nothing : _changed_execution_target_ids_by_application( changed_execution_target_ids, ) - previous_groups = Dict(group.application.id => group for group in previous.groups) + previous_slots = previous.groups_by_application_slot + visited_slots = falses(length(previous_slots)) groups = CompiledApplicationExecutionGroup[] batches = AbstractExecutionBatch[] sizehint!(groups, length(previous.groups)) @@ -4656,35 +4712,47 @@ function _refresh_model_execution_plan( targets_constructed = 0 batches_constructed = 0 groups_reused = 0 - for application in _ordered_model_applications(compiled) - application.id in manual_application_ids && continue - previous_group = pop!(previous_groups, application.id, nothing) - if !isnothing(previous_group) && !isnothing(changed_application_ids) && - !(application.id in changed_application_ids) - push!(groups, previous_group) - append!(batches, previous_group.batches) - groups_reused += 1 - continue - end - changed_ids = isnothing(changed_by_application) ? nothing : - get(changed_by_application, application.id, ()) - refreshed = _refresh_model_execution_group!( - previous_group, previous.cohorts, compiled, env_bindings, application, - temporal_streams, output_retention, constants, performance, changed_ids, - ) - if !isnothing(refreshed.group) - push!(groups, refreshed.group) - append!(batches, refreshed.group.batches) + # These are the compiler's existing dependency-ordered root entries; + # call-only applications are already excluded by that same schedule. + for entry in compiled.scenario_plan.application_schedule.entries + counts = _with_metadata_entry(compiled.applications_by_id, entry.application_id) do application + _with_previous_execution_group(previous_slots, application.id, + application.slot, visited_slots, + ) do previous_group + if !isnothing(previous_group) && !isnothing(changed_application_ids) && + !(application.id in changed_application_ids) + push!(groups, previous_group) + append!(batches, previous_group.batches) + return (0, 0, 1) + end + changed_ids = isnothing(changed_by_application) ? nothing : + get(changed_by_application, application.id, ()) + refreshed = _refresh_model_execution_group!( + previous_group, previous.cohorts, compiled, env_bindings, application, + temporal_streams, output_retention, constants, performance, changed_ids, + ) + if !isnothing(refreshed.group) + push!(groups, refreshed.group) + append!(batches, refreshed.group.batches) + end + return (refreshed.targets_constructed, refreshed.batches_constructed, + Int(refreshed.group_reused)) + end end - targets_constructed += refreshed.targets_constructed - batches_constructed += refreshed.batches_constructed - groups_reused += refreshed.group_reused + targets_constructed += counts[1] + batches_constructed += counts[2] + groups_reused += counts[3] end # A removed application (or one now exclusively called) has no scheduled - # membership to merge. Retire only its former owners, never scan survivors. - for group in values(previous_groups) - for object_id in group.membership.object_ids - remove_cohort_target!(previous.cohorts, group.application.id, object_id) + # membership. Visit each remaining old slot at its existing type boundary. + for slot in eachindex(previous_slots) + visited_slots[slot] && continue + _with_metadata_entry(previous_slots, slot) do group + isnothing(group) && return nothing + for object_id in group.membership.object_ids + remove_cohort_target!(previous.cohorts, group.application.id, object_id) + end + return nothing end end same_groups = _same_execution_members(previous.groups, groups) @@ -4868,7 +4936,7 @@ function _model_application_output_variables( # variables that may acquire destinations at a later lifecycle barrier. plans = compiled.scenario_plan.distributed_output_plans if plans isa CompiledDistributedOutputPlans - for plan in _application_plans(plans.by_application, application.slot) + for plan in _application_plans(plans.by_application, application.id) for variable_ in keys(plan.declarations) variable = Symbol(variable_) variable in variables || push!(variables, variable) @@ -6047,7 +6115,7 @@ function _prepare_targeted_newborn_targets( for application in callee_applications isempty(application.target_ids) && continue recipe = _application_plans( - compiled.scenario_plan.input_recipes_by_application, application.slot, + compiled.scenario_plan.input_recipes_by_application, application.id, ) _compile_application_consumer_bindings!( input_bindings, model, application, recipe, @@ -6132,10 +6200,14 @@ function _append_targeted_newborn_targets!( application = compiled.applications_by_id[partial_application.id]::typeof(partial_application) for object_id in partial_application.target_ids key = (application.id, object_id) + cache = get(targeted_runtime.call_context_caches, key, nothing)::Union{Nothing,CallContextCache} + stamp = isnothing(cache) ? Ref(UInt64(0)) : + (getfield(cache, :execution_stamp)::Base.RefValue{UInt64}) status_view = _compile_model_status_view( runtime_model(context), partial_application, object_id, get(targeted_input_bindings, key, ()), compiled.applications_by_id, - targeted_runtime.application_positions, compiled.distributed_outputs, + targeted_runtime.application_positions, compiled.distributed_outputs; + execution_stamp=stamp, ) outputs = _runtime_model_output_streams( status_view.status, application, object_id, context.temporal_streams, @@ -6143,17 +6215,52 @@ function _append_targeted_newborn_targets!( ) output_targets = _runtime_model_output_targets(compiled, application, object_id) environment_binding = _environment_binding_for(environment_bindings, application.id, object_id) - cache = get!(targeted_runtime.call_context_caches, key) do - CallContextCache(nothing) + # Targeted admission has already resolved this callee without nested + # calls. The general payload/cache helper accepts the actual tuple; + # nested manual newborns retain their existing full-refresh path. + call_bindings = () + if isnothing(cache) + cache = _newborn_call_context_cache(context, application, object_id, + status_view.bound_inputs, output_targets, call_bindings, environment_bindings, stamp) + targeted_runtime.call_context_caches[key] = cache end push!(targets, _targeted_newborn_call_target( context, application, object_id, _application_model(application, object_id), - status_view, outputs, output_targets, environment_bindings, environment_binding, cache, + status_view, outputs, output_targets, call_bindings, + environment_bindings, environment_binding, cache, )) end return targets end +# Adopt a pre-barrier newborn's logical counter when the ordinary compiler +# installs its view. This is cold construction over an existing cache directory, +# never a kernel-time identity lookup or a second target store. +function _targeted_call_execution_stamp(model::CompositeModel, key) + targeted = lifecycle_delta(model).targeted_topology_runtime + if targeted isa _TargetedTopologyRuntime + cache = get(targeted.call_context_caches, key, nothing)::Union{Nothing,CallContextCache} + isnothing(cache) || return getfield(cache, :execution_stamp)::Base.RefValue{UInt64} + end + return Ref(UInt64(0)) +end + +# Build a real context only on the first preparation of this newborn owner. +# Repeated target retrieval never changes an active default shell or its leases. +# Call bindings come from resolution, not from the shape of a cached prototype. +function _newborn_call_context_cache(context::RunContext, application, object_id, + bound_inputs, output_targets, call_bindings::Tuple, environment_bindings, + stamp::Base.RefValue{UInt64}, +) + prepared = _prepare_model_execution_context!( + nothing, context.compiled, environment_bindings, application, object_id, + bound_inputs, output_targets, call_bindings, context.temporal_streams, + context.output_retention, context.time, context.constants, + context.publication_allowed, context.environment, + ) + return CallContextCache(prepared, stamp) +end + # Status views, publication tuples and handles leave heterogeneous assembly at # this boundary. Reuse one concrete payload constructor for each actual schema. function _targeted_newborn_call_target( @@ -6164,20 +6271,21 @@ function _targeted_newborn_call_target( status_view::CompiledModelStatusView, outputs::Tuple, output_targets::NamedTuple, + call_bindings::Tuple, environment_bindings::CompiledEnvironmentBindings, environment_binding, - cache::CallContextCache, -) + cache::CallContextCache{RC}, +) where {RC<:RunContext} # Keep the targeted runtime's cache and partial binding shell. In # particular, do not intern this owner into the post-barrier cohort store. execution_target = _compiled_execution_target( object_id, model, status_view, status_view.temporal_inputs, - status_view.bound_inputs, output_targets, outputs, (), + status_view.bound_inputs, output_targets, outputs, call_bindings, environment_binding, cache.default, cache, ) return CallTarget( execution_target, context.compiled, environment_bindings, application, - object_id, (), context.temporal_streams, context.output_retention, + object_id, cache.default.calls, context.temporal_streams, context.output_retention, context.time, context.constants, context.publication_allowed, context.environment, ) end @@ -6510,15 +6618,16 @@ end end @inline function _record_call_execution!(cache, ::Nothing) - cache.execution_revision += UInt64(1) + cache.execution_stamp[] += UInt64(1) return nothing end @inline function _record_call_execution!(cache, frame::CallEvaluationFrame) - cache.execution_revision += UInt64(1) + stamp = cache.execution_stamp + stamp[] += UInt64(1) ancestor = frame while ancestor !== nothing - ancestor.executions[cache] = cache.execution_revision + ancestor.executions[stamp] = stamp[] ancestor = ancestor.parent end return frame @@ -6601,9 +6710,19 @@ end target.output_targets, target.execution_target.call_bindings, target.temporal_streams, target.output_retention, target.time, target.constants, publication_allowed, environment, ) - _run_owned_call_kernel!( - target.execution_target, environment_value, context, frame, - ) + # The common context is concrete in this cache owner. Keep its sampled + # row unboxed at the kernel call; stale/trial contexts retain the general + # path when their descendant tuple or environment type differs. + DefaultContext = typeof(cache.default) + if context isa DefaultContext + _run_owned_call_kernel!( + target.execution_target, environment_value, context::DefaultContext, frame, + ) + else + _run_owned_call_kernel!( + target.execution_target, environment_value, context, frame, + ) + end finally acquired && (cache.in_use = false) end @@ -7266,11 +7385,7 @@ function _refresh_simulation_runtime!(simulation::Simulation) if !isnothing(dirty_environment_object_ids) changed_execution_application_ids = Set{Symbol}() for object_id in dirty_environment_object_ids - for application in get( - simulation.compiled.applications_by_object, - object_id, - (), - ) + _foreach_object_application(simulation.compiled, object_id) do application push!( changed_execution_application_ids, application.id, @@ -7817,7 +7932,7 @@ function _prepare_simulation!( # An existing simulation may have refreshed its environment while retaining # its schedule. Compare the current base step even after that refresh. preparation = _scenario_preparation(model) - _authored_application_recipes(preparation) + _validate_authored_scenario(preparation) prepared = preparation.resolved compiled = model.binding_cache if !isnothing(prepared) || !isnothing(compiled) @@ -8150,7 +8265,7 @@ function _model_request_matches_distributed_output( return any( plan -> request.var in keys(plan.declarations) && _selector_labels_may_overlap(request.selector, plan.selector), - _application_plans(plans.by_application, application.slot), + _application_plans(plans.by_application, application.id), ) end diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl index b30aa9d78..416882e0a 100644 --- a/src/composite_model/status_construction.jl +++ b/src/composite_model/status_construction.jl @@ -44,3 +44,45 @@ function _status_construction_recipe!(cache, existing_names::Tuple, edit_names:: StatusConstructionRecipe(existing_names, edit_names) end end + +"""An exact reference layout using the canonical StatusConstructionRecipe.""" +struct ExactReferenceFactory{Existing,Edited,Result,R} + construction::R + + ExactReferenceFactory{Existing,Edited,Result,R}(construction::R) where {Existing,Edited,Result,R} = + new{Existing,Edited,Result,R}(construction) +end + +_status_schema_names(::Type{Nothing}) = () +_status_schema_names(::Type{Status{Names,Refs}}) where {Names,Refs} = Names +_status_schema_references(::Type{Status{Names,Refs}}) where {Names,Refs} = Refs +_status_schema_values(::Nothing) = () +_status_schema_values(status::Status) = refvalues(status) + +_selected_status_reference_type(::ExistingStatusReference{I}, existing, edited) where {I} = + fieldtype(existing, I) +_selected_status_reference_type(::EditedStatusReference{I}, existing, edited) where {I} = + fieldtype(edited, I) + +# Host/schema-time operation: names and exact reference types only, no values, +# defaults, callback calls or fake Status objects. +function ExactReferenceFactory(::Type{Existing}, ::Type{Edited}, ::Type{Result}, edit_names::Tuple) where {Existing,Edited<:Tuple,Result<:Status} + (Existing === Nothing || Existing <: Status) && isconcretetype(Existing) && + isconcretetype(Edited) && isconcretetype(Result) || + throw(ArgumentError("An exact reference factory requires concrete status/reference schemas.")) + fieldcount(Edited) == length(edit_names) && all(T -> T <: Ref, fieldtypes(Edited)) || + throw(ArgumentError("Edited reference types do not match their declared field names.")) + original_refs = Existing === Nothing ? Tuple{} : _status_schema_references(Existing) + construction = StatusConstructionRecipe(_status_schema_names(Existing), edit_names) + selected_types = map(construction.actions) do action + _selected_status_reference_type(action, original_refs, Edited) + end + _status_schema_names(Result) == typeof(construction).parameters[1] && + Tuple{selected_types...} === _status_schema_references(Result) || + throw(ArgumentError("Reference selections do not produce the admitted status schema.")) + return ExactReferenceFactory{Existing,Edited,Result,typeof(construction)}(construction) +end + +@inline function _construct_status(factory::ExactReferenceFactory{Existing,Edited,Result}, original::Existing, edited::Edited) where {Existing,Edited,Result} + return _construct_status(factory.construction, _status_schema_values(original), edited)::Result +end diff --git a/src/input_schema.jl b/src/input_schema.jl index 506b6f302..155e3be5c 100644 --- a/src/input_schema.jl +++ b/src/input_schema.jl @@ -74,11 +74,17 @@ end return schema end -function _input_default_values(schema::NamedTuple) - pairs_ = Pair{Symbol,Any}[] - for (name, declaration) in pairs(schema) - declaration isa Default || continue - push!(pairs_, Symbol(name) => declaration.value) +@inline _input_default_entry(::Val, declaration) = NamedTuple() +@inline _input_default_entry(::Val{Name}, declaration::Default) where {Name} = + NamedTuple{(Name,)}((declaration.value,)) + +# Unroll only the fixed names. Entry dispatch still reads each actual +# declaration, including Any/Union fields, without a type-based default mask. +@generated function _input_default_values(schema::NamedTuple{Names}) where {Names} + result = :(NamedTuple()) + for index in reverse(eachindex(Names)) + entry = :(_input_default_entry(Val{$(QuoteNode(Names[index]))}(), getfield(schema, $index))) + result = :(merge($entry, $result)) end - return (; pairs_...) + return result end diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index 99a2028aa..a7ca926c3 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -310,7 +310,7 @@ function apply_model_graph_edit( candidate = _apply_model_graph_edit!(candidate, edit) _mark_bindings_dirty!(candidate) if !isnothing(preparation) && - _authored_specs_match(preparation.source_specs, candidate.applications) + _authored_specs_match(preparation, candidate) candidate.scenario_plan_cache = preparation _model_owned_scenario_preparation(candidate, preparation).resolved = nothing end diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index b6652867b..cc2f9f70b 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -217,7 +217,7 @@ function _model_graph_compiled( applications, applications_by_id, ordered_applications, - _applications_by_object(applications), + _applications_by_object(applications, model.registry.objects), input_bindings, call_bindings, input_by_target, @@ -246,59 +246,40 @@ function _model_graph_compiled( ) end -function _model_graph_fallback_application(model, raw_spec, timeline, slot) - spec = as_model_spec(raw_spec) - selector = applies_to(spec) - selector isa AbstractObjectMultiplicity || error( - "Model application for process `$(process(spec))` has no valid `ModelSpec(...; on=...)` selector.", - ) - application_id = something(application_name(spec), process(spec)) - target_matcher = _compile_selector_matcher(model, selector) - target_ids = _resolve_object_ids(model, selector, target_matcher) - output_names, canonical_output_names = _compiled_output_names(spec) - return CompiledModelApplication( - CompiledApplicationPlan( - slot, - application_id, - spec, - process(spec), - application_name(spec), - selector, - target_matcher, - timestep(spec), - _model_application_clock(model, spec, target_ids, timeline), - _compiled_object_model_overrides(spec, target_ids, application_id), - output_names, - canonical_output_names, - ), - target_ids, - ) -end - function _model_graph_compile_applications(model, timeline, diagnostics) - applications = _model_graph_phase!(diagnostics, :applications, CompiledModelApplication[]) do - _compile_model_applications(model, Tuple(model.applications), timeline) + preparation = _scenario_preparation(model) + if isnothing(preparation.failure) + applications = _model_graph_phase!(diagnostics, :applications, CompiledModelApplication[]) do + _resolve_application_recipes(model, preparation.authored, timeline) + end + isempty(applications) || return applications + isempty(model.applications) && return applications end - isempty(applications) || return applications - isempty(model.applications) && return applications recovered = CompiledModelApplication[] recovered_ids = Set{Symbol}() - for (slot, raw_spec) in pairs(model.applications) + for record in preparation.authored + if record isa ScenarioPreparationFailure + application_ids = isnothing(record.application_id) ? Symbol[] : [record.application_id] + push!(diagnostics, _model_graph_diagnostic( + record.error, :applications; + code=Symbol(record.phase, :_error), application_ids, + suggestions=["Fix the authored application declaration."], + )) + continue + end try - application = _model_graph_fallback_application(model, raw_spec, timeline, slot) + application = only(_resolve_application_recipes(model, (record,), timeline)) application.id in recovered_ids && error( "Duplicate recovered model application id `$(application.id)`.", ) push!(recovered_ids, application.id) push!(recovered, application) catch err - spec = as_model_spec(raw_spec) - application_id = something(application_name(spec), process(spec)) push!(diagnostics, _model_graph_diagnostic( err, :application_recovery; - application_ids=[application_id], + application_ids=[record.id], suggestions=["Fix the application selector or authored configuration."], )) end diff --git a/test/runtests.jl b/test/runtests.jl index 02c4a6b40..0a8bef9a0 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -50,6 +50,8 @@ else include("test-execution-cohorts.jl") include("test-execution-cohort-refresh.jl") include("test-model-canonical-cohorts.jl") + include("test-model-persistent-empty-groups.jl") + include("test-model-slot-group-refresh.jl") end @testset "Organ creation allocations" begin @@ -80,14 +82,20 @@ else @testset "Reusable scenario plans" begin include("test-model-prepared-scenario.jl") include("test-model-scenario-authoring.jl") + include("test-model-authored-call-plans.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") + include("test-input-default-values.jl") + include("test-application-membership-slots.jl") + include("test-registered-status-dispatch.jl") include("test-owned-metadata-tables.jl") include("test-resolved-input-materialization.jl") + include("test-input-source-matching.jl") end @testset "Isolated model diagnostics" begin include("test-model-diagnostic-isolation.jl") + include("test-model-diagnostic-authoring-recovery.jl") end @testset "Public native compilation API" begin @@ -104,6 +112,9 @@ else @testset "Selector candidate scope fast path" begin include("test-selector-candidate-empty-scope.jl") + include("test-selector-query-scope-root.jl") + include("test-selector-query-scope-append.jl") + include("test-selector-ancestor-index.jl") end @testset "Lifecycle without target additions" begin @@ -132,6 +143,7 @@ else @testset "Accepted call evaluations" begin include("test-model-call-evaluations.jl") + include("test-model-call-execution-identity.jl") include("test-call-evaluation-parent-generation.jl") end @@ -187,6 +199,8 @@ else @testset "Scheduled newborn initializers" begin include("test-model-initializers.jl") include("test-model-newborn-execution-owner.jl") + include("test-model-newborn-context-initializer.jl") + include("test-model-newborn-context-nested.jl") include("test-model-runtime-call-names.jl") end diff --git a/test/test-application-membership-slots.jl b/test/test-application-membership-slots.jl new file mode 100644 index 000000000..6bf54445e --- /dev/null +++ b/test/test-application-membership-slots.jl @@ -0,0 +1,124 @@ +module ApplicationMembershipSlotChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "membership_slot_probe" verbose=false +struct SlotProbe{T} <: AbstractMembership_Slot_ProbeModel + parameter::T +end +PSE.inputs_(::SlotProbe) = NamedTuple() +PSE.outputs_(::SlotProbe) = NamedTuple() +PSE.run!(::SlotProbe, status, environment, constants, context) = nothing + +function applications() + payloads = (1f0, 1.0, Int8(1), Int16(1), Int32(1), Int64(1)) + names = (:first, :second, :third, :fourth, :fifth, :sixth) + return ntuple(6) do index + ModelSpec(SlotProbe(payloads[index]); name=names[index], on=Many(scale=:Leaf)) + end +end + +@testset "slot views preserve the sole reverse index and heterogeneous catalog" begin + model = CompositeModel(Object(:leaf; scale=:Leaf), Object(7; scale=:Leaf); + applications=applications()) + compiled = run!(model; steps=0, outputs=:none).compiled + @test keytype(compiled.applications_by_object) === ObjectId + @test length(unique(typeof(application.spec.model) for application in compiled.applications)) == 6 + for id in (ObjectId(:leaf), ObjectId(7)) + view = PSE._application_membership_slots(compiled, id) + @test view.members === compiled.applications_by_object[id] + @test view.applications === compiled.applications_by_id + @test collect(view) == collect(1:6) + @test eltype(view) === Int + seen = Tuple{Symbol,Int}[] + PSE._foreach_object_application(compiled, id) do application + push!(seen, (application.id, application.slot)) + end + @test seen == [(application.id, application.slot) for application in compiled.applications] + # The view owns no copied membership and observes the current index order. + reverse!(view.members) + try + @test collect(view) == collect(6:-1:1) + finally + reverse!(view.members) + end + end + @test isempty(PSE._application_membership_slots(compiled, ObjectId(:absent))) + catalog = compiled.applications_by_id + slot = parse(Int, "6") + @test (@inferred PSE._with_metadata_entry(application -> application.id, catalog, slot)) === :sixth + @test_throws BoundsError PSE._with_metadata_entry(identity, catalog, 0) + @test_throws BoundsError PSE._with_metadata_entry(identity, catalog, 7) + @test (@inferred PSE._with_metadata_entry(application -> application.id, + catalog, Symbol(only(["sixth"])))) === :sixth + @test PSE._with_metadata_entry(identity, catalog, :sixth) === catalog[:sixth] + @test PSE._with_metadata_entry(identity, catalog, Int32(6)) === catalog[:sixth] + @test_throws KeyError PSE._with_metadata_entry(identity, catalog, :missing) + @test_throws ArgumentError PSE._application_membership_slot(catalog, deepcopy(catalog[1])) +end + +@testset "closed application indexes retain the registry identity schema" begin + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=applications()) + compiled = run!(model; steps=0, outputs=:none).compiled + status = PSE.model_status(model, :leaf) + closed = PSE._closed_object_family_store(model.registry.objects) + index = PSE._applications_by_object(compiled.applications, closed) + @test keytype(index) === ObjectId{Symbol} + @test PSE._application_index_object_id(index, ObjectId(:leaf)) === ObjectId(:leaf) + @test_throws ArgumentError PSE._application_index_object_id(index, ObjectId(7)) + @test index[ObjectId(:leaf)] == compiled.applications_by_object[ObjectId(:leaf)] + @test all(left === right for (left, right) in zip(index[ObjectId(:leaf)], compiled.applications)) + @test PSE.model_status(model, :leaf) === status +end + + +@testset "partial catalogs use local positions and preserve exact wrapper identity" begin + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=applications()) + compiled = run!(model; steps=0, outputs=:none).compiled + # A partial application is a distinct membership owner with the same plan. + sixth = compiled.applications_by_id[:sixth] + second = compiled.applications_by_id[:second] + partial_sixth = PSE.CompiledModelApplication(sixth.plan, ObjectId[ObjectId(:leaf)]) + partial_second = PSE.CompiledModelApplication(second.plan, ObjectId[ObjectId(:leaf)]) + partials = (partial_sixth, partial_second) + catalog = PSE._applications_by_id(partials) + @test catalog isa PSE.CompiledMetadataTable + @test keys(catalog) === (:sixth, :second) + index = PSE._applications_by_object(partials, model.registry.objects) + members = index[ObjectId(:leaf)] + slots = PSE.ApplicationMembershipSlots(catalog, members) + @test collect(slots) == [1, 2] + seen = Tuple{Symbol,Int}[] + for slot in slots + PSE._with_metadata_entry(catalog, slot) do application + push!(seen, (application.id, application.slot)) + end + end + @test seen == [(:sixth, 6), (:second, 2)] + @test (@inferred PSE._with_metadata_entry(application -> application.id, + catalog, parse(Int, "2"))) === :second + @test PSE._with_metadata_entry(identity, catalog, 1) === partial_sixth + @test PSE._with_metadata_entry(identity, catalog, 2) === partial_second + @test PSE._with_metadata_entry(identity, catalog, :sixth) === partial_sixth + @test PSE._with_metadata_entry(identity, catalog, :second) === partial_second + @test_throws ArgumentError PSE._application_membership_slot(catalog, sixth) + @test_throws ArgumentError PSE._application_membership_slot(compiled.applications_by_id, partial_sixth) + # Do not silently replace a partial wrapper by a canonical one with equal id. + push!(members, sixth) + @test_throws ArgumentError collect(slots) + pop!(members) + @test collect(slots) == [1, 2] + empty_catalog = PSE._applications_by_id(()) + empty_slots = PSE.ApplicationMembershipSlots(empty_catalog, ()) + @test isempty(empty_slots) + @test collect(empty_slots) == Int[] + @test_throws BoundsError PSE._with_metadata_entry(identity, empty_catalog, 1) + @test_throws KeyError PSE._with_metadata_entry(identity, empty_catalog, :missing) + # Owner field names are ordinary metadata identities, not property forwarding. + metadata = PSE.CompiledMetadataTable((entries=Ref(1), length=Ref(2f0))) + @test PSE._with_metadata_entry(identity, metadata, :entries) === metadata[:entries] + @test PSE._with_metadata_entry(identity, metadata, :length) === metadata[:length] +end + +end diff --git a/test/test-input-default-values.jl b/test/test-input-default-values.jl new file mode 100644 index 000000000..e2cf1b5dd --- /dev/null +++ b/test/test-input-default-values.jl @@ -0,0 +1,156 @@ +module InputDefaultValuesChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine + +@testset "concrete declaration tuples infer ordered defaults and retain live aliases" begin + buffer = Float32[2, 3] + cell = Ref{Any}(Float32[4, 5]) + cells = Base.RefValue{Any}[cell, Ref{Any}(6f0)] + schema = (required=Required(Real), scalar=Default(1.25f0), + buffer=Default(buffer), cell=Default(cell), cells=Default(cells), + final_required=Required(AbstractVector)) + defaults = @inferred PSE._input_default_values(schema) + @test keys(defaults) === (:scalar, :buffer, :cell, :cells) + @test defaults.scalar === 1.25f0 + @test defaults.buffer === buffer + @test defaults.cell === cell + @test defaults.cells === cells + @test defaults.cells[1] === defaults.cell + @test fieldtype(typeof(defaults), :scalar) === Float32 + @test fieldtype(typeof(defaults), :cell) === Base.RefValue{Any} + @test fieldtype(typeof(defaults), :cells) === Vector{Base.RefValue{Any}} + buffer[1] = 8f0 + cell[] = [9.0] + next = @inferred PSE._input_default_values(schema) + @test next.buffer === buffer + @test next.buffer == Float32[8, 3] + @test next.cell === cell + @test next.cell[] isa Vector{Float64} + @test defaults.cell[] === next.cell[] + @test (@inferred PSE._input_default_values(NamedTuple())) === NamedTuple() + @test (@inferred PSE._input_default_values((a=Required(Real), b=Required(AbstractVector)))) === NamedTuple() +end + +function generic_default(value::T) where {T} + return PSE._input_default_values((before=Required(Real), + selected=Default(value), after=Required(T))) +end + +@testset "wide concrete declarations infer every selected field" begin + names = ntuple(index -> Symbol(:input_, index), 12) + payload = Ref{Any}(Float32[12]) + declarations = (Required(Real), Default(1f0), Default(Int128(2)), + Required(AbstractVector), Default(2 // 3), Default(payload), + Required(Float32), Default(Float32[7]), Default(Int16(8)), + Required(Number), Default((left=9f0,)), Default(:last)) + schema = NamedTuple{names}(declarations) + defaults = @inferred PSE._input_default_values(schema) + @test keys(defaults) === (names[2], names[3], names[5], names[6], + names[8], names[9], names[11], names[12]) + @test defaults.input_2 === 1f0 + @test defaults.input_3 === Int128(2) + @test defaults.input_5 === 2 // 3 + @test defaults.input_6 === payload + @test defaults.input_8 === declarations[8].value + @test defaults.input_9 === Int16(8) + @test defaults.input_11 === (left=9f0,) + @test defaults.input_12 === :last + payload[] = :fresh + @test (@inferred PSE._input_default_values(schema)).input_6[] === :fresh +end + +@testset "generic numerical values retain their exact types" begin + for value in (Float32(1.5), Int128(7), 2 // 3, big"1.25") + defaults = @inferred generic_default(value) + @test keys(defaults) === (:selected,) + @test defaults.selected === value + @test typeof(defaults.selected) === typeof(value) + end +end + +@testset "Any and union declarations select actual defaults without a type-based mask" begin + AnySchema = NamedTuple{(:a, :b, :c, :d),Tuple{Any,Any,Any,Any}} + payload = Float32[10] + first = AnySchema((Required(Real), Default(2f0), nothing, Default(payload))) + result = PSE._input_default_values(first) + @test keys(result) === (:b, :d) + @test result.b === 2f0 + @test result.d === payload + second = AnySchema((Default(payload), Required(Float32), 3, :plain)) + result = PSE._input_default_values(second) + @test keys(result) === (:a,) + @test result.a === payload + + UnionSchema = NamedTuple{(:choice, :buffer), + Tuple{Union{Required{Real},Default{Float32}},Default{Vector{Float32}}}} + absent = UnionSchema((Required(Real), Default(payload))) + present = UnionSchema((Default(3f0), Default(payload))) + @test keys(PSE._input_default_values(absent)) === (:buffer,) + @test PSE._input_default_values(absent).buffer === payload + @test keys(PSE._input_default_values(present)) === (:choice, :buffer) + @test PSE._input_default_values(present).choice === 3f0 + @test PSE._input_default_values(present).buffer === payload + + # This extraction helper historically skipped plain values. Validating an + # inputs_ declaration remains the separate responsibility of _input_schema. + @test PSE._input_default_values((plain=1.0, required=Required(Real), + selected=Default(payload), marker=nothing)) == (selected=payload,) +end + +@testset "fresh schema values are read once and never retained by extraction" begin + reads = Ref(0) + current = Ref{Any}(Float32[1]) + schema() = (reads[] += 1; (buffer=Default(current[]), required=Required(Real))) + first_schema = schema() + first = PSE._input_default_values(first_schema) + @test reads[] == 1 + @test first.buffer === current[] + current[] = Float64[2] + next_schema = schema() + next = PSE._input_default_values(next_schema) + @test reads[] == 2 + @test first.buffer == Float32[1] + @test next.buffer === current[] + @test next.buffer isa Vector{Float64} + @test PSE._input_default_values(first_schema).buffer === first.buffer + @test reads[] == 2 +end + +PSE.@process "tuple_input_defaults" verbose=false +struct MutableInputDefaults{P} <: AbstractTuple_Input_DefaultsModel + payload::P +end +PSE.inputs_(model::MutableInputDefaults) = + (buffer=Default(model.payload[]), optional=Default(1f0)) +PSE.outputs_(::MutableInputDefaults) = NamedTuple() +PSE.run!(::MutableInputDefaults, status, environment, constants, context) = nothing + +@testset "canonical callers still copy fresh defaults for every real object" begin + payload = Ref{Any}(Float32[1, 2]) + model = CompositeModel(Object(:first; scale=:Leaf), Object(:second; scale=:Leaf); + applications=(ModelSpec(MutableInputDefaults(payload); name=:defaults, + on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + first = model_status(model, :first).buffer + second = model_status(model, :second).buffer + @test first == second == Float32[1, 2] + @test first !== second + @test first !== payload[] + payload[] = Float64[7, 8] + register_object!(model, Object(:third; scale=:Leaf)) + step!(simulation) + third = model_status(model, :third).buffer + @test third == [7.0, 8.0] + @test third isa Vector{Float64} + @test third !== payload[] + @test first isa Vector{Float32} + @test second isa Vector{Float32} + first[1] = 9f0 + @test second == Float32[1, 2] + @test third == [7.0, 8.0] + @test model_status(model, :third).optional === 1f0 +end + +end # module InputDefaultValuesChecks diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl new file mode 100644 index 000000000..077035beb --- /dev/null +++ b/test/test-input-source-matching.jl @@ -0,0 +1,145 @@ +module InputSourceMatchingChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "source_match_writer" verbose=false +PSE.@process "source_match_alternative" verbose=false +struct Writer{T} <: AbstractSource_Match_WriterModel + value::T +end +struct AlternativeWriter{T} <: AbstractSource_Match_AlternativeModel + value::T +end +PSE.inputs_(::Union{Writer,AlternativeWriter}) = NamedTuple() +PSE.outputs_(model::Union{Writer,AlternativeWriter}) = (x=zero(model.value),) +PSE.run!(model::Union{Writer,AlternativeWriter}, status, environment, constants, context) = + (status.x = model.value; nothing) + +function matching_fixture() + names = (:a, :b, :c, :d, :e, :f) + models = (Writer(1f0), Writer(2.0), Writer(Int8(3)), Writer(Int16(4)), + Writer(Int32(5)), AlternativeWriter(Int64(6))) + objects = ntuple(index -> Object(index; status=Status(x=models[index].value)), 6) + applications = ntuple(index -> ModelSpec(models[index]; + name=names[index], on=One(id=index)), 6) + simulation = run!(CompositeModel(objects...; applications); steps=0, outputs=:none) + compiled = simulation.compiled + owner(name, index) = PSE.CompiledWriterOwner(index, name, ObjectId(index), nothing, :local) + ownership = Dict( + (ObjectId(1), :x) => [owner(:a, 1), owner(:b, 2), owner(:c, 3), + owner(:d, 4), owner(:missing, 99)], + (ObjectId(2), :x) => [owner(:b, 2), owner(:a, 1), owner(:e, 5), owner(:f, 6)], + ) + distributed = PSE.CompiledDistributedOutputs((), Dict(), ownership, Dict()) + return simulation, distributed +end + +function matched(compiled, distributed, ids; process=nothing, application=nothing, + potential=(), allow_empty=false) + return PSE._matching_input_source_applications(compiled.applications_by_object, + ObjectId.(ids), :x, process, application, distributed, potential; + applications_by_id=compiled.applications_by_id, allow_empty) +end + +@testset "local and ownership matching preserve first occurrence order" begin + simulation, distributed = matching_fixture() + compiled = simulation.compiled + references = [PSE.refvalue(model_status(simulation.model, id), :x) for id in 1:6] + @test compiled.applications_by_id isa PSE.CompiledMetadataTable + @test matched(compiled, distributed, (1, 2)) == [:a, :b, :c, :d, :e, :f] + @test matched(compiled, distributed, (2, 1)) == [:b, :a, :e, :f, :c, :d] + @test matched(compiled, distributed, (1, 2); application=:c) == [:c] + alternative = compiled.applications_by_id[:f] + @test matched(compiled, distributed, (1, 2); process=alternative.process) == [:f] + @test matched(compiled, distributed, (1, 2); potential=(:c,)) == [:c] + @test isempty(matched(compiled, distributed, (1, 2); + application=:missing, potential=(:missing,), allow_empty=true)) + @test_throws ErrorException matched(compiled, distributed, (1, 2); + application=:missing, potential=(:missing,)) + @test [model_status(simulation.model, id).x for id in 1:6] == [1, 2, 3, 4, 5, 6] + @test all(PSE.refvalue(model_status(simulation.model, id), :x) === references[id] + for id in 1:6) + @test current_step(simulation) == 0 +end + +@testset "an already matched owner still requires its distributed index" begin + _, distributed = matching_fixture() + matches = [:a] + failure = try + PSE._append_distributed_input_source_applications!(matches, distributed, + ObjectId(1), :x, nothing, nothing, nothing) + nothing + catch exception + exception + end + @test failure isa ErrorException + @test sprint(showerror, failure) == + "Distributed output producer matching requires the compiled application index." + @test matches == [:a] + @test PSE._append_distributed_input_source_applications!(matches, distributed, + ObjectId(7), :x, nothing, nothing, nothing) === matches +end + +@testset "planned singleton matching retains a real newborn partial overlay" begin + simulation, _ = matching_fixture() + compiled = simulation.compiled + newborn = register_object!(simulation.model, Object(7; status=Status(x=7f0))) + reference = PSE.refvalue(newborn.status, :x) + partial = PSE._partial_model_application(compiled.applications_by_id[:a], + ObjectId[ObjectId(7)]) + overlay = PSE._ApplicationsByObjectOverlay(compiled.applications_by_object, + Dict(ObjectId(7) => PSE.CompiledModelApplication[partial])) + @test !(ObjectId(7) in compiled.applications_by_id[:a].target_ids) + @test PSE._matching_input_source_applications(overlay, ObjectId[ObjectId(7)], + :x, nothing, nothing, PSE.NoCompiledDistributedOutputs(), (:a,); + applications_by_id=compiled.applications_by_id) == [:a] + @test newborn.status.x === 7f0 + @test PSE.refvalue(newborn.status, :x) === reference + @test current_step(simulation) == 0 +end + +@testset "one producer on several local objects is recorded once in first occurrence order" begin + model = CompositeModel( + Object(1; kind=:local, status=Status(x=1f0)), + Object(2; kind=:local, status=Status(x=2f0)), + Object(3; kind=:local, status=Status(x=3f0)), + Object(4; status=Status(x=4.0)); + applications=( + ModelSpec(Writer(1f0); name=:shared, on=Many(kind=:local)), + ModelSpec(AlternativeWriter(4.0); name=:other, on=One(id=4)), + )) + simulation = run!(model; steps=0, outputs=:none) + compiled = simulation.compiled + shared = compiled.applications_by_id[:shared] + other = compiled.applications_by_id[:other] + shared_owner = PSE.CompiledWriterOwner(shared.slot, :shared, ObjectId(1), nothing, :local) + other_owner = PSE.CompiledWriterOwner(other.slot, :other, ObjectId(4), nothing, :distributed) + ownership = Dict( + (ObjectId(1), :x) => [shared_owner, other_owner], + (ObjectId(2), :x) => [shared_owner], + (ObjectId(3), :x) => [other_owner, shared_owner], + ) + distributed = PSE.CompiledDistributedOutputs((), Dict(), ownership, Dict()) + @test shared.target_ids == ObjectId.([1, 2, 3]) + @test matched(compiled, PSE.NoCompiledDistributedOutputs(), (2, 1, 3, 1)) == [:shared] + @test matched(compiled, distributed, (2, 1, 3, 1)) == [:shared, :other] + @test matched(compiled, distributed, (4, 3, 2, 1)) == [:other, :shared] + @test matched(compiled, distributed, (2, 1, 3, 1); process=shared.process) == [:shared] + @test matched(compiled, distributed, (2, 1, 3, 1); application=:other) == [:other] + + newborn = register_object!(model, Object(5; kind=:local, status=Status(x=5f0))) + reference = PSE.refvalue(newborn.status, :x) + partial = PSE._partial_model_application(shared, ObjectId[ObjectId(5)]) + overlay = PSE._ApplicationsByObjectOverlay(compiled.applications_by_object, + Dict(ObjectId(5) => PSE.CompiledModelApplication[partial])) + @test PSE._matching_input_source_applications(overlay, ObjectId.([5, 2, 1, 3]), + :x, nothing, nothing, distributed; + applications_by_id=compiled.applications_by_id) == [:shared, :other] + @test newborn.status.x === 5f0 + @test PSE.refvalue(newborn.status, :x) === reference + @test [model_status(model, id).x for id in 1:4] == [1, 2, 3, 4] + @test current_step(simulation) == 0 +end + +end diff --git a/test/test-model-adaptive-selectors.jl b/test/test-model-adaptive-selectors.jl index 659b73f44..dcf2c083f 100644 --- a/test/test-model-adaptive-selectors.jl +++ b/test/test-model-adaptive-selectors.jl @@ -628,7 +628,7 @@ end # vector, because writer filtering mutates those returned vectors. application = simulation.compiled.applications_by_id[:partition] recipe = PlantSimEngine._application_plans( - simulation.compiled.scenario_plan.input_recipes_by_application, application.slot) + simulation.compiled.scenario_plan.input_recipes_by_application, application.id) cache = PlantSimEngine._input_query_cache(model.registry.objects, recipe.query_count) routes = Dict(plan.input => (plan, slot) for (plan, slot) in zip(recipe.explicit, recipe.query_slots)) diff --git a/test/test-model-authored-call-plans.jl b/test/test-model-authored-call-plans.jl new file mode 100644 index 000000000..f76e63c4c --- /dev/null +++ b/test/test-model-authored-call-plans.jl @@ -0,0 +1,203 @@ +module AuthoredCallPlanChecks + +using Dates, PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "authored_call_leaf" verbose=false +PSE.@process "authored_call_driver" verbose=false +PSE.@process "authored_call_creator" verbose=false +PSE.@process "authored_call_broken" verbose=false + +struct Leaf <: AbstractAuthored_Call_LeafModel end +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Leaf) = (value=0f0, calls=0) +function PSE.run!(::Leaf, status, environment, constants, context) + status.value += 2f0 + status.calls += 1 + return nothing +end + +struct Driver{D} <: AbstractAuthored_Call_DriverModel + dependency_calls::D +end +PSE.inputs_(::Driver) = NamedTuple() +PSE.outputs_(::Driver) = (seen=0f0, drivers=0) +function PSE.dep(model::Driver) + model.dependency_calls[] += 1 + return (leaf=Call(One(Scope(ObjectId(:future_root)); scale=:Leaf, application=:leaf)),) +end +function PSE.run!(::Driver, status, environment, constants, context) + status.drivers += 1 + status.seen = only(run_call!(context, :leaf; publish=true)).status.value + return nothing +end + +function scene(; every=Hour(1), environment=(duration=Hour(1),), with_leaf=false) + dependencies = Ref(0) + driver = ModelSpec(Driver(dependencies); name=:driver, on=One(id=:scene), every) + leaf = ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf), every) + normalized_count = dependencies[] + @test PSE.model_calls(driver).leaf isa One + @test dependencies[] == normalized_count + model = CompositeModel(Object(:scene; scale=:Scene, + status=Status(seen=0f0, drivers=0)); applications=(driver, leaf), environment) + @test dependencies[] == normalized_count + if with_leaf + register_leaf!(model) + end + return (; model, dependencies, normalized_count, driver) +end + +function register_leaf!(model) + register_object!(model, Object(:future_root; scale=:Plant, parent=:scene)) + return register_object!(model, Object(:leaf; scale=:Leaf, parent=:future_root, + status=Status(value=3f0, calls=0))) +end + +@testset "constructor prepares normalized Call routes but resolves symbolic Scope at run" begin + data = scene() + preparation = data.model.scenario_plan_cache + recipe = preparation.authored[1] + authored = only(recipe.call_plans) + @test authored isa PSE.CompiledModelCallPlan + @test authored.application_id === :driver + @test PSE._compiled_call_name(authored) === :leaf + @test PSE._compiled_call_mode(authored) === :manual + @test authored.matcher.scope isa Scope + @test authored.potential_callee_application_ids == (:leaf,) + @test isempty(preparation.authored[2].call_plans) + @test isnothing(preparation.failure) + applications = PSE._compile_model_applications(data.model, Tuple(data.model.applications), + PSE._model_timeline(data.model)) + @test applications[1].call_plans === recipe.call_plans + @test_throws "No instance or object ID" PSE._compile_model_call_plans(data.model, applications) + @test data.dependencies[] == data.normalized_count + @test isnothing(preparation.failure) # unresolved live scope is not an authoring failure + + register_leaf!(data.model) + simulation = run!(data.model; steps=2, outputs=:all) + resolved = only(simulation.compiled.scenario_plan.call_plans) + @test resolved.matcher.scope isa PSE.CompiledNamedScope + @test resolved.matcher.scope.root_id === ObjectId(:future_root) + @test only(recipe.call_plans).matcher.scope isa Scope + @test model_status(data.model, :leaf).value === 7f0 + @test model_status(data.model, :leaf).calls == 2 + @test model_status(data.model, :scene).seen === 7f0 + @test outputs(simulation)[(:leaf, ObjectId(:leaf), :value)] == [(1.0, 5f0), (2.0, 7f0)] + PSE._compile_model_call_plans(data.model, simulation.compiled.applications) + @test data.dependencies[] == data.normalized_count + + # A compiler call with another explicit spec set must use that set's + # prepared declarations, never the model's default preparation cache. + alternate_driver = ModelSpec(Driver(data.dependencies); name=:alternate_driver, + on=One(id=:scene), calls=(leaf=One(Scope(ObjectId(:future_root)); + scale=:Leaf, application=:alternate_leaf),)) + alternate_leaf = ModelSpec(Leaf(); name=:alternate_leaf, on=Many(scale=:Leaf)) + before_compile = data.dependencies[] + alternate = PSE.compile_composite_model(data.model, (alternate_driver, alternate_leaf)) + @test only(alternate.scenario_plan.call_plans).application_id === :alternate_driver + @test only(alternate.scenario_plan.call_plans).potential_callee_application_ids == (:alternate_leaf,) + @test data.dependencies[] == before_compile + @test data.model.scenario_plan_cache === preparation +end + +@testset "cadence and environment stay runtime while Call declarations remain shared" begin + data = scene(; every=Hour(2), with_leaf=true) + preparation = data.model.scenario_plan_cache + authored = preparation.authored[1].call_plans + original = run!(data.model; steps=0) + @test original.compiled.applications_by_id[:driver].clock.dt == 2.0 + data.model.environment = (duration=Hour(2),) + mark_environment_binding_dirty!(data.model) + restarted = run!(data.model; steps=2) + @test restarted.compiled.applications_by_id[:driver].clock.dt == 1.0 + @test original.compiled.applications_by_id[:driver].clock.dt == 2.0 + @test restarted.compiled.applications_by_id[:driver].call_plans === authored + @test model_status(data.model, :leaf).calls == 2 + @test data.dependencies[] == data.normalized_count +end + +struct Creator{D} <: AbstractAuthored_Call_CreatorModel + dependency_calls::D +end +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (created=false,) +function PSE.dep(model::Creator) + model.dependency_calls[] += 1 + return (start=Initializer(One(Subtree(); scale=:Leaf, application=:leaf)),) +end +function PSE.run!(::Creator, status, environment, constants, context) + status.created && return nothing + object = register_object!(runtime_model(context), Object(:born; scale=:Leaf, + parent=:scene, status=Status(value=3f0, calls=0))) + run_initializer!(context, :start, object) + status.created = true + return nothing +end + +@testset "default Initializer mode retains scheduled newborn and publication semantics" begin + dependencies = Ref(0) + creator = ModelSpec(Creator(dependencies); name=:creator, on=One(id=:scene)) + normalized_count = dependencies[] + model = CompositeModel(Object(:scene; scale=:Scene); applications=(creator, + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)))) + @test PSE._compiled_call_mode(only(model.scenario_plan_cache.authored[1].call_plans)) === :initializer + @test dependencies[] == normalized_count + simulation = run!(model; outputs=:all) + @test model_status(model, :born).calls == 1 + @test model_status(model, :born).value === 5f0 + @test isempty(get(outputs(simulation), (:leaf, ObjectId(:born), :calls), [])) + continue!(simulation) + @test model_status(model, :born).calls == 2 + @test outputs(simulation)[(:leaf, ObjectId(:born), :calls)] == [(2.0, 2)] + @test dependencies[] == normalized_count +end + +const failed_declarations = Ref(0) +struct Broken <: AbstractAuthored_Call_BrokenModel end +function PSE.outputs_(::Broken) + failed_declarations[] += 1 + error("intentional authored output failure") +end + +@testset "partial reports retain later Call declarations and original application slots" begin + failed_declarations[] = 0 + dependencies = Ref(0) + driver = ModelSpec(Driver(dependencies); name=:driver, on=One(id=:scene)) + model = CompositeModel(Object(:scene; scale=:Scene, status=Status(seen=0f0, drivers=0)), + Object(:future_root; scale=:Plant, parent=:scene), + Object(:leaf; scale=:Leaf, parent=:future_root, status=Status(value=3f0, calls=0)); + applications=(ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), + ModelSpec(Broken(); name=:broken, on=One(id=:scene)), driver)) + @test model.scenario_plan_cache.failure.application_id === :broken + @test length(model.scenario_plan_cache.authored[3].call_plans) == 1 + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:leaf, :driver] + @test [application.slot for application in report.applications] == [1, 3] + @test length(report.call_bindings) == 1 + binding = only(report.call_bindings) + @test binding.application_id === :driver + @test binding.callee_object_ids == [ObjectId(:leaf)] + @test binding.callee_application_ids == [:leaf] + @test failed_declarations[] == 1 +end + +@testset "partial live membership filters only missing callee applications" begin + dependencies = Ref(0) + driver = ModelSpec(Driver(dependencies); name=:driver, on=One(id=:scene)) + model = CompositeModel(Object(:scene; scale=:Scene, status=Status(seen=0f0, drivers=0)), + Object(:future_root; scale=:Plant, parent=:scene); + applications=(ModelSpec(Leaf(); name=:leaf, on=One(id=:missing)), driver)) + preparation = model.scenario_plan_cache + @test isnothing(preparation.failure) + @test only(preparation.authored[2].call_plans).potential_callee_application_ids == (:leaf,) + # This is the same subset resolution used by the read-only graph report. + applications = PSE._resolve_application_recipes(model, + (preparation.authored[2],), PSE._model_timeline(model)) + @test isempty(only(PSE._compile_model_call_plans(model, applications)).potential_callee_application_ids) + @test only(preparation.authored[2].call_plans).potential_callee_application_ids == (:leaf,) + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:driver] + @test !isempty(report.diagnostics) +end + +end diff --git a/test/test-model-call-context-cache.jl b/test/test-model-call-context-cache.jl index e598fe6c7..7b1cc2c5b 100644 --- a/test/test-model-call-context-cache.jl +++ b/test/test-model-call-context-cache.jl @@ -377,7 +377,7 @@ end scene = cache_scene(Float64) run!(scene.model; steps=1, outputs=:none) target = only(call_targets(scene.capture[], :middle)) - cache = PSE.CallContextCache(nothing) + cache = PSE.CallContextCache(nothing, Ref(UInt64(0))) normal1 = prepare_test_cache(cache, target, target.environment) @test cache.default === nothing && cache.transient === normal1 @test prepare_test_cache(cache, target, target.environment) === normal1 diff --git a/test/test-model-call-evaluations.jl b/test/test-model-call-evaluations.jl index dff74ff15..cac3fe80c 100644 --- a/test/test-model-call-evaluations.jl +++ b/test/test-model-call-evaluations.jl @@ -625,27 +625,29 @@ end end end -@testset "execution stamps track mutable cache identities independently" begin - left = PSE.CallContextCache(nothing) - right = PSE.CallContextCache(nothing) +@testset "execution stamps track logical cells independently of cache wrappers" begin + left_stamp, right_stamp = Ref(UInt64(0)), Ref(UInt64(0)) + left = PSE.CallContextCache(nothing, left_stamp) + right = PSE.CallContextCache(nothing, right_stamp) + alias = PSE.CallContextCache(nothing, left_stamp) frame = PSE.CallEvaluationFrame() - @test frame.executions isa IdDict{Any,UInt64} - @test left !== right + @test frame.executions isa IdDict{Base.RefValue{UInt64},UInt64} + @test left !== right !== alias @test left.default === right.default === nothing PSE._record_call_execution!(left, frame) PSE._record_call_execution!(right, frame) @test length(frame.executions) == 2 - @test frame.executions[left] == frame.executions[right] == UInt64(1) + @test frame.executions[left_stamp] == frame.executions[right_stamp] == UInt64(1) left.transient = (candidate=:changed,) left.in_use = true - PSE._record_call_execution!(left, frame) - @test frame.executions[left] == UInt64(2) - @test frame.executions[right] == UInt64(1) - @test PSE._call_execution_matches(left, frame.executions) - @test PSE._call_execution_matches(right, frame.executions) - left.execution_revision += UInt64(1) - @test !PSE._call_execution_matches(left, frame.executions) - @test PSE._call_execution_matches(right, frame.executions) + PSE._record_call_execution!(alias, frame) + @test frame.executions[left_stamp] == UInt64(2) + @test frame.executions[right_stamp] == UInt64(1) + @test PSE._call_execution_matches(left_stamp, frame.executions) + @test PSE._call_execution_matches(right_stamp, frame.executions) + PSE._record_call_execution!(alias, nothing) + @test !PSE._call_execution_matches(left_stamp, frame.executions) + @test PSE._call_execution_matches(right_stamp, frame.executions) PSE._clear_call_execution_stamps!(frame) @test isempty(frame.executions) PSE._clear_call_execution_stamps!(frame) @@ -662,8 +664,8 @@ end pending_left = evaluate_call!(left) pending_right = evaluate_call!(right) @test length(pending_left.frame.executions) == 1 - @test haskey(pending_left.frame.executions, left.context_cache) - @test !haskey(pending_left.frame.executions, right.context_cache) + @test haskey(pending_left.frame.executions, left.context_cache.execution_stamp) + @test !haskey(pending_left.frame.executions, right.context_cache.execution_stamp) run_call!(right; publish=false) @test accept_call!(pending_left) === pending_left @test_throws ArgumentError accept_call!(pending_right) @@ -682,8 +684,8 @@ end outer = evaluate_call!(context, :middle) leaf = only(call_targets(middle.context_cache.default, :leaf)) @test length(outer.frame.executions) == 2 - @test haskey(outer.frame.executions, middle.context_cache) - @test haskey(outer.frame.executions, leaf.context_cache) + @test haskey(outer.frame.executions, middle.context_cache.execution_stamp) + @test haskey(outer.frame.executions, leaf.context_cache.execution_stamp) @test isempty(leaf.context_cache.evaluation.executions) @test isempty(raw(simulation, :leaf, :leaf, :seen)) @test accept_call!(outer) === outer diff --git a/test/test-model-call-execution-identity.jl b/test/test-model-call-execution-identity.jl new file mode 100644 index 000000000..dcdad9d43 --- /dev/null +++ b/test/test-model-call-execution-identity.jl @@ -0,0 +1,256 @@ +module NestedSelectionEvaluationAliasChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "selection_alias_child" verbose=false +PSE.@process "selection_alias_middle" verbose=false +PSE.@process "selection_alias_creator" verbose=false + +struct Child <: AbstractSelection_Alias_ChildModel end +PSE.inputs_(::Child) = NamedTuple() +PSE.outputs_(::Child) = (calls=0, value=0.0) +function PSE.run!(::Child, status, environment, constants, context) + status.calls += 1 + status.value = Float64(status.calls) + return nothing +end + +struct Middle <: AbstractSelection_Alias_MiddleModel + call_child::Bool +end +PSE.inputs_(::Middle) = NamedTuple() +PSE.outputs_(::Middle) = (calls=0, value=0.0) +function PSE.run!(model::Middle, status, environment, constants, context) + status.calls += 1 + status.value = Float64(status.calls) + # Declared calls are parent-controlled and may be conditional. Both cases + # use the same declared graph and the same real newborn registration path. + model.call_child && run_call!(context, :child; publish=true) + return nothing +end + +struct Creator{C} <: AbstractSelection_Alias_CreatorModel + capture::C +end +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (created=false,) +function PSE.run!(model::Creator, status, environment, constants, context) + status.created && return nothing + runtime = runtime_model(context) + middle = register_object!(runtime, Object(:middle; scale=:Middle, parent=:owner, + status=Status(calls=0, value=0.0))) + register_object!(runtime, Object(:child; scale=:Leaf, parent=:middle, + status=Status(calls=0, value=0.0))) + first = only(call_targets(context, :middle; objects=middle)) + second = only(call_targets(context, :middle; objects=middle)) + shared_status = first.status === second.status === model_status(runtime, :middle) + shared_parent_cache = first.context_cache === second.context_cache + evaluation = evaluate_call!(first) + stamp_count = length(evaluation.frame.executions) + first_revision = first.context_cache.execution_stamp[] + run_call!(second; publish=false) + first_stamp_changed = first.context_cache.execution_stamp[] != first_revision + model_guard_valid = try + PSE._validate_call_model_state(evaluation.frame, evaluation.frame.compiled) + true + catch + false + end + stale_rejected, rejection = false, "" + try + accept_call!(evaluation) + catch error + rejection = error isa ArgumentError ? sprint(showerror, error) : string(typeof(error)) + stale_rejected = error isa ArgumentError && occursin("stale", rejection) + end + model.capture[] = (; shared_status, shared_parent_cache, stamp_count, + first_stamp_changed, model_guard_valid, stale_rejected, rejection) + status.created = true + return nothing +end + +function run_alias_case(call_child::Bool) + capture = Ref{Any}() + model = CompositeModel(Object(:owner; scale=:Scene); + applications=( + ModelSpec(Creator(capture); name=:creator, on=One(id=:owner), + calls=(middle=Many(Subtree(); scale=:Middle, application=:middle),)), + ModelSpec(Middle(call_child); name=:middle, on=Many(scale=:Middle), + calls=(child=One(Subtree(); scale=:Leaf, application=:child),)), + ModelSpec(Child(); name=:child, on=Many(scale=:Leaf)), + )) + simulation = run!(model; steps=1, outputs=:all) + return (; data=capture[], middle_calls=model_status(model, :middle).calls, + middle_value=model_status(model, :middle).value, + child_calls=model_status(model, :child).calls, + middle_history=get(outputs(simulation), (:middle, ObjectId(:middle), :calls), []), + child_history=get(outputs(simulation), (:child, ObjectId(:child), :calls), [])) +end + +@testset "rerunning another selection of the same canonical status invalidates its evaluation" begin + for call_child in (true, false) + result = run_alias_case(call_child) + @info "selection evaluation alias diagnostic" call_child diagnostic=result.data + @test result.data.shared_status + @test result.data.model_guard_valid # no timeline/topology/model mutation between the two runs + @test result.middle_calls == 2 + @test result.middle_value == 2.0 + @test result.child_calls == (call_child ? 2 : 0) + @test result.data.stale_rejected + @test isempty(result.middle_history) + @test isempty(result.child_history) + end +end + +end + +module StableCallExecutionIdentityChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "stable_execution_leaf" verbose=false +PSE.@process "stable_execution_controller" verbose=false +PSE.@process "stable_execution_creator" verbose=false + +struct Leaf <: AbstractStable_Execution_LeafModel end +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Leaf) = (calls=0,) +PSE.run!(::Leaf, status, environment, constants, context) = (status.calls += 1; nothing) + +function evaluate_then_rerun(first, second) + shared_status = first.status === second.status + shared_view = first.execution_target.status_view === second.execution_target.status_view + shared_cache = first.context_cache === second.context_cache + evaluation = evaluate_call!(first) + run_call!(second; publish=false) + model_guard_valid = try + PSE._validate_call_model_state(evaluation.frame, evaluation.frame.compiled) + true + catch + false + end + rejected, message = false, "" + try + accept_call!(evaluation) + catch error + message = error isa ArgumentError ? sprint(showerror, error) : string(typeof(error)) + rejected = error isa ArgumentError && occursin("stale", message) + end + return (; shared_status, shared_view, shared_cache, model_guard_valid, rejected, message) +end + +struct Controller{C} <: AbstractStable_Execution_ControllerModel + capture::C + use_other_binding::Bool +end +PSE.inputs_(::Controller) = NamedTuple() +PSE.outputs_(::Controller) = (done=false,) +function PSE.run!(model::Controller, status, environment, constants, context) + first = only(call_targets(context, :a)) + second = only(call_targets(context, model.use_other_binding ? :b : :a)) + model.capture[] = evaluate_then_rerun(first, second) + status.done = true + return nothing +end + +@testset "different bindings to one application/object share scientific execution identity" begin + for use_other_binding in (false, true) + capture = Ref{Any}() + model = CompositeModel(Object(:owner; scale=:Scene), + Object(:leaf; scale=:Leaf, parent=:owner, status=Status(calls=0)); + applications=( + ModelSpec(Controller(capture, use_other_binding); name=:controller, on=One(id=:owner), + calls=(a=One(id=:leaf, application=:leaf), b=One(id=:leaf, application=:leaf))), + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), + )) + simulation = run!(model; outputs=:all) + data = capture[] + @info "two-binding evaluation identity diagnostic" use_other_binding diagnostic=data + @test data.shared_status + @test data.shared_view + @test data.model_guard_valid + @test data.rejected + @test model_status(model, :leaf).calls == 2 + @test isempty(get(outputs(simulation), (:leaf, ObjectId(:leaf), :calls), [])) + end +end + +struct Creator{C} <: AbstractStable_Execution_CreatorModel + capture::C + reparent_before_barrier::Bool +end +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (created=false,) +function PSE.run!(model::Creator, status, environment, constants, context) + status.created && return nothing + object = register_object!(runtime_model(context), + Object(:leaf; scale=:Leaf, parent=:owner, status=Status(calls=0))) + first = only(call_targets(context, :leaf; objects=object)) + second = only(call_targets(context, :leaf; objects=object)) + before_barrier = evaluate_then_rerun(first, second) + model.capture[] = (; before_barrier, context, retained=first) + model.reparent_before_barrier && reparent_object!(runtime_model(context), :leaf, :axis) + status.created = true + return nothing +end + +@testset "targeted prebarrier and retained views keep their logical execution stamp" begin + for reparent_before_barrier in (false, true) + capture = Ref{Any}() + model = CompositeModel(Object(:owner; scale=:Scene), + Object(:axis; scale=:Axis, parent=:owner); + applications=( + ModelSpec(Creator(capture, reparent_before_barrier); name=:creator, on=One(id=:owner), + calls=(leaf=Many(Subtree(); scale=:Leaf, application=:leaf),)), + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), + )) + simulation = run!(model; outputs=:all) + data = capture[] + @info "targeted prebarrier evaluation identity diagnostic" reparent_before_barrier diagnostic=data.before_barrier + @test data.before_barrier.shared_status + @test data.before_barrier.model_guard_valid + @test data.before_barrier.rejected + @test model_status(model, :leaf).calls == 2 + @test isempty(get(outputs(simulation), (:leaf, ObjectId(:leaf), :calls), [])) + + # Materialize the canonical owner before starting a candidate. No + # binding observation/change may accidentally provide the stale guard. + current = only(call_targets(data.context, :leaf)) + after_barrier = evaluate_then_rerun(data.retained, current) + @info "retained postbarrier evaluation identity diagnostic" reparent_before_barrier diagnostic=after_barrier + @test after_barrier.shared_status + @test after_barrier.model_guard_valid + @test after_barrier.rejected + @test model_status(model, :leaf).calls == 4 + @test isempty(get(outputs(simulation), (:leaf, ObjectId(:leaf), :calls), [])) + + # A full metadata refresh also keeps the logical stamp, including when + # the token is evaluated through a retained pre-refresh view afterward. + PSE.Advanced.refresh_bindings!(model; force=true) + refreshed = only(call_targets(data.context, :leaf)) + after_force = evaluate_then_rerun(data.retained, refreshed) + @info "retained full-refresh evaluation identity diagnostic" reparent_before_barrier diagnostic=after_force + @test after_force.shared_status + @test after_force.model_guard_valid + @test after_force.rejected + @test model_status(model, :leaf).calls == 6 + @test isempty(get(outputs(simulation), (:leaf, ObjectId(:leaf), :calls), [])) + end +end + +function record_without_evaluation!(cache, count) + for _ in 1:count + PSE._record_call_execution!(cache, nothing) + end + return nothing +end + +@testset "ordinary execution stamp updates allocate no per-call bookkeeping" begin + stamp = Ref(UInt64(0)) + cache = PSE.CallContextCache(nothing, stamp) + record_without_evaluation!(cache, 1000) + @test (@allocated record_without_evaluation!(cache, 1000)) == 0 + @test stamp[] == UInt64(2000) +end + +end diff --git a/test/test-model-diagnostic-authoring-recovery.jl b/test/test-model-diagnostic-authoring-recovery.jl new file mode 100644 index 000000000..0faae511a --- /dev/null +++ b/test/test-model-diagnostic-authoring-recovery.jl @@ -0,0 +1,148 @@ +module DiagnosticAuthoringRecoveryChecks + +using Dates, PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "diagnostic_authoring_recovery_good" verbose=false +PSE.@process "diagnostic_authoring_recovery_broken" verbose=false +PSE.@process "diagnostic_authoring_recovery_coupled" verbose=false +struct Good{N} <: AbstractDiagnostic_Authoring_Recovery_GoodModel end +PSE.inputs_(::Good) = NamedTuple() +PSE.outputs_(::Good{N}) where {N} = NamedTuple{(N,)}((0.0,)) +function PSE.run!(::Good{N}, status, environment, constants, context) where {N} + setproperty!(status, N, getproperty(status, N) + 1.0) + return nothing +end + +struct OpaqueDeclarationError <: Exception + owner::Module +end +Base.showerror(io::IO, ::OpaqueDeclarationError) = print(io, "opaque declaration failed once") +const broken_calls = Ref(0) +struct Broken <: AbstractDiagnostic_Authoring_Recovery_BrokenModel end +PSE.inputs_(::Broken) = NamedTuple() +function PSE.outputs_(::Broken) + broken_calls[] += 1 + throw(OpaqueDeclarationError(@__MODULE__)) +end + +struct Coupled <: AbstractDiagnostic_Authoring_Recovery_CoupledModel end +PSE.inputs_(::Coupled) = (driver=Required(Float64),) +PSE.outputs_(::Coupled) = (after=0.0,) +PSE.run!(::Coupled, status, environment, constants, context) = + (status.after = status.driver + 1.0; nothing) + +struct BadProcess <: AbstractModel end +PSE.process(::BadProcess) = 42 + +@testset "diagnostic recovery uses captured authoring and keeps valid later applications" begin + broken_calls[] = 0 + model = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(Good{:before}(); name=:before, on=One(id=:root)), + ModelSpec(Broken(); name=:broken, on=One(id=:root)), + ModelSpec(Good{:after}(); name=:after, on=One(id=:root)), + ), environment=(duration=Hour(1),)) + preparation = model.scenario_plan_cache + @test broken_calls[] == 1 + @test length(preparation.authored) == 3 + @test preparation.authored[1] isa PSE.AuthoredApplicationRecipe + @test preparation.authored[2] isa PSE.ScenarioPreparationFailure + @test preparation.authored[3] isa PSE.AuthoredApplicationRecipe + @test preparation.failure === preparation.authored[2] + @test preparation.failure.phase === :output_ports + @test preparation.failure.application_id === :broken + + for _ in 1:2 + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:before, :after] + @test any(row -> row.application_ids == [:broken] && + row.code === :output_ports_error && occursin("opaque declaration", row.message), + report.diagnostics) + @test broken_calls[] == 1 # module-global state cannot be hidden by deepcopy + @test report.model !== model + @test report.model.scenario_plan_cache.failure.error === preparation.failure.error + end + @test isnothing(model_status(model, :root)) + @test model.scenario_plan_cache === preparation + @test isnothing(preparation.resolved) + @test isnothing(PSE.Advanced.compiled_bindings(model)) + + # Runtime and topology/cadence refreshes keep the original error frozen. + register_object!(model, Object(:other; scale=:Scene)) + model.environment = (duration=Hour(2),) + mark_environment_binding_dirty!(model) + @test_throws OpaqueDeclarationError run!(model; steps=0) + @test_throws OpaqueDeclarationError PSE._prepare_scenario_plan(model; force=true) + @test broken_calls[] == 1 + @test model.scenario_plan_cache === preparation + @test_throws OpaqueDeclarationError PSE.compile_model_report(model; strict=true) + @test broken_calls[] == 1 +end + +@testset "recovered later applications retain authored slots and coupled inputs" begin + broken_calls[] = 0 + model = CompositeModel(Object(:root; scale=:Scene, + status=Status(before=2.0, driver=0.0, after=0.0)); applications=( + ModelSpec(Good{:before}(); name=:before, on=One(id=:root)), + ModelSpec(Broken(); name=:broken, on=One(id=:root)), + ModelSpec(Coupled(); name=:after, on=One(id=:root), + inputs=(driver=One(within=Self(), application=:before, var=:before),)), + )) + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:before, :after] + @test [application.slot for application in report.applications] == [1, 3] + @test length(report.input_bindings) == 1 + binding = only(report.input_bindings) + @test binding.application_id === :after + @test binding.input === :driver + @test binding.source_ids == [ObjectId(:root)] + @test binding.source_application_ids == [:before] + @test PSE.refvalue(model_status(report.model, :root), :driver) === + PSE.refvalue(model_status(report.model, :root), :before) + @test model_status(model, :root).driver == 0.0 + @test !any(row -> occursin("BoundsError", row.message), report.diagnostics) + @test broken_calls[] == 1 +end + +@testset "normalization failures do not hide later valid declarations" begin + model = CompositeModel(Object(:root; scale=:Scene); applications=( + 42, + ModelSpec(Good{:after}(); name=:after, on=One(id=:root)), + )) + preparation = model.scenario_plan_cache + @test preparation.authored[1] isa PSE.ScenarioPreparationFailure + @test preparation.authored[2] isa PSE.AuthoredApplicationRecipe + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:after] + @test !isempty(report.diagnostics) + + bad_process = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(BadProcess(); name=:bad_process, on=One(id=:root)), + ModelSpec(Good{:after}(); name=:after, on=One(id=:root)), + )) + @test bad_process.scenario_plan_cache.failure.phase === :application_identifiers + @test bad_process.scenario_plan_cache.failure.error isa ArgumentError + process_report = PSE.compile_model_report(bad_process) + @test [application.id for application in process_report.applications] == [:after] + @test any(row -> occursin("process identifier must be a Symbol", row.message), + process_report.diagnostics) +end + +@testset "membership failures recover valid applications through the same resolver" begin + model = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(Good{:before}(); name=:before, on=One(id=:root)), + ModelSpec(Good{:missing}(); name=:missing, on=One(id=:missing)), + ModelSpec(Good{:after}(); name=:after, on=One(id=:root)), + )) + @test isnothing(model.scenario_plan_cache.failure) + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:before, :after] + @test any(row -> row.phase === :application_recovery && row.application_ids == [:missing], + report.diagnostics) + register_object!(model, Object(:missing; scale=:Leaf)) + repaired = PSE.compile_model_report(model) + @test [application.id for application in repaired.applications] == [:before, :missing, :after] + @test isempty(repaired.diagnostics) +end + +end diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 6d83f4b92..811006bfa 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -76,7 +76,7 @@ end function reader_recipe(compiled) application = compiled.applications_by_id[:reader] recipe = PSE._application_plans(compiled.scenario_plan.input_recipes_by_application, - application.slot) + application.id) return application, recipe end diff --git a/test/test-model-newborn-context-initializer.jl b/test/test-model-newborn-context-initializer.jl new file mode 100644 index 000000000..b3cfaa7eb --- /dev/null +++ b/test/test-model-newborn-context-initializer.jl @@ -0,0 +1,75 @@ +module NewbornInitializerContextChecks + +using Dates, PlantSimEngine, Random, Test +const PSE = PlantSimEngine + +PSE.@process "newborn_context_leaf" verbose=false +PSE.@process "newborn_context_creator" verbose=false +struct Leaf{R,C} <: AbstractNewborn_Context_LeafModel + rng::R + contexts::C +end +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Leaf) = (calls=0, draw=0.0, seen_time=0.0, seen_T=0f0, allowed=true) +function PSE.run!(model::Leaf, status, environment, constants, context) + push!(model.contexts, context) + status.calls += 1 + status.draw = rand(model.rng) + status.seen_time = context.time + status.seen_T = environment.T + status.allowed = context.publication_allowed + return nothing +end +struct Creator <: AbstractNewborn_Context_CreatorModel end +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (day=0,) +function PSE.run!(::Creator, status, environment, constants, context) + status.day += 1 + if status.day == 2 + born = register_object!(runtime_model(context), Object(:born; scale=:Leaf, parent=:owner, + status=Status(calls=0, draw=0.0, seen_time=0.0, seen_T=0f0, allowed=true))) + run_initializer!(context, :initialize, born) + end + return nothing +end + +@testset "newborn context has invocation time/environment without replay or shared scheduled cache" begin + rng = Xoshiro(31) + reference = copy(rng) + contexts = Any[] + model = CompositeModel(Object(:owner; scale=:Scene); + applications=( + ModelSpec(Creator(); name=:creator, on=One(id=:owner), + calls=(initialize=Initializer(One(scale=:Leaf, within=Subtree(), application=:leaf)),)), + ModelSpec(Leaf(rng, contexts); name=:leaf, on=Many(scale=:Leaf)), + ), environment=(T=3f0,duration=Hour(1))) + simulation = run!(model; steps=2, outputs=:all) + born = model_status(model, :born) + first_draw = rand(reference) + @test born.calls == 1 + @test born.draw == first_draw + @test born.seen_time == 2.0 + @test born.seen_T === 3f0 + @test !born.allowed + @test length(contexts) == 1 + first = only(contexts) + @test first.time == 2.0 + @test !first.publication_allowed + @test first.environment isa PSE.NoEnvironmentOverride + @test first.calls === () + @test isempty(get(outputs(simulation),(:leaf,ObjectId(:born),:draw),[])) + + continue!(simulation; steps=1) + second_draw = rand(reference) + @test born.calls == 2 + @test born.draw == second_draw + @test born.seen_time == 3.0 + @test born.allowed + @test length(contexts) == 2 + @test contexts[2] !== first + @test first.time == 2.0 + @test outputs(simulation)[(:leaf,ObjectId(:born),:calls)] == [(3.0,2)] + @test outputs(simulation)[(:leaf,ObjectId(:born),:draw)] == [(3.0,second_draw)] +end + +end diff --git a/test/test-model-newborn-context-nested.jl b/test/test-model-newborn-context-nested.jl new file mode 100644 index 000000000..6af1d5b56 --- /dev/null +++ b/test/test-model-newborn-context-nested.jl @@ -0,0 +1,93 @@ +module NewbornNestedContextChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "newborn_nested_leaf" verbose=false +PSE.@process "newborn_nested_middle" verbose=false +PSE.@process "newborn_nested_creator" verbose=false +struct Leaf{C} <: AbstractNewborn_Nested_LeafModel + contexts::C +end +struct Middle{C} <: AbstractNewborn_Nested_MiddleModel + contexts::C +end +struct Creator{C} <: AbstractNewborn_Nested_CreatorModel + capture::C +end +PSE.inputs_(::Union{Leaf,Middle,Creator}) = NamedTuple() +PSE.outputs_(::Union{Leaf,Middle}) = (value=0.0,calls=0,seen_time=0.0) +PSE.outputs_(::Creator) = (created=false,value=0.0) +function PSE.run!(model::Leaf, status, environment, constants, context) + push!(model.contexts,context) + status.calls += 1 + status.value = 5.0 + context.time + status.seen_time = context.time + return nothing +end +function PSE.run!(model::Middle, status, environment, constants, context) + push!(model.contexts,context) + status.calls += 1 + run_call!(context,:child;publish=true) + status.value = only(call_targets(context,:child)).status.value + context.time + status.seen_time = context.time + return nothing +end +function PSE.run!(model::Creator, status, environment, constants, context) + status.created && return nothing + runtime = runtime_model(context) + middle = register_object!(runtime,Object(:middle;scale=:Middle,parent=:owner, + status=Status(value=0.0,calls=0,seen_time=0.0))) + register_object!(runtime,Object(:child;scale=:Leaf,parent=:middle, + status=Status(value=0.0,calls=0,seen_time=0.0))) + first = only(call_targets(context,:middle;objects=middle)) + second = only(call_targets(context,:middle;objects=middle)) + before_calls = (model_status(runtime,:middle).calls,model_status(runtime,:child).calls) + dirty_after_get = PSE.bindings_dirty(runtime) + run_call!(first;publish=true) + model.capture[] = (;first,second,before_calls,dirty_after_get,creator_context=context) + status.value = first.status.value + status.created = true + return nothing +end + +@testset "manual newborn nested calls keep their resolved graph through full refresh" begin + capture = Ref{Any}() + middle_contexts,leaf_contexts = Any[],Any[] + model = CompositeModel(Object(:owner;scale=:Scene); + applications=( + ModelSpec(Creator(capture);name=:creator,on=One(id=:owner), + calls=(middle=Many(scale=:Middle,within=Subtree(),application=:middle),)), + ModelSpec(Middle(middle_contexts);name=:middle,on=Many(scale=:Middle), + calls=(child=One(scale=:Leaf,within=Subtree(),application=:child),)), + ModelSpec(Leaf(leaf_contexts);name=:child,on=Many(scale=:Leaf)), + )) + simulation = run!(model;steps=1,outputs=:all) + data = capture[] + @test data.before_calls == (0,0) + @test !data.dirty_after_get # nested target used the existing full-refresh fallback + @test length(data.first.execution_target.call_bindings) == 1 + @test PSE._compiled_call_name(only(data.first.execution_target.call_bindings)) === :child + # Independent explicit selections may refresh nested execution owners. + # Both views must still expose the same live registry-owned scientific state. + @test data.first.status === data.second.status === model_status(model, :middle) + @test only(middle_contexts) === data.first.context_cache.default + @test only(middle_contexts) !== only(leaf_contexts) + @test only(middle_contexts) !== data.creator_context + @test only(middle_contexts).time == only(leaf_contexts).time == 1.0 + @test only(middle_contexts).publication_allowed && only(leaf_contexts).publication_allowed + @test length(call_targets(only(middle_contexts),:child)) == 1 + @test model_status(model,:middle).value == 7.0 + @test model_status(model,:child).value == 6.0 + @test outputs(simulation)[(:middle,ObjectId(:middle),:calls)] == [(1.0,1)] + @test outputs(simulation)[(:child,ObjectId(:child),:calls)] == [(1.0,1)] + + run_call!(data.second;publish=false) + @test model_status(model,:middle).calls == model_status(model,:child).calls == 2 + @test outputs(simulation)[(:middle,ObjectId(:middle),:calls)] == [(1.0,1)] + @test outputs(simulation)[(:child,ObjectId(:child),:calls)] == [(1.0,1)] + continue!(simulation;steps=1) + @test model_status(model,:middle).calls == model_status(model,:child).calls == 2 + @test model_status(model,:middle).seen_time == model_status(model,:child).seen_time == 1.0 +end + +end diff --git a/test/test-model-newborn-execution-owner.jl b/test/test-model-newborn-execution-owner.jl index 48497d822..777525d78 100644 --- a/test/test-model-newborn-execution-owner.jl +++ b/test/test-model-newborn-execution-owner.jl @@ -73,13 +73,24 @@ end @test data.first.status === data.second.status === model_status(model, :born) @test data.first.execution_target.status_view.status === data.first.status @test data.first.context_cache === data.second.context_cache - @test data.first.execution_target.context === nothing - @test data.first.context_cache.default === nothing - @test data.first.context_cache.execution_revision == 2 + @test data.first.execution_target.context isa PSE.RunContext + @test data.first.context_cache.default === data.first.execution_target.context + @test data.second.execution_target.context === data.first.execution_target.context + @test data.first.execution_target.context.object_id === ObjectId(:born) + @test data.first.execution_target.context.application.id === :newborn_state + @test data.first.execution_target.context.bound_inputs === data.first.bound_inputs + @test data.first.execution_target.context.calls === data.first.calls + @test data.first.context_cache.execution_stamp[] == 2 @test !data.first.context_cache.in_use @test data.lease_checks == [true, true] @test length(contexts) == 2 @test contexts[1] !== contexts[2] + @test contexts[1] === data.first.context_cache.default + @test contexts[1].time == contexts[2].time == 1.0 + @test contexts[1].publication_allowed + @test !contexts[2].publication_allowed + @test contexts[1].environment isa PSE.NoEnvironmentOverride + @test contexts[2].environment isa PSE.NoEnvironmentOverride @test data.dirty @test isnothing(data.prebarrier_location) @test !PSE.bindings_dirty(model) @@ -92,7 +103,7 @@ end # stamps after the ordinary lifecycle barrier installs current bindings. run_call!(data.first; publish=false) @test data.first.time == 1.0 - @test data.first.context_cache.execution_revision == 3 + @test data.first.context_cache.execution_stamp[] == 3 @test model_status(model, :born).calls == 3 @test outputs(simulation)[(:newborn_state, ObjectId(:born), :calls)] == [(1.0, 2)] continue!(simulation) diff --git a/test/test-model-persistent-empty-groups.jl b/test/test-model-persistent-empty-groups.jl new file mode 100644 index 000000000..b4428720b --- /dev/null +++ b/test/test-model-persistent-empty-groups.jl @@ -0,0 +1,98 @@ +module PersistentEmptyExecutionGroupChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "persistent_empty_counter" verbose=false +struct Counter{C} <: AbstractPersistent_Empty_CounterModel + declarations::C +end +PSE.inputs_(::Counter) = NamedTuple() +function PSE.outputs_(model::Counter) + model.declarations[] += 1 + return (count=0,) +end +PSE.run!(::Counter, status, environment, constants, context) = (status.count += 1; nothing) + +@testset "an ordinary learned group survives removal and same-schema return" begin + declarations = Ref(0) + original = Status(count=0) + model = CompositeModel(Object(:first;scale=:Leaf,status=original); + applications=(ModelSpec(Counter(declarations);name=:counter,on=Many(scale=:Leaf)),)) + simulation = run!(model;steps=1,outputs=:all) + group = only(simulation.execution_plan.groups) + @test original.count == 1 + remove_object!(model,:first) + step!(simulation) + @test only(simulation.execution_plan.groups) === group + @test isempty(group.batches) + @test isempty(group.membership.object_ids) + @test original.count == 1 + @test outputs(simulation)[(:counter,ObjectId(:first),:count)] == [(1.0,1)] + born = register_object!(model,Object(:next;scale=:Leaf,status=Status(count=10))) + step!(simulation) + @test only(simulation.execution_plan.groups) === group + @test born.status.count == 11 + @test original.count == 1 + @test only(only(group.batches).targets).object_id === ObjectId(:next) + @test outputs(simulation)[(:counter,ObjectId(:next),:count)] == [(3.0,11)] + @test outputs(simulation)[(:counter,ObjectId(:first),:count)] == [(1.0,1)] +end + +@testset "an admitted empty group fills its closed slot without dummy values" begin + declarations = Ref(0) + model = CompositeModel(Object(:scene;scale=:Scene); + applications=(ModelSpec(Counter(declarations);name=:counter,on=Many(scale=:Leaf)),)) + simulation = run!(model;steps=0,outputs=:none) + compiled = simulation.compiled + application = compiled.applications_by_id[:counter] + environment_plan = simulation.environment_bindings.application_plans_by_id[:counter] + Empty = NamedTuple{(),Tuple{}} + I = ObjectId{Symbol} + # This is a supplied future reference descriptor, not inferred from an + # output default and not instantiated as a placeholder Status. + Full = Status{(:count,),Tuple{Base.RefValue{Int}}} + View = PSE.CompiledModelStatusView{Full,Full,Tuple{},Empty,Empty} + Context = PSE.RunContext{typeof(compiled),typeof(application),Tuple{},Empty,Empty, + typeof(simulation.temporal_streams),typeof(simulation.output_retention), + typeof(simulation.constants),PSE.NoEnvironmentOverride,I} + Binding = PSE.CompiledEnvironmentBinding{typeof(environment_plan),Nothing,PSE.EnvironmentContext{I}} + Target = PSE.CompiledExecutionTarget{typeof(PSE.model_(application.spec)),View, + Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} + Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I}} + Batch = PSE.CompiledExecutionBatch{typeof(application),Rows, + PSE.RawGlobalModelEnvironment{Nothing},PSE.CompiledOutputPublication{Tuple{}}} + before_callbacks = declarations[] + future = PSE._empty_model_execution_group(application,Batch,simulation.execution_plan.cohorts) + @test declarations[] == before_callbacks + @test length(model.registry.objects) == 1 + @test isnothing(model_status(model,:scene)) + @test isempty(future.batches) + @test isempty(future.membership.object_ids) + + previous = simulation.execution_plan + closed = PSE.CompiledExecutionPlan(previous.cohorts,previous.topology, + (future,),previous.batches,(future,),previous.schedule, + previous.model_revision,previous.environment_revision) + simulation = PSE._simulation_with_execution_plan(simulation,closed) + Plan = typeof(simulation.execution_plan) + @test simulation.execution_plan.groups_by_application_slot isa Tuple + @test simulation.execution_plan.batches isa AbstractVector + @test simulation.execution_plan.topology isa PSE.DynamicExecution + + born = register_object!(model,Object(:born;scale=:Leaf,status=Status(count=7))) + step!(simulation) + @test born.status.count == 8 + @test typeof(simulation.execution_plan) === Plan + @test only(simulation.execution_plan.groups) === future + @test only(simulation.execution_plan.groups_by_application_slot) === future + @test eltype(future.batches) === Batch + @test only(only(future.batches).targets).status_view.status === born.status + remove_object!(model,:born) + step!(simulation) + @test typeof(simulation.execution_plan) === Plan + @test only(simulation.execution_plan.groups) === future + @test isempty(future.batches) + @test born.status.count == 8 +end + +end diff --git a/test/test-model-runtime-call-names.jl b/test/test-model-runtime-call-names.jl index 66ebb29f7..725e2325b 100644 --- a/test/test-model-runtime-call-names.jl +++ b/test/test-model-runtime-call-names.jl @@ -34,7 +34,10 @@ function PSE.run!(model::CaptureOwner, status, environment, constants, context) return nothing end -@noinline cli_name(args::Vector{String}) = Symbol(only(args)) +@noinline function cli_name(args::Vector{String}) + length(args) == 1 || throw(ArgumentError("Expected exactly one call name, got $(length(args)).")) + return Symbol(args[1]) +end cli_targets(context, args) = call_targets(context, cli_name(args)) cli_model(context, args) = call_model(context, cli_name(args)) cli_run(context, args; publish=false, objects=nothing) = @@ -68,6 +71,8 @@ function manual_fixture() end @testset "runtime Symbol calls keep finite heterogeneous target branches" begin + @test_throws ArgumentError cli_name(String[]) + @test_throws ArgumentError cli_name(["a", "b"]) fixture = manual_fixture() simulation = run!(fixture.model; outputs=:all) context = fixture.capture[] diff --git a/test/test-model-slot-group-refresh.jl b/test/test-model-slot-group-refresh.jl new file mode 100644 index 000000000..ecf861096 --- /dev/null +++ b/test/test-model-slot-group-refresh.jl @@ -0,0 +1,92 @@ +module SlotGroupRefreshChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "slot_group_counter" verbose=false +struct SlotCounter{T} <: AbstractSlot_Group_CounterModel + increment::T +end +PSE.inputs_(::SlotCounter) = NamedTuple() +PSE.outputs_(model::SlotCounter) = (count=zero(model.increment),) +function PSE.run!(model::SlotCounter, status, environment, constants, context) + status.count += model.increment + return nothing +end + +function six_group_simulation() + increments = (1.0f0, 1.0, Int8(1), Int16(1), Int32(1), Int64(1)) + ids = (:first, :second, :third, :fourth, :fifth, :sixth) + applications = ntuple(6) do index + ModelSpec(SlotCounter(increments[index]); name=ids[index], on=One(id=ids[index])) + end + objects = ntuple(index -> Object(ids[index]; + status=Status(count=zero(increments[index]))), 6) + return run!(CompositeModel(objects...; applications); steps=0, outputs=:none) +end + +@testset "runtime slot dispatch stays inside six concrete group schemas" begin + simulation = six_group_simulation() + previous = simulation.execution_plan + groups = Tuple(previous.groups) + slots = Tuple(previous.groups_by_application_slot) + @test length(groups) == length(slots) == 6 + @test length(unique(typeof.(groups))) == 6 + runtime_slot = parse(Int, "6") + @test (@inferred PSE._with_metadata_entry(group -> group.application.id, + slots, runtime_slot)) === :sixth + @test PSE._with_metadata_entry(group -> group.application.id, + previous.groups_by_application_slot, runtime_slot) === :sixth + @test_throws BoundsError PSE._with_metadata_entry(identity, slots, 0) + @test_throws BoundsError PSE._with_metadata_entry(identity, slots, 7) + @test_throws BoundsError PSE._with_metadata_entry(identity, + previous.groups_by_application_slot, 7) + @test all(group -> model_status(simulation.model, + only(group.membership.object_ids)).count == 0, groups) + + closed = PSE.CompiledExecutionPlan(previous.cohorts, previous.topology, + groups, previous.batches, slots, previous.schedule, + previous.model_revision, previous.environment_revision) + simulation = PSE._simulation_with_execution_plan(simulation, closed) + step!(simulation) + @test current_step(simulation) == 1 + @test all(group -> model_status(simulation.model, + only(group.membership.object_ids)).count == 1, groups) + @test simulation.execution_plan.groups === groups + @test simulation.execution_plan.groups_by_application_slot === slots +end + +@testset "previous group matching preserves owner identity after slot changes" begin + simulation = six_group_simulation() + first_group, second_group = simulation.execution_plan.groups[1:2] + reordered = (second_group, nothing, first_group) + visited = falses(3) + counts = PSE._with_previous_execution_group(reordered, + first_group.application.id, 1, visited) do group + @test group === first_group + return (2, 3, 1) + end + @test counts === (2, 3, 1) + @test visited == Bool[false, false, true] + preferred_counts = PSE._with_previous_execution_group(reordered, + second_group.application.id, 1, visited) do group + @test group === second_group + return (0, 0, 1) + end + @test preferred_counts === (0, 0, 1) + @test visited == Bool[true, false, true] + + missing_visited = falses(3) + missing_counts = PSE._with_previous_execution_group(reordered, + :missing, 9, missing_visited) do group + @test isnothing(group) + return (0, 0, 0) + end + @test missing_counts === (0, 0, 0) + @test !any(missing_visited) + @test all(group -> model_status(simulation.model, + only(group.membership.object_ids)).count == 0, + simulation.execution_plan.groups) +end + +end diff --git a/test/test-owned-metadata-tables.jl b/test/test-owned-metadata-tables.jl index 975b3d305..737c11dad 100644 --- a/test/test-owned-metadata-tables.jl +++ b/test/test-owned-metadata-tables.jl @@ -26,7 +26,7 @@ second_entry(table) = table[2] @test Tuple(values(table)) === (left, right) @test_throws BoundsError table[0] @test_throws BoundsError table[3] - @test_throws ErrorException table[:missing] + @test_throws KeyError table[:missing] left[] = 7 @test table[:left][] == 7 @test right[] === 2f0 @@ -84,7 +84,7 @@ end @test source === compiled.applications[2] @test compiled.applications_by_id[2] === source @test compiled.scenario_plan.applications_by_id[:source] === source.plan - @test PSE._application_plans(compiled.scenario_plan.input_recipes_by_application, 1) === recipe + @test PSE._application_plans(compiled.scenario_plan.input_recipes_by_application, :reader) === recipe @test recipe isa PSE.CompiledApplicationInputRecipe @test ismutabletype(typeof(recipe)) @test all(name -> isconst(typeof(recipe), name), fieldnames(typeof(recipe))) diff --git a/test/test-registered-status-dispatch.jl b/test/test-registered-status-dispatch.jl new file mode 100644 index 000000000..46530d0a6 --- /dev/null +++ b/test/test-registered-status-dispatch.jl @@ -0,0 +1,165 @@ +module RegisteredStatusDispatchChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +const Seed32 = Status{(:seed,),Tuple{Base.RefValue{Float32}}} +const Seed64 = Status{(:seed,),Tuple{Base.RefValue{Float64}}} +const SeedReal = Status{(:seed,),Tuple{Base.RefValue{Real}}} +const SeedAny = Status{(:seed,),Tuple{Base.RefValue{Any}}} +const Full32 = Status{(:seed,:value,:visits), + Tuple{Base.RefValue{Float32},Base.RefValue{Float64},Base.RefValue{Int}}} +const Full64 = Status{(:seed,:value,:visits), + Tuple{Base.RefValue{Float64},Base.RefValue{Float64},Base.RefValue{Int}}} +const FullReal = Status{(:seed,:value,:visits), + Tuple{Base.RefValue{Real},Base.RefValue{Float64},Base.RefValue{Int}}} +const FullAny = Status{(:seed,:value,:visits), + Tuple{Base.RefValue{Any},Base.RefValue{Float64},Base.RefValue{Int}}} + +function closed_model(model, future::Tuple) + previous = model.registry + active = PSE._closed_object_family_store(previous.objects) + I = keytype(active) + empty_families = map(future) do S + PSE.ObjectFamily{I,S}(Union{Nothing,PSE.ObjectFamilyRow{I,S}}[]) + end + families = (active.catalog.families..., empty_families...) + store = PSE.ObjectFamilyStore(PSE.ClosedObjectFamilyCatalog(families), + active.locations, active.status_owners, active.layout_cache) + registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + fields = map(fieldnames(typeof(model))) do name + name === :registry ? registry : getfield(model, name) + end + return PSE.CompositeModel(fields...) +end + +@testset "eight erased statuses execute inside their concrete family branch" begin + supplied = [Status(value=Float32(index), payload=ntuple(identity, index)) for index in 1:8] + model = CompositeModel((Object(index; status=status) for (index,status) in enumerate(supplied))...) + catalog = PSE._closed_object_family_store(model.registry.objects).catalog + seen = DataType[] + for index in 1:8 + erased = model_object(model, index).status + matched = PSE._with_registered_status(catalog, erased) do status + push!(seen, typeof(status)) + status.value += 1f0 + status === supplied[index] + end + @test matched + @test supplied[index].value === Float32(index + 1) + end + @test seen == typeof.(supplied) + @test_throws ArgumentError PSE._with_registered_status(identity, catalog, Status(unknown=1)) +end + +@testset "newborn registration and finishing retain real reference types" begin + model = closed_model(CompositeModel(Object(:owner; status=Status(count=0))), + (Seed32,Seed64,SeedReal,SeedAny,Full32,Full64,FullReal,FullAny)) + for (id, seed, Expected) in ((:a, Status(seed=3f0), Full32), + (:b, Status(seed=4.0), Full64), + (:c, Status((seed=Ref{Real}(5f0),)), FullReal), + (:d, Status((seed=Ref{Any}(6f0),)), FullAny)) + object = Object(id; parent=:owner, scale=:Leaf, status=seed) + @test register_object!(model, object) === object + @test model_status(model, id) === seed + @test object_id(model, seed) === ObjectId(id) + seed_ref = PSE.refvalue(seed, :seed) + value, visits = Ref(0.5), Ref(0) + recipe = PSE._CanonicalStatusRecipe(seed) + PSE._status_recipe_set_reference!(recipe, :value, value) + PSE._status_recipe_set_reference!(recipe, :visits, visits) + PSE._finish_canonical_status_recipe(model, recipe) do status + @test typeof(status) === Expected + PSE._replace_model_object_status!(model, object, status) + end + full = model_status(model, id) + @test typeof(full) === Expected + @test PSE.refvalue(full, :seed) === seed_ref + @test PSE.refvalue(full, :value) === value + @test PSE.refvalue(full, :visits) === visits + @test full === object.status + @test object_id(model, full) === ObjectId(id) + @test_throws ArgumentError object_id(model, seed) + if Expected === FullAny + seed_ref[] = :later + @test full.seed === :later + elseif Expected === FullReal + seed_ref[] = 9.0 + @test full.seed === 9.0 + end + end + unsupported = Object(:wrong; parent=:owner, status=Status(seed=Int8(1))) + original = unsupported.status + @test_throws ArgumentError register_object!(model, unsupported) + @test unsupported.status === original + @test !haskey(model.registry.objects, ObjectId(:wrong)) + @test !(ObjectId(:wrong) in model_object(model, :owner).children) +end + +PSE.@process "registered_status_review_private" verbose=false +struct PrivateWriter <: AbstractRegistered_Status_Review_PrivateModel end +PSE.inputs_(::PrivateWriter) = NamedTuple() +PSE.outputs_(::PrivateWriter) = (x=0.0,) +PSE.environment_inputs_(::PrivateWriter) = NamedTuple() +PSE.environment_outputs_(::PrivateWriter) = NamedTuple() +function PSE.run!(::PrivateWriter, status, environment, constants, context) + status.x += 1.0 + return nothing +end + +@testset "private stream-only schema is not a canonical object family" begin + source = CompositeModel(Object(:leaf; status=Status(seed=1.0)); + applications=(ModelSpec(PrivateWriter(); name=:private_writer, + on=One(id=:leaf), output_routing=(x=:stream_only,)),)) + model = closed_model(source, ()) + canonical = model_status(model, :leaf) + @test propertynames(canonical) == (:seed,) + + # The private (seed,x) status belongs to this application's runtime view. + # It must not need an unused (seed,x) canonical registry family. + simulation = run!(model; steps=2, outputs=:all) + @test model_status(model, :leaf) === canonical + @test propertynames(model_status(model, :leaf)) == (:seed,) + rows = collect_outputs(simulation, :leaf, :x; sink=nothing) + @test getproperty.(rows, :value) == [1.0, 2.0] +end + +@testset "the shared conversion executes once on the actual supplied status" begin + seen = Tuple{Symbol,DataType}[] + transform = (name,value) -> begin + push!(seen, (name,typeof(value))) + value + end + model = closed_model(CompositeModel(Object(:owner; status=Status(count=0)); + type_promotion=Dict(Float64=>Float32), status_transform=transform), (Seed32,)) + baseline_calls = length(seen) + supplied = Status(seed=3.0) + born = register_object!(model, Object(:leaf; parent=:owner, status=supplied)) + effective = model_status(model, :leaf) + @test typeof(effective) === Seed32 + @test effective === born.status + @test effective.seed === 3f0 + @test supplied.seed === 3.0 + @test length(seen) == baseline_calls + 1 + @test last(seen) == (:seed,Float64) + @test PSE.refvalue(effective, :seed) !== PSE.refvalue(supplied, :seed) + @test object_id(model, effective) === ObjectId(:leaf) + @test_throws ArgumentError register_object!(model, Object(:other; status=supplied)) + @test length(seen) == baseline_calls + 1 + @test !haskey(model.registry.objects, ObjectId(:other)) +end + +@testset "unadmitted edited reference types fail without replacing live state" begin + seed = Status(seed=2.0) + model = closed_model(CompositeModel(Object(:leaf; status=seed)), (Full64,)) + recipe = PSE._CanonicalStatusRecipe(seed) + PSE._status_recipe_set_reference!(recipe, :value, Ref(0f0)) + PSE._status_recipe_set_reference!(recipe, :visits, Ref(0)) + publish = status -> PSE._replace_model_object_status!(model, :leaf, status) + @test_throws ArgumentError PSE._finish_canonical_status_recipe(publish, model, recipe) + @test model_status(model, :leaf) === seed + @test object_id(model, seed) === ObjectId(:leaf) +end + +end diff --git a/test/test-selector-ancestor-index.jl b/test/test-selector-ancestor-index.jl new file mode 100644 index 000000000..c40fc152d --- /dev/null +++ b/test/test-selector-ancestor-index.jl @@ -0,0 +1,73 @@ +module IndexedAncestorChecks + +using Test, PlantSimEngine +using PlantSimEngine.GraphEditor +const PSE = PlantSimEngine + +nearest_ancestor(model, id; kwargs...) = PSE._ancestor_id(model, ObjectId(id); kwargs...) +function ancestor_scene() + CompositeModel( + Object(:scene; scale=:Scene, kind=:scene), + Object(1; scale=:Plant, kind=:plant, parent=:scene), + Object(:middle; scale=:Plant, kind=:dormant, parent=1), + Object(:axis; scale=:Axis, kind=:plant, parent=:middle), + Object(:leaf; scale=:Leaf, kind=:photosynthetic, parent=:axis), + Object(2; scale=:Plant, kind=:plant, parent=:scene), + ) +end + +@testset "nearest indexed ancestor and lifecycle contracts" begin + model=ancestor_scene() + @test nearest_ancestor(model,:leaf;scale=:Plant)==ObjectId(:middle) + @test nearest_ancestor(model,:leaf;kind=:plant)==ObjectId(:axis) + @test nearest_ancestor(model,:leaf;scale=:Plant,kind=:plant)==ObjectId(1) + @test nearest_ancestor(model,:leaf;scale=:Leaf)==ObjectId(:leaf) + @test isnothing(nearest_ancestor(model,:leaf;scale=:Leaf,include_self=false)) + @test nearest_ancestor(model,:leaf;include_self=false)==ObjectId(:axis) + @test nearest_ancestor(model,:leaf)==ObjectId(:leaf) + @test isnothing(nearest_ancestor(model,:scene;include_self=false)) + @test isnothing(nearest_ancestor(model,:leaf;scale=:Absent)) + @test isnothing(nearest_ancestor(model,:leaf;scale=:Plant,kind=:Absent)) + + relabeled=apply_model_graph_edit(model, + SetModelObjectMetadata(:middle;scale=:Axis,kind=:plant)) + @test ObjectId(:middle) ∉ relabeled.registry.by_scale[:Plant] + @test ObjectId(:middle) ∈ relabeled.registry.by_scale[:Axis] + @test ObjectId(:middle) ∈ relabeled.registry.by_kind[:plant] + @test nearest_ancestor(relabeled,:leaf;scale=:Plant)==ObjectId(1) + @test nearest_ancestor(model,:leaf;scale=:Plant)==ObjectId(:middle) + relabeled=apply_model_graph_edit(relabeled, + SetModelObjectMetadata(:axis;kind=:dormant)) + @test nearest_ancestor(relabeled,:leaf;scale=:Axis,kind=:plant)==ObjectId(:middle) + + register_object!(model,Object(:new_leaf;scale=:Leaf,kind=:photosynthetic,parent=:axis)) + @test nearest_ancestor(model,:new_leaf;scale=:Plant,kind=:plant)==ObjectId(1) + reparent_object!(model,:axis,2) + @test nearest_ancestor(model,:leaf;scale=:Plant)==ObjectId(2) + @test nearest_ancestor(model,:new_leaf;scale=:Plant)==ObjectId(2) + remove_object!(model,:axis) + @test !haskey(model.registry.by_scale, :Axis) + @test !haskey(model.registry.by_scale, :Leaf) + @test_throws ErrorException nearest_ancestor(model,:leaf;scale=:Plant) +end + +@testset "indexed ancestry retains inconsistent-cache validation order" begin + model=ancestor_scene() + path=model.registry.ancestor_ids_by_object[ObjectId(:leaf)] + path[end-1]=ObjectId(:dangling) + # Missing labels return before examining the corrupted ancestor, exactly + # as the prior implementation did. The label-free branch also stays intact. + @test isnothing(nearest_ancestor(model,:leaf;scale=:Absent)) + @test isnothing(nearest_ancestor(model,:leaf;scale=:Plant,kind=:Absent)) + @test nearest_ancestor(model,:leaf;include_self=false)==ObjectId(:dangling) + failure=try + nearest_ancestor(model,:leaf;scale=:Plant) + nothing + catch error + error + end + @test failure isa ErrorException + @test sprint(showerror,failure)=="No model object with id `dangling`." +end + +end diff --git a/test/test-selector-query-scope-append.jl b/test/test-selector-query-scope-append.jl new file mode 100644 index 000000000..4f42280ab --- /dev/null +++ b/test/test-selector-query-scope-append.jl @@ -0,0 +1,118 @@ +module SelectorQueryScopeAppendChecks + +using PlantSimEngine, PlantSimEngine.Diagnostics, Test +const PSE = PlantSimEngine +PSE.@process "query_scope_append_aggregate" verbose=false +struct ScopeAggregate <: AbstractQuery_Scope_Append_AggregateModel end +PSE.inputs_(::ScopeAggregate) = (values=Required(AbstractVector),) +PSE.outputs_(::ScopeAggregate) = (total=0f0,) +PSE.run!(::ScopeAggregate, status, environment, constants, context) = + (status.total = sum(status.values); nothing) + +function append_scene(scope; relation=nothing, scale=:Leaf) + selector = isnothing(relation) ? + Many(scope; scale, var=:x, from_status=true) : + Many(Relation(relation), scope; scale, var=:x, from_status=true) + model = CompositeModel( + Object(:scene; scale=:Scene), + Object(:plant_a; scale=:Plant, parent=:scene, status=Status(x=100f0)), + Object(:consumer; scale=:Axis, parent=:plant_a), + Object(1; scale=:Leaf, parent=:consumer, status=Status(x=1f0)), + Object(2; scale=:Leaf, parent=:consumer, status=Status(x=2f0)), + Object(:plant_b; scale=:Plant, parent=:scene, status=Status(x=200f0)), + Object(10; scale=:Leaf, parent=:plant_b, status=Status(x=10f0)); + applications=(ModelSpec(ScopeAggregate(); name=:aggregate, on=One(id=:consumer), + inputs=(values=selector,)),)) + simulation = run!(model) + return (; model, simulation, binding=only(simulation.compiled.input_bindings)) +end + +function add_leaf!(model, id, parent) + return register_object!(model, + Object(id; scale=:Leaf, parent, status=Status(x=Float32(id)))) +end + +@testset "Many growth keeps live refs and a query-local scope across lifecycle changes" begin + for scope in (Subtree(), SelfPlant(), Ancestor(scale=:Plant)) + data = append_scene(scope) + model, simulation, binding = data.model, data.simulation, data.binding + @test model_status(model, :consumer).total === 3f0 + carrier, ids = input_carrier(binding), binding.source_ids + first_refs = copy(parent(carrier)) + add_leaf!(model, 3, :consumer) + add_leaf!(model, 4, :plant_a) + add_leaf!(model, 20, :plant_b) + continue!(simulation) + current = only(simulation.compiled.input_bindings) + expected = scope isa Subtree ? [1, 2, 3] : [1, 2, 3, 4] + @test current.source_ids == ObjectId.(expected) + @test current.source_ids === ids + @test input_carrier(current) === carrier + @test all(parent(carrier)[index] === first_refs[index] for index in eachindex(first_refs)) + @test all(reference === PSE.refvalue(model_status(model, id), :x) + for (id, reference) in zip(current.source_ids, parent(carrier))) + @test model_status(model, :consumer).total === Float32(sum(expected)) + + # A later append query must use the new ancestor, never a root retained + # from the previous addition. Structural refresh still owns removals. + reparent_object!(model, :consumer, :plant_b) + continue!(simulation) + expected = scope isa Subtree ? [1, 2, 3] : [1, 2, 3, 10, 20] + @test only(simulation.compiled.input_bindings).source_ids == ObjectId.(expected) + @test model_status(model, :consumer).total === Float32(sum(expected)) + add_leaf!(model, 21, :plant_b) + continue!(simulation) + expected = scope isa Subtree ? [1, 2, 3] : [1, 2, 3, 10, 20, 21] + @test only(simulation.compiled.input_bindings).source_ids == ObjectId.(expected) + @test model_status(model, :consumer).total === Float32(sum(expected)) + remove_object!(model, 20) + continue!(simulation) + expected = scope isa Subtree ? [1, 2, 3] : [1, 2, 3, 10, 21] + @test only(simulation.compiled.input_bindings).source_ids == ObjectId.(expected) + @test model_status(model, :consumer).total === Float32(sum(expected)) + end +end + +function append_selected!(data, ids) + compiled = data.simulation.compiled + return PSE._append_added_many_sources!(data.model, data.binding, ObjectId.(ids), + PSE._applications_by_object(compiled.applications, data.model.registry.objects), compiled.applications_by_id, + compiled.distributed_outputs) +end + +@testset "Many append preserves label and relation short-circuit error order" begin + data = append_scene(SelfPlant()) + reparent_object!(data.model, :consumer, :scene) # no current Plant anchor + register_object!(data.model, Object(30; scale=:Branch, parent=:scene)) + @test append_selected!(data, Int[]) + @test append_selected!(data, [30]) # a rejected label must not resolve scope + @test data.binding.source_ids == ObjectId.([1, 2]) + add_leaf!(data.model, 31, :scene) + @test_throws "No `scale=:Plant` ancestor" append_selected!(data, [31]) + @test data.binding.source_ids == ObjectId.([1, 2]) + + related = append_scene(SelfPlant(); relation=:descendants) + reparent_object!(related.model, :consumer, :scene) + add_leaf!(related.model, 31, :scene) + @test append_selected!(related, [31]) # rejected relation must not resolve scope + add_leaf!(related.model, 32, :consumer) + @test_throws "No `scale=:Plant` ancestor" append_selected!(related, [32]) + @test related.binding.source_ids == ObjectId.([1, 2]) +end + +@testset "nearest Ancestor append keeps its singular point semantics" begin + data = append_scene(Ancestor(scale=:Plant); scale=:Plant) + @test data.binding.source_ids == [ObjectId(:plant_a)] + @test model_status(data.model, :consumer).total === 100f0 + register_object!(data.model, + Object(33; scale=:Plant, parent=:consumer, status=Status(x=33f0))) + @test append_selected!(data, [33]) + @test data.binding.source_ids == [ObjectId(:plant_a)] + reparent_object!(data.model, :consumer, :scene) + register_object!(data.model, + Object(34; scale=:Plant, parent=:scene, status=Status(x=34f0))) + @test append_selected!(data, [34]) # no ancestor remains a nonmatch, not an anchor error + @test data.binding.source_ids == [ObjectId(:plant_a)] +end + +end diff --git a/test/test-selector-query-scope-root.jl b/test/test-selector-query-scope-root.jl new file mode 100644 index 000000000..9e80ec7f0 --- /dev/null +++ b/test/test-selector-query-scope-root.jl @@ -0,0 +1,139 @@ +module SelectorQueryScopeRootChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +sorted_ids(ids...) = PSE._sort_object_ids!(ObjectId[ObjectId(id) for id in ids]) + +function scope_scene() + return CompositeModel( + Object(:scene; scale=:Scene), + Object(:plant_a; scale=:Plant, parent=:scene), + Object(:axis_a; scale=:Axis, parent=:plant_a), + Object(1; scale=:Leaf, kind=:active, parent=:axis_a), + Object(10; scale=:Leaf, kind=:active, parent=:axis_a), + Object(Symbol("2"); scale=:Leaf, kind=:dormant, parent=:plant_a), + Object(:plant_b; scale=:Plant, parent=:scene), + Object(:axis_b; scale=:Axis, parent=:plant_b), + Object(20; scale=:Leaf, kind=:active, parent=:axis_b), + Object(:leaf_b; scale=:Leaf, kind=:dormant, parent=:plant_b), + ) +end + +@testset "one query anchor preserves topology scopes, default scopes, and ID order" begin + model = scope_scene() + leaves_a = sorted_ids(1, 10, Symbol("2")) + leaves_b = sorted_ids(20, :leaf_b) + @test leaves_a == ObjectId[ObjectId(1), ObjectId(10), ObjectId(Symbol("2"))] + @test resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf); context=1) == leaves_a + @test resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf); context=20) == leaves_b + @test resolve_object_ids(model, Many(Subtree(); scale=:Leaf); context=:plant_a) == leaves_a + @test resolve_object_ids(model, Many(Subtree(); scale=:Leaf); context=:axis_a) == sorted_ids(1, 10) + @test resolve_object_ids(model, Many(Ancestor(scale=:Plant); scale=:Leaf); context=1) == leaves_a + @test resolve_object_ids(model, Many(Ancestor(scale=:Axis); scale=:Leaf); context=1) == sorted_ids(1, 10) + @test resolve_object_ids(model, One(Ancestor(scale=:Plant); scale=:Plant); context=1) == + sorted_ids(:plant_a) + @test resolve_object_ids(model, Many(Scope(ObjectId(:plant_a)); scale=:Leaf)) == leaves_a + + selector = Many(scale=:Leaf) + matcher = PSE._compile_selector_matcher(model, selector) + @test isnothing(matcher.scope) + @test PSE._resolve_object_ids(model, selector, matcher; + context=ObjectId(1), default_scope=SelfPlant()) == leaves_a + @test isnothing(matcher.scope) + @test PSE._resolve_object_ids(model, selector, matcher; + context=ObjectId(:axis_b), default_scope=Subtree()) == sorted_ids(20) +end + +@testset "relation roots and explicit scope remain an intersection" begin + model = scope_scene() + @test isempty(resolve_object_ids(model, + Many(Relation(:descendants), Scope(ObjectId(:plant_b)); scale=:Leaf); + context=:plant_a)) + @test resolve_object_ids(model, + Many(Relation(:descendants), Scope(ObjectId(:axis_a)); scale=:Leaf); + context=:plant_a) == sorted_ids(1, 10) + @test resolve_object_ids(model, + Many(Relation(:ancestors), Scope(ObjectId(:plant_a)); scale=(:Plant, :Axis)); + context=1) == sorted_ids(:axis_a, :plant_a) + @test resolve_object_ids(model, + Many(Relation(:siblings), SelfPlant(); scale=:Leaf); context=1) == sorted_ids(10) +end + +@testset "query anchors stay fresh after reparenting and removal" begin + model = scope_scene() + selector = Many(SelfPlant(); scale=:Leaf) + matcher = PSE._compile_selector_matcher(model, selector) + query() = PSE._resolve_object_ids(model, selector, matcher; context=ObjectId(1)) + @test query() == sorted_ids(1, 10, Symbol("2")) + reparent_object!(model, 1, :axis_b) + @test query() == sorted_ids(1, 20, :leaf_b) + @test resolve_object_ids(model, Many(Subtree(); scale=:Leaf); context=:plant_a) == + sorted_ids(10, Symbol("2")) + remove_object!(model, 20) + @test query() == sorted_ids(1, :leaf_b) + + named_selector = Many(Scope(ObjectId(:axis_a)); scale=:Leaf) + named_matcher = PSE._compile_selector_matcher(model, named_selector) + remove_object!(model, :axis_a) + @test isempty(PSE._resolve_object_ids(model, named_selector, named_matcher)) + @test_throws "No instance or object ID" resolve_object_ids(model, named_selector) +end + +function query_error(model, selector; kwargs...) + try + resolve_object_ids(model, selector; kwargs...) + return "" + catch error + return sprint(showerror, error) + end +end + +@testset "raw authored scopes remain in cardinality and context errors" begin + model = scope_scene() + for selector in (One(SelfPlant(); scale=:Leaf), + One(Subtree(); scale=:Leaf), + One(Ancestor(scale=:Plant); scale=:Leaf), + One(Scope(ObjectId(:plant_a)); scale=:Leaf)) + error = query_error(model, selector; context=:axis_a) + @test occursin("Expected exactly one object", error) + @test occursin(string(selector), error) + @test !occursin("CompiledNamedScope", error) + end + @test_throws "current object context" resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf)) + @test_throws "current object context" resolve_object_ids(model, Many(Subtree(); scale=:Leaf)) + @test_throws "current object context" resolve_object_ids(model, + Many(Ancestor(scale=:Plant); scale=:Leaf)) + @test_throws "No matching ancestor" resolve_object_ids(model, + Many(Ancestor(scale=:Axis); scale=:Leaf); context=:plant_a) + @test_throws "No `scale=:Plant` ancestor" resolve_object_ids(model, + Many(SelfPlant(); scale=:Leaf); context=:scene) + @test_throws "No instance or object ID" resolve_object_ids(model, + Many(Scope(ObjectId(:missing)); scale=:Leaf)) +end + +function budget_scene() + objects = Object[Object(:scene; scale=:Scene)] + for plant in (:plant_a, :plant_b) + push!(objects, Object(plant; scale=:Plant, parent=:scene)) + for index in 1:32 + push!(objects, Object(Symbol(plant, :_leaf_, index); scale=:Leaf, + species=index == 1 ? :rare : :common, parent=plant)) + end + end + return CompositeModel(objects...) +end + +@testset "one anchor serves complete local walks and borrowed global index buckets" begin + model = budget_scene() + leaf_index = PSE._smallest_indexed_candidates(model; scale=:Leaf) + @test !isnothing(PSE._descendant_ids_up_to(model, ObjectId(:plant_a), leaf_index.estimate)) + rare_index = PSE._smallest_indexed_candidates(model; scale=:Leaf, species=:rare) + @test isnothing(PSE._descendant_ids_up_to(model, ObjectId(:plant_a), rare_index.estimate)) + @test resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf); context=:plant_a) == + sorted_ids((Symbol(:plant_a_leaf_, index) for index in 1:32)...) + @test resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf, species=:rare); context=:plant_a) == + sorted_ids(:plant_a_leaf_1) +end + +end diff --git a/test/test-status-construction.jl b/test/test-status-construction.jl index f52de5bb6..80a333f7c 100644 --- a/test/test-status-construction.jl +++ b/test/test-status-construction.jl @@ -19,7 +19,7 @@ const PSE = PlantSimEngine @test PSE._status_recipe_set_reference!(edits, :replace, replacement) @test PSE._status_recipe_set_reference!(edits, :tail, tail) @test !PSE._status_recipe_set_reference!(edits, :tail, tail) - constructed = PSE._finish_status_recipe(model, edits) + constructed = PSE._finish_canonical_status_recipe(identity, model, edits) @test propertynames(constructed) == (:keep, :replace, :tail) @test PSE.refvalue(constructed, :keep) === keep @test PSE.refvalue(constructed, :replace) === replacement @@ -27,14 +27,14 @@ const PSE = PlantSimEngine @test PSE._status_recipe_reference(edits, :keep) === keep @test PSE._status_recipe_reference(edits, :replace) === replacement @test_throws KeyError PSE._status_recipe_reference(edits, :absent) - @test PSE._finish_status_recipe(model, PSE._CanonicalStatusRecipe(original)) === original + @test PSE._finish_canonical_status_recipe(identity, model, PSE._CanonicalStatusRecipe(original)) === original cache = model.registry.objects.layout_cache layout = only(values(cache)) same_shape = PSE._CanonicalStatusRecipe(Status(keep=8, replace=9.0)) PSE._status_recipe_set_reference!(same_shape, :replace, Ref(big"10.0")) PSE._status_recipe_set_reference!(same_shape, :tail, Ref([11.0f0])) - another = PSE._finish_status_recipe(model, same_shape) + another = PSE._finish_canonical_status_recipe(identity, model, same_shape) @test typeof(another) !== typeof(constructed) @test another.replace isa BigFloat @test another.tail isa Vector{Float32} @@ -47,13 +47,13 @@ const PSE = PlantSimEngine external = Ref(storage, 1) external_edit = PSE._CanonicalStatusRecipe(Status(keep=1)) PSE._status_recipe_set_reference!(external_edit, :external, external) - external_status = PSE._finish_status_recipe(model, external_edit) + external_status = PSE._finish_canonical_status_recipe(identity, model, external_edit) @test PSE.refvalue(external_status, :external) === external storage[1] = 13.0 @test external_status.external == 13.0 - empty_a = PSE._finish_status_recipe(model, PSE._CanonicalStatusRecipe(nothing)) - empty_b = PSE._finish_status_recipe(model, PSE._CanonicalStatusRecipe(nothing)) + empty_a = PSE._finish_canonical_status_recipe(identity, model, PSE._CanonicalStatusRecipe(nothing)) + empty_b = PSE._finish_canonical_status_recipe(identity, model, PSE._CanonicalStatusRecipe(nothing)) @test propertynames(empty_a) == () @test getfield(empty_a, :identity) !== getfield(empty_b, :identity) @test all(isbits, values(cache)) From 865681cbe626f8a1ef0f7ed7f8da7a92a786ce8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 21:28:08 +0100 Subject: [PATCH 011/324] Include shared selector anchors and indexed ancestry in the canonical runtime --- src/composite_model/selectors.jl | 68 +++++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index bb53208ea..b392076b0 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -578,13 +578,17 @@ function _ancestor_id( final_index < firstindex(ancestors) && return nothing isnothing(scale) && isnothing(kind) && return @inbounds ancestors[final_index] - !isnothing(scale) && !haskey(model.registry.by_scale, scale) && return nothing - !isnothing(kind) && !haskey(model.registry.by_kind, kind) && return nothing + scale_ids = isnothing(scale) ? nothing : get(model.registry.by_scale, scale, nothing) + !isnothing(scale) && isnothing(scale_ids) && return nothing + kind_ids = isnothing(kind) ? nothing : get(model.registry.by_kind, kind, nothing) + !isnothing(kind) && isnothing(kind_ids) && return nothing for index in final_index:-1:firstindex(ancestors) id = @inbounds ancestors[index] - object = _model_object(model, id)::Object - (isnothing(scale) || object.scale === scale) && - (isnothing(kind) || object.kind === kind) && return id + # Preserve the existing unknown-object error for a dangling cached + # ancestor, without fetching every live Object merely for its labels. + haskey(model.registry.objects, id) || _model_object(model, id) + (isnothing(scale_ids) || id in scale_ids) && + (isnothing(kind_ids) || id in kind_ids) && return id end return nothing end @@ -715,12 +719,12 @@ function _authored_selector_matcher(selector::AbstractObjectMultiplicity) ) end +_selector_matcher_with_scope(matcher::CompiledSelectorMatcher, scope) = + CompiledSelectorMatcher(scope, matcher.relation, matcher.scale, matcher.kind, + matcher.species, matcher.id, matcher.defaults_to_context) + function _resolve_selector_matcher(model::CompositeModel, matcher::CompiledSelectorMatcher) - return CompiledSelectorMatcher( - _compile_selector_scope(model, matcher.scope), matcher.relation, - matcher.scale, matcher.kind, matcher.species, matcher.id, - matcher.defaults_to_context, - ) + return _selector_matcher_with_scope(matcher, _compile_selector_scope(model, matcher.scope)) end _compile_selector_matcher(model::CompositeModel, selector::AbstractObjectMultiplicity) = @@ -842,6 +846,25 @@ function _selector_subtree_root(model::CompositeModel, scope, context) return nothing end +# A query owns its resolved root only until its current candidates are consumed. +# Existing compiled named scopes already carry this root; relations and nearest +# ancestor queries retain their original point predicates. +function _query_scope_matcher(matcher::CompiledSelectorMatcher, scope, root) + (isnothing(matcher.relation) && !isnothing(root) && + !(scope isa CompiledNamedScope)) || return matcher + return _selector_matcher_with_scope(matcher, CompiledNamedScope(scope, root)) +end + +function _query_scope_matcher(model::CompositeModel, matcher::CompiledSelectorMatcher, + context, default_scope) + isnothing(matcher.relation) || return matcher + scope = isnothing(matcher.scope) ? default_scope : matcher.scope + if scope isa Ancestor && !isnothing(matcher.scale) && matcher.scale == scope.scale + return matcher + end + return _query_scope_matcher(matcher, scope, _selector_subtree_root(model, scope, context)) +end + # On Julia 1.10, keep the target ID unboxed when the ancestor's ID type is unknown. @inline function _object_is_in_subtree(model::CompositeModel, object_id::ObjectId, root_id::ObjectId) return root_id in _object_ancestor_ids(model.registry, object_id) @@ -1058,14 +1081,20 @@ function _selector_matches_object_id( if default_to_context && matcher.defaults_to_context && !isnothing(context) return object_id == _object_id_from_context(context) end - object = _model_object(model, object_id) - _matches_object_criteria( - object; - scale=matcher.scale, - kind=matcher.kind, - species=matcher.species, - id=matcher.id, - ) || return false + _selector_matches_object_labels(model, matcher, object_id) || return false + return _selector_matches_object_topology(model, matcher, object_id; + context, default_scope, relation_resolved) +end + +@inline function _selector_matches_object_labels(model::CompositeModel, + matcher::CompiledSelectorMatcher, object_id::ObjectId) + return _matches_object_criteria(_model_object(model, object_id); + scale=matcher.scale, kind=matcher.kind, species=matcher.species, id=matcher.id) +end + +function _selector_matches_object_topology(model::CompositeModel, + matcher::CompiledSelectorMatcher, object_id::ObjectId; + context=nothing, default_scope=nothing, relation_resolved::Bool=false) scope = isnothing(matcher.scope) ? default_scope : matcher.scope if isnothing(matcher.relation) if scope isa Ancestor && @@ -1283,8 +1312,9 @@ function _resolve_object_ids( relation_resolved = true _relation_object_ids(model, relation, context) end + matching_matcher = _query_scope_matcher(matcher, scope, subtree_root) ids = _matching_selector_ids( - model, matcher, candidate_ids, context, default_to_context, default_scope, relation_resolved, + model, matching_matcher, candidate_ids, context, default_to_context, default_scope, relation_resolved, ) # Cardinality diagnostics may need all available labels in the topology From 7a598e05baa99390277752082f396574629532f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 21:58:27 +0100 Subject: [PATCH 012/324] Fix typed object capture during environment refresh --- src/composite_model/runtime_outputs.jl | 37 +++++++------- ...test-model-environment-binding-identity.jl | 51 +++++++++++++++++++ 2 files changed, 71 insertions(+), 17 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 25db2249a..cc8f4dd09 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7379,23 +7379,26 @@ function _refresh_simulation_runtime!(simulation::Simulation) lifecycle_delta(model).full_environment ? nothing : copy(lifecycle_delta(model).environment_dirty_ids) - changed_execution_application_ids = nothing - changed_execution_target_ids = - Set{Tuple{Symbol,ObjectId}}() - if !isnothing(dirty_environment_object_ids) - changed_execution_application_ids = Set{Symbol}() - for object_id in dirty_environment_object_ids - _foreach_object_application(simulation.compiled, object_id) do application - push!( - changed_execution_application_ids, - application.id, - ) - push!( - changed_execution_target_ids, - (application.id, object_id), - ) + changed_environment_target_ids = Set{Tuple{Symbol,ObjectId}}() + changed_environment_application_ids = if isnothing(dirty_environment_object_ids) + nothing + else + application_ids = Set{Symbol}() + for dirty_object_id in dirty_environment_object_ids + # The lifecycle set can contain heterogeneous IDs. Capture the + # canonical index's identity schema inside this query instead + # of an existential ObjectId in the application callback. + let object_id = _application_index_object_id( + simulation.compiled.applications_by_object, + dirty_object_id, + ) + _foreach_object_application(simulation.compiled, object_id) do application + push!(application_ids, application.id) + push!(changed_environment_target_ids, (application.id, object_id)) + end end end + application_ids end previous_environment_bindings = isnothing(simulation.performance) ? nothing : @@ -7443,8 +7446,8 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.output_retention, simulation.constants, simulation.performance, - changed_execution_application_ids, - changed_execution_target_ids, + changed_environment_application_ids, + changed_environment_target_ids, ) simulation.execution_plan = execution_refresh.plan _runtime_performance_finish!( diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 3f5035737..42c0cc478 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -142,4 +142,55 @@ end @test data.backend.samples == samples end end + +@testset "partial and full environment refresh preserve scientific owners and sampling" begin + data = fixture(Float32) + simulation = data.simulation + original_compiled = simulation.compiled + kept_status = model_status(data.model, :scheduled_keep) + moved_status = model_status(data.model, :scheduled_move) + kept_binding = simulation.environment_bindings.by_target[(:scheduled_probe, ObjectId(:scheduled_keep))] + moved_binding = simulation.environment_bindings.by_target[(:scheduled_probe, ObjectId(:scheduled_move))] + + move_object!(data.model, :scheduled_move, (cell=:b,)) + samples = data.backend.samples + PSE._refresh_simulation_runtime!(simulation) + @test data.backend.samples == samples + @test simulation.compiled === original_compiled + @test model_status(data.model, :scheduled_keep) === kept_status + @test model_status(data.model, :scheduled_move) === moved_status + @test simulation.environment_bindings.by_target[(:scheduled_probe, ObjectId(:scheduled_keep))] === kept_binding + refreshed_move = simulation.environment_bindings.by_target[(:scheduled_probe, ObjectId(:scheduled_move))] + @test refreshed_move !== moved_binding + @test refreshed_move.handle.cell === :b + @test refreshed_move.backend === data.backend + scheduled = only(batch for batch in simulation.execution_plan.batches + if batch.application.id === :scheduled_probe) + @test only(target for target in scheduled.targets if target.object_id === ObjectId(:scheduled_keep)) === data.kept + continue!(simulation) + @test kept_status.seen === 10.0f0 + @test moved_status.seen === 20.0f0 + + # A full refresh keeps the whole-application sentinel rather than treating + # an empty set as a proof that no execution payload must be refreshed. + data.backend.values[:a] = 12.0f0 + data.backend.values[:b] = 22.0f0 + mark_environment_binding_dirty!(data.model) + samples = data.backend.samples + PSE._refresh_simulation_runtime!(simulation) + @test data.backend.samples == samples + @test simulation.compiled === original_compiled + @test all(binding -> binding.backend === data.backend, + simulation.environment_bindings.bindings) + continue!(simulation) + @test kept_status.seen === 12.0f0 + @test moved_status.seen === 22.0f0 + @test kept_status.calls == moved_status.calls == 3 + @test outputs(simulation)[(:scheduled_probe, ObjectId(:scheduled_move), :seen)] == + [(1.0, 10.0f0), (2.0, 20.0f0), (3.0, 22.0f0)] + target = only(call_targets(data.capture[], :leaves)) + run_call!(target; publish=false) + @test target.status.seen === 12.0f0 + @test target.environment_binding.backend === data.backend +end end From 912503de3ef25d3e639e54924300c9fb66979787 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 22:12:40 +0100 Subject: [PATCH 013/324] Preserve current environment owners across public refreshes --- src/composite_model/environment_bindings.jl | 58 ++++++ src/composite_model/registry_topology.jl | 36 ---- src/composite_model/runtime_outputs.jl | 21 ++- ...test-model-environment-binding-identity.jl | 165 +++++++++++++++++- 4 files changed, 239 insertions(+), 41 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 89b09ea68..e6da39138 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -717,3 +717,61 @@ end function explain_environment_bindings(model::CompositeModel) return explain_environment_bindings(refresh_environment_bindings!(deepcopy(model))) end + +function refresh_environment_bindings!(model::CompositeModel, compiled=refresh_bindings!(model); force::Bool=false) + cached = getfield(model, :environment_binding_cache)::Union{Nothing,CompiledEnvironmentBindings} + return _refresh_environment_bindings!(model, compiled, cached; force) +end + +# Canonical model caches keep the same container schema: plan/binding Vectors, +# Symbol/target/object Dicts, the sample Dict, and SC == typeof(model). Backends, +# handles, remapping, and alternate compiled applications remain values inside +# those containers. Targeted partial shells are never installed in this cache. +# Use the prepared shell only as its type witness; the current model cache is +# authoritative and can have been replaced by a public refresh in the meantime. +@inline function _current_environment_binding_owner(model::CompositeModel, + ::E, +) where {E<:CompiledEnvironmentBindings} + return getfield(model, :environment_binding_cache)::Union{Nothing,E} +end + +function _refresh_environment_bindings!(model::CompositeModel, compiled, + cached::Union{Nothing,CompiledEnvironmentBindings}; force::Bool=false, +) + if force || model.environment_bindings_dirty || isnothing(cached) + delta = model.lifecycle_delta + refreshed = if !force && !isnothing(cached) && !delta.full_environment + # A public Advanced refresh may have prepared another application + # set. Reconcile that current owner before using its plans for a + # partial event in this compiled scene. + partial_owner = cached.applications_identity == objectid(compiled.applications) ? + cached : _reconcile_environment_binding_metadata(model, compiled, cached) + if isnothing(partial_owner) + compile_environment_bindings(model, compiled) + else + _refresh_environment_bindings_for_objects( + model, + compiled, + partial_owner, + delta.environment_dirty_ids, + ) + end + else + compile_environment_bindings(model, compiled) + end + model.environment_binding_cache = refreshed + model.environment_bindings_dirty = false + _reset_lifecycle_delta_if_consumed!(model) + return refreshed + elseif cached.model_revision == compiled.revision && + cached.environment_revision == model.environment_revision && + cached.applications_identity == objectid(compiled.applications) + return cached + else + reconciled = _reconcile_environment_binding_metadata(model, compiled, cached) + refreshed = isnothing(reconciled) ? + compile_environment_bindings(model, compiled) : reconciled + model.environment_binding_cache = refreshed + return refreshed + end +end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 9e5802911..3d26045a1 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1839,42 +1839,6 @@ function refresh_bindings!( return model.binding_cache end -function refresh_environment_bindings!(model::CompositeModel, compiled=refresh_bindings!(model); force::Bool=false) - if force || model.environment_bindings_dirty || isnothing(model.environment_binding_cache) - delta = model.lifecycle_delta - if !force && - !isnothing(model.environment_binding_cache) && - !delta.full_environment - model.environment_binding_cache = _refresh_environment_bindings_for_objects( - model, - compiled, - model.environment_binding_cache, - delta.environment_dirty_ids, - ) - else - model.environment_binding_cache = compile_environment_bindings(model, compiled) - end - model.environment_bindings_dirty = false - _reset_lifecycle_delta_if_consumed!(model) - elseif model.environment_binding_cache.model_revision == compiled.revision && - model.environment_binding_cache.environment_revision == - model.environment_revision && - model.environment_binding_cache.applications_identity == - objectid(compiled.applications) - return model.environment_binding_cache - else - reconciled = _reconcile_environment_binding_metadata( - model, - compiled, - model.environment_binding_cache, - ) - model.environment_binding_cache = isnothing(reconciled) ? - compile_environment_bindings(model, compiled) : - reconciled - end - return model.environment_binding_cache -end - function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) ids = _indexed_object_ids( model; diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index cc8f4dd09..873351771 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7293,9 +7293,14 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.compiled.changed_execution_target_ids : nothing, ) started_at = _runtime_performance_start(simulation.performance) - simulation.environment_bindings = refresh_environment_bindings!( + environment_owner = _current_environment_binding_owner(model, simulation.environment_bindings) + environment_delta_covers_runtime = !isnothing(environment_owner) && + environment_owner.environment_revision == simulation.environment_bindings.environment_revision && + environment_owner.applications_identity == simulation.environment_bindings.applications_identity + simulation.environment_bindings = _refresh_environment_bindings!( model, simulation.compiled, + environment_owner, ) _runtime_performance_finish!( simulation.performance, @@ -7324,7 +7329,7 @@ function _refresh_simulation_runtime!(simulation::Simulation) ), ) end - changed_execution_application_ids = output_retention_reused ? + changed_execution_application_ids = output_retention_reused && environment_delta_covers_runtime ? simulation.compiled.changed_execution_application_ids : nothing started_at = _runtime_performance_start(simulation.performance) @@ -7375,8 +7380,15 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.performance, lifecycle_delta(model), ) + environment_owner = _current_environment_binding_owner(model, simulation.environment_bindings) + # A public refresh can consume the lifecycle delta before this + # Simulation observes it. A later partial event only describes changes + # since that newer cache, so it cannot bound this runtime's stale rows. + environment_delta_covers_runtime = !isnothing(environment_owner) && + environment_owner.environment_revision == simulation.environment_bindings.environment_revision && + environment_owner.applications_identity == simulation.environment_bindings.applications_identity dirty_environment_object_ids = - lifecycle_delta(model).full_environment ? + lifecycle_delta(model).full_environment || !environment_delta_covers_runtime ? nothing : copy(lifecycle_delta(model).environment_dirty_ids) changed_environment_target_ids = Set{Tuple{Symbol,ObjectId}}() @@ -7406,9 +7418,10 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.environment_bindings.by_target, ) started_at = _runtime_performance_start(simulation.performance) - simulation.environment_bindings = refresh_environment_bindings!( + simulation.environment_bindings = _refresh_environment_bindings!( model, simulation.compiled, + environment_owner, ) _runtime_performance_finish!( simulation.performance, diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 42c0cc478..79dfe39c3 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -14,8 +14,11 @@ end EA.base_step_seconds(::Backend) = 3600.0 EA.get_nsteps(::Backend) = 8 EA.environment_variables(::Backend) = Set((:T,)) +mutable struct Handle + cell::Symbol +end EA.bind_environment(::Backend, object::Object, context, config) = - (cell=isnothing(geometry(object)) ? :a : geometry(object).cell,) + Handle(isnothing(geometry(object)) ? :a : geometry(object).cell) function EA.sample(backend::Backend, handle, ::Symbol, time) backend.samples += 1 return backend.values[handle.cell] @@ -193,4 +196,164 @@ end @test target.status.seen === 12.0f0 @test target.environment_binding.backend === data.backend end + +@testset "the typed boundary selects the current model cache after public refresh" begin + data = fixture(Float32) + simulation = data.simulation + prepared = simulation.environment_bindings + @test PSE._current_environment_binding_owner(data.model, prepared) === prepared + + move_object!(data.model, :scheduled_move, (cell=:b,)) + partial = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + current = PSE._current_environment_binding_owner(data.model, prepared) + is_current_partial = current === partial && current !== prepared + @test is_current_partial + @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b + @test all(binding -> binding.backend === data.backend, current.bindings) + samples = data.backend.samples + clean = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) + same_clean = clean === partial + @test same_clean + @test data.backend.samples == samples + + mark_environment_binding_dirty!(data.model) + @test isnothing(PSE._current_environment_binding_owner(data.model, prepared)) + full = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + current = PSE._current_environment_binding_owner(data.model, prepared) + is_current_full = current === full && current !== partial + @test is_current_full + same_schema = typeof(full) === typeof(prepared) + @test same_schema + @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b + + # Advanced compilation may replace model metadata before this Simulation + # resumes. The current cache remains authoritative even for another set of + # applications; the common refresh algorithm reconciles it when requested. + alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( + ModelSpec(Leaf(0.0f0); name=:scheduled_probe, on=Many(kind=:scheduled), + environment=Environment(provider=:shell_probe)), + )) + alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) + current = PSE._current_environment_binding_owner(data.model, prepared) + is_current_alternate = current === alternate && current !== full + @test is_current_alternate + @test length(current.bindings) == 2 + @test current.applications_identity == objectid(alternate_compiled.applications) + samples = data.backend.samples + restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) + is_restored = restored === PSE.compiled_environment_bindings(data.model) + @test is_restored + @test restored.applications_identity == objectid(simulation.compiled.applications) + @test length(restored.bindings) == 4 + @test all(binding -> binding.backend === data.backend, restored.bindings) + @test restored.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b + @test data.backend.samples == samples +end + +@testset "a public refresh cannot hide stale runtime geometry bindings" begin + for full in (false, true), pending_after_public in (false, true) + data = fixture(Float32) + simulation = data.simulation + move_object!(data.model, :scheduled_move, (cell=:b,)) + full && mark_environment_binding_dirty!(data.model) + public = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + @test !PSE.environment_bindings_dirty(data.model) + @test isempty(PSE.lifecycle_delta(data.model).environment_dirty_ids) + pending_after_public && move_object!(data.model, :scheduled_keep, (cell=:b,)) + samples = data.backend.samples + PSE._refresh_simulation_runtime!(simulation) + @test data.backend.samples == samples + uses_current = simulation.environment_bindings === PSE.compiled_environment_bindings(data.model) + @test uses_current + if !pending_after_public + uses_public = simulation.environment_bindings === public + @test uses_public + end + scheduled = only(batch for batch in simulation.execution_plan.batches + if batch.application.id === :scheduled_probe) + moved = only(target for target in scheduled.targets + if target.object_id === ObjectId(:scheduled_move)) + kept = only(target for target in scheduled.targets + if target.object_id === ObjectId(:scheduled_keep)) + @test moved.environment_binding.handle.cell === :b + @test kept.environment_binding.handle.cell === (pending_after_public ? :b : :a) + @test moved.environment_binding.backend === data.backend + @test model_status(data.model, :scheduled_move).calls == 1 + continue!(simulation) + @test model_status(data.model, :scheduled_move).seen === 20.0f0 + @test model_status(data.model, :scheduled_keep).seen === (pending_after_public ? 20.0f0 : 10.0f0) + @test model_status(data.model, :scheduled_move).calls == 2 + @test model_status(data.model, :scheduled_keep).calls == 2 + @test outputs(simulation)[(:scheduled_probe, ObjectId(:scheduled_move), :seen)] == + [(1.0, 10.0f0), (2.0, 20.0f0)] + end +end + +@testset "a later addition also observes previously refreshed geometry" begin + data = fixture(Float32) + simulation = data.simulation + move_object!(data.model, :scheduled_move, (cell=:b,)) + PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + newborn = register_object!(data.model, Object(:scheduled_new; + scale=:Leaf, kind=:scheduled, parent=:scene, geometry=(cell=:a,))) + samples = data.backend.samples + PSE._refresh_simulation_runtime!(simulation) + @test data.backend.samples == samples + moved_bindings = [target.environment_binding for batch in simulation.execution_plan.batches + for target in batch.targets if target.object_id === ObjectId(:scheduled_move)] + @test only(moved_bindings).handle.cell === :b + @test only(moved_bindings).backend === data.backend + continue!(simulation) + @test model_status(data.model, :scheduled_move).seen === 20.0f0 + @test model_status(data.model, :scheduled_move).calls == 2 + @test newborn.status.seen === 10.0f0 + @test newborn.status.calls == 1 + @test outputs(simulation)[(:scheduled_probe, ObjectId(:scheduled_move), :seen)] == + [(1.0, 10.0f0), (2.0, 20.0f0)] +end + +@testset "a pending move reconciles an authoritative Advanced subset cache" begin + data = fixture(Float32) + simulation = data.simulation + alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( + ModelSpec(Leaf(0.0f0); name=:manual_probe, on=Many(kind=:manual), + environment=Environment(provider=:shell_probe)), + )) + alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) + @test length(alternate.bindings) == 1 + @test !haskey(alternate.application_plans_by_id, :scheduled_probe) + move_object!(data.model, :scheduled_move, (cell=:b,)) + samples = data.backend.samples + PSE._refresh_simulation_runtime!(simulation) + @test data.backend.samples == samples + uses_current = simulation.environment_bindings === PSE.compiled_environment_bindings(data.model) + @test uses_current + @test simulation.environment_bindings.applications_identity == objectid(simulation.compiled.applications) + @test length(simulation.environment_bindings.bindings) == 4 + handles_current = all(batch -> all(target -> + target.environment_binding.handle === simulation.environment_bindings.by_target[ + (batch.application.id, target.object_id)].handle, batch.targets), + simulation.execution_plan.batches) + @test handles_current + scheduled = only(batch for batch in simulation.execution_plan.batches + if batch.application.id === :scheduled_probe) + target = only(target for target in scheduled.targets + if target.object_id === ObjectId(:scheduled_move)) + @test target.environment_binding.handle.cell === :b + @test target.environment_binding.backend === data.backend + @test model_status(data.model, :scheduled_move).calls == 1 + continue!(simulation) + @test model_status(data.model, :scheduled_move).seen === 20.0f0 + @test model_status(data.model, :scheduled_move).calls == 2 + @test model_status(data.model, :manual).calls == 0 + @test outputs(simulation)[(:scheduled_probe, ObjectId(:scheduled_move), :seen)] == + [(1.0, 10.0f0), (2.0, 20.0f0)] + selected = only(call_targets(data.capture[], :leaves)) + run_call!(selected; publish=false) + @test selected.status.seen === 10.0f0 + @test selected.environment_binding.backend === data.backend + manual_handle_current = selected.environment_binding.handle === + simulation.environment_bindings.by_target[(:manual_probe, ObjectId(:manual))].handle + @test manual_handle_current +end end From 8b784f25f086ba9807f6df392851e631f2500bae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 6 Nov 2026 22:43:36 +0100 Subject: [PATCH 014/324] Use one batch kernel path and concrete preparation metadata --- .../guides/extensions/environment_backends.md | 7 + src/composite_model/compilation.jl | 30 +- src/composite_model/runtime_outputs.jl | 456 +++++------------- src/time/runtime/environment_backends.jl | 7 + test/runtests.jl | 3 + test/test-model-authored-spec-matching.jl | 124 +++++ test/test-model-execution-batch-times.jl | 181 +++++++ test/test-model-output-retention-owners.jl | 173 +++++++ 8 files changed, 634 insertions(+), 347 deletions(-) create mode 100644 test/test-model-authored-spec-matching.jl create mode 100644 test/test-model-execution-batch-times.jl create mode 100644 test/test-model-output-retention-owners.jl diff --git a/docs/src/guides/extensions/environment_backends.md b/docs/src/guides/extensions/environment_backends.md index 57bb0848c..15daabc5f 100644 --- a/docs/src/guides/extensions/environment_backends.md +++ b/docs/src/guides/extensions/environment_backends.md @@ -25,6 +25,13 @@ The required methods are: - `sample(backend, handle, variable, time)`: read a value from the stored, accepted environment state. +The `time` argument is an index on the simulation's base-step clock. Per-target +backend sampling uses `float(step)` with the same clock when outputs or +performance counters are enabled. Global forcing tables select their row from +the scheduler step. Hard calls use the floating clock saved by their runtime +context. Accept a suitable `Real` argument in backend methods; floating +representations such as `Float32` are preserved. + Implement `environment_variables(backend)` if you can list the available variable names without an expensive calculation. PlantSimEngine can then check that the required names exist when it prepares the simulation. diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b93c579c5..f4c21418e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -822,8 +822,34 @@ function _model_owned_scenario_preparation(model::CompositeModel, preparation::S return owned end -_authored_specs_match(preparation::ScenarioPreparation, model::CompositeModel) = - _authored_specs_match(preparation.source_specs, model.applications) +# Read each immutable source declaration inside its exact owner schema. Live +# applications are iterated in order; no source tuple or model value escapes. +@generated function _authored_specs_match( + preparation::ScenarioPreparation{M,S}, + model::CompositeModel, +) where {M,S<:Tuple} + count = fieldcount(S) + comparisons = Expr[] + for index in 1:count + next = index == 1 ? :(iterate(live_specs)) : + :(iterate(live_specs, getfield(current, 2))) + push!(comparisons, :(current = $next)) + push!(comparisons, :(isnothing(current) && return false)) + expected_type = fieldtype(S, index) + push!(comparisons, :(candidate = getfield(current, 1))) + push!(comparisons, :(candidate isa $expected_type || return false)) + push!(comparisons, :( + getfield(getfield(preparation, :source_specs), $index) === + (candidate::$expected_type) || return false + )) + end + return quote + live_specs = getfield(model, :applications) + length(live_specs) == $count || return false + $(comparisons...) + return true + end +end function _scenario_preparation(model::CompositeModel; force::Bool=false) preparation = model.scenario_plan_cache diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 873351771..4281c4584 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1694,12 +1694,17 @@ explain_writers(sim::Simulation) = explain_writers(sim.compiled) explain_environment_bindings(sim::Simulation) = explain_environment_bindings(sim.environment_bindings) -function _compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) - application = get(compiled.applications_by_id, id, nothing) - isnothing(application) && error("No compiled model application with id `$(id)`.") - return application +@inline function _compiled_application_by_id(f::F, compiled::CompiledCompositeModel, + id::Symbol, +) where {F} + haskey(compiled.applications_by_id, id) || + error("No compiled model application with id `$(id)`.") + return _with_metadata_entry(f, compiled.applications_by_id, id) end +_compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) = + _compiled_application_by_id(identity, compiled, id) + function _environment_binding_for(env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId) return get(env_bindings.by_target, (application_id, object_id), nothing) end @@ -1902,45 +1907,46 @@ function _initialize_changed_model_output_streams!( (), ) isempty(variables) && continue - application = _compiled_application_by_id(compiled, application_id) - model_outputs = keys(_local_output_schema(application.spec)) - if haskey(compiled.status_views_by_target, (application_id, object_id)) - for variable in variables - variable in model_outputs || continue - _initialize_model_output_stream!( - streams, - compiled, - retention, - application, - object_id, - variable, - sizehint_steps, - ) - end - end - compiled.distributed_outputs isa CompiledDistributedOutputs || continue - groups = get( - compiled.distributed_outputs.by_execution_target, - (application_id, object_id), - nothing, - ) - isnothing(groups) && continue - for binding in values(groups) - for variable_ in keys(binding.declarations) - variable = Symbol(variable_) - variable in variables || continue - for destination_id in binding.destination_ids + _compiled_application_by_id(compiled, application_id) do application + model_outputs = keys(_local_output_schema(application.spec)) + if haskey(compiled.status_views_by_target, (application_id, object_id)) + for variable in variables + variable in model_outputs || continue _initialize_model_output_stream!( streams, compiled, retention, application, - destination_id, + object_id, variable, sizehint_steps, ) end end + compiled.distributed_outputs isa CompiledDistributedOutputs || return nothing + groups = get( + compiled.distributed_outputs.by_execution_target, + (application_id, object_id), + nothing, + ) + isnothing(groups) && return nothing + for binding in values(groups) + for variable_ in keys(binding.declarations) + variable = Symbol(variable_) + variable in variables || continue + for destination_id in binding.destination_ids + _initialize_model_output_stream!( + streams, + compiled, + retention, + application, + destination_id, + variable, + sizehint_steps, + ) + end + end + end end end return streams @@ -1961,22 +1967,23 @@ function _initialize_model_output_streams!( target_keys, ) for (application_id, variables) in retention.retained_outputs_by_application - application = _compiled_application_by_id(compiled, application_id) - for variable in variables - for object_id in _model_output_object_ids( - compiled, - application, - variable, - ) - _initialize_model_output_stream!( - streams, + _compiled_application_by_id(compiled, application_id) do application + for variable in variables + for object_id in _model_output_object_ids( compiled, - retention, application, - object_id, variable, - sizehint_steps, ) + _initialize_model_output_stream!( + streams, + compiled, + retention, + application, + object_id, + variable, + sizehint_steps, + ) + end end end end @@ -2046,7 +2053,7 @@ end "`$(expected_type)` to `$(typeof(value))`. CompositeModel temporal ", "streams require a stable output type.", ) - sample_time = float(time) + sample_time = Float64(time) _model_publish_sample!( stream, sample_time, @@ -2804,7 +2811,7 @@ end return RunContext( compiled, environment_bindings, application, object_id, calls, bound_inputs, output_targets, temporal_streams, output_retention, - float(time), constants, publication_allowed, environment, + Float64(time), constants, publication_allowed, environment, ) end runtime_changed = @@ -2871,54 +2878,6 @@ function _synchronize_model_execution_batch_contexts!( return nothing end -@inline function _run_model_execution_target_without_calls!( - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - application::CompiledModelApplication, - target::CompiledExecutionTarget, - time::Real, - constants, - temporal_streams, - output_retention, - sampled_environment, - publish_outputs::Bool, -) - status = isempty(target.input_bindings) ? - target.status_view.status : - _materialize_model_inputs!( - target.status_view.status, - target.input_bindings, - compiled, - application, - temporal_streams, - time, - ) - environment_value = sampled_environment isa UnspecifiedModelEnvironment ? - _model_environment_for_binding( - env_bindings, - application, - target.environment_binding, - time, - ) : sampled_environment - context = if target.context isa RunContext - target.context.time = time - target.context - else - _prepare_model_execution_context!( - nothing, compiled, env_bindings, application, target.object_id, - target.bound_inputs, target.output_targets, target.call_bindings, - temporal_streams, output_retention, time, constants, - true, _NO_ENVIRONMENT_OVERRIDE, - ) - end - run!(target.model, status, environment_value, constants, context) - if publish_outputs - isempty(target.output_bindings) || - _model_publish_runtime_outputs!(target.output_bindings, time) - end - return status -end - @inline function _run_model_execution_target!( compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, @@ -2930,19 +2889,9 @@ end output_retention, sampled_environment, publish_outputs::Bool, + performance::Union{Nothing,RuntimePerformanceCounters}=nothing, ) - isempty(target.call_bindings) && return _run_model_execution_target_without_calls!( - compiled, - env_bindings, - application, - target, - time, - constants, - temporal_streams, - output_retention, - sampled_environment, - publish_outputs, - ) + started_at = _runtime_performance_start(performance) status = isempty(target.input_bindings) ? target.status_view.status : _materialize_model_inputs!( @@ -2953,6 +2902,8 @@ end temporal_streams, time, ) + _runtime_performance_finish!(performance, :temporal_input_materialization, started_at) + started_at = _runtime_performance_start(performance) environment_value = sampled_environment isa UnspecifiedModelEnvironment ? _model_environment_for_binding( env_bindings, @@ -2960,6 +2911,7 @@ end target.environment_binding, time, ) : sampled_environment + _runtime_performance_finish!(performance, :environment_sampling, started_at) context = if target.context isa RunContext target.context.time = time target.context @@ -2981,10 +2933,14 @@ end _NO_ENVIRONMENT_OVERRIDE, ) end + started_at = _runtime_performance_start(performance) run!(target.model, status, environment_value, constants, context) + _runtime_performance_finish!(performance, :scientific_kernel_execution, started_at) if publish_outputs + started_at = _runtime_performance_start(performance) isempty(target.output_bindings) || _model_publish_runtime_outputs!(target.output_bindings, time) + _runtime_performance_finish!(performance, :output_publication, started_at) end return status end @@ -3045,14 +3001,17 @@ end constants, temporal_streams, output_retention, + performance::Union{Nothing,RuntimePerformanceCounters}=nothing, ) batch_time = float(time) + started_at = _runtime_performance_start(performance) shared_environment = _model_execution_batch_environment( batch.environment_provider, env_bindings, batch.application, time, ) + _runtime_performance_finish!(performance, :environment_sampling, started_at) _synchronize_model_execution_batch_contexts!( batch, compiled, @@ -3063,80 +3022,6 @@ end constants, ) publish_outputs = batch.output_publication.enabled - if isempty(first(batch.targets).call_bindings) - if isnothing(temporal_streams) - for target in batch.targets - _run_model_execution_target_without_calls!( - compiled, - env_bindings, - batch.application, - target, - batch_time, - constants, - temporal_streams, - output_retention, - shared_environment, - publish_outputs, - ) - end - return nothing - end - for target in batch.targets - status = isempty(target.input_bindings) ? - target.status_view.status : - _materialize_model_inputs!( - target.status_view.status, - target.input_bindings, - compiled, - batch.application, - temporal_streams, - time, - ) - environment_value = shared_environment isa UnspecifiedModelEnvironment ? - _model_environment_for_binding( - env_bindings, - batch.application, - target.environment_binding, - time, - ) : shared_environment - context = target.context - if context isa RunContext - context.time = batch_time - else - context = _prepare_model_execution_context!( - context, - compiled, - env_bindings, - batch.application, - target.object_id, - target.bound_inputs, - target.output_targets, - target.call_bindings, - temporal_streams, - output_retention, - batch_time, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, - ) - end - run!( - target.model, - status, - environment_value, - constants, - context, - ) - if publish_outputs - isempty(target.output_bindings) || - _model_publish_runtime_outputs!( - target.output_bindings, - time, - ) - end - end - return nothing - end for target in batch.targets _run_model_execution_target!( compiled, @@ -3149,123 +3034,7 @@ end output_retention, shared_environment, publish_outputs, - ) - end - return nothing -end - -function _run_model_execution_batch_profiled!( - batch::CompiledExecutionBatch, - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - time::Real, - constants, - temporal_streams, - output_retention, - performance::RuntimePerformanceCounters, -) - batch_time = float(time) - started_at = _runtime_performance_start(performance) - shared_environment = _model_execution_batch_environment( - batch.environment_provider, - env_bindings, - batch.application, - time, - ) - _runtime_performance_finish!( - performance, - :environment_sampling, - started_at, - ) - _synchronize_model_execution_batch_contexts!( - batch, - compiled, - env_bindings, - temporal_streams, - output_retention, - batch_time, - constants, - ) - publish_outputs = batch.output_publication.enabled - for target in batch.targets - started_at = _runtime_performance_start(performance) - status = isempty(target.input_bindings) ? - target.status_view.status : - _materialize_model_inputs!( - target.status_view.status, - target.input_bindings, - compiled, - batch.application, - temporal_streams, - time, - ) - _runtime_performance_finish!( performance, - :temporal_input_materialization, - started_at, - ) - - started_at = _runtime_performance_start(performance) - environment_value = - shared_environment isa UnspecifiedModelEnvironment ? - _model_environment_for_binding( - env_bindings, - batch.application, - target.environment_binding, - time, - ) : shared_environment - _runtime_performance_finish!( - performance, - :environment_sampling, - started_at, - ) - - context = if target.context isa RunContext - target.context.time = batch_time - target.context - else - _prepare_model_execution_context!( - target.context, - compiled, - env_bindings, - batch.application, - target.object_id, - target.bound_inputs, - target.output_targets, - target.call_bindings, - temporal_streams, - output_retention, - batch_time, - constants, - true, - _NO_ENVIRONMENT_OVERRIDE, - ) - end - started_at = _runtime_performance_start(performance) - run!( - target.model, - status, - environment_value, - constants, - context, - ) - _runtime_performance_finish!( - performance, - :scientific_kernel_execution, - started_at, - ) - - publish_outputs || continue - started_at = _runtime_performance_start(performance) - isempty(target.output_bindings) || - _model_publish_runtime_outputs!( - target.output_bindings, - time, - ) - _runtime_performance_finish!( - performance, - :output_publication, - started_at, ) end return nothing @@ -4846,20 +4615,20 @@ function _model_output_retention_covers_binding( binding, ) plan.retain_all && return true - consumer = _compiled_application_by_id(compiled, binding.application_id) - for application_id in binding.source_application_ids - source = _compiled_application_by_id(compiled, application_id) - required = _model_temporal_retention_horizon( - binding, - consumer, - source, - compiled.scenario_plan.timeline, - ) - key = (application_id, binding.source_var) - key in plan.temporal_dependencies || return false - get(plan.dependency_horizons, key, -Inf) >= required || return false + return _compiled_application_by_id(compiled, binding.application_id) do consumer + for source_application_id in binding.source_application_ids + covered = _compiled_application_by_id(compiled, source_application_id) do source + required = _model_temporal_retention_horizon( + binding, consumer, source, compiled.scenario_plan.timeline, + ) + key = (source_application_id, binding.source_var) + key in plan.temporal_dependencies && + get(plan.dependency_horizons, key, -Inf) >= required + end + covered || return false + end + return true end - return true end function _model_output_retention_covers_addition( @@ -4964,24 +4733,19 @@ function compile_model_output_retention( timeline = compiled.scenario_plan.timeline for binding in compiled.input_bindings binding.carrier_hint == :temporal_stream || continue - consumer = _compiled_application_by_id(compiled, binding.application_id) - for application_id in binding.source_application_ids - source = _compiled_application_by_id(compiled, application_id) - required = _model_temporal_retention_horizon( - binding, - consumer, - source, - timeline, - ) - key = (application_id, binding.source_var) - push!( - temporal_dependencies, - key, - ) - dependency_horizons[key] = max( - get(dependency_horizons, key, 0.0), - required, - ) + _compiled_application_by_id(compiled, binding.application_id) do consumer + for source_application_id in binding.source_application_ids + _compiled_application_by_id(compiled, source_application_id) do source + required = _model_temporal_retention_horizon( + binding, consumer, source, timeline, + ) + key = (source_application_id, binding.source_var) + push!(temporal_dependencies, key) + dependency_horizons[key] = max( + get(dependency_horizons, key, 0.0), required, + ) + end + end end end @@ -5004,14 +4768,15 @@ function compile_model_output_retention( end retained_outputs_by_application = Dict{Symbol,Vector{Symbol}}() retained_keys = if retain_all - Set( - (application.id, variable) - for application in compiled.applications - for variable in _model_application_output_variables( - compiled, - application, - ) - ) + all_outputs = Set{Tuple{Symbol,Symbol}}() + for retained_application_id in keys(compiled.applications_by_id) + _compiled_application_by_id(compiled, retained_application_id) do application + for variable in _model_application_output_variables(compiled, application) + push!(all_outputs, (application.id, variable)) + end + end + end + all_outputs else union(temporal_dependencies, requested_outputs) end @@ -5036,14 +4801,15 @@ end function _explain_output_retention(compiled::CompiledCompositeModel, plan) keys_to_explain = if plan.retain_all - Set( - (application.id, variable) - for application in compiled.applications - for variable in _model_application_output_variables( - compiled, - application, - ) - ) + all_outputs = Set{Tuple{Symbol,Symbol}}() + for retained_application_id in keys(compiled.applications_by_id) + _compiled_application_by_id(compiled, retained_application_id) do application + for variable in _model_application_output_variables(compiled, application) + push!(all_outputs, (application.id, variable)) + end + end + end + all_outputs else union(plan.temporal_dependencies, plan.requested_outputs) end @@ -7558,7 +7324,7 @@ end :application_groups_considered, ) for batch in group.batches - _run_model_execution_batch_profiled!( + _run_model_execution_batch!( batch, simulation.compiled, simulation.environment_bindings, diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index d3213fb64..b94888078 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -199,6 +199,13 @@ Sample one environmental variable through an opaque compiled backend `handle`. The four-argument method reads the backend's committed state. The five-argument method reads a transient backend-specific `state` supplied through `run_call!(context, name; environment=state)`. + +`time` is an index on the simulation's base-step clock. Per-target backend +sampling uses `float(step)` consistently, independently of output retention and +performance instrumentation. Global forcing rows retain their scheduler-step +lookup. Backends should accept an appropriate `Real` clock; normalization +preserves floating representations such as `Float32`. Hard calls use the +floating clock captured by their runtime context. """ function sample(backend::AbstractEnvironmentBackend, handle, variable::Symbol, time) error( diff --git a/test/runtests.jl b/test/runtests.jl index 0a8bef9a0..6b6b44526 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -83,8 +83,10 @@ else include("test-model-prepared-scenario.jl") include("test-model-scenario-authoring.jl") include("test-model-authored-call-plans.jl") + include("test-model-authored-spec-matching.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") + include("test-model-output-retention-owners.jl") include("test-input-default-values.jl") include("test-application-membership-slots.jl") include("test-registered-status-dispatch.jl") @@ -267,6 +269,7 @@ else @testset "Composite model environment sampling" begin include("test-model-environment-sampling.jl") + include("test-model-execution-batch-times.jl") include("test-model-environment-binding-identity.jl") include("test-model-global-environment-sample-schema.jl") end diff --git a/test/test-model-authored-spec-matching.jl b/test/test-model-authored-spec-matching.jl new file mode 100644 index 000000000..5ccd3c52f --- /dev/null +++ b/test/test-model-authored-spec-matching.jl @@ -0,0 +1,124 @@ +module AuthoredSpecMatchChecks + +using Test, PlantSimEngine +const PSE=PlantSimEngine +PSE.@process "authored_spec_match" verbose=false +struct MatchModel{P,R,G} <: AbstractAuthored_Spec_MatchModel + parameters::P + declaration_reads::R + parameter_getters::G +end +function Base.getproperty(model::MatchModel,name::Symbol) + name===:parameters && (getfield(model,:parameter_getters)[]+=1) + return getfield(model,name) +end +PSE.inputs_(::MatchModel)=NamedTuple() +function PSE.outputs_(model::MatchModel) + getfield(model,:declaration_reads)[]+=1 + return (x=0f0,) +end +PSE.run!(::MatchModel,status,environment,constants,context)=nothing +function fixture(count=40) + reads=Ref(0);getters=Ref(0) + # Different large immutable layouts expose tuple headers escaping through + # heterogeneous iteration, as encountered in real downstream models. + specs=Any[ModelSpec(MatchModel(ntuple(Float64,512+(index%8)),reads,getters); + name=Symbol(:app_,index),on=Many(scale=:Leaf),output_routing=(x=:stream_only,)) + for index in 1:count] + model=CompositeModel(Object(:leaf;scale=:Leaf,status=Status(seed=1f0));applications=specs) + return (;model,reads,getters) +end +function cached_matches!(model,count) + for _ in 1:count + preparation=PSE._scenario_preparation(model) + PSE._validate_authored_scenario(preparation) + end + return nothing +end + +@testset "Heterogeneous live authoring declarations" begin + data=fixture();model=data.model + preparation=model.scenario_plan_cache + reads=data.reads[];getters=data.getters[] + @test length(unique(typeof(spec) for spec in model.applications))==8 + @test PSE._authored_specs_match(preparation,model) + cached_matches!(model,100) + cached_matches!(model,100) + bytes=@allocated cached_matches!(model,100) + @test bytes==0 + @test data.reads[]==reads + @test data.getters[]==getters + @test model.scenario_plan_cache===preparation + @test model_status(model,:leaf).seed===1f0 + + first_spec=model.applications[1] + replacement=ModelSpec(MatchModel(ntuple(Float64,520),data.reads,data.getters); + name=:app_1,on=Many(scale=:Leaf),output_routing=(x=:stream_only,)) + before_reads=data.reads[];before_getters=data.getters[] + model.applications[1]=replacement + @test !PSE._authored_specs_match(preparation,model) + @test data.reads[]==before_reads && data.getters[]==before_getters + model.applications[1]=first_spec + @test PSE._authored_specs_match(preparation,model) + same_type_replacement=ModelSpec(MatchModel(ntuple(i->Float64(i)+1,513),data.reads,data.getters); + name=:app_1,on=Many(scale=:Leaf),output_routing=(x=:stream_only,)) + @test typeof(same_type_replacement)===typeof(first_spec) + model.applications[1]=same_type_replacement + @test !PSE._authored_specs_match(preparation,model) + model.applications[1]=first_spec + @test PSE._authored_specs_match(preparation,model) + reverse!(model.applications) + @test !PSE._authored_specs_match(preparation,model) + reverse!(model.applications) + push!(model.applications,first_spec) + @test !PSE._authored_specs_match(preparation,model) + pop!(model.applications) + @test PSE._authored_specs_match(preparation,model) + + # A real changed declaration must rebuild; the new spec then matches live. + model.applications[1]=replacement + refreshed=PSE._scenario_preparation(model) + @test refreshed!==preparation + @test PSE._authored_specs_match(refreshed,model) + before_force=data.reads[] + forced=PSE._scenario_preparation(model;force=true) + @test forced!==refreshed + @test data.reads[]>before_force + @test PSE._authored_specs_match(forced,model) + @test model_status(model,:leaf).seed===1f0 +end + +@testset "Authoring owner reconstruction and independent copy" begin + data=fixture(8);original=data.model + preparation=original.scenario_plan_cache + old_snapshot=PSE._prepare_scenario_plan(original) + @test preparation.resolved===old_snapshot + other=CompositeModel(Object(:leaf;scale=:Leaf,status=Status(seed=1f0)); + applications=copy(original.applications)) + before=data.reads[];before_getters=data.getters[] + other.scenario_plan_cache=preparation + owned=PSE._scenario_preparation(other) + @test owned!==preparation + @test owned.owner===other + @test owned.resolved===nothing + @test PSE._authored_specs_match(owned,other) + @test data.reads[]==before && data.getters[]==before_getters + @test original.scenario_plan_cache===preparation + @test preparation.owner===original + @test preparation.resolved===old_snapshot + copied=deepcopy(original) + copied_owner=PSE._scenario_preparation(copied) + @test copied_owner.owner===copied + @test copied_owner!==preparation + @test PSE._authored_specs_match(copied_owner,copied) + copied.applications[1]=copied.applications[2] + @test !PSE._authored_specs_match(copied_owner,copied) + @test PSE._authored_specs_match(preparation,original) +end + +@testset "Empty authoring declarations" begin + model=CompositeModel(Object(:empty;status=Status(seed=1))) + @test PSE._authored_specs_match(PSE._scenario_preparation(model),model) +end + +end diff --git a/test/test-model-execution-batch-times.jl b/test/test-model-execution-batch-times.jl new file mode 100644 index 000000000..387bc8200 --- /dev/null +++ b/test/test-model-execution-batch-times.jl @@ -0,0 +1,181 @@ +module ExecutionBatchTimeChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +struct WrappedTime <: Real + value::Float32 +end +Base.float(time::WrappedTime) = time.value +mutable struct Backend <: EA.AbstractEnvironmentBackend + samples::Vector{Symbol} +end +EA.base_step_seconds(::Backend) = 1.0 +EA.get_nsteps(::Backend) = 8 +EA.environment_variables(::Backend) = Set((:T,)) +EA.bind_environment(::Backend, object::Object, context, config) = nothing +function sample_value(backend, kind, value) + push!(backend.samples, kind) + return value +end +EA.sample(backend::Backend, handle, variable::Symbol, ::Integer) = + sample_value(backend, :integer, 10.0f0) +EA.sample(backend::Backend, handle, variable::Symbol, ::Float32) = + sample_value(backend, :float32, 20.0f0) +EA.sample(backend::Backend, handle, variable::Symbol, ::Float64) = + sample_value(backend, :float64, 30.0f0) +EA.sample(backend::Backend, handle, variable::Symbol, ::WrappedTime) = + sample_value(backend, :wrapped, 40.0f0) + +PSE.@process "execution_time_source" verbose=false +PSE.@process "execution_time_consumer" verbose=false +PSE.@process "execution_time_controller" verbose=false +PSE.@process "execution_time_leaf" verbose=false +struct Source <: AbstractExecution_Time_SourceModel end +struct Consumer <: AbstractExecution_Time_ConsumerModel end +struct Controller <: AbstractExecution_Time_ControllerModel end +struct Leaf <: AbstractExecution_Time_LeafModel end +PSE.inputs_(::Union{Source,Controller,Leaf}) = NamedTuple() +PSE.inputs_(::Consumer) = (signal=Required(Float32),) +PSE.outputs_(::Source) = (signal=0.0f0, env_tag=0.0f0, context_time=0.0) +PSE.outputs_(::Consumer) = (observed=0.0f0, env_tag=0.0f0, context_time=0.0) +PSE.outputs_(::Union{Controller,Leaf}) = (seen=0.0f0, calls=0, context_time=0.0) +PSE.environment_inputs_(::Union{Source,Consumer,Controller,Leaf}) = (T=0.0f0,) +function PSE.run!(::Source, status, environment, constants, context) + status.signal += environment.T + status.env_tag = environment.T + status.context_time = context.time + return nothing +end +function PSE.run!(::Consumer, status, environment, constants, context) + status.observed = status.signal + status.env_tag = environment.T + status.context_time = context.time + return nothing +end +function PSE.run!(::Controller, status, environment, constants, context) + status.seen = environment.T + status.calls += 1 + status.context_time = context.time + run_call!(context, :leaf; publish=true) + return nothing +end +function PSE.run!(::Leaf, status, environment, constants, context) + status.seen = environment.T + status.calls += 1 + status.context_time = context.time + return nothing +end +function temporal_fixture(performance) + backend = Backend(Symbol[]) + model = CompositeModel(Object(:source; scale=:Source, status=Status(signal=0.0f0)), + Object(:consumer; scale=:Consumer, status=Status(signal=0.0f0)); + applications=( + ModelSpec(Source(); name=:source, on=One(id=:source)), + ModelSpec(Consumer(); name=:consumer, on=One(id=:consumer), + inputs=(PreviousTimeStep(:signal) => One(SceneScope(); id=:source, application=:source, var=:signal))), + ), environment=backend) + simulation = run!(model; steps=3, outputs=:all, performance) + return (; model, simulation, backend) +end +batch_for(simulation, application) = only(batch for batch in simulation.execution_plan.batches + if batch.application.id === application) +function execute_prepared!(data, application, time) + simulation = data.simulation + return PSE._run_model_execution_batch!(batch_for(simulation, application), + simulation.compiled, simulation.environment_bindings, time, + simulation.constants, simulation.temporal_streams, simulation.output_retention, + simulation.performance) +end + +@testset "one batch loop preserves temporal materialization and output publication" begin + for performance in (false, true) + data = temporal_fixture(performance) + @test data.backend.samples == fill(:float64, 6) + @test outputs(data.simulation)[(:source, ObjectId(:source), :signal)] == + [(1.0, 30.0f0), (2.0, 60.0f0), (3.0, 90.0f0)] + @test outputs(data.simulation)[(:consumer, ObjectId(:consumer), :observed)] == + [(1.0, 0.0f0), (2.0, 30.0f0), (3.0, 60.0f0)] + @test model_status(data.model, :source).context_time === 3.0 + @test model_status(data.model, :consumer).context_time === 3.0 + execute_prepared!(data, :source, 4.0f0) + execute_prepared!(data, :consumer, 4.0f0) + @test data.backend.samples[end-1:end] == [:float32, :float32] + @test model_status(data.model, :source).signal === 110.0f0 + @test model_status(data.model, :consumer).observed === 90.0f0 + @test model_status(data.model, :consumer).env_tag === 20.0f0 + @test model_status(data.model, :consumer).context_time === 4.0 + @test last(outputs(data.simulation)[(:consumer, ObjectId(:consumer), :observed)]) == (4.0, 90.0f0) + # float(time) defines the prepared clock without requiring a direct + # Float64 conversion from an arbitrary Real wrapper. Float32 is kept + # for model-facing sampling and converted only in context storage. + execute_prepared!(data, :source, WrappedTime(5.0f0)) + @test last(data.backend.samples) === :float32 + @test model_status(data.model, :source).signal === 130.0f0 + @test model_status(data.model, :source).context_time === 5.0 + @test last(outputs(data.simulation)[(:source, ObjectId(:source), :signal)]) == (5.0, 130.0f0) + if performance + counters = PSE.Advanced.runtime_performance(data.simulation) + @test all(haskey(counters.elapsed_seconds, metric) for metric in ( + :temporal_input_materialization, :environment_sampling, + :scientific_kernel_execution, :output_publication)) + end + end +end + +@testset "prepared batches without temporal storage retain their context factory" begin + backend = Backend(Symbol[]) + model = CompositeModel(Object(:source; scale=:Source, status=Status(signal=0.0f0)); + applications=(ModelSpec(Source(); name=:source, on=One(id=:source)),), environment=backend) + compiled = PSE.Advanced.refresh_bindings!(model) + environment = PSE.Advanced.refresh_environment_bindings!(model, compiled) + plan = PSE.compile_model_execution_plan(compiled, environment) + batch = only(plan.batches) + @test isnothing(only(batch.targets).context) + PSE._run_model_execution_batch!(batch, compiled, environment, 1, nothing, nothing, nothing) + @test backend.samples == [:float64] + @test model_status(model, :source).signal === 30.0f0 + @test model_status(model, :source).context_time === 1.0 + PSE._run_model_execution_batch!(batch, compiled, environment, 2.0f0, nothing, nothing, nothing) + @test last(backend.samples) === :float32 + @test model_status(model, :source).signal === 50.0f0 + @test model_status(model, :source).context_time === 2.0 +end + +@testset "ordinary controllers retain their hard-call clocks and publication" begin + for performance in (false, true) + backend = Backend(Symbol[]) + model = CompositeModel(Object(:owner; scale=:Scene), Object(:leaf; scale=:Leaf, parent=:owner); + applications=( + ModelSpec(Controller(); name=:controller, on=One(id=:owner), + calls=(leaf=One(id=:leaf, application=:leaf),)), + ModelSpec(Leaf(); name=:leaf, on=One(id=:leaf)), + ), environment=backend) + simulation = run!(model; steps=2, outputs=:all, performance) + @test backend.samples == fill(:float64, 4) + @test model_status(model, :owner).seen === 30.0f0 + @test model_status(model, :owner).calls == 2 + @test model_status(model, :leaf).seen === 30.0f0 + @test model_status(model, :leaf).calls == 2 + @test model_status(model, :leaf).context_time === 2.0 + @test outputs(simulation)[(:leaf, ObjectId(:leaf), :seen)] == [(1.0, 30.0f0), (2.0, 30.0f0)] + end +end + +@testset "public retention choice does not change sampling dispatch" begin + values = Float32[] + sampled_kinds = Vector{Symbol}[] + for retained in (:none, :all) + backend = Backend(Symbol[]) + model = CompositeModel(Object(:source; scale=:Source); + applications=(ModelSpec(Source(); name=:source, on=One(id=:source)),), environment=backend) + simulation = run!(model; steps=1, outputs=retained) + @test simulation.temporal_streams isa PSE.RuntimeStorage + push!(values, model_status(model, :source).signal) + push!(sampled_kinds, backend.samples) + end + @test values[1] === values[2] + @test sampled_kinds == [[:float64], [:float64]] + @test values == [30.0f0, 30.0f0] +end +end diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl new file mode 100644 index 000000000..06008d213 --- /dev/null +++ b/test/test-model-output-retention-owners.jl @@ -0,0 +1,173 @@ +module OutputRetentionOwnerChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "retention_owner_writer" verbose=false +PSE.@process "retention_owner_reader" verbose=false +PSE.@process "retention_owner_distributor" verbose=false + +struct Writer <: AbstractRetention_Owner_WriterModel end +PSE.inputs_(::Writer) = NamedTuple() +PSE.outputs_(::Writer) = (live=0f0, private=0f0) +function PSE.run!(::Writer, status, environment, constants, context) + status.live = Float32(context.time) + status.private = 2f0 * status.live + return nothing +end + +struct Reader <: AbstractRetention_Owner_ReaderModel end +PSE.inputs_(::Reader) = (lag=Default(Float32[]),) +PSE.outputs_(::Reader) = (seen=0f0,) +PSE.run!(::Reader, status, environment, constants, context) = + (status.seen = sum(status.lag; init=0f0); nothing) + +function local_scene(; temporal=false) + specs = (ModelSpec(Writer(); name=:writer, on=Many(scale=:Leaf), + output_routing=(private=:stream_only,)),) + if temporal + specs = (specs..., ModelSpec(Reader(); name=:reader, on=One(id=0), + inputs=(PreviousTimeStep(:lag) => Many(SceneScope(); scale=:Leaf, + application=:writer, var=:private),))) + end + return CompositeModel(Object(0; scale=:Scene), Object(1; scale=:Leaf, parent=0); + applications=specs) +end + +stream(simulation, application, id, variable) = + simulation.temporal_streams[(application, ObjectId(id), variable)] + +@testset "callback lookup preserves identity and missing-application diagnostics" begin + simulation = run!(local_scene(); steps=0, outputs=:none) + compiled = simulation.compiled + application = compiled.applications_by_id[:writer] + @test PSE._compiled_application_by_id(compiled, :writer) === application + @test PSE._compiled_application_by_id(identity, compiled, :writer) === application + @test PSE._compiled_application_by_id(compiled, :writer) do selected + selected.id === :writer && selected.plan === application.plan + end + error = try + PSE._compiled_application_by_id(identity, compiled, :missing) + nothing + catch exception + exception + end + @test error isa ErrorException + @test sprint(showerror, error) == "No compiled model application with id `missing`." + @test current_step(simulation) == 0 +end + +@testset "none, all and selective local retention keep stream-only ownership and removed history" begin + request = OutputRequest(Many(scale=:Leaf), :private; name=:chosen, application=:writer) + for selection in (:none, :all, request) + simulation = run!(local_scene(); steps=2, outputs=selection) + @test model_status(simulation.model, 1).live === 2f0 + @test !hasproperty(model_status(simulation.model, 1), :private) + retained = simulation.output_retention + @test eltype(retained.temporal_dependencies) === Tuple{Symbol,Symbol} + @test eltype(retained.requested_outputs) === Tuple{Symbol,Symbol} + if selection === :none + @test isempty(simulation.temporal_streams) + else + @test stream(simulation, :writer, 1, :private) == [(1.0, 2f0), (2.0, 4f0)] + @test haskey(simulation.temporal_streams, (:writer, ObjectId(1), :live)) == + (selection === :all) + end + register_object!(simulation.model, Object(2; scale=:Leaf, parent=0)) + step!(simulation) + @test model_status(simulation.model, 2).live === 3f0 + @test !hasproperty(model_status(simulation.model, 2), :private) + old_history = selection === :none ? nothing : stream(simulation, :writer, 1, :private) + before_removal = isnothing(old_history) ? nothing : copy(old_history) + remove_object!(simulation.model, 1) + step!(simulation) + @test model_status(simulation.model, 2).live === 4f0 + if selection === :none + @test isempty(simulation.temporal_streams) + else + @test stream(simulation, :writer, 1, :private) === old_history + @test old_history == before_removal + @test stream(simulation, :writer, 2, :private) == [(3.0, 6f0), (4.0, 8f0)] + end + end +end + +@testset "dependency-only temporal streams survive source growth and removal" begin + simulation = run!(local_scene(; temporal=true); steps=2, outputs=:none) + @test model_status(simulation.model, 0).seen === 2f0 + original_retention = simulation.output_retention + @test (:writer, :private) in original_retention.temporal_dependencies + @test isempty(original_retention.requested_outputs) + @test stream(simulation, :writer, 1, :private) isa PSE.TemporalDependencyBuffer{Float32} + register_object!(simulation.model, Object(2; scale=:Leaf, parent=0)) + continue!(simulation; steps=2) + @test model_status(simulation.model, 0).seen === 12f0 + @test PSE._model_output_retention_covers_addition(simulation.output_retention, simulation.compiled) + @test simulation.output_retention === original_retention + first_history = stream(simulation, :writer, 1, :private) + removed_samples = collect(first_history) + remove_object!(simulation.model, 1) + step!(simulation) + @test model_status(simulation.model, 0).seen === 8f0 + @test stream(simulation, :writer, 1, :private) === first_history + @test collect(first_history) == removed_samples + @test stream(simulation, :writer, 2, :private) isa PSE.TemporalDependencyBuffer{Float32} +end + +struct Distributor <: AbstractRetention_Owner_DistributorModel end +PSE.inputs_(::Distributor) = NamedTuple() +PSE.outputs_(::Distributor) = (delivered=Distributed(Default(0f0)),) +function PSE.run!(::Distributor, status, environment, constants, context) + destinations = output_targets(context, (:delivered,)) + for index in eachindex(object_ids(destinations)) + destinations.columns.delivered[index] = Float32(context.time) + end + return nothing +end +function distributed_scene(; with_leaf=true) + objects = with_leaf ? (Object(0; scale=:Scene), Object(1; scale=:Leaf, parent=0)) : + (Object(0; scale=:Scene),) + return CompositeModel(objects...; applications=( + ModelSpec(Distributor(); name=:distributed, on=One(id=0), + outputs_to=(OutputTo(Many(Subtree(); scale=:Leaf); vars=(:delivered,)),)),)) +end + +@testset "distributed destinations keep none/all/selective retention and removed samples" begin + request = OutputRequest(Many(scale=:Leaf), :delivered; + name=:distributed_values, application=:distributed) + for selection in (:none, :all, request) + simulation = run!(distributed_scene(); steps=2, outputs=selection) + register_object!(simulation.model, Object(2; scale=:Leaf, parent=0)) + step!(simulation) + @test model_status(simulation.model, 1).delivered === 3f0 + @test model_status(simulation.model, 2).delivered === 3f0 + old_history = selection === :none ? nothing : stream(simulation, :distributed, 1, :delivered) + removed_samples = isnothing(old_history) ? nothing : copy(old_history) + remove_object!(simulation.model, 1) + step!(simulation) + @test model_status(simulation.model, 2).delivered === 4f0 + if selection === :none + @test isempty(simulation.temporal_streams) + else + @test stream(simulation, :distributed, 1, :delivered) === old_history + @test old_history == removed_samples + @test stream(simulation, :distributed, 2, :delivered) == [(3.0, 3f0), (4.0, 4f0)] + end + end +end + +@testset "initially empty distributed declarations still retain future outputs" begin + simulation = run!(distributed_scene(; with_leaf=false); steps=0, outputs=:all) + @test simulation.output_retention.retained_outputs_by_application[:distributed] == [:delivered] + @test isempty(simulation.temporal_streams) + register_object!(simulation.model, Object(1; scale=:Leaf, parent=0)) + step!(simulation) + @test stream(simulation, :distributed, 1, :delivered) == [(1.0, 1f0)] + retained_stream = stream(simulation, :distributed, 1, :delivered) + PSE._initialize_model_output_streams!(simulation.temporal_streams, simulation.compiled, + simulation.output_retention, 0, [(:distributed, ObjectId(0))]) + @test stream(simulation, :distributed, 1, :delivered) === retained_stream + @test retained_stream == [(1.0, 1f0)] +end + +end From 6d7a08465a7ede97b7473931c043d6dc4282d993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 00:31:42 +0100 Subject: [PATCH 015/324] Keep prepared owners authoritative across lifecycle refresh --- .../guides/extensions/environment_backends.md | 11 +- src/composite_model/compilation.jl | 244 +++++++++++++---- src/composite_model/environment_bindings.jl | 2 + src/composite_model/registry_topology.jl | 89 +----- src/composite_model/runtime_outputs.jl | 35 ++- src/composite_model/selectors.jl | 24 +- src/time/runtime/environment_backends.jl | 7 +- src/visualization/model_graph_view.jl | 25 +- test/runtests.jl | 2 + test/test-model-api-stabilization.jl | 17 +- test/test-model-authored-spec-matching.jl | 176 ++++++------ ...est-model-diagnostic-authoring-recovery.jl | 54 ++++ test/test-model-prepared-authoring-owner.jl | 153 +++++++++++ test/test-model-public-refresh-owners.jl | 259 ++++++++++++++++++ 14 files changed, 835 insertions(+), 263 deletions(-) create mode 100644 test/test-model-prepared-authoring-owner.jl create mode 100644 test/test-model-public-refresh-owners.jl diff --git a/docs/src/guides/extensions/environment_backends.md b/docs/src/guides/extensions/environment_backends.md index 15daabc5f..e86f59dcd 100644 --- a/docs/src/guides/extensions/environment_backends.md +++ b/docs/src/guides/extensions/environment_backends.md @@ -25,12 +25,11 @@ The required methods are: - `sample(backend, handle, variable, time)`: read a value from the stored, accepted environment state. -The `time` argument is an index on the simulation's base-step clock. Per-target -backend sampling uses `float(step)` with the same clock when outputs or -performance counters are enabled. Global forcing tables select their row from -the scheduler step. Hard calls use the floating clock saved by their runtime -context. Accept a suitable `Real` argument in backend methods; floating -representations such as `Float32` are preserved. +The `time` argument is an index on the simulation's base-step clock. Scheduled +targets use `float(step)` (`Float64` with the ordinary scheduler), independently +of retained outputs and performance counters. Global forcing tables select +their row from the scheduler step. Hard calls use the `Float64` clock saved by +their runtime context. Accept a suitable `Real` argument in backend methods. Implement `environment_variables(backend)` if you can list the available variable names without an expensive calculation. PlantSimEngine can then diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f4c21418e..8700c9eb2 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -649,29 +649,6 @@ function _compiled_application_schedule( ) end -""" -Immutable application, dependency-declaration, and timeline metadata shared by -every lifecycle refresh of a compiled scenario. -""" -struct CompiledScenarioPlan{AP,AI,ATI,IP,IPI,IR,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL} - applications::AP - applications_by_id::AI - application_target_candidates::ATI - input_plans::IP - input_plans_by_application::IPI - input_recipes_by_application::IR - call_plans::CP - call_plans_by_application::CPI - distributed_output_plans::DOP - call_owners::CO - manual_application_ids::MA - application_children::AC - application_order::AO - ordered_application_plans::OAP - application_schedule::AS - timeline::TL -end - # Authoring records contain declarations, never current target identities, # status values, resolved overrides, clocks, or simulation-owned storage. struct AuthoredApplicationRecipe{S,M,H,ON,CN,CP} @@ -719,6 +696,42 @@ mutable struct ScenarioPreparation{M,S,A,F} resolved::Any end +# Preserve the genuine owner, without copying its source tuple or encoding the +# result types of declaration hooks in every runtime plan. Lifecycle refresh +# needs only the owner identity and the immutable source-declaration schema. +struct CompiledScenarioAuthoring{M,S} + preparation::ScenarioPreparation{M,S} + + function CompiledScenarioAuthoring(preparation::ScenarioPreparation{M,S}) where {M,S} + return new{M,S}(preparation) + end +end + +""" +Immutable application, dependency-declaration, and timeline metadata shared by +every lifecycle refresh of a compiled scenario. +""" +struct CompiledScenarioPlan{SA,AP,AI,ATI,IP,IPI,IR,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL} + authoring::SA + applications::AP + applications_by_id::AI + application_target_candidates::ATI + input_plans::IP + input_plans_by_application::IPI + input_recipes_by_application::IR + call_plans::CP + call_plans_by_application::CPI + distributed_output_plans::DOP + call_owners::CO + manual_application_ids::MA + application_children::AC + application_order::AO + ordered_application_plans::OAP + application_schedule::AS + timeline::TL +end + + function _authored_specs_match(source_specs, specs) length(source_specs) == length(specs) || return false return all(pair -> pair[1] === pair[2], zip(source_specs, specs)) @@ -871,11 +884,11 @@ function _authored_application_recipes(preparation::ScenarioPreparation) return preparation.authored end -function _authored_application_recipes(model::CompositeModel, raw_specs) +function _scenario_preparation(model::CompositeModel, raw_specs) if _authored_specs_match(model.applications, raw_specs) - return _authored_application_recipes(_scenario_preparation(model)) + return _scenario_preparation(model) end - return _authored_application_recipes(_prepare_authored_scenario(model, raw_specs)) + return _prepare_authored_scenario(model, raw_specs) end # The snapshot owns its target lists. Runtime application membership can @@ -1386,6 +1399,7 @@ end function _compiled_scenario_plan( model::CompositeModel, + preparation::ScenarioPreparation, applications, input_plans, call_plans, @@ -1430,6 +1444,7 @@ function _compiled_scenario_plan( ) input_plans_by_application = _plans_by_application(applications, input_plans) return CompiledScenarioPlan( + CompiledScenarioAuthoring(preparation), application_plans, application_plans_by_id, _application_target_candidate_index(model, application_plans), @@ -1750,6 +1765,112 @@ mutable struct CompiledCompositeModel{SC,SP,AP,AI,OA,ABO,IB,CB,IBI,CBI,DBI,DCBI, execution_generation::UInt64 end +# Public configuration refresh is the authoring boundary. It selects one +# genuine preparation, then gives the shared worker a resolved snapshot only +# when the existing lifecycle metadata cannot be extended. +function refresh_bindings!( + model::CompositeModel, + specs=model.applications; + force::Bool=false, + performance=nothing, +) + specs === model.applications || return compile_composite_model(model, specs; performance) + preparation = _scenario_preparation(model; force) + _validate_authored_scenario(preparation) + previous = model.binding_cache + prepared = preparation.resolved + owner_changed = !isnothing(previous) && + previous.scenario_plan.authoring.preparation !== preparation + if owner_changed || _binding_refresh_required(model, previous, prepared, force) + if owner_changed || !_can_extend_binding_refresh(model, previous, prepared, force) + if owner_changed || isnothing(prepared) + plan, applications = _resolve_prepared_scenario( + model, preparation, _model_timeline(model); performance, + ) + prepared = PreparedScenario(plan, + Vector{ObjectId}[application.target_ids for application in applications]) + end + end + end + return _refresh_prepared_bindings!(model, previous, prepared; force, performance) +end + +_binding_refresh_required(model, previous, prepared, force) = + force || model.bindings_dirty || isnothing(previous) || + (!isnothing(prepared) && prepared.plan !== previous.scenario_plan) + +function _can_extend_binding_refresh(model, previous, prepared, force) + delta = model.lifecycle_delta + return !force && isnothing(prepared) && !isnothing(previous) && + !isempty(delta.structural_dirty_ids) && + delta.structural_kind in (:addition, :structural) +end + +# This is the sole binding refresh algorithm. Its inputs are already-owned +# declaration metadata and live membership; it does not invoke author hooks. +function _refresh_prepared_bindings!( + model::CompositeModel, previous, prepared; + force::Bool=false, performance=nothing, +) + _binding_refresh_required(model, previous, prepared, force) || return previous + delta = model.lifecycle_delta + dirty_object_ids = delta.structural_dirty_ids + can_extend = _can_extend_binding_refresh(model, previous, prepared, force) + if can_extend && delta.structural_kind === :addition + refreshed = _extend_compiled_scene(model, previous, dirty_object_ids; performance) + elseif can_extend && delta.structural_kind === :structural + structural = _prepare_structural_compiled_delta(model, previous, dirty_object_ids, performance) + refreshed = _extend_compiled_scene( + model, structural.compiled, dirty_object_ids; + forced_input_binding_keys=structural.forced_input_binding_keys, + forced_call_target_keys=structural.forced_call_target_keys, + previous_temporal_sources_seed=structural.previous_temporal_sources, + changed_application_ids_seed=structural.changed_application_ids, + changed_target_ids_seed=structural.changed_target_ids, + pure_addition=false, structural_dirty_ids=dirty_object_ids, performance, + ) + _remove_stale_status_views!(refreshed, structural.changed_target_ids) + else + prepared isa PreparedScenario || _unprepared_runtime_configuration() + refreshed = _compile_scene(model, prepared; performance) + if !force && !isnothing(previous) && previous.distributed_outputs isa CompiledDistributedOutputs + _preserve_recompiled_model_status_views!(refreshed, previous) + end + end + model.binding_cache = refreshed + _record_runtime_owner_replacement!(model, previous, refreshed) + model.bindings_dirty = false + _consume_structural_lifecycle_delta!(model) + return refreshed +end + +function _unprepared_runtime_configuration() + throw(ArgumentError("The authored model configuration changed after preparation. " * + "Call Advanced.refresh_bindings!(model; force=true) before continuing the simulation.")) +end + +# A running simulation already fixes its compiled representation. Read the +# CURRENT model-owned cache through that witness, including a cache replaced +# by public force, rather than reusing an old simulation's metadata owner. +function _refresh_runtime_bindings!( + model::CompositeModel, witness::C; performance=nothing, +) where {C<:CompiledCompositeModel} + current = getfield(model, :binding_cache) + current isa C || _unprepared_runtime_configuration() + return _refresh_owned_runtime_bindings!(model, current::C; performance) +end + +function _refresh_owned_runtime_bindings!( + model::CompositeModel, current::CompiledCompositeModel{SC,SP}; performance=nothing, +) where {SC,SP} + preparation = getfield(getfield(current.scenario_plan, :authoring), :preparation) + preparation.owner === model || _unprepared_runtime_configuration() + getfield(model, :scenario_plan_cache) === preparation || _unprepared_runtime_configuration() + _authored_specs_match(preparation, model) || _unprepared_runtime_configuration() + prepared = getfield(preparation, :resolved)::Union{Nothing,PreparedScenario{SP}} + return _refresh_prepared_bindings!(model, current, prepared; performance) +end + function _index_dynamic_input_binding!( index::SelectorCandidateIndex, model::CompositeModel, @@ -2071,7 +2192,9 @@ function _model_timeline(model::CompositeModel) return _timeline_context(backend) end -function _compile_resolved_scenario_plan(model::CompositeModel, applications, timeline) +function _compile_resolved_scenario_plan( + model::CompositeModel, preparation::ScenarioPreparation, applications, timeline, +) distributed_output_plans = _compile_model_output_destination_plans(model, applications) input_plans = _compile_model_input_plans( @@ -2082,6 +2205,7 @@ function _compile_resolved_scenario_plan(model::CompositeModel, applications, ti call_plans = _compile_model_call_plans(model, applications) return _compiled_scenario_plan( model, + preparation, applications, input_plans, call_plans, @@ -2096,15 +2220,24 @@ function _build_scenario_plan( timeline; performance=nothing, ) + preparation = _scenario_preparation(model, raw_specs) + return _resolve_prepared_scenario(model, preparation, timeline; performance) +end + +function _resolve_prepared_scenario( + model::CompositeModel, preparation::ScenarioPreparation, timeline; + performance=nothing, +) + recipes = _authored_application_recipes(preparation) started_at = _runtime_performance_start(performance) - applications = _compile_model_applications(model, raw_specs, timeline) + applications = _resolve_application_recipes(model, recipes, timeline) _runtime_performance_finish!( performance, :application_target_compile, started_at, ) started_at = _runtime_performance_start(performance) - scenario_plan = _compile_resolved_scenario_plan(model, applications, timeline) + scenario_plan = _compile_resolved_scenario_plan(model, preparation, applications, timeline) _validate_model_call_plan_cadences!(applications, scenario_plan.call_plans, timeline) _validate_manual_model_output_destination_plans!( scenario_plan.distributed_output_plans, @@ -2136,14 +2269,16 @@ function _prepare_scenario_plan( return prepared end compiled = compiled_bindings(model) - if !isnothing(compiled) && compiled.scenario_plan.timeline.base_step_seconds == timeline.base_step_seconds + if !isnothing(compiled) && + compiled.scenario_plan.authoring.preparation === preparation && + compiled.scenario_plan.timeline.base_step_seconds == timeline.base_step_seconds prepared = PreparedScenario(compiled.scenario_plan, Vector{ObjectId}[copy(app.target_ids) for app in compiled.applications]) preparation.resolved = prepared return prepared end end - plan, applications = _build_scenario_plan(model, model.applications, timeline; performance) + plan, applications = _resolve_prepared_scenario(model, preparation, timeline; performance) prepared = PreparedScenario(plan, Vector{ObjectId}[app.target_ids for app in applications]) # A running simulation still needs its pending topology refresh. Give # an adapter the requested snapshot without replacing that live plan. @@ -2404,7 +2539,10 @@ function _new_application_targets( new_count = length(application.target_ids) + length(matched) if (application.applies_to isa One && new_count != 1) || (application.applies_to isa OptionalOne && new_count > 1) - return nothing + # Reuse canonical selector diagnostics without replaying authored + # model declarations or preparing any new status/default values. + _resolve_object_ids(model, application.applies_to, application.target_matcher) + error("Inconsistent lifecycle target cardinality for application `$(application.id)`.") end end return targets @@ -2445,7 +2583,8 @@ end function _insert_sorted_object_ids!(ids, added_ids) isempty(added_ids) && return ids - sizehint!(ids, length(ids) + length(added_ids)) + # Keep the vector's amortized reserve; an exact hint can shrink and copy it + # at every lifecycle barrier. push! grows storage only when necessary. for object_id in added_ids found, position = _sorted_object_id_position(ids, object_id) found || _insert_with_spare_capacity!(ids, position, object_id) @@ -3899,11 +4038,6 @@ function _extend_compiled_scene( added_ids, performance, ) - isnothing(new_targets) && return compile_composite_model( - model, - model.applications; - performance=performance, - ) applications = compiled.applications applications_by_id = compiled.applications_by_id new_target_application_ids = sort!( @@ -4821,11 +4955,13 @@ function explain_initialization(model::CompositeModel) end function _compile_model_applications(model::CompositeModel, raw_specs, timeline) - recipes = _authored_application_recipes(model, raw_specs) + recipes = _authored_application_recipes(_scenario_preparation(model, raw_specs)) return _resolve_application_recipes(model, recipes, timeline) end -function _resolve_application_recipes(model::CompositeModel, recipes::Tuple, timeline) +function _resolve_application_recipes( + model::CompositeModel, recipes::Tuple, timeline; on_environment_error=nothing, +) applications = CompiledModelApplication[] for recipe in recipes target_matcher = _resolve_selector_matcher(model, recipe.target_matcher) @@ -4834,7 +4970,7 @@ function _resolve_application_recipes(model::CompositeModel, recipes::Tuple, tim sizehint!(target_ids, length(target_ids) + 1) spec = _model_spec_with_environment_hints( model, recipe.spec, _model_application_hint_scale(model, target_ids), - recipe.environment_hint, + recipe.environment_hint; on_error=on_environment_error, ) model_overrides = _compiled_object_model_overrides(spec, target_ids, recipe.id) push!(applications, CompiledModelApplication( @@ -4851,13 +4987,18 @@ function _resolve_application_recipes(model::CompositeModel, recipes::Tuple, tim return applications end -function _model_spec_with_environment_hints(model::CompositeModel, spec, scale::Symbol, authored_hint) +function _model_spec_with_environment_hints( + model::CompositeModel, spec, scale::Symbol, authored_hint; on_error=nothing, +) hint = _normalize_environment_hint(scale, process(spec), authored_hint) current_bindings = environment_bindings(spec) has_explicit_bindings = !(current_bindings isa NamedTuple && isempty(keys(current_bindings))) new_bindings = has_explicit_bindings || isnothing(hint.bindings) ? current_bindings : hint.bindings - new_bindings = _model_environment_bindings_with_environment_sources(spec, new_bindings) + new_bindings = _model_environment_bindings_with_environment_sources(spec, new_bindings; on_error) + # Only the diagnostic consumer records a rejected configuration and keeps + # its actual authored spec visible. Strict compilation throws below. + isnothing(new_bindings) && return spec current_window = environment_window(spec) new_window = isnothing(current_window) && !isnothing(hint.window) ? hint.window : current_window @@ -4870,18 +5011,23 @@ function _model_spec_with_environment_hints(model::CompositeModel, spec, scale:: ) end -function _model_environment_bindings_with_environment_sources(spec, bindings) +function _model_environment_bindings_with_environment_sources(spec, bindings; on_error=nothing) sources = _environment_source_overrides(spec) isempty(keys(sources)) && return bindings bindings = bindings isa NamedTuple ? bindings : NamedTuple() model_inputs = Set(Symbol.(keys(environment_inputs_(spec)))) unknown = Symbol[target for target in keys(sources) if !(Symbol(target) in model_inputs)] - isempty(unknown) || error( - "`Environment(; sources=...)` for process `$(process(spec))` contains ", - "unknown model-facing environment input(s) `$(Tuple(unknown))`. Declared ", - "`environment_inputs_` are `$(Tuple(sort!(collect(model_inputs); by=string)))`." - ) + if !isempty(unknown) + message = string( + "`Environment(; sources=...)` for process `$(process(spec))` contains ", + "unknown model-facing environment input(s) `$(Tuple(unknown))`. Declared ", + "`environment_inputs_` are `$(Tuple(sort!(collect(model_inputs); by=string)))`." + ) + isnothing(on_error) && error(message) + on_error(ErrorException(message)) + return nothing + end targets = Symbol[Symbol(target) for target in keys(bindings)] for target in keys(sources) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index e6da39138..5664ee66d 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -760,6 +760,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, compile_environment_bindings(model, compiled) end model.environment_binding_cache = refreshed + _record_runtime_owner_replacement!(model, cached, refreshed) model.environment_bindings_dirty = false _reset_lifecycle_delta_if_consumed!(model) return refreshed @@ -772,6 +773,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, refreshed = isnothing(reconciled) ? compile_environment_bindings(model, compiled) : reconciled model.environment_binding_cache = refreshed + _record_runtime_owner_replacement!(model, cached, refreshed) return refreshed end end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 3d26045a1..8abb0aa9f 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -976,6 +976,15 @@ function _consume_structural_lifecycle_delta!(model::CompositeModel) return consumed end +# A public refresh can replace a prepared owner without a topology or +# environment mutation. Publish that cold change through the same generation +# checked after each scheduled application. Clean identity-preserving refresh +# remains a no-op, and per-object execution performs no extra lookup. +function _record_runtime_owner_replacement!(model::CompositeModel, previous, current) + previous === current || (model.runtime_revision += 1) + return nothing +end + bindings_dirty(model::CompositeModel) = model.bindings_dirty environment_bindings_dirty(model::CompositeModel) = model.environment_bindings_dirty lifecycle_delta(model::CompositeModel) = model.lifecycle_delta @@ -1758,86 +1767,6 @@ function _geometry_inheriting_descendants(model::CompositeModel, root_id::Object return ids end -function refresh_bindings!( - model::CompositeModel, - specs=model.applications; - force::Bool=false, - performance=nothing, -) - uses_model_applications = specs === model.applications - if !uses_model_applications - return compile_composite_model( - model, - specs; - performance=performance, - ) - end - preparation = _scenario_preparation(model; force) - _validate_authored_scenario(preparation) - prepared = preparation.resolved - previous = model.binding_cache - plan_changed = !isnothing(prepared) && !isnothing(previous) && - prepared.plan !== previous.scenario_plan - if force || model.bindings_dirty || isnothing(previous) || plan_changed - delta = model.lifecycle_delta - dirty_object_ids = delta.structural_dirty_ids - can_extend = !force && - isnothing(prepared) && - !isnothing(model.binding_cache) && - !isempty(dirty_object_ids) - if can_extend && delta.structural_kind == :addition - model.binding_cache = _extend_compiled_scene( - model, - model.binding_cache, - dirty_object_ids, - ; - performance=performance, - ) - elseif can_extend && delta.structural_kind == :structural - delta = _prepare_structural_compiled_delta( - model, - model.binding_cache, - dirty_object_ids, - performance, - ) - model.binding_cache = _extend_compiled_scene( - model, - delta.compiled, - dirty_object_ids; - forced_input_binding_keys=delta.forced_input_binding_keys, - forced_call_target_keys=delta.forced_call_target_keys, - previous_temporal_sources_seed=delta.previous_temporal_sources, - changed_application_ids_seed=delta.changed_application_ids, - changed_target_ids_seed=delta.changed_target_ids, - pure_addition=false, - structural_dirty_ids=dirty_object_ids, - performance=performance, - ) - _remove_stale_status_views!( - model.binding_cache, - delta.changed_target_ids, - ) - else - previous_binding_cache = model.binding_cache - refreshed_binding_cache = isnothing(prepared) ? - compile_composite_model(model; performance) : - _compile_scene(model, prepared; performance) - if !force && - !isnothing(previous_binding_cache) && - previous_binding_cache.distributed_outputs isa - CompiledDistributedOutputs - _preserve_recompiled_model_status_views!( - refreshed_binding_cache, - previous_binding_cache, - ) - end - model.binding_cache = refreshed_binding_cache - end - model.bindings_dirty = false - _consume_structural_lifecycle_delta!(model) - end - return model.binding_cache -end function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) ids = _indexed_object_ids( diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 4281c4584..25bd724fd 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5567,7 +5567,6 @@ function _new_object_applications( compiled, requested_ids, ) - isnothing(new_targets) && return nothing for slot in sort!(Int[ compiled.applications_by_id[application_id].slot for application_id in keys(new_targets) @@ -6070,7 +6069,7 @@ function _current_topology_call_targets( cached_targets, ) isnothing(targeted) || return targeted - compiled = refresh_bindings!(model) + compiled = _refresh_runtime_bindings!(model, context.compiled) environment_bindings = refresh_environment_bindings!(model, compiled) bindings = get( compiled.call_bindings_by_target, @@ -6917,7 +6916,8 @@ end function _refresh_simulation_runtime!(simulation::Simulation) model = simulation.model - if bindings_dirty(model) || + unobserved_compiled_owner = simulation.compiled !== getfield(model, :binding_cache) + if bindings_dirty(model) || unobserved_compiled_owner || simulation.compiled.revision != model_revision(model) lifecycle = lifecycle_delta(model) _runtime_performance_count_lifecycle_delta!( @@ -6948,10 +6948,16 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.environment_bindings.by_target, ) started_at = _runtime_performance_start(simulation.performance) - simulation.compiled = refresh_bindings!( - model; + simulation.compiled = _refresh_runtime_bindings!( + model, simulation.compiled; performance=simulation.performance, ) + # A previously published owner can change membership beyond the + # pending lifecycle delta, including at the same topology revision. + # Ordinary observed growth retains incremental request checks. + if unobserved_compiled_owner + simulation.output_request_model_revision = -1 + end _runtime_performance_finish!( simulation.performance, :binding_refresh, @@ -7013,7 +7019,7 @@ function _refresh_simulation_runtime!(simulation::Simulation) ), ) end - pure_object_addition = + pure_object_addition = !unobserved_compiled_owner && simulation.compiled.status_view_refresh_is_pure_addition output_retention_reused = pure_object_addition && _model_output_retention_covers_addition( @@ -7055,14 +7061,12 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.compiled, simulation.output_retention, 0, - output_retention_reused ? + output_retention_reused && !unobserved_compiled_owner ? simulation.compiled.changed_execution_target_ids : nothing, ) started_at = _runtime_performance_start(simulation.performance) environment_owner = _current_environment_binding_owner(model, simulation.environment_bindings) - environment_delta_covers_runtime = !isnothing(environment_owner) && - environment_owner.environment_revision == simulation.environment_bindings.environment_revision && - environment_owner.applications_identity == simulation.environment_bindings.applications_identity + environment_delta_covers_runtime = environment_owner === simulation.environment_bindings simulation.environment_bindings = _refresh_environment_bindings!( model, simulation.compiled, @@ -7095,7 +7099,8 @@ function _refresh_simulation_runtime!(simulation::Simulation) ), ) end - changed_execution_application_ids = output_retention_reused && environment_delta_covers_runtime ? + changed_execution_application_ids = !unobserved_compiled_owner && + output_retention_reused && environment_delta_covers_runtime ? simulation.compiled.changed_execution_application_ids : nothing started_at = _runtime_performance_start(simulation.performance) @@ -7140,6 +7145,7 @@ function _refresh_simulation_runtime!(simulation::Simulation) execution_refresh.groups_reused, ) elseif environment_bindings_dirty(model) || + simulation.environment_bindings !== getfield(model, :environment_binding_cache) || simulation.environment_bindings.environment_revision != environment_revision(model) _runtime_performance_count_lifecycle_delta!( @@ -7150,9 +7156,7 @@ function _refresh_simulation_runtime!(simulation::Simulation) # A public refresh can consume the lifecycle delta before this # Simulation observes it. A later partial event only describes changes # since that newer cache, so it cannot bound this runtime's stale rows. - environment_delta_covers_runtime = !isnothing(environment_owner) && - environment_owner.environment_revision == simulation.environment_bindings.environment_revision && - environment_owner.applications_identity == simulation.environment_bindings.applications_identity + environment_delta_covers_runtime = environment_owner === simulation.environment_bindings dirty_environment_object_ids = lifecycle_delta(model).full_environment || !environment_delta_covers_runtime ? nothing : @@ -7552,7 +7556,8 @@ function _refresh_output_request_targets!( simulation.performance, :output_request_target_refreshes, ) - added_object_ids = _incremental_output_request_object_ids(lifecycle) + added_object_ids = simulation.output_request_model_revision == -1 ? + nothing : _incremental_output_request_object_ids(lifecycle) for request in simulation.output_requests matcher = simulation.output_request_matchers[request.name] application_id, object_targets = diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index b392076b0..9a60f139e 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -578,21 +578,27 @@ function _ancestor_id( final_index < firstindex(ancestors) && return nothing isnothing(scale) && isnothing(kind) && return @inbounds ancestors[final_index] - scale_ids = isnothing(scale) ? nothing : get(model.registry.by_scale, scale, nothing) - !isnothing(scale) && isnothing(scale_ids) && return nothing - kind_ids = isnothing(kind) ? nothing : get(model.registry.by_kind, kind, nothing) - !isnothing(kind) && isnothing(kind_ids) && return nothing + !isnothing(scale) && !haskey(model.registry.by_scale, scale) && return nothing + !isnothing(kind) && !haskey(model.registry.by_kind, kind) && return nothing for index in final_index:-1:firstindex(ancestors) id = @inbounds ancestors[index] - # Preserve the existing unknown-object error for a dangling cached - # ancestor, without fetching every live Object merely for its labels. - haskey(model.registry.objects, id) || _model_object(model, id) - (isnothing(scale_ids) || id in scale_ids) && - (isnothing(kind_ids) || id in kind_ids) && return id + _ancestor_matches_indexed_labels(model, id, scale, kind) && return id end return nothing end +# An ancestry path may contain several concrete ObjectId types. Keep each +# scalar index lookup inside that identity's dispatch boundary so immutable +# index and family-store headers do not escape across a dynamic call. +@noinline function _ancestor_matches_indexed_labels( + model::CompositeModel, id::ObjectId, + scale::Union{Nothing,Symbol}, kind::Union{Nothing,Symbol}, +) + _model_object(model, id) + return (isnothing(scale) || id in model.registry.by_scale[scale]) && + (isnothing(kind) || id in model.registry.by_kind[kind]) +end + function _ancestor_ids(model::CompositeModel, current_id::ObjectId) ids = ObjectId[] parent_id = _model_object(model, current_id).parent diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index b94888078..025baef27 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -203,9 +203,10 @@ method reads a transient backend-specific `state` supplied through `time` is an index on the simulation's base-step clock. Per-target backend sampling uses `float(step)` consistently, independently of output retention and performance instrumentation. Global forcing rows retain their scheduler-step -lookup. Backends should accept an appropriate `Real` clock; normalization -preserves floating representations such as `Float32`. Hard calls use the -floating clock captured by their runtime context. +lookup. Backends should accept an appropriate `Real` clock. The ordinary +scheduler normalizes integer steps to `Float64`; already floating per-target +clocks retain their representation. Hard calls use the `Float64` clock captured +by their runtime context. """ function sample(backend::AbstractEnvironmentBackend, handle, variable::Symbol, time) error( diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index cc2f9f70b..4a79183c7 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -175,6 +175,7 @@ end function _model_graph_compiled( model, + preparation, applications, input_plans, call_plans, @@ -191,6 +192,7 @@ function _model_graph_compiled( timeline = _model_timeline(model) scenario_plan = _compiled_scenario_plan( model, + preparation, applications, input_plans, call_plans, @@ -246,16 +248,7 @@ function _model_graph_compiled( ) end -function _model_graph_compile_applications(model, timeline, diagnostics) - preparation = _scenario_preparation(model) - if isnothing(preparation.failure) - applications = _model_graph_phase!(diagnostics, :applications, CompiledModelApplication[]) do - _resolve_application_recipes(model, preparation.authored, timeline) - end - isempty(applications) || return applications - isempty(model.applications) && return applications - end - +function _model_graph_compile_applications(model, preparation, timeline, diagnostics) recovered = CompiledModelApplication[] recovered_ids = Set{Symbol}() for record in preparation.authored @@ -269,7 +262,13 @@ function _model_graph_compile_applications(model, timeline, diagnostics) continue end try - application = only(_resolve_application_recipes(model, (record,), timeline)) + on_environment_error = err -> push!(diagnostics, _model_graph_diagnostic( + err, :environment_bindings; + application_ids=[record.id], + suggestions=["Map only declared model-facing environment inputs."], + )) + application = only(_resolve_application_recipes(model, (record,), timeline; + on_environment_error)) application.id in recovered_ids && error( "Duplicate recovered model application id `$(application.id)`.", ) @@ -342,7 +341,8 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) nothing, ) - applications = _model_graph_compile_applications(model, timeline, diagnostics) + preparation = _scenario_preparation(model) + applications = _model_graph_compile_applications(model, preparation, timeline, diagnostics) isempty(applications) && !isempty(model.applications) && return CompositeModelCompilationReport( model, initial_status_variables, @@ -513,6 +513,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) compiled = try _model_graph_compiled( model, + preparation, applications, input_plans, call_plans, diff --git a/test/runtests.jl b/test/runtests.jl index 6b6b44526..168a0c3b0 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -82,6 +82,8 @@ else @testset "Reusable scenario plans" begin include("test-model-prepared-scenario.jl") include("test-model-scenario-authoring.jl") + include("test-model-prepared-authoring-owner.jl") + include("test-model-public-refresh-owners.jl") include("test-model-authored-call-plans.jl") include("test-model-authored-spec-matching.jl") include("test-compilation-metadata.jl") diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index f0272e8f5..9db404f20 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -2830,6 +2830,9 @@ end group for group in original_groups if group.application.id == :leaf_context ) + # The group is the live mutable owner. Save its ordered wrappers so later + # identity assertions do not compare a refreshed owner with itself. + original_context_batches = copy(original_context_group.batches) @test [ [target.object_id for target in batch.targets] for batch in original_context_group.batches @@ -2847,9 +2850,9 @@ end ObjectId.([:leaf_a, :leaf_z, :leaf_zz]) @test [ [target.object_id for target in batch.targets] - for batch in original_context_group.batches + for batch in original_context_batches ] == [ObjectId.([:leaf_a]), ObjectId.([:leaf_z])] - @test simulation.execution_plan.groups !== original_groups + @test simulation.execution_plan.groups === original_groups @test simulation.execution_plan.batches !== original_batches refreshed_source_group = only( @@ -2862,16 +2865,18 @@ end ) @test refreshed_source_group === original_source_group @test only(refreshed_source_group.batches) === original_source_batch - @test refreshed_context_group.batches[1] === original_context_group.batches[1] - @test refreshed_context_group.batches[2] === original_context_group.batches[2] + @test refreshed_context_group === original_context_group + @test refreshed_context_group.batches[1] === original_context_batches[1] + @test refreshed_context_group.batches[2] === original_context_batches[2] @test refreshed_context_group.batches[3].targets.cohort === - original_context_group.batches[1].targets.cohort + original_context_batches[1].targets.cohort for batch in simulation.execution_plan.batches, target in batch.targets key = (batch.application.id, target.object_id) haskey(original_targets, key) || continue previous_target = original_targets[key] @test target === previous_target @test target.context === previous_target.context + @test target.context.compiled === simulation.compiled location = PlantSimEngine.cohort_location(simulation.execution_plan.cohorts, key...) @test location.cohort === original_locations[key].cohort @test location.row == original_locations[key].row @@ -2895,7 +2900,7 @@ end performance.counts, :execution_groups_updated_in_place, 0, - ) == 1 + ) == 2 # source append and the context family's additional ordered run @test model_object(model, :leaf_zz).status.signal == 1.0 @test model_object(model, :leaf_a).status.signal == 2.0 @test model_object(model, :leaf_z).status.signal == 2.0 diff --git a/test/test-model-authored-spec-matching.jl b/test/test-model-authored-spec-matching.jl index 5ccd3c52f..a4ca37ea2 100644 --- a/test/test-model-authored-spec-matching.jl +++ b/test/test-model-authored-spec-matching.jl @@ -1,124 +1,134 @@ module AuthoredSpecMatchChecks using Test, PlantSimEngine -const PSE=PlantSimEngine +const PSE = PlantSimEngine PSE.@process "authored_spec_match" verbose=false -struct MatchModel{P,R,G} <: AbstractAuthored_Spec_MatchModel +struct MatchModel{P, R, G} <: AbstractAuthored_Spec_MatchModel parameters::P declaration_reads::R parameter_getters::G end -function Base.getproperty(model::MatchModel,name::Symbol) - name===:parameters && (getfield(model,:parameter_getters)[]+=1) - return getfield(model,name) +function Base.getproperty(model::MatchModel, name::Symbol) + name === :parameters && (getfield(model, :parameter_getters)[] += 1) + return getfield(model, name) end -PSE.inputs_(::MatchModel)=NamedTuple() +PSE.inputs_(::MatchModel) = NamedTuple() function PSE.outputs_(model::MatchModel) - getfield(model,:declaration_reads)[]+=1 + getfield(model, :declaration_reads)[] += 1 return (x=0f0,) end -PSE.run!(::MatchModel,status,environment,constants,context)=nothing +PSE.run!(::MatchModel, status, environment, constants, context) = nothing function fixture(count=40) - reads=Ref(0);getters=Ref(0) + reads = Ref(0) + getters = Ref(0) # Different large immutable layouts expose tuple headers escaping through # heterogeneous iteration, as encountered in real downstream models. - specs=Any[ModelSpec(MatchModel(ntuple(Float64,512+(index%8)),reads,getters); - name=Symbol(:app_,index),on=Many(scale=:Leaf),output_routing=(x=:stream_only,)) - for index in 1:count] - model=CompositeModel(Object(:leaf;scale=:Leaf,status=Status(seed=1f0));applications=specs) - return (;model,reads,getters) + specs = Any[ + ModelSpec(MatchModel(ntuple(Float64, 512 + (index % 8)), reads, getters); + name=Symbol(:app_, index), on=Many(scale=:Leaf), + output_routing=(x=:stream_only,)) + for index in 1:count + ] + model = CompositeModel(Object(:leaf; scale=:Leaf, status=Status(seed=1f0)); + applications=specs) + return (; model, reads, getters) end -function cached_matches!(model,count) +function cached_matches!(model, count) for _ in 1:count - preparation=PSE._scenario_preparation(model) + preparation = PSE._scenario_preparation(model) PSE._validate_authored_scenario(preparation) end return nothing end @testset "Heterogeneous live authoring declarations" begin - data=fixture();model=data.model - preparation=model.scenario_plan_cache - reads=data.reads[];getters=data.getters[] - @test length(unique(typeof(spec) for spec in model.applications))==8 - @test PSE._authored_specs_match(preparation,model) - cached_matches!(model,100) - cached_matches!(model,100) - bytes=@allocated cached_matches!(model,100) - @test bytes==0 - @test data.reads[]==reads - @test data.getters[]==getters - @test model.scenario_plan_cache===preparation - @test model_status(model,:leaf).seed===1f0 + data = fixture() + model = data.model + preparation = model.scenario_plan_cache + reads = data.reads[] + getters = data.getters[] + @test length(unique(typeof(spec) for spec in model.applications)) == 8 + @test PSE._authored_specs_match(preparation, model) + cached_matches!(model, 100) + cached_matches!(model, 100) + bytes = @allocated cached_matches!(model, 100) + @test bytes == 0 + @test data.reads[] == reads + @test data.getters[] == getters + @test model.scenario_plan_cache === preparation + @test model_status(model, :leaf).seed === 1f0 - first_spec=model.applications[1] - replacement=ModelSpec(MatchModel(ntuple(Float64,520),data.reads,data.getters); - name=:app_1,on=Many(scale=:Leaf),output_routing=(x=:stream_only,)) - before_reads=data.reads[];before_getters=data.getters[] - model.applications[1]=replacement - @test !PSE._authored_specs_match(preparation,model) - @test data.reads[]==before_reads && data.getters[]==before_getters - model.applications[1]=first_spec - @test PSE._authored_specs_match(preparation,model) - same_type_replacement=ModelSpec(MatchModel(ntuple(i->Float64(i)+1,513),data.reads,data.getters); - name=:app_1,on=Many(scale=:Leaf),output_routing=(x=:stream_only,)) - @test typeof(same_type_replacement)===typeof(first_spec) - model.applications[1]=same_type_replacement - @test !PSE._authored_specs_match(preparation,model) - model.applications[1]=first_spec - @test PSE._authored_specs_match(preparation,model) + first_spec = model.applications[1] + replacement = ModelSpec(MatchModel(ntuple(Float64, 520), data.reads, data.getters); + name=:app_1, on=Many(scale=:Leaf), output_routing=(x=:stream_only,)) + before_reads = data.reads[] + before_getters = data.getters[] + model.applications[1] = replacement + @test !PSE._authored_specs_match(preparation, model) + @test data.reads[] == before_reads && data.getters[] == before_getters + model.applications[1] = first_spec + @test PSE._authored_specs_match(preparation, model) + same_type_replacement = ModelSpec(MatchModel(ntuple(i -> Float64(i) + 1, 513), data.reads, data.getters); + name=:app_1, on=Many(scale=:Leaf), output_routing=(x=:stream_only,)) + @test typeof(same_type_replacement) === typeof(first_spec) + model.applications[1] = same_type_replacement + @test !PSE._authored_specs_match(preparation, model) + model.applications[1] = first_spec + @test PSE._authored_specs_match(preparation, model) reverse!(model.applications) - @test !PSE._authored_specs_match(preparation,model) + @test !PSE._authored_specs_match(preparation, model) reverse!(model.applications) - push!(model.applications,first_spec) - @test !PSE._authored_specs_match(preparation,model) + push!(model.applications, first_spec) + @test !PSE._authored_specs_match(preparation, model) pop!(model.applications) - @test PSE._authored_specs_match(preparation,model) + @test PSE._authored_specs_match(preparation, model) # A real changed declaration must rebuild; the new spec then matches live. - model.applications[1]=replacement - refreshed=PSE._scenario_preparation(model) - @test refreshed!==preparation - @test PSE._authored_specs_match(refreshed,model) - before_force=data.reads[] - forced=PSE._scenario_preparation(model;force=true) - @test forced!==refreshed + model.applications[1] = replacement + refreshed = PSE._scenario_preparation(model) + @test refreshed !== preparation + @test PSE._authored_specs_match(refreshed, model) + before_force = data.reads[] + forced = PSE._scenario_preparation(model;force=true) + @test forced !== refreshed @test data.reads[]>before_force - @test PSE._authored_specs_match(forced,model) - @test model_status(model,:leaf).seed===1f0 + @test PSE._authored_specs_match(forced, model) + @test model_status(model, :leaf).seed === 1f0 end @testset "Authoring owner reconstruction and independent copy" begin - data=fixture(8);original=data.model - preparation=original.scenario_plan_cache - old_snapshot=PSE._prepare_scenario_plan(original) - @test preparation.resolved===old_snapshot - other=CompositeModel(Object(:leaf;scale=:Leaf,status=Status(seed=1f0)); + data = fixture(8) + original = data.model + preparation = original.scenario_plan_cache + old_snapshot = PSE._prepare_scenario_plan(original) + @test preparation.resolved === old_snapshot + other = CompositeModel(Object(:leaf; scale=:Leaf, status=Status(seed=1f0)); applications=copy(original.applications)) - before=data.reads[];before_getters=data.getters[] + before = data.reads[] + before_getters = data.getters[] other.scenario_plan_cache=preparation - owned=PSE._scenario_preparation(other) - @test owned!==preparation - @test owned.owner===other - @test owned.resolved===nothing - @test PSE._authored_specs_match(owned,other) - @test data.reads[]==before && data.getters[]==before_getters - @test original.scenario_plan_cache===preparation - @test preparation.owner===original - @test preparation.resolved===old_snapshot - copied=deepcopy(original) - copied_owner=PSE._scenario_preparation(copied) - @test copied_owner.owner===copied - @test copied_owner!==preparation - @test PSE._authored_specs_match(copied_owner,copied) - copied.applications[1]=copied.applications[2] - @test !PSE._authored_specs_match(copied_owner,copied) - @test PSE._authored_specs_match(preparation,original) + owned = PSE._scenario_preparation(other) + @test owned !== preparation + @test owned.owner === other + @test owned.resolved === nothing + @test PSE._authored_specs_match(owned, other) + @test data.reads[] == before && data.getters[] == before_getters + @test original.scenario_plan_cache === preparation + @test preparation.owner === original + @test preparation.resolved === old_snapshot + copied = deepcopy(original) + copied_owner = PSE._scenario_preparation(copied) + @test copied_owner.owner === copied + @test copied_owner !== preparation + @test PSE._authored_specs_match(copied_owner, copied) + copied.applications[1] = copied.applications[2] + @test !PSE._authored_specs_match(copied_owner, copied) + @test PSE._authored_specs_match(preparation, original) end @testset "Empty authoring declarations" begin - model=CompositeModel(Object(:empty;status=Status(seed=1))) - @test PSE._authored_specs_match(PSE._scenario_preparation(model),model) + model = CompositeModel(Object(:empty;status=Status(seed=1))) + @test PSE._authored_specs_match(PSE._scenario_preparation(model), model) end end diff --git a/test/test-model-diagnostic-authoring-recovery.jl b/test/test-model-diagnostic-authoring-recovery.jl index 0faae511a..56b8d2713 100644 --- a/test/test-model-diagnostic-authoring-recovery.jl +++ b/test/test-model-diagnostic-authoring-recovery.jl @@ -145,4 +145,58 @@ end @test isempty(repaired.diagnostics) end + +@testset "invalid environment source names keep editable application metadata" begin + model = CompositeModel(Object(:root; scale=:Scene, status=Status(seed=1.0)); + applications=( + ModelSpec(Good{:signal}(); name=:configured, on=One(id=:root), + environment=Environment(sources=(T=:temperature,))), + ModelSpec(Good{:later}(); name=:later, on=One(id=:root)), + )) + original = model_status(model, :root) + for _ in 1:2 + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:configured, :later] + configured = only(application for application in report.applications + if application.id === :configured) + @test environment_config(configured.spec).config.sources == (T=:temperature,) + @test configured.target_ids == [ObjectId(:root)] + @test configured.clock.dt == 1.0 + @test any(diagnostic -> diagnostic.application_ids == [:configured] && + occursin("unknown model-facing environment input", diagnostic.message), + report.diagnostics) + @test isnothing(report.compiled) + @test model_status(model, :root) === original + @test !hasproperty(original, :signal) + end + @test_throws ErrorException PSE.compile_model_report(model; strict=true) + @test_throws ErrorException run!(model; steps=0) +end + +const failed_environment_port_reads = Ref(0) +struct FailedEnvironmentPorts <: AbstractDiagnostic_Authoring_Recovery_GoodModel end +PSE.inputs_(::FailedEnvironmentPorts) = NamedTuple() +PSE.outputs_(::FailedEnvironmentPorts) = (signal=0.0,) +function PSE.environment_inputs_(::FailedEnvironmentPorts) + failed_environment_port_reads[] += 1 + throw(OpaqueDeclarationError(@__MODULE__)) +end + +@testset "recovery never retries an environment declaration that itself failed" begin + failed_environment_port_reads[] = 0 + model = CompositeModel(Object(:root; scale=:Scene); applications=( + ModelSpec(FailedEnvironmentPorts(); name=:failed, on=One(id=:root), + environment=Environment(sources=(T=:temperature,))), + ModelSpec(Good{:later}(); name=:later, on=One(id=:root)), + )) + for expected_reads in 1:2 + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:later] + @test failed_environment_port_reads[] == expected_reads + @test any(diagnostic -> diagnostic.application_ids == [:failed] && + occursin("opaque declaration failed once", diagnostic.message), + report.diagnostics) + end +end + end diff --git a/test/test-model-prepared-authoring-owner.jl b/test/test-model-prepared-authoring-owner.jl new file mode 100644 index 000000000..3363cd50a --- /dev/null +++ b/test/test-model-prepared-authoring-owner.jl @@ -0,0 +1,153 @@ +module PreparedAuthoringOwnerChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "prepared_authoring_owner_probe" verbose=false + +struct Probe{H,M} <: AbstractPrepared_Authoring_Owner_ProbeModel + hint_calls::H + empty_hint::M +end +PSE.inputs_(::Probe) = NamedTuple() +PSE.outputs_(::Probe) = (visits=0,) +function PSE.environment_hint(model::Probe) + model.hint_calls[] += 1 + return model.empty_hint[] ? NamedTuple() : nothing +end +PSE.run!(::Probe, status, environment, constants, context) = (status.visits += 1; nothing) + +function fixture(; selector=Many(scale=:Leaf)) + hint_calls, empty_hint = Ref(0), Ref(false) + model = CompositeModel(Object(:root; scale=:Scene), + Object(:leaf; scale=:Leaf, parent=:root); + applications=(ModelSpec(Probe(hint_calls, empty_hint); name=:probe, on=selector),)) + return (; model, hint_calls, empty_hint) +end + +@testset "canonical lifecycle consumes the genuine prepared declaration owner" begin + data = fixture() + simulation = run!(data.model; steps=1, outputs=:all) + plan = simulation.compiled.scenario_plan + preparation = data.model.scenario_plan_cache + @test plan.authoring.preparation === preparation + @test preparation.owner === data.model + @test preparation.source_specs === Tuple(data.model.applications) + @test data.hint_calls[] == 1 + original_ref = PSE.refvalue(model_status(data.model, :leaf), :visits) + + register_object!(data.model, Object(:born; scale=:Leaf, parent=:root)) + step!(simulation) + @test simulation.compiled.scenario_plan === plan + @test simulation.compiled.scenario_plan.authoring.preparation === preparation + @test data.model.scenario_plan_cache === preparation + @test data.hint_calls[] == 1 + @test model_status(data.model, :leaf).visits == 2 + @test model_status(data.model, :born).visits == 1 + @test PSE.refvalue(model_status(data.model, :leaf), :visits) === original_ref + + reparent_object!(data.model, :born, :leaf) + step!(simulation) + remove_object!(data.model, :born) + step!(simulation) + @test data.hint_calls[] == 1 + @test simulation.compiled.scenario_plan === plan + @test model_status(data.model, :leaf).visits == 4 + @test collect(outputs(simulation)[(:probe, ObjectId(:born), :visits)]) == [(2.0, 1), (3.0, 2)] +end + +@testset "public force installs the current owner even when hint result types change" begin + data = fixture() + simulation = run!(data.model; steps=1, outputs=:all) + old_compiled = simulation.compiled + old_preparation = data.model.scenario_plan_cache + # These two valid hints normalize identically, but their authored A types + # differ. The runtime owner stores the preparation, not a copied A tuple. + data.empty_hint[] = true + current = Advanced.refresh_bindings!(data.model; force=true) + new_preparation = data.model.scenario_plan_cache + @test new_preparation !== old_preparation + @test typeof(new_preparation) !== typeof(old_preparation) + @test current !== old_compiled + @test current isa typeof(old_compiled) + @test current.scenario_plan.authoring.preparation === new_preparation + @test data.hint_calls[] == 2 + @test !PSE.bindings_dirty(data.model) + @test current.revision == old_compiled.revision + + # No intervening birth/revision is needed to make public force authoritative. + step!(simulation) + @test simulation.compiled === current + @test simulation.compiled.scenario_plan.authoring.preparation === new_preparation + @test data.hint_calls[] == 2 + @test model_status(data.model, :leaf).visits == 2 + register_object!(data.model, Object(:born; scale=:Leaf, parent=:root)) + step!(simulation) + @test simulation.compiled.scenario_plan.authoring.preparation === new_preparation + @test data.hint_calls[] == 2 + @test model_status(data.model, :leaf).visits == 3 + @test model_status(data.model, :born).visits == 1 +end + +@testset "alternate compilation has its own owner without taking over the live cache" begin + data = fixture() + simulation = run!(data.model; steps=0, outputs=:none) + canonical = simulation.compiled + preparation = data.model.scenario_plan_cache + alternate_specs = (ModelSpec(Probe(Ref(0), Ref(false)); name=:alternate, on=One(id=:leaf)),) + alternate = Advanced.refresh_bindings!(data.model, alternate_specs) + @test data.model.binding_cache === canonical + @test data.model.scenario_plan_cache === preparation + @test alternate.scenario_plan.authoring.preparation !== preparation + @test alternate.scenario_plan.authoring.preparation.owner === data.model + @test alternate.scenario_plan.authoring.preparation.source_specs === alternate_specs + @test PSE._refresh_runtime_bindings!(data.model, canonical) === canonical + step!(simulation) + @test simulation.compiled === canonical + @test model_status(data.model, :leaf).visits == 1 + + copied = deepcopy(data.model) + copied_preparation = copied.scenario_plan_cache + @test copied_preparation !== preparation + @test copied_preparation.owner === copied + @test copied.binding_cache.scenario_plan.authoring.preparation === copied_preparation + @test PSE._refresh_runtime_bindings!(copied, copied.binding_cache) === copied.binding_cache + @test copied_preparation.source_specs !== preparation.source_specs + @test data.model.scenario_plan_cache === preparation +end + +@testset "full configuration invalidation is repaired by the public authoring boundary" begin + data = fixture() + simulation = run!(data.model; steps=1, outputs=:none) + PSE._mark_bindings_dirty!(data.model) + @test_throws ArgumentError step!(simulation) + @test model_status(data.model, :leaf).visits == 1 + current = Advanced.refresh_bindings!(data.model; force=true) + @test data.hint_calls[] == 2 + step!(simulation) + @test simulation.compiled === current + @test data.hint_calls[] == 2 + @test model_status(data.model, :leaf).visits == 2 +end + +@testset "invalid lifecycle cardinality does not replay authored hooks" begin + for selector in (One(scale=:Leaf), OptionalOne(scale=:Leaf)) + data = fixture(; selector) + simulation = run!(data.model; steps=0, outputs=:none) + before = data.hint_calls[] + register_object!(data.model, Object(:extra; scale=:Leaf, parent=:root)) + message = try + step!(simulation) + "no error" + catch error + sprint(showerror, error) + end + @test occursin("Expected ", message) + @test occursin("matched_ids=", message) + @test occursin("requested=", message) + @test occursin("suggestions=", message) + @test data.hint_calls[] == before + @test model_status(data.model, :leaf).visits == 0 + end +end + +end diff --git a/test/test-model-public-refresh-owners.jl b/test/test-model-public-refresh-owners.jl new file mode 100644 index 000000000..6935c5faf --- /dev/null +++ b/test/test-model-public-refresh-owners.jl @@ -0,0 +1,259 @@ +module PublicRefreshOwnerChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI +PSE.@process "force_authority_count" verbose=false +struct Counter <: AbstractForce_Authority_CountModel end +PSE.inputs_(::Counter) = NamedTuple() +PSE.outputs_(::Counter) = (visits=0,) +PSE.run!(::Counter, status, environment, constants, context) = (status.visits += 1; nothing) + +@testset "public force owns the next step without an intervening mutation" begin + first_spec = ModelSpec(Counter(); name=:probe, on=One(id=:leaf1)) + model = CompositeModel(Object(:root; scale=:Scene), + Object(:leaf1; scale=:Leaf, parent=:root, status=Status(visits=0)), + Object(:leaf2; scale=:Leaf, parent=:root, status=Status(visits=0)); + applications=(first_spec,)) + simulation = run!(model; steps=1, outputs=:none) + previous = simulation.compiled + previous_runtime_revision = model.runtime_revision + replacement = ModelSpec(Counter(); name=:probe, on=One(id=:leaf2)) + @test typeof(replacement) === typeof(first_spec) + model.applications[1] = replacement + current = Advanced.refresh_bindings!(model; force=true) + owner_replaced = current !== previous + @test owner_replaced + same_compiled_schema = current isa typeof(previous) + @test same_compiled_schema + @test !PSE.bindings_dirty(model) + @test only(current.applications).target_ids == [ObjectId(:leaf2)] + @test model.runtime_revision > previous_runtime_revision + published = model.runtime_revision + clean = Advanced.refresh_bindings!(model) + clean_identity_preserved = clean === current + @test clean_identity_preserved + @test model.runtime_revision == published + continue!(simulation; steps=1) + @info "force binding authority after continue" leaf1=model_status(model, :leaf1).visits leaf2=model_status(model, :leaf2).visits adopted=(simulation.compiled === current) + @test model_status(model, :leaf1).visits == 1 + @test model_status(model, :leaf2).visits == 1 + adopted_current = simulation.compiled === current + @test adopted_current +end + +mutable struct Backend <: EA.AbstractEnvironmentBackend + binds::Int +end +struct Handle + generation::Int +end +EA.base_step_seconds(::Backend) = 3600.0 +EA.get_nsteps(::Backend) = 4 +EA.environment_variables(::Backend) = Set((:T,)) +function EA.bind_environment(backend::Backend, ::Object, context, config) + backend.binds += 1 + return Handle(backend.binds) +end +EA.sample(::Backend, handle::Handle, ::Symbol, time) = Float64(handle.generation) + +PSE.@process "force_authority_environment" verbose=false +struct EnvironmentProbe <: AbstractForce_Authority_EnvironmentModel end +PSE.inputs_(::EnvironmentProbe) = NamedTuple() +PSE.outputs_(::EnvironmentProbe) = (seen=0.0, visits=0) +PSE.environment_inputs_(::EnvironmentProbe) = (T=0.0,) +function PSE.run!(::EnvironmentProbe, status, environment, constants, context) + status.seen = environment.T + status.visits += 1 + return nothing +end + +@testset "public environment force installs its newly compiled handle" begin + backend = Backend(0) + model = CompositeModel(Object(:leaf; scale=:Leaf, + status=Status(seen=0.0, visits=0)); applications=( + ModelSpec(EnvironmentProbe(); name=:probe, on=One(id=:leaf), + environment=Environment(provider=:force_probe)),), environment=backend) + simulation = run!(model; steps=1, outputs=:none) + previous = simulation.environment_bindings + previous_runtime_revision = model.runtime_revision + current = Advanced.refresh_environment_bindings!(model, simulation.compiled; force=true) + key = (:probe, ObjectId(:leaf)) + expected_generation = current.by_target[key].handle.generation + owner_replaced = current !== previous + @test owner_replaced + @test expected_generation > previous.by_target[key].handle.generation + @test !PSE.environment_bindings_dirty(model) + @test model.runtime_revision > previous_runtime_revision + published = model.runtime_revision + clean = Advanced.refresh_environment_bindings!(model, simulation.compiled) + clean_identity_preserved = clean === current + @test clean_identity_preserved + @test model.runtime_revision == published + continue!(simulation; steps=1) + adopted = simulation.environment_bindings === current + @info "force environment authority after continue" seen=model_status(model, :leaf).seen expected_generation adopted + @test adopted + @test model_status(model, :leaf).seen == Float64(expected_generation) + @test model_status(model, :leaf).visits == 2 +end + +PSE.@process "force_authority_controller" verbose=false +struct Controller <: AbstractForce_Authority_ControllerModel end +PSE.inputs_(::Controller) = NamedTuple() +PSE.outputs_(::Controller) = (visits=0,) +function PSE.run!(::Controller, status, environment, constants, context) + status.visits += 1 + if status.visits == 2 + model = runtime_model(context) + model.applications[2] = ModelSpec(Counter(); name=:probe, on=One(id=:leaf2)) + Advanced.refresh_bindings!(model; force=true) + end + return nothing +end + +@testset "public force inside a kernel wakes the shared lifecycle barrier" begin + model = CompositeModel(Object(:root; scale=:Scene, status=Status(visits=0)), + Object(:leaf1; scale=:Leaf, parent=:root, status=Status(visits=0)), + Object(:leaf2; scale=:Leaf, parent=:root, status=Status(visits=0)); + applications=(ModelSpec(Controller(); name=:controller, on=One(id=:root)), + ModelSpec(Counter(); name=:probe, on=One(id=:leaf1)))) + simulation = run!(model; steps=2, outputs=:none) + @info "in-kernel force binding authority" leaf1=model_status(model, :leaf1).visits leaf2=model_status(model, :leaf2).visits adopted=(simulation.compiled === model.binding_cache) + @test model_status(model, :root).visits == 2 + @test model_status(model, :leaf1).visits == 1 + @test model_status(model, :leaf2).visits == 1 + adopted_current = simulation.compiled === model.binding_cache + @test adopted_current + @test simulation.runtime_revision == model.runtime_revision +end + +PSE.@process "force_authority_capture" verbose=false +struct Capture{C} <: AbstractForce_Authority_CaptureModel + context::C +end +PSE.inputs_(::Capture) = NamedTuple() +PSE.outputs_(::Capture) = (visits=0,) +function PSE.run!(model::Capture, status, environment, constants, context) + status.visits += 1 + model.context[] = context + return nothing +end + +@testset "forced owner replacement invalidates a pending call evaluation" begin + for force_environment in (false, true) + capture = Ref{Any}() + model = CompositeModel(Object(:root; scale=:Scene, status=Status(visits=0)), + Object(:leaf; scale=:Leaf, parent=:root, status=Status(visits=0)); + applications=(ModelSpec(Capture(capture); name=:capture, on=One(id=:root), + calls=(child=One(id=:leaf, application=:probe),)), + ModelSpec(Counter(); name=:probe, on=One(id=:leaf))), + environment=Backend(0)) + simulation = run!(model; steps=1, outputs=:all) + evaluation = evaluate_call!(capture[], :child) + @test model_status(model, :leaf).visits == 1 + previous = model.runtime_revision + if force_environment + Advanced.refresh_environment_bindings!(model, simulation.compiled; force=true) + else + Advanced.refresh_bindings!(model; force=true) + end + @test model.runtime_revision > previous + @test_throws ArgumentError accept_call!(evaluation) + @test model_status(model, :leaf).visits == 1 + @test isempty(get(outputs(simulation), (:probe, ObjectId(:leaf), :visits), [])) + end +end + +end + +module SelectiveRefreshOwnerChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "selective_force_authority_probe" verbose=false +PSE.@process "selective_force_authority_controller" verbose=false +struct Counter <: AbstractSelective_Force_Authority_ProbeModel end +PSE.inputs_(::Counter) = NamedTuple() +PSE.outputs_(::Counter) = (visits=0,) +PSE.run!(::Counter, status, environment, constants, context) = (status.visits += 1; nothing) + +function check_memberships(simulation) + rows = collect_outputs(simulation, :chosen; sink=nothing) + scientific_rows = [(row.object_id, row.timestep, row.value) for row in rows] + @info "selective force authority" scientific_rows + @test scientific_rows == [(:leaf1, 1, 1), (:leaf2, 2, 1)] + targets = simulation.output_request_targets[:chosen][2] + @test [(membership.start_time, membership.end_time) + for membership in targets[ObjectId(:leaf1)].memberships] == [(0.0, 1.0)] + @test haskey(targets, ObjectId(:leaf2)) + if haskey(targets, ObjectId(:leaf2)) + @test [(membership.start_time, membership.end_time) + for membership in targets[ObjectId(:leaf2)].memberships] == [(2.0, nothing)] + end + model = runtime_model(simulation) + @test model_status(model, :leaf1).visits == 1 + @test model_status(model, :leaf2).visits == 1 + @test outputs(simulation)[(:probe, ObjectId(:leaf1), :visits)] == [(1.0, 1)] + @test outputs(simulation)[(:probe, ObjectId(:leaf2), :visits)] == [(2.0, 1)] +end + +@testset "public force refreshes selective membership, including a later pending addition" begin + for pending_addition in (false, true) + model = CompositeModel(Object(:root; scale=:Scene), + Object(:leaf1; scale=:Leaf, parent=:root, status=Status(visits=0)), + Object(:leaf2; scale=:Leaf, parent=:root, status=Status(visits=0)); + applications=(ModelSpec(Counter(); name=:probe, on=One(id=:leaf1)),)) + request = OutputRequest(Many(scale=:Leaf), :visits; + name=:chosen, application=:probe) + simulation = run!(model; steps=1, outputs=request) + previous_revision = PSE.model_revision(model) + model.applications[1] = ModelSpec(Counter(); name=:probe, on=One(id=:leaf2)) + current = Advanced.refresh_bindings!(model; force=true) + @test PSE.model_revision(model) == previous_revision + pending_addition && register_object!(model, Object(:unrelated; scale=:Axis, parent=:root)) + continue!(simulation; steps=1) + adopted = simulation.compiled === model.binding_cache + @test adopted + if !pending_addition + adopted_forced_owner = simulation.compiled === current + @test adopted_forced_owner + end + @info "selective force followed by pending addition" pending_addition adopted + check_memberships(simulation) + end +end + +struct Controller <: AbstractSelective_Force_Authority_ControllerModel + birth::Bool +end +PSE.inputs_(::Controller) = NamedTuple() +PSE.outputs_(::Controller) = (visits=0,) +function PSE.run!(controller::Controller, status, environment, constants, context) + status.visits += 1 + if status.visits == 2 + model = runtime_model(context) + model.applications[2] = ModelSpec(Counter(); name=:probe, on=One(id=:leaf2)) + Advanced.refresh_bindings!(model; force=true) + controller.birth && register_object!(model, Object(:unrelated; scale=:Axis, parent=:root)) + end + return nothing +end + +@testset "in-kernel force reconciles selective membership before the remaining application" begin + for birth in (false, true) + model = CompositeModel(Object(:root; scale=:Scene, status=Status(visits=0)), + Object(:leaf1; scale=:Leaf, parent=:root, status=Status(visits=0)), + Object(:leaf2; scale=:Leaf, parent=:root, status=Status(visits=0)); + applications=(ModelSpec(Controller(birth); name=:controller, on=One(id=:root)), + ModelSpec(Counter(); name=:probe, on=One(id=:leaf1)))) + request = OutputRequest(Many(scale=:Leaf), :visits; name=:chosen, application=:probe) + simulation = run!(model; steps=2, outputs=request) + @test model_status(model, :root).visits == 2 + adopted = simulation.compiled === model.binding_cache + @test adopted + check_memberships(simulation) + end +end + +end From 189e43be60bf74c3dc69a65df0bd99ea7cae68ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 01:16:16 +0100 Subject: [PATCH 016/324] Normalize dependencies once and isolate live plans from snapshots --- docs/src/guides/coupling.md | 3 + src/ModelSpec.jl | 44 ++- src/composite_model/compilation.jl | 11 +- src/composite_model/scenario_dsl.jl | 8 +- test/runtests.jl | 2 + test/test-model-runtime-snapshot-isolation.jl | 195 +++++++++++++ test/test-model-spec-normalization.jl | 271 ++++++++++++++++++ 7 files changed, 522 insertions(+), 12 deletions(-) create mode 100644 test/test-model-runtime-snapshot-isolation.jl create mode 100644 test/test-model-spec-normalization.jl diff --git a/docs/src/guides/coupling.md b/docs/src/guides/coupling.md index a57a27708..6cee54e21 100644 --- a/docs/src/guides/coupling.md +++ b/docs/src/guides/coupling.md @@ -14,6 +14,9 @@ Choose how to connect your models from the calculation you need: A **model application** is a model configured with `ModelSpec`: it has a name, a choice of objects, and any settings needed for its inputs or timing. +`ModelSpec` reads the model's `dep` method once to collect its default `Input`, +`Call`, and `Initializer` bindings. Later environment remapping reuses those +bindings. Build a new `ModelSpec` when you want to change them. ## Value coupling diff --git a/src/ModelSpec.jl b/src/ModelSpec.jl index 239297e10..ac898a5f2 100644 --- a/src/ModelSpec.jl +++ b/src/ModelSpec.jl @@ -16,6 +16,11 @@ selected destination objects, `every` selects application cadence, and and intentional duplicate-writer ordering are declared directly with `output_routing` and `updates`. +Model-authored `Input`, `Call`, and `Initializer` defaults from `dep(model)` +are read once when this application is constructed. Preparing its environment +preserves those normalized declarations. Build a new specification to change +the model's default bindings. + # Example ```julia @@ -275,7 +280,8 @@ function _build_model_spec( normalized_name = _normalize_application_name(name) normalized_on = isnothing(on) ? nothing : _validate_selector_context(on, :application_target) - default_inputs = _model_default_value_inputs(base_model) + dependencies = dep(base_model) + default_inputs = _model_default_value_inputs(dependencies) explicit_inputs = _normalize_application_bindings(inputs) normalized_inputs = _merge_value_inputs(default_inputs, explicit_inputs) for selector in values(normalized_inputs) @@ -289,7 +295,7 @@ function _build_model_spec( normalized_input_origins, :inputs, ) - default_calls = _model_default_model_calls(base_model) + default_calls = _model_default_model_calls(dependencies) explicit_calls = _normalize_application_bindings(calls) normalized_calls = _merge_value_inputs(default_calls, explicit_calls) for binding in values(normalized_calls) @@ -309,7 +315,7 @@ function _build_model_spec( normalized_environment_window = _normalize_environment_window(environment_window) normalized_output_routing = _normalize_output_routing(output_routing) normalized_updates = _normalize_updates(updates) - return ModelSpec{typeof(base_model),typeof(normalized_name),typeof(normalized_on),typeof(normalized_inputs),typeof(normalized_input_origins),typeof(normalized_calls),typeof(normalized_call_origins),typeof(normalized_outputs_to),typeof(normalized_environment),typeof(every),typeof(normalized_environment_bindings),typeof(normalized_environment_window),typeof(normalized_output_routing),typeof(normalized_updates)}( + return _normalized_model_spec( base_model, normalized_name, normalized_on, @@ -327,6 +333,38 @@ function _build_model_spec( ) end +# All callers provide normalized declarations. Keep the field assembly here so +# environment resolution can preserve authored bindings without re-reading dep. +function _normalized_model_spec( + model::AbstractModel, name, on, inputs, input_origins, calls, call_origins, + outputs_to, environment, every, environment_bindings, environment_window, + output_routing, updates, +) + return ModelSpec( + model, name, on, inputs, input_origins, calls, call_origins, outputs_to, + environment, every, environment_bindings, environment_window, + output_routing, updates, + ) +end + +function _model_spec_with_environment_settings( + spec::ModelSpec; environment_bindings=spec.environment_bindings, + environment_window=spec.environment_window, +) + normalized_bindings = environment_bindings === spec.environment_bindings ? + spec.environment_bindings : + _normalize_environment_bindings(environment_bindings) + normalized_window = environment_window === spec.environment_window ? + spec.environment_window : + _normalize_environment_window(environment_window) + return _normalized_model_spec( + spec.model, spec.name, spec.applies_to, spec.inputs, spec.input_origins, + spec.calls, spec.call_origins, spec.outputs_to, spec.environment, + spec.timestep, normalized_bindings, normalized_window, + spec.output_routing, spec.updates, + ) +end + function _validate_scenario_application_references!( bindings::NamedTuple, origins::NamedTuple, diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 8700c9eb2..bd403847f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1861,14 +1861,15 @@ function _refresh_runtime_bindings!( end function _refresh_owned_runtime_bindings!( - model::CompositeModel, current::CompiledCompositeModel{SC,SP}; performance=nothing, -) where {SC,SP} + model::CompositeModel, current::CompiledCompositeModel; performance=nothing, +) preparation = getfield(getfield(current.scenario_plan, :authoring), :preparation) preparation.owner === model || _unprepared_runtime_configuration() getfield(model, :scenario_plan_cache) === preparation || _unprepared_runtime_configuration() _authored_specs_match(preparation, model) || _unprepared_runtime_configuration() - prepared = getfield(preparation, :resolved)::Union{Nothing,PreparedScenario{SP}} - return _refresh_prepared_bindings!(model, current, prepared; performance) + # Adapter snapshots do not replace live metadata. The current published + # owner and lifecycle delta determine the running simulation's refresh. + return _refresh_prepared_bindings!(model, current, nothing; performance) end function _index_dynamic_input_binding!( @@ -5004,7 +5005,7 @@ function _model_spec_with_environment_hints( new_window = isnothing(current_window) && !isnothing(hint.window) ? hint.window : current_window (new_bindings === current_bindings && new_window === current_window) && return spec - return _replace_model_spec( + return _model_spec_with_environment_settings( spec; environment_bindings=new_bindings, environment_window=new_window, diff --git a/src/composite_model/scenario_dsl.jl b/src/composite_model/scenario_dsl.jl index 8bc52a891..b070c90bf 100644 --- a/src/composite_model/scenario_dsl.jl +++ b/src/composite_model/scenario_dsl.jl @@ -180,18 +180,18 @@ function _normalize_application_bindings(bindings) ) end -function _model_default_value_inputs(model) +function _model_default_value_inputs(dependencies) defaults = Pair{Symbol,Any}[] - for (dep_name, selector) in pairs(dep(model)) + for (dep_name, selector) in pairs(dependencies) selector isa Input || continue push!(defaults, Symbol(dep_name) => selector.selector) end return (; defaults...) end -function _model_default_model_calls(model) +function _model_default_model_calls(dependencies) defaults = Pair{Symbol,Any}[] - for (dep_name, declaration) in pairs(dep(model)) + for (dep_name, declaration) in pairs(dependencies) if declaration isa Call push!(defaults, Symbol(dep_name) => declaration.selector) elseif declaration isa Initializer diff --git a/test/runtests.jl b/test/runtests.jl index 168a0c3b0..502041ef9 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -85,6 +85,8 @@ else include("test-model-prepared-authoring-owner.jl") include("test-model-public-refresh-owners.jl") include("test-model-authored-call-plans.jl") + include("test-model-spec-normalization.jl") + include("test-model-runtime-snapshot-isolation.jl") include("test-model-authored-spec-matching.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") diff --git a/test/test-model-runtime-snapshot-isolation.jl b/test/test-model-runtime-snapshot-isolation.jl new file mode 100644 index 000000000..c1594f6e4 --- /dev/null +++ b/test/test-model-runtime-snapshot-isolation.jl @@ -0,0 +1,195 @@ +module RuntimeSnapshotIsolationChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "runtime_snapshot_isolation" verbose=false + +struct Probe{C,H} <: AbstractRuntime_Snapshot_IsolationModel + hint_calls::C + empty_hint::H +end +PSE.inputs_(::Probe) = NamedTuple() +PSE.outputs_(::Probe) = (visits=0,) +function PSE.environment_hint(model::Probe) + model.hint_calls[] += 1 + return model.empty_hint[] ? NamedTuple() : nothing +end +function PSE.run!(::Probe, status, environment, constants, context) + status.visits += 1 + return nothing +end + +function fixture() + hint_calls, empty_hint = Ref(0), Ref(false) + spec = ModelSpec(Probe(hint_calls, empty_hint); name=:probe, on=Many(scale=:Leaf)) + model = CompositeModel(Object(:root; scale=:Scene), + Object(:leaf; scale=:Leaf, parent=:root); applications=(spec,)) + simulation = run!(model; steps=1, outputs=:all) + return (; model, simulation, hint_calls, empty_hint) +end + +@testset "adapter snapshots leave current live metadata and structural deltas authoritative" begin + data = fixture() + model, simulation = data.model, data.simulation + compiled = simulation.compiled + plan = compiled.scenario_plan + preparation = model.scenario_plan_cache + original_ref = PSE.refvalue(model_status(model, :leaf), :visits) + @test data.hint_calls[] == 1 + + clean_snapshot = PSE._prepare_scenario_plan(model; force=true) + @test identity(clean_snapshot.plan !== plan) + @test identity(clean_snapshot.plan.authoring.preparation === preparation) + @test identity(model.binding_cache === compiled) + step!(simulation) + @test identity(simulation.compiled === compiled) + @test identity(simulation.compiled.scenario_plan === plan) + @test model_status(model, :leaf).visits == 2 + @test data.hint_calls[] == 1 + + register_object!(model, Object(:born; scale=:Leaf, parent=:root)) + born_snapshot = PSE._prepare_scenario_plan(model; force=true) + @test identity(born_snapshot.plan !== plan) + @test ObjectId(:born) in only(PSE._scenario_applications(born_snapshot)).target_ids + @test identity(model.binding_cache === compiled) + @test PSE.bindings_dirty(model) + step!(simulation) + @test identity(simulation.compiled.scenario_plan === plan) + @test identity(simulation.compiled.scenario_plan.authoring.preparation === preparation) + @test identity(PSE.refvalue(model_status(model, :leaf), :visits) === original_ref) + @test model_status(model, :leaf).visits == 3 + @test model_status(model, :born).visits == 1 + @test data.hint_calls[] == 1 + + reparent_object!(model, :born, :leaf) + reparent_snapshot = PSE._prepare_scenario_plan(model; force=true) + @test identity(reparent_snapshot.plan !== plan) + step!(simulation) + @test identity(simulation.compiled.scenario_plan === plan) + @test model_status(model, :leaf).visits == 4 + @test model_status(model, :born).visits == 2 + @test data.hint_calls[] == 1 + + remove_object!(model, :born) + removed_snapshot = PSE._prepare_scenario_plan(model; force=true) + @test only(PSE._scenario_applications(removed_snapshot)).target_ids == [ObjectId(:leaf)] + step!(simulation) + @test identity(simulation.compiled.scenario_plan === plan) + @test model_status(model, :leaf).visits == 5 + @test data.hint_calls[] == 1 + @test collect(outputs(simulation)[(:probe, ObjectId(:born), :visits)]) == [(3.0, 1), (4.0, 2)] + @test collect(outputs(simulation)[(:probe, ObjectId(:leaf), :visits)]) == + [(1.0, 1), (2.0, 2), (3.0, 3), (4.0, 4), (5.0, 5)] + + # Public force really publishes new authored metadata; an adapter snapshot + # afterward cannot silently replace that CURRENT cache a second time. + data.empty_hint[] = true + current = Advanced.refresh_bindings!(model; force=true) + current_plan = current.scenario_plan + @test identity(current_plan !== plan) + @test current isa typeof(compiled) + @test data.hint_calls[] == 2 + forced_snapshot = PSE._prepare_scenario_plan(model; force=true) + @test identity(forced_snapshot.plan !== current_plan) + @test identity(forced_snapshot.plan.authoring.preparation === current_plan.authoring.preparation) + @test identity(model.binding_cache === current) + step!(simulation) + @test identity(simulation.compiled === current) + @test identity(simulation.compiled.scenario_plan === current_plan) + @test data.hint_calls[] == 2 + @test model_status(model, :leaf).visits == 6 + @test collect(outputs(simulation)[(:probe, ObjectId(:leaf), :visits)]) == + [(1.0, 1), (2.0, 2), (3.0, 3), (4.0, 4), (5.0, 5), (6.0, 6)] +end + +PSE.@process "snapshot_selection_child" verbose=false +PSE.@process "snapshot_selection_controller" verbose=false +struct SelectionChild <: AbstractSnapshot_Selection_ChildModel end +PSE.inputs_(::SelectionChild) = NamedTuple() +PSE.outputs_(::SelectionChild) = (value=0, child_calls=0) +function PSE.run!(::SelectionChild, status, environment, constants, context) + status.value += 1 + status.child_calls += 1 + return nothing +end + +struct SelectionController{H,F} <: AbstractSnapshot_Selection_ControllerModel + hint_calls::H + snapshot_before_selection::F +end +PSE.inputs_(::SelectionController) = NamedTuple() +PSE.outputs_(::SelectionController) = (seen=0, controllers=0, + kept_current_owner=true, kept_selected_owner=true) +function PSE.dep(::SelectionController) + return (child=Call(One(Subtree(); scale=:Leaf, application=:child)),) +end +function PSE.environment_hint(model::SelectionController) + model.hint_calls[] += 1 + return nothing +end +function PSE.run!(model::SelectionController, status, environment, constants, context) + before = context.compiled + if model.snapshot_before_selection[] + PSE._prepare_scenario_plan(runtime_model(context); force=true) + end + # This is a real controller invocation and the public explicit-selection + # accessor. It refreshes even when no topology mutation is pending. + targets = call_targets(context, :child; objects=ObjectId(:leaf)) + status.kept_current_owner = runtime_model(context).binding_cache === before + status.kept_selected_owner = targets.compiled === before + target = only(targets) + run_call!(target; publish=true) + status.seen = target.status.value + status.controllers += 1 + return nothing +end + +@testset "clean snapshot inside a real controller does not republish through explicit selection" begin + hints, take_snapshot = Ref(0), Ref(false) + model = CompositeModel(Object(:root; scale=:Scene), + Object(:leaf; scale=:Leaf, parent=:root); applications=( + ModelSpec(SelectionController(hints, take_snapshot); + name=:controller, on=One(id=:root)), + ModelSpec(SelectionChild(); name=:child, on=One(id=:leaf)), + )) + simulation = run!(model; outputs=:all) + current = simulation.compiled + current_plan = current.scenario_plan + @test hints[] == 1 + @test model_status(model, :root).kept_current_owner + @test model_status(model, :root).kept_selected_owner + take_snapshot[] = true + step!(simulation) + @test hints[] == 1 + @test identity(simulation.compiled === current) + @test identity(simulation.compiled.scenario_plan === current_plan) + @test identity(model.binding_cache === current) + @test model_status(model, :root).kept_current_owner + @test model_status(model, :root).kept_selected_owner + @test model_status(model, :root).seen == 2 + @test model_status(model, :root).controllers == 2 + @test model_status(model, :leaf).value == 2 + @test model_status(model, :leaf).child_calls == 2 + @test collect(outputs(simulation)[(:child, ObjectId(:leaf), :value)]) == [(1.0, 1), (2.0, 2)] + @test collect(outputs(simulation)[(:controller, ObjectId(:root), :seen)]) == [(1.0, 1), (2.0, 2)] +end + +@testset "explicit public host refresh still installs its prepared snapshot" begin + data = fixture() + model, simulation = data.model, data.simulation + previous = simulation.compiled + snapshot = PSE._prepare_scenario_plan(model; force=true) + @test identity(model.binding_cache === previous) + current = Advanced.refresh_bindings!(model) + @test identity(current !== previous) + @test identity(current.scenario_plan === snapshot.plan) + @test identity(model.binding_cache === current) + @test data.hint_calls[] == 1 + step!(simulation) + @test identity(simulation.compiled === current) + @test model_status(model, :leaf).visits == 2 + @test data.hint_calls[] == 1 + @test collect(outputs(simulation)[(:probe, ObjectId(:leaf), :visits)]) == [(1.0, 1), (2.0, 2)] +end + +end diff --git a/test/test-model-spec-normalization.jl b/test/test-model-spec-normalization.jl new file mode 100644 index 000000000..5eac2ea21 --- /dev/null +++ b/test/test-model-spec-normalization.jl @@ -0,0 +1,271 @@ +module NormalizedModelSpecChecks + +using Dates, PlantMeteo, PlantSimEngine, Test +using PlantSimEngine.Diagnostics: object_address +const PSE = PlantSimEngine +PSE.@process "normalized_spec_declarations" verbose=false +PSE.@process "normalized_spec_snapshot" verbose=false +PSE.@process "normalized_spec_leaf" verbose=false +PSE.@process "normalized_spec_driver" verbose=false +PSE.@process "normalized_spec_creator" verbose=false +PSE.@process "normalized_spec_defaults" verbose=false + +struct Declarations{D,C,F} <: AbstractNormalized_Spec_DeclarationsModel + dependencies::D + calls::C + forbid_replay::F +end +function PSE.dep(model::Declarations) + model.calls[] += 1 + model.forbid_replay[] && error("dependency declarations were replayed") + return model.dependencies +end +struct TestWindow <: PlantMeteo.AbstractSamplingWindow end + +@testset "one dependency snapshot and one normalized ModelSpec assembly" begin + input = Input(One(Self(); process=:normalized_spec_leaf, var=:value)) + call = Call(One(Self(); process=:normalized_spec_leaf)) + initializer = Initializer(One(Subtree(); application=:leaf, scale=:Leaf)) + dependencies = (value=input, leaf=call, start=initializer) + calls, forbidden = Ref(0), Ref(false) + model = Declarations(dependencies, calls, forbidden) + spec = ModelSpec(model; name="driver", on=Many(scale=:Controller), + outputs_to=(OutputTo(Many(scale=:Leaf); vars=(:distributed,)),), + environment=Environment(provider=:global), every=Hour(2), + output_routing=(trace=:stream_only,), updates=Updates(:trace; after=:producer)) + @test calls[] == 1 + @test spec.model === model + @test spec.name === :driver + @test spec.inputs.value === input.selector + @test spec.calls.leaf === call.selector + @test spec.calls.start === initializer + @test spec.input_origins === (value=:model_default,) + @test spec.call_origins === (leaf=:model_default, start=:model_default) + + # Environment resolution has no authority to reconstruct already-authored + # dependencies, replace model defaults, or change their origin. + forbidden[] = true + bindings = (T=(source=:air, reducer=MeanWeighted()),) + updated = PSE._model_spec_with_environment_settings(spec; + environment_bindings=bindings, environment_window=TestWindow) + @test calls[] == 1 + @test updated.environment_bindings === bindings + @test updated.environment_window isa TestWindow + for name in fieldnames(typeof(spec)) + name in (:environment_bindings, :environment_window) && continue + @test getfield(updated, name) === getfield(spec, name) + end + unchanged = PSE._model_spec_with_environment_settings(updated) + @test unchanged === updated + @test calls[] == 1 + @test_throws "Unsupported environment binding" PSE._model_spec_with_environment_settings( + spec; environment_bindings=(T=17,)) + @test_throws "Unsupported environment sampling window" PSE._model_spec_with_environment_settings( + spec; environment_window=3) + @test calls[] == 1 + + # Scenario overrides keep their existing validation and origin rules. + forbidden[] = false + explicit_input = One(application=:source, var=:value) + explicit_call = OptionalOne(application=:replacement) + overridden = ModelSpec(model; inputs=(value=explicit_input,), calls=(leaf=explicit_call,)) + @test calls[] == 2 + @test overridden.inputs.value === explicit_input + @test overridden.calls.leaf === explicit_call + @test overridden.calls.start === initializer + @test overridden.input_origins === (value=:model_spec,) + @test overridden.call_origins === (leaf=:model_spec, start=:model_default) + @test_throws "`process=` in scenario" ModelSpec(model; + inputs=(value=One(process=:normalized_spec_leaf),)) + @test_throws "`process=` in scenario" ModelSpec(model; + calls=(leaf=One(process=:normalized_spec_leaf),)) + @test_throws "`Initializer` requires `One" Initializer(Many(scale=:Leaf)) +end + +struct Snapshot{C} <: AbstractNormalized_Spec_SnapshotModel + calls::C +end +function PSE.dep(model::Snapshot) + model.calls[] += 1 + id = Symbol(:leaf_, model.calls[]) + return (value=Input(One(id=id, var=:value)), leaf=Call(One(id=id))) +end + +@testset "Input and Call defaults belong to the same declaration event" begin + calls = Ref(0) + first = ModelSpec(Snapshot(calls)) + @test calls[] == 1 + @test object_address(first.inputs.value).id == object_address(first.calls.leaf).id + second = ModelSpec(Snapshot(calls)) + @test calls[] == 2 + @test object_address(second.inputs.value).id == object_address(second.calls.leaf).id + @test object_address(first.inputs.value).id != object_address(second.inputs.value).id + + # A genuine author edit still uses the normal builder once, preserving + # the existing normalized declarations and their supplied origin maps. + renamed = PSE._replace_model_spec(first; name=:renamed) + @test calls[] == 3 + @test renamed.name === :renamed + @test renamed.inputs === first.inputs + @test renamed.calls === first.calls + @test renamed.input_origins === first.input_origins + @test renamed.call_origins === first.call_origins +end + +struct Leaf <: AbstractNormalized_Spec_LeafModel end +PSE.inputs_(::Leaf) = NamedTuple() +PSE.environment_inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Leaf) = (value=1f0, calls=0) +function PSE.run!(::Leaf, status, environment, constants, context) + status.value += 2f0 + status.calls += 1 + return nothing +end + +struct Driver{C,F} <: AbstractNormalized_Spec_DriverModel + dependency_calls::C + forbid_replay::F +end +function PSE.dep(model::Driver) + model.dependency_calls[] += 1 + model.forbid_replay[] && error("dependency declarations were replayed") + return (leaf=Call(One(Self(); process=:normalized_spec_leaf)),) +end +PSE.inputs_(::Driver) = NamedTuple() +PSE.outputs_(::Driver) = (seen=0f0, drivers=0) +PSE.environment_inputs_(::Driver) = (T=0f0,) +PSE.environment_hint(::Driver) = (bindings=(T=(source=:air,),),) +function PSE.run!(::Driver, status, environment, constants, context) + status.seen = only(run_call!(context, :leaf; publish=true)).status.value + environment.T + status.drivers += 1 + return nothing +end + +@testset "public hinted execution preserves model-authored Call origin without dep replay" begin + calls, forbidden = Ref(0), Ref(false) + driver = ModelSpec(Driver(calls, forbidden); name=:driver, on=One(id=:leaf)) + @test calls[] == 1 + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=(driver, + ModelSpec(Leaf(); name=:leaf, on=One(id=:leaf))), + environment=(air=17f0, duration=Hour(1))) + forbidden[] = true + simulation = run!(model; outputs=:all) + @test calls[] == 1 + resolved = simulation.compiled.applications_by_id[:driver].spec + @test resolved.calls === driver.calls + @test resolved.call_origins === driver.call_origins + @test resolved.environment_bindings.T.source === :air + @test model_status(model, :leaf).seen === 20f0 + @test model_status(model, :leaf).calls == 1 + @test model_status(model, :leaf).drivers == 1 + @test outputs(simulation)[(:leaf, ObjectId(:leaf), :value)] == [(1.0, 3f0)] +end + +@testset "hint and explicit remapping/window retain their existing precedence" begin + calls, forbidden = Ref(0), Ref(false) + source = Driver(calls, forbidden) + spec = ModelSpec(source; name=:driver, on=One(id=:leaf), + environment=Environment(sources=(T=:explicit_air,))) + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=(spec,), + environment=(air=17f0, explicit_air=23f0, duration=Hour(1))) + forbidden[] = true + hint = (bindings=(T=(source=:air, reducer=MeanWeighted()),), window=TestWindow) + resolved = PSE._model_spec_with_environment_hints(model, spec, :Leaf, hint) + @test calls[] == 1 + @test resolved.environment_bindings.T.source === :explicit_air + @test resolved.environment_window isa TestWindow + @test resolved.calls === spec.calls + @test resolved.call_origins === spec.call_origins + + forbidden[] = false + explicit_window = PlantMeteo.RollingWindow(3.0) + explicit = ModelSpec(source; environment_bindings=(T=(source=:chosen,),), + environment_window=explicit_window) + forbidden[] = true + resolved = PSE._model_spec_with_environment_hints(model, explicit, :Leaf, hint) + @test resolved.environment_bindings.T.source === :chosen + @test resolved.environment_window === explicit_window + @test calls[] == 2 + + invalid = ModelSpec(Leaf(); environment=Environment(sources=(unknown=:air,))) + @test_throws "unknown model-facing environment input" PSE._model_spec_with_environment_hints( + model, invalid, :Leaf, nothing) + errors = Any[] + diagnostic = PSE._model_spec_with_environment_hints(model, invalid, :Leaf, nothing; + on_error=error -> push!(errors, error)) + @test diagnostic === invalid + @test length(errors) == 1 + @test occursin("unknown model-facing environment input", sprint(showerror, only(errors))) +end + +struct Creator{C} <: AbstractNormalized_Spec_CreatorModel + dependency_calls::C +end +function PSE.dep(model::Creator) + model.dependency_calls[] += 1 + return (start=Initializer(One(Subtree(); scale=:Leaf, application=:leaf)),) +end +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (created=false,) +PSE.environment_inputs_(::Creator) = (T=0f0,) +PSE.environment_hint(::Creator) = (bindings=(T=(source=:air,),),) +function PSE.run!(::Creator, status, environment, constants, context) + status.created && return nothing + object = register_object!(runtime_model(context), Object(:born; scale=:Leaf, + parent=:scene, status=Status(value=3f0, calls=0))) + run_initializer!(context, :start, object) + status.created = true + return nothing +end + +@testset "environment rewrite preserves real newborn Initializer mode" begin + calls = Ref(0) + creator = ModelSpec(Creator(calls); name=:creator, on=One(id=:scene)) + model = CompositeModel(Object(:scene; scale=:Scene); applications=(creator, + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf))), + environment=(air=17f0, duration=Hour(1))) + simulation = run!(model; outputs=:all) + resolved = simulation.compiled.applications_by_id[:creator].spec + @test calls[] == 1 + @test resolved.calls.start === creator.calls.start + @test resolved.calls.start isa Initializer + @test resolved.call_origins === (start=:model_default,) + @test model_status(model, :born).calls == 1 + @test model_status(model, :born).value === 5f0 + @test isempty(get(outputs(simulation), (:leaf, ObjectId(:born), :calls), [])) + continue!(simulation) + @test calls[] == 1 + @test model_status(model, :born).calls == 2 + @test outputs(simulation)[(:leaf, ObjectId(:born), :calls)] == [(2.0, 2)] +end + +struct FreshDefaults <: AbstractNormalized_Spec_DefaultsModel end +PSE.inputs_(::FreshDefaults) = (buffer=Default(Int[]),) +PSE.outputs_(::FreshDefaults) = (count=0,) +PSE.environment_inputs_(::FreshDefaults) = (T=0f0,) +PSE.environment_hint(::FreshDefaults) = (bindings=(T=(source=:air,),),) +function PSE.run!(::FreshDefaults, status, environment, constants, context) + push!(status.buffer, Int(context.time)) + status.count += 1 + return nothing +end + +@testset "normal mutable default values remain fresh for initial and newborn objects" begin + model = CompositeModel(Object(:a; scale=:Leaf), Object(:b; scale=:Leaf); + applications=(ModelSpec(FreshDefaults(); name=:defaults, on=Many(scale=:Leaf)),), + environment=(air=17f0, duration=Hour(1))) + simulation = run!(model) + a, b = model_status(model, :a), model_status(model, :b) + @test a.buffer == b.buffer == [1] + @test a.buffer !== b.buffer + register_object!(model, Object(:c; scale=:Leaf)) + continue!(simulation) + c = model_status(model, :c) + @test a.buffer == b.buffer == [1, 2] + @test c.buffer == [2] + @test c.buffer !== a.buffer && c.buffer !== b.buffer + @test a.count == b.count == 2 + @test c.count == 1 +end + +end From 20333c7248cce27c1d812fa662c4b321b3dd7a45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 02:07:43 +0100 Subject: [PATCH 017/324] Resolve distributed defaults at birth and adopt refreshed schedules --- src/ModelSpec.jl | 16 +- src/composite_model/compilation.jl | 136 +++++++++------ src/composite_model/runtime_outputs.jl | 34 ++-- src/output_schema.jl | 5 + src/visualization/model_graph_editor_api.jl | 2 +- src/visualization/model_graph_view.jl | 9 +- test/runtests.jl | 2 + test/test-model-api-stabilization.jl | 4 +- .../test-model-distributed-route-ownership.jl | 162 ++++++++++++++++++ test/test-model-refreshed-schedule.jl | 135 +++++++++++++++ 10 files changed, 426 insertions(+), 79 deletions(-) create mode 100644 test/test-model-distributed-route-ownership.jl create mode 100644 test/test-model-refreshed-schedule.jl diff --git a/src/ModelSpec.jl b/src/ModelSpec.jl index ac898a5f2..da69b28e9 100644 --- a/src/ModelSpec.jl +++ b/src/ModelSpec.jl @@ -133,12 +133,11 @@ function _normalize_outputs_to(destinations) )) end -function _resolved_output_destinations(spec::ModelSpec, effective_model=model_(spec)) - schema = _distributed_output_schema(effective_model) +function _output_destination_layout(spec::ModelSpec, distributed_names, effective_model=model_(spec)) destinations = spec.outputs_to application = isnothing(spec.name) ? process(effective_model) : spec.name context = "Application `$(application)`" - for name in keys(schema) + for name in distributed_names get(spec.output_routing, name, :canonical) === :stream_only && throw(ArgumentError( "$(context) cannot route Distributed output `$(name)` as stream_only: " * "output targets write destination status. Use canonical routing for this variable.", @@ -150,14 +149,14 @@ function _resolved_output_destinations(spec::ModelSpec, effective_model=model_(s inferred && length(destinations) != 1 && throw(ArgumentError( "$(context) has multiple OutputTo destinations; specify `vars` for every entry.", )) - names = inferred ? keys(schema) : destination.vars + names = inferred ? distributed_names : destination.vars isempty(names) && throw(ArgumentError( "$(context) has no Distributed outputs to infer for OutputTo.", )) for name in names - haskey(schema, name) || throw(ArgumentError( + name in distributed_names || throw(ArgumentError( "$(context) binds `$(name)` in OutputTo, but it is not declared as " * - "a Distributed output. Declared distributed outputs: `$(keys(schema))`.", + "a Distributed output. Declared distributed outputs: `$(distributed_names)`.", )) name in used && throw(ArgumentError( "$(context) binds distributed output `$(name)` more than once in outputs_to.", @@ -166,12 +165,12 @@ function _resolved_output_destinations(spec::ModelSpec, effective_model=model_(s end ( selector=destination.selector, - vars=NamedTuple{names}(map(name -> schema[name], names)), + variable_names=Tuple(names), coverage=destination.coverage, origin=inferred ? :inferred : :explicit, ) end - missing = Tuple(name for name in keys(schema) if !(name in used)) + missing = Tuple(name for name in distributed_names if !(name in used)) isempty(missing) || throw(ArgumentError( "$(context) declares Distributed output(s) `$(missing)` without an " * "OutputTo binding in `outputs_to`.", @@ -179,6 +178,7 @@ function _resolved_output_destinations(spec::ModelSpec, effective_model=model_(s return resolved end + """ Updates(vars...; after=nothing) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index bd403847f..3370cda26 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -197,15 +197,14 @@ end _compiled_call_name(::CompiledModelCallPlan{NAME}) where {NAME} = NAME @inline _compiled_call_mode(::CompiledModelCallPlan{NAME,MODE}) where {NAME,MODE} = MODE -"""Immutable authored cross-object output declaration for one application.""" -struct CompiledModelOutputDestinationPlan{GROUP,SEL,M,D,C} +"""Immutable value-free cross-object output route for one application.""" +struct CompiledModelOutputDestinationPlan{GROUP,NAMES,SEL,M,C} slot::Int application_slot::Int application_id::Symbol group::Symbol selector::SEL matcher::M - declarations::D multiplicity::Symbol coverage::C end @@ -217,15 +216,15 @@ function CompiledModelOutputDestinationPlan( group::Symbol, selector, matcher, - declarations, + variable_names::Tuple{Vararg{Symbol}}, multiplicity, coverage, ) return CompiledModelOutputDestinationPlan{ group, + variable_names, typeof(selector), typeof(matcher), - typeof(declarations), typeof(coverage), }( slot, @@ -234,15 +233,25 @@ function CompiledModelOutputDestinationPlan( group, selector, matcher, - declarations, multiplicity, coverage, ) end -"""Resolved destination membership before status references are constructed.""" -struct ResolvedModelOutputDestination{P} +_output_destination_variable_names(::CompiledModelOutputDestinationPlan{GROUP,NAMES}) where {GROUP,NAMES} = NAMES + +@inline function Base.getproperty(plan::CompiledModelOutputDestinationPlan, name::Symbol) + name === :variable_names && return _output_destination_variable_names(plan) + return getfield(plan, name) +end + +Base.propertynames(plan::CompiledModelOutputDestinationPlan) = + (fieldnames(typeof(plan))..., :variable_names) + +"""Real effective declarations and membership before status references are constructed.""" +struct ResolvedModelOutputDestination{P,D} plan::P + declarations::D execution_object_id::ObjectId destination_ids::Vector{ObjectId} end @@ -277,7 +286,6 @@ end name === :group && return getfield(plan, :group) name === :selector && return getfield(plan, :selector) name === :matcher && return getfield(plan, :matcher) - name === :declarations && return getfield(plan, :declarations) name === :multiplicity && return getfield(plan, :multiplicity) name === :coverage && return getfield(plan, :coverage) return getproperty(plan, name) @@ -333,11 +341,11 @@ struct CompiledApplicationScheduleEntry end """Immutable cadence definitions for root-scheduled applications.""" -struct CompiledApplicationSchedule{E,A,P,G} - entries::E - always_entry_indices::A - periodic_entry_indices::P - generic_entry_indices::G +mutable struct CompiledApplicationSchedule{E,A,P,G} + const entries::E + const always_entry_indices::A + const periodic_entry_indices::P + const generic_entry_indices::G end """Reverse candidate index for compiled selector matchers.""" @@ -1301,7 +1309,7 @@ function _application_output_selectors( variable in _model_canonical_output_names(application) && push!(selectors, application.applies_to) for plan in _application_plans(plans.by_application, application.id) - variable in keys(plan.declarations) || continue + variable in plan.variable_names || continue push!(selectors, plan.selector) end return selectors @@ -2323,9 +2331,11 @@ function _compile_scene( :call_binding_compile, started_at, ) + applications_by_id = _applications_by_id(applications) distributed_outputs = _compile_model_distributed_outputs( model, applications, + applications_by_id, scenario_plan.manual_application_ids, scenario_plan.distributed_output_plans, ) @@ -2370,7 +2380,6 @@ function _compile_scene( call_owners = scenario_plan.call_owners application_children = scenario_plan.application_children application_order = scenario_plan.application_order - applications_by_id = _applications_by_id(applications) ordered_applications = Tuple( applications_by_id[application_id] for application_id in application_order @@ -5209,27 +5218,32 @@ end _resolve_model_output_destinations( ::CompositeModel, - applications, + applications_by_id, ::NoCompiledDistributedOutputPlans, ) = () +# Port names are authored metadata; defaults belong to the actual initial or +# newborn destination event, never a previous binding's cached declaration. +function _model_output_destination_declarations( + application, execution_object_id, + ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, +) where {GROUP,NAMES} + effective_model = _application_model(application, execution_object_id) + selected = NamedTuple{NAMES}(_output_schema(effective_model)) + return map(output -> output.declaration, selected) +end + function _resolve_model_output_destinations( model::CompositeModel, - applications, + applications_by_id, compiled_plans::CompiledDistributedOutputPlans, ) resolved = ResolvedModelOutputDestination[] for plan in compiled_plans.plans - application = applications[plan.application_slot] + application = applications_by_id[plan.application_id] for execution_object_id in application.target_ids - effective_model = _application_model(application, execution_object_id) - declarations = _distributed_output_schema(effective_model) - names = keys(plan.declarations) - effective_declarations = NamedTuple{names}(map(name -> declarations[name], names)) - effective_plan = CompiledModelOutputDestinationPlan( - plan.slot, plan.application_slot, plan.application_id, plan.group, - plan.selector, plan.matcher, effective_declarations, plan.multiplicity, - plan.coverage, + declarations = _model_output_destination_declarations( + application, execution_object_id, plan, ) destination_ids = _dependency_object_ids( model, @@ -5241,7 +5255,8 @@ function _resolve_model_output_destinations( push!( resolved, ResolvedModelOutputDestination( - effective_plan, + plan, + declarations, execution_object_id, destination_ids, ), @@ -5268,7 +5283,7 @@ function _push_compiled_writer_owner!( return ownership end -function _validate_compiled_writer_ownership!(ownership, applications) +function _validate_compiled_writer_ownership!(ownership, applications_by_id) groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() for ((object_id, variable), owners) in ownership sort!(owners; by=owner -> owner.application_slot) @@ -5290,7 +5305,7 @@ function _validate_compiled_writer_ownership!(ownership, applications) ), ( owner.application_slot, - applications[owner.application_slot], + applications_by_id[owner.application_id], ), ) end @@ -5301,6 +5316,7 @@ end function _compile_model_writer_ownership( applications, + applications_by_id, manual_application_ids, resolved_destinations, ) @@ -5329,9 +5345,8 @@ function _compile_model_writer_ownership( end for resolved in resolved_destinations plan = resolved.plan - application = applications[plan.application_slot] for destination_id in resolved.destination_ids - for variable_ in keys(plan.declarations) + for variable_ in plan.variable_names variable = Symbol(variable_) _push_compiled_writer_owner!( ownership, @@ -5348,7 +5363,7 @@ function _compile_model_writer_ownership( end end end - return _validate_compiled_writer_ownership!(ownership, applications) + return _validate_compiled_writer_ownership!(ownership, applications_by_id) end _validate_manual_model_output_destination_plans!(::NoCompiledDistributedOutputPlans, _) = nothing @@ -6143,7 +6158,7 @@ function _validate_required_model_output_destinations!( missing = NamedTuple[] for resolved in resolved_destinations for destination_id in resolved.destination_ids - for (variable_, declaration) in pairs(resolved.plan.declarations) + for (variable_, declaration) in pairs(resolved.declarations) declaration isa Required || continue variable = Symbol(variable_) if _status_has_variable(model, destination_id, variable) @@ -6220,7 +6235,7 @@ function _prepare_model_output_destination_statuses!( model, destination_id, ) - for (variable_, declaration) in pairs(resolved.plan.declarations) + for (variable_, declaration) in pairs(resolved.declarations) declaration isa Default || continue variable = Symbol(variable_) if preparation isa Status @@ -6256,7 +6271,7 @@ function _model_output_destination_columns( model::CompositeModel, resolved::ResolvedModelOutputDestination, ) - declarations = resolved.plan.declarations + declarations = resolved.declarations names = Tuple(Symbol.(keys(declarations))) columns = map(names) do variable refs = Base.RefValue[ @@ -6333,7 +6348,7 @@ function _index_model_output_destination_ids(bindings) index = Dict{Tuple{Symbol,Symbol},Vector{ObjectId}}() merged_keys = Set{Tuple{Symbol,Symbol}}() for binding in bindings - for variable_ in keys(binding.declarations) + for variable_ in binding.plan.variable_names variable = Symbol(variable_) key = (binding.application_id, variable) destination_ids = get(index, key, nothing) @@ -6362,6 +6377,7 @@ end function _compile_model_distributed_outputs( model::CompositeModel, applications, + applications_by_id, manual_application_ids, ::NoCompiledDistributedOutputPlans, ) @@ -6375,16 +6391,18 @@ end function _compile_model_distributed_outputs( model::CompositeModel, applications, + applications_by_id, manual_application_ids, plans::CompiledDistributedOutputPlans, ) resolved = _resolve_model_output_destinations( model, - applications, + applications_by_id, plans, ) ownership = _compile_model_writer_ownership( applications, + applications_by_id, manual_application_ids, resolved, ) @@ -6507,6 +6525,11 @@ function _incremental_distributed_output_addition!( resolved_additions, ResolvedModelOutputDestination( binding.plan, + _model_output_destination_declarations( + applications_by_id[binding.application_id], + binding.execution_object_id, + binding.plan, + ), binding.execution_object_id, destination_ids, ), @@ -6543,7 +6566,7 @@ function _incremental_distributed_output_addition!( for resolved in resolved_additions plan = resolved.plan for destination_id in resolved.destination_ids - for variable_ in keys(plan.declarations) + for variable_ in plan.variable_names variable = Symbol(variable_) _stage_distributed_writer_owner!( staged_ownership, @@ -6561,7 +6584,7 @@ function _incremental_distributed_output_addition!( end end end - _validate_compiled_writer_ownership!(staged_ownership, applications) + _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) _prepare_model_output_destination_statuses!(model, resolved_additions) column_additions = Any[] @@ -6570,7 +6593,7 @@ function _incremental_distributed_output_addition!( groups = previous.by_execution_target[key] binding = getproperty(groups, resolved.plan.group) columns = _model_output_destination_columns(model, resolved) - for variable in keys(binding.declarations) + for variable in binding.plan.variable_names existing_references = parent(getproperty(binding.columns, variable)) added_references = parent(getproperty(columns, variable)) eltype(added_references) <: eltype(existing_references) || @@ -6585,7 +6608,7 @@ function _incremental_distributed_output_addition!( for addition in column_additions binding = addition.binding resolved = addition.resolved - for variable_ in keys(binding.declarations) + for variable_ in binding.plan.variable_names variable = Symbol(variable_) append!( parent(getproperty(binding.columns, variable)), @@ -6641,6 +6664,7 @@ function _refresh_model_distributed_outputs( current = _compile_model_distributed_outputs( model, applications, + applications_by_id, manual_application_ids, plans, ) @@ -6664,7 +6688,7 @@ function _new_writers_on_existing_destinations(outputs, new_targets, added_ids) if isnothing(by_variable) by_variable = Dict{Symbol,Vector{Tuple{ObjectId,Symbol}}}() end - for variable in keys(group.declarations) + for variable in group.plan.variable_names push!( get!(Vector{Tuple{ObjectId,Symbol}}, by_variable, variable), (destination, application_id), @@ -6689,7 +6713,7 @@ function _changed_writers_on_surviving_destinations(model, previous, current, ch if isnothing(by_variable) by_variable = Dict{Symbol,Vector{Tuple{ObjectId,Symbol}}}() end - for variable in keys(group.declarations) + for variable in group.plan.variable_names push!(get!(Vector{Tuple{ObjectId,Symbol}}, by_variable, variable), (destination, group.application_id)) end @@ -7557,7 +7581,7 @@ function _input_plan_writer_applications( application.id, (), ) - for variable in keys(plan.declarations) + for variable in plan.variable_names candidates = get!(Vector{CompiledModelApplication}, writers, variable) # An application can write the same name through several # destination plans. Keep it once, in application order. @@ -7596,7 +7620,7 @@ function _application_may_output_variable( application.applies_to, ) && return true return any( - plan -> variable in keys(plan.declarations) && + plan -> variable in plan.variable_names && _selector_labels_may_overlap(source_selector, plan.selector), _application_plans(plans.by_application, application.id), ) @@ -7616,7 +7640,7 @@ function _application_declares_distributed_output( plans::CompiledDistributedOutputPlans, ) return any( - plan -> variable in keys(plan.declarations) && + plan -> variable in plan.variable_names && _selector_labels_may_overlap(source_selector, plan.selector), _application_plans(plans.by_application, application.id), ) @@ -7895,11 +7919,13 @@ function _compile_model_output_destination_plans( ) plans = CompiledModelOutputDestinationPlan[] for application in applications - destinations = _resolved_output_destinations(application.spec) + distributed_names = _distributed_output_names(application.spec) + destinations = _output_destination_layout(application.spec, distributed_names) if !isnothing(application.model_overrides) for replacement in values(application.model_overrides) - _resolved_output_destinations(application.spec, replacement) - Set(keys(_distributed_output_schema(replacement))) == Set(keys(_distributed_output_schema(application.spec))) || + replacement_names = _distributed_output_names(replacement) + _output_destination_layout(application.spec, replacement_names, replacement) + Set(replacement_names) == Set(distributed_names) || error("Object override for application `$(application.id)` has incompatible distributed output names.") end end @@ -7919,7 +7945,7 @@ function _compile_model_output_destination_plans( Symbol(group_name), selector, _compile_selector_matcher(model, selector), - getproperty(destination, :vars), + getproperty(destination, :variable_names), multiplicity(selector), getproperty(destination, :coverage), ), @@ -7955,9 +7981,11 @@ end function _application_declares_output_name(application, variable::Symbol) variable in _model_output_names(application) && return true - destinations = _resolved_output_destinations(application.spec) + destinations = _output_destination_layout( + application.spec, _distributed_output_names(application.spec), + ) return any( - destination -> variable in keys(destination.vars), + destination -> variable in destination.variable_names, values(destinations), ) end @@ -9098,7 +9126,7 @@ function _explain_output_bindings(outputs::CompiledDistributedOutputs, compiled) origin=origin, destination_ids=[id.value for id in binding.destination_ids], destination_count=length(binding.destination_ids), - variables=Tuple(Symbol.(keys(binding.declarations))), + variables=Tuple(Symbol.(binding.plan.variable_names)), column_types=NamedTuple{Tuple(keys(binding.columns))}( Tuple(typeof(column) for column in values(binding.columns)), ), diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 25bd724fd..7aa9307da 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1260,7 +1260,8 @@ function _retain_execution_group(previous::G, current::G) where {G<:CompiledAppl return previous end -mutable struct RuntimeApplicationSchedule +mutable struct RuntimeApplicationSchedule{P} + const definition::P next_due_steps::Vector{Int} heap::Vector{Int} due_entry_indices::Vector{Int} @@ -1345,6 +1346,7 @@ function _runtime_application_schedule( ) entry_count = length(plan.entries) schedule = RuntimeApplicationSchedule( + plan, fill(typemax(Int), entry_count), Int[], Int[], @@ -1364,6 +1366,15 @@ function _runtime_application_schedule( return schedule end +# Author/configuration refresh can replace the cadence or its root order. +# Ordinary lifecycle refresh shares its immutable definition and reuses the heap. +@inline function _refreshed_runtime_application_schedule( + previous::RuntimeApplicationSchedule, definition::CompiledApplicationSchedule, +) + previous.definition === definition && return previous + return _runtime_application_schedule(definition; after_step=previous.last_step) +end + @inline function _generic_schedule_entry_is_due( entry::CompiledApplicationScheduleEntry, step::Int, @@ -1931,7 +1942,7 @@ function _initialize_changed_model_output_streams!( ) isnothing(groups) && return nothing for binding in values(groups) - for variable_ in keys(binding.declarations) + for variable_ in binding.plan.variable_names variable = Symbol(variable_) variable in variables || continue for destination_id in binding.destination_ids @@ -3280,7 +3291,7 @@ function _runtime_model_distributed_output_streams( isnothing(groups) && return () outputs = Any[] for binding in values(groups) - for variable_ in keys(binding.declarations) + for variable_ in binding.plan.variable_names variable = Symbol(variable_) variable in retained_variables || continue source_streams = Any[ @@ -3371,7 +3382,7 @@ function _runtime_model_output_targets( alignment_id = length(anchors) end target = OutputTargets(binding, alignment_id) - for name in keys(binding.declarations) + for name in binding.plan.variable_names push!(names, name) push!(targets, target) end @@ -3799,7 +3810,7 @@ function _model_execution_outputs_match( if !isnothing(groups) isnothing(temporal_streams) && return false for binding in values(groups) - for variable_ in keys(binding.declarations) + for variable_ in binding.plan.variable_names variable = Symbol(variable_) variable in variables || continue output_index += 1 @@ -3884,7 +3895,7 @@ function _model_execution_output_targets_match( count = 0 ordered_bindings = values(bindings) for (index, binding) in enumerate(ordered_bindings) - for name in keys(binding.declarations) + for name in binding.plan.variable_names hasproperty(targets, name) || return false target = getproperty(targets, name) target.binding === binding || return false @@ -3892,10 +3903,10 @@ function _model_execution_output_targets_match( end # A monotonic addition can extend existing columns and streams in place. # Rebuild only if it changes which destination declarations are aligned. - current = getproperty(targets, first(keys(binding.declarations))) + current = getproperty(targets, first(binding.plan.variable_names)) for previous_index in 1:(index - 1) previous = ordered_bindings[previous_index] - previous_target = getproperty(targets, first(keys(previous.declarations))) + previous_target = getproperty(targets, first(previous.plan.variable_names)) was_aligned = current.alignment_id == previous_target.alignment_id now_aligned = binding.destination_ids == previous.destination_ids was_aligned == now_aligned || return false @@ -4538,7 +4549,8 @@ function _refresh_model_execution_plan( same_groups ? previous.groups : groups, same_batches ? previous.batches : batches, groups_by_slot, - previous.schedule, + _refreshed_runtime_application_schedule(previous.schedule, + compiled.scenario_plan.application_schedule), compiled.revision, env_bindings.environment_revision, ), @@ -4706,7 +4718,7 @@ function _model_application_output_variables( plans = compiled.scenario_plan.distributed_output_plans if plans isa CompiledDistributedOutputPlans for plan in _application_plans(plans.by_application, application.id) - for variable_ in keys(plan.declarations) + for variable_ in plan.variable_names variable = Symbol(variable_) variable in variables || push!(variables, variable) end @@ -8050,7 +8062,7 @@ function _model_request_matches_distributed_output( plans = compiled.scenario_plan.distributed_output_plans plans isa CompiledDistributedOutputPlans || return false return any( - plan -> request.var in keys(plan.declarations) && + plan -> request.var in plan.variable_names && _selector_labels_may_overlap(request.selector, plan.selector), _application_plans(plans.by_application, application.id), ) diff --git a/src/output_schema.jl b/src/output_schema.jl index 9804bde51..8e3f7ab5d 100644 --- a/src/output_schema.jl +++ b/src/output_schema.jl @@ -43,6 +43,11 @@ function _local_output_schema(model) return NamedTuple{names}(map(name -> schema[name], names)) end +function _distributed_output_names(model) + schema = _output_schema(model) + return Tuple(name for name in keys(schema) if schema[name] isa Distributed) +end + function _distributed_output_schema(model) schema = _output_schema(model) names = Tuple(name for name in keys(schema) if schema[name] isa Distributed) diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index a7ca926c3..672fd672e 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -726,7 +726,7 @@ end function _apply_model_graph_edit!(model::CompositeModel, edit::SetModelOutputDestinations) spec = _model_edit_spec(model, edit.application) replacement = _replace_model_spec(spec; outputs_to=edit.destinations) - _resolved_output_destinations(replacement) + _output_destination_layout(replacement, _distributed_output_names(replacement)) return _replace_model_edit_spec!(model, edit.application, replacement) end diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 4a79183c7..c01489306 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -442,6 +442,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) _compile_model_distributed_outputs( model, applications, + _applications_by_id(applications), manual_application_ids, distributed_output_plans, ) @@ -819,7 +820,7 @@ end function _model_graph_output_destinations(spec) resolved = try - _resolved_output_destinations(spec) + _output_destination_layout(spec, _distributed_output_names(spec)) catch # Invalid declarations remain editable; compilation reports the error. nothing @@ -828,7 +829,7 @@ function _model_graph_output_destinations(spec) Dict{String,Any}( "selector" => _model_graph_selector_dict(destination.selector), "vars" => isnothing(destination.vars) ? nothing : collect(string.(destination.vars)), - "resolvedVars" => isnothing(resolved) ? nothing : collect(string.(keys(resolved[index].vars))), + "resolvedVars" => isnothing(resolved) ? nothing : collect(string.(resolved[index].variable_names)), "origin" => isnothing(destination.vars) ? "inferred" : "explicit", "coverage" => string(destination.coverage), ) @@ -1685,7 +1686,7 @@ end function _model_graph_distributed_initialization!(rows, report) destinations = try plans = _compile_model_output_destination_plans(report.model, report.applications) - _resolve_model_output_destinations(report.model, report.applications, plans) + _resolve_model_output_destinations(report.model, _applications_by_id(report.applications), plans) catch # A binding error is already in the report. Valid destinations can still # expose required storage when later compilation phases fail. @@ -1694,7 +1695,7 @@ function _model_graph_distributed_initialization!(rows, report) for destination in destinations for object_id in destination.destination_ids object = _model_object(report.model, object_id) - for (variable, declaration) in pairs(destination.plan.declarations) + for (variable, declaration) in pairs(destination.declarations) supplied = variable in get(report.initial_status_variables, object_id, Set{Symbol}()) value = supplied ? object.status[variable] : declaration isa Default ? declaration.value : nothing diff --git a/test/runtests.jl b/test/runtests.jl index 502041ef9..fd7ea0df6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -87,6 +87,7 @@ else include("test-model-authored-call-plans.jl") include("test-model-spec-normalization.jl") include("test-model-runtime-snapshot-isolation.jl") + include("test-model-refreshed-schedule.jl") include("test-model-authored-spec-matching.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") @@ -304,6 +305,7 @@ else @testset "Distributed output declarations" begin include("test-model-output-destination-declarations.jl") + include("test-model-distributed-route-ownership.jl") end @testset "Distributed output runtime" begin diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 9db404f20..bbd98d8c8 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -1672,7 +1672,9 @@ end @test !ismutabletype(typeof(scenario_plan)) @test !ismutabletype(typeof(application_plan)) - @test !ismutabletype(typeof(application_schedule)) + @test ismutabletype(typeof(application_schedule)) + @test all(name -> isconst(typeof(application_schedule), name), + fieldnames(typeof(application_schedule))) @test !ismutabletype(typeof(only(application_schedule.entries))) @test ismutabletype(typeof(application)) @test isconst(typeof(application), :plan) diff --git a/test/test-model-distributed-route-ownership.jl b/test/test-model-distributed-route-ownership.jl new file mode 100644 index 000000000..23c7c8663 --- /dev/null +++ b/test/test-model-distributed-route-ownership.jl @@ -0,0 +1,162 @@ +module DistributedRouteOwnershipChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "route_ownership_before" verbose=false +PSE.@process "route_ownership_broken" verbose=false +PSE.@process "route_ownership_writer" verbose=false + +struct Before <: AbstractRoute_Ownership_BeforeModel end +PSE.inputs_(::Before) = NamedTuple() +PSE.outputs_(::Before) = (before=0,) +PSE.run!(::Before, status, environment, constants, context) = (status.before += 1; nothing) + +const failed_output_calls = Ref(0) +struct Broken <: AbstractRoute_Ownership_BrokenModel end +PSE.inputs_(::Broken) = NamedTuple() +function PSE.outputs_(::Broken) + failed_output_calls[] += 1 + error("intentional route ownership authoring failure") +end + +struct Writer{S,C} <: AbstractRoute_Ownership_WriterModel + seed::S + output_calls::C +end +PSE.inputs_(::Writer) = NamedTuple() +function PSE.outputs_(model::Writer) + model.output_calls[] += 1 + return (writer_runs=0, payload=Distributed(Default(fill(model.seed[], 2)))) +end +PSE.run!(::Writer, status, environment, constants, context) = (status.writer_runs += 1; nothing) + +writer_spec(writer) = ModelSpec(writer; name=:writer, on=One(id=:scene), + outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope())),)) + +@testset "public diagnostics retain distributed outputs after a skipped authored slot" begin + failed_output_calls[] = 0 + seed, queries = Ref(1f0), Ref(0) + model = CompositeModel(Object(:scene; scale=:Scene), Object(:a; scale=:Leaf), + Object(:b; scale=:Leaf); applications=( + ModelSpec(Before(); name=:before, on=One(id=:scene)), + ModelSpec(Broken(); name=:broken, on=One(id=:scene)), + writer_spec(Writer(seed, queries)), + )) + @test failed_output_calls[] == 1 + seed[] = 7f0 + report = PSE.compile_model_report(model) + @test [app.id for app in report.applications] == [:before, :writer] + @test [app.slot for app in report.applications] == [1, 3] + @test failed_output_calls[] == 1 + messages = [diagnostic.message for diagnostic in report.diagnostics] + @test !any(message -> occursin("BoundsError", message), messages) + @test any(message -> occursin("intentional route ownership", message), messages) + left, right = model_status(report.model, :a), model_status(report.model, :b) + has_left = left isa Status && hasproperty(left, :payload) + has_right = right isa Status && hasproperty(right, :payload) + @test has_left && has_right + if has_left && has_right + @test left.payload == right.payload == fill(7f0, 2) + @test identity(left.payload !== right.payload) + end + @test isnothing(model_status(model, :a)) + @test isnothing(model_status(model, :b)) + @test identity(PSE.Advanced.compiled_bindings(model) === nothing) +end + +@testset "real initial and newborn distributed defaults use fresh model values" begin + seed, queries = Ref(1f0), Ref(0) + supplied = Float32[99, 99] + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:a; scale=:Leaf, status=Status(payload=supplied)), + Object(:b; scale=:Leaf); applications=(writer_spec(Writer(seed, queries)),)) + author_calls = queries[] + seed[] = 7f0 + simulation = run!(model; outputs=:all) + a, b = model_status(model, :a), model_status(model, :b) + @test queries[] > author_calls + @test identity(a.payload === supplied) + @test a.payload == Float32[99, 99] + @test b.payload == Float32[7, 7] + @test identity(a.payload !== b.payload) + before_birth_calls = queries[] + b.payload[1] = 42f0 + seed[] = 11f0 + register_object!(model, Object(:c; scale=:Leaf)) + step!(simulation) + c = model_status(model, :c) + @test queries[] > before_birth_calls + @test a.payload == Float32[99, 99] + @test b.payload == Float32[42, 7] + @test c.payload == Float32[11, 11] + @test identity(c.payload !== a.payload && c.payload !== b.payload) + @test model_status(model, :scene).writer_runs == 2 + @test outputs(simulation)[(:writer, ObjectId(:scene), :writer_runs)] == [(1.0, 1), (2.0, 2)] +end +@testset "logical destination plans keep static names and no scientific defaults" begin + seed, queries = Ref(2f0), Ref(0) + spec = writer_spec(Writer(seed, queries)) + before_layout = queries[] + layout = only(PSE._output_destination_layout(spec, (:payload,))) + @test queries[] == before_layout + @test layout.variable_names === (:payload,) + @test layout.origin === :inferred + @test layout.coverage === :exact + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:leaf; scale=:Leaf); applications=(spec,)) + applications = PSE._compile_model_applications(model, model.applications, + PSE._model_timeline(model)) + destinations = PSE._compile_model_output_destination_plans(model, applications) + plan = only(destinations.plans) + @test (@inferred PSE._output_destination_variable_names(plan)) === (:payload,) + @test !hasproperty(plan, :declarations) + @test !(:declarations in fieldnames(typeof(plan))) + @test plan.variable_names === (:payload,) + seed[] = 8f0 + before_actual = queries[] + declarations = @inferred PSE._model_output_destination_declarations( + only(applications), ObjectId(:scene), plan) + @test queries[] == before_actual + 1 + @test declarations.payload.value == Float32[8, 8] + resolved = only(PSE._resolve_model_output_destinations(model, PSE._applications_by_id(applications), destinations)) + @test identity(resolved.plan === plan) + @test resolved.declarations.payload.value == Float32[8, 8] + @test isnothing(model_status(model, :leaf)) + simulation = run!(model; steps=0) + binding = only(simulation.compiled.distributed_outputs.bindings) + @test binding.variable_names === (:payload,) + @test !hasproperty(binding, :declarations) + @test !(:declarations in fieldnames(typeof(binding))) + @test identity(binding.columns.payload[1] === model_status(model, :leaf).payload) +end + +@testset "public graph views and destination edits preserve exact resolved port names" begin + GE = PSE.GraphEditor + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:leaf; scale=:Leaf); applications=(writer_spec(Writer(Ref(3f0), Ref(0))),)) + view = GE.model_graph_view(model) + @test isempty(view.diagnostics) + inferred = only(only(view.applications)["outputsTo"]) + @test inferred["vars"] === nothing + @test inferred["origin"] == "inferred" + @test inferred["resolvedVars"] == ["payload"] + + edited = GE.apply_model_graph_edit(model, GE.SetModelOutputDestinations( + GE.GlobalApplicationRef(:writer), (OutputTo(One(id=:leaf); vars=(:payload,)),), + )) + explicit_view = GE.model_graph_view(edited) + @test isempty(explicit_view.diagnostics) + explicit = only(only(explicit_view.applications)["outputsTo"]) + @test explicit["vars"] == ["payload"] + @test explicit["origin"] == "explicit" + @test explicit["resolvedVars"] == ["payload"] + @test only(outputs_to(only(model.applications))).vars === nothing + @test only(outputs_to(only(edited.applications))).vars === (:payload,) + @test_throws "not declared as a Distributed output" GE.apply_model_graph_edit( + model, GE.SetModelOutputDestinations(GE.GlobalApplicationRef(:writer), + (OutputTo(One(id=:leaf); vars=(:unknown,)),)), + ) + @test isnothing(model_status(model, :leaf)) + @test isnothing(model_status(edited, :leaf)) +end + +end diff --git a/test/test-model-refreshed-schedule.jl b/test/test-model-refreshed-schedule.jl new file mode 100644 index 000000000..dc6b1b1a3 --- /dev/null +++ b/test/test-model-refreshed-schedule.jl @@ -0,0 +1,135 @@ +module PublicScheduleForceChecks + +using Dates, PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "public_schedule_force" verbose=false + +struct Tick{T} <: AbstractPublic_Schedule_ForceModel + trace::T +end +PSE.inputs_(::Tick) = NamedTuple() +PSE.outputs_(::Tick) = (ticks=0,) +function PSE.run!(model::Tick, status, environment, constants, context) + push!(model.trace, Int(context.time)) + status.ticks += 1 + return nothing +end + +@testset "public configuration refresh adopts the current cadence within its prepared schema" begin + for (old_cadence, new_cadence, expected) in ( + (2, 4, [1, 5]), + (4, 2, [1, 3, 5, 7]), + (3, 5, [1, 6]), + ) + @testset "cadence $old_cadence to $new_cadence" begin + trace = Int[] + spec = ModelSpec(Tick(trace); name=:tick, on=One(id=:scene), + every=Hour(old_cadence)) + model = CompositeModel(Object(:scene; scale=:Scene); + applications=(spec,), + environment=[(duration=Hour(1), T=20.0) for _ in 1:7]) + simulation = run!(model; steps=1, outputs=:all) + @test trace == [1] + original_cell = PSE.refvalue(model_status(model, :scene), :ticks) + previous_type = typeof(simulation.compiled) + model.applications[1] = PSE._replace_model_spec(model.applications[1]; + every=Hour(new_cadence)) + current = Advanced.refresh_bindings!(model; force=true) + @test typeof(current) === previous_type + @test PSE.refvalue(model_status(model, :scene), :ticks) === original_cell + continue!(simulation; steps=6) + @test trace == expected + @test model_status(model, :scene).ticks == length(expected) + @test collect(outputs(simulation)[(:tick, ObjectId(:scene), :ticks)]) == + [(Float64(time), value) for (value, time) in enumerate(expected)] + end + end +end + +@testset "a changed schedule schema requires a fresh simulation" begin + for (old_cadence, new_cadence, expected) in ((1, 3, [1, 4, 7]), (3, 1, collect(1:7))) + trace = Int[] + model = CompositeModel(Object(:scene; scale=:Scene); + applications=(ModelSpec(Tick(trace); name=:tick, on=One(id=:scene), + every=Hour(old_cadence)),), + environment=[(duration=Hour(1), T=20.0) for _ in 1:7]) + simulation = run!(model; steps=1, outputs=:all) + original_cell = PSE.refvalue(model_status(model, :scene), :ticks) + previous_type = typeof(simulation.compiled) + model.applications[1] = PSE._replace_model_spec(model.applications[1]; + every=Hour(new_cadence)) + current = Advanced.refresh_bindings!(model; force=true) + @test typeof(current) !== previous_type + @test_throws ArgumentError step!(simulation) + @test trace == [1] + fresh = run!(model; steps=7, outputs=:all) + @test trace == [1; expected] + @test PSE.refvalue(model_status(model, :scene), :ticks) === original_cell + @test model_status(model, :scene).ticks == 1 + length(expected) + @test collect(outputs(fresh)[(:tick, ObjectId(:scene), :ticks)]) == + [(Float64(time), value + 1) for (value, time) in enumerate(expected)] + end +end + +@testset "growth shares the definition and copied timelines own their heaps" begin + trace = Int[] + model = CompositeModel(Object(:scene; scale=:Scene); + applications=(ModelSpec(Tick(trace); name=:tick, on=One(id=:scene), every=Hour(2)),), + environment=[(duration=Hour(1), T=20.0) for _ in 1:7]) + simulation = run!(model; steps=1, outputs=:all) + schedule = simulation.execution_plan.schedule + definition = simulation.compiled.scenario_plan.application_schedule + @test schedule.definition === definition + register_object!(model, Object(:unused; scale=:Other)) + step!(simulation) + @test simulation.execution_plan.schedule === schedule + @test simulation.compiled.scenario_plan.application_schedule === definition + @test schedule.definition === definition + @test trace == [1] + + copied = deepcopy(simulation) + @test copied.execution_plan.schedule !== schedule + @test copied.execution_plan.schedule.heap !== schedule.heap + @test copied.execution_plan.schedule.definition === + copied.compiled.scenario_plan.application_schedule + @test copied.execution_plan.schedule.definition !== definition + step!(copied) + @test model_status(copied.model, :scene).ticks == 2 + @test model_status(model, :scene).ticks == 1 + @test schedule.last_step == 2 + @test copied.execution_plan.schedule.last_step == 3 +end + +PSE.@process "schedule_force_midstep" verbose=false +struct ChangeCadence <: AbstractSchedule_Force_MidstepModel end +PSE.inputs_(::ChangeCadence) = NamedTuple() +PSE.outputs_(::ChangeCadence) = (forced=false,) +function PSE.run!(::ChangeCadence, status, environment, constants, context) + if context.time == 3.0 && !status.forced + model = runtime_model(context) + model.applications[2] = PSE._replace_model_spec(model.applications[2]; every=Hour(5)) + Advanced.refresh_bindings!(model; force=true) + status.forced = true + end + return nothing +end + +@testset "a mid-step force preserves applications already due and replans following steps" begin + trace = Int[] + model = CompositeModel(Object(:scene; scale=:Scene); + applications=( + ModelSpec(ChangeCadence(); name=:change_tick, on=One(id=:scene)), + ModelSpec(Tick(trace); name=:tick, on=One(id=:scene), every=Hour(2)), + ), environment=[(duration=Hour(1), T=20.0) for _ in 1:8]) + simulation = run!(model; steps=8, outputs=:all) + @test model_status(model, :scene).forced + @test trace == [1, 3, 6] + @test model_status(model, :scene).ticks == 3 + @test collect(outputs(simulation)[(:tick, ObjectId(:scene), :ticks)]) == + [(1.0, 1), (3.0, 2), (6.0, 3)] + @test simulation.execution_plan.schedule.definition === + simulation.compiled.scenario_plan.application_schedule + @test simulation.execution_plan.schedule.last_step == current_step(simulation) == 8 +end + +end From fd82bfa573c5c2176009b3a5468983a3599b153f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 02:36:55 +0100 Subject: [PATCH 018/324] Prepare authored variable metadata once without retaining defaults --- src/ModelSpec.jl | 3 +- src/PlantSimEngine.jl | 3 +- src/composite_model/authored_ports.jl | 113 +++++ src/composite_model/compilation.jl | 140 +++--- src/composite_model/environment_bindings.jl | 17 +- src/composite_model/runtime_outputs.jl | 18 +- src/composite_model_api.jl | 4 +- src/native_compilation.jl | 2 +- src/time/runtime/environment_backends.jl | 17 +- src/variable_contracts.jl | 12 +- src/visualization/model_graph_view.jl | 44 +- test/runtests.jl | 1 + test/test-initial-status-preparation.jl | 10 +- test/test-model-authored-port-inventory.jl | 463 ++++++++++++++++++ ...est-model-diagnostic-authoring-recovery.jl | 5 +- test/test-model-input-plan-output-metadata.jl | 34 +- test/test-model-scenario-authoring.jl | 4 +- test/test-model-spec-normalization.jl | 8 +- 18 files changed, 742 insertions(+), 156 deletions(-) create mode 100644 src/composite_model/authored_ports.jl create mode 100644 test/test-model-authored-port-inventory.jl diff --git a/src/ModelSpec.jl b/src/ModelSpec.jl index da69b28e9..2caca944f 100644 --- a/src/ModelSpec.jl +++ b/src/ModelSpec.jl @@ -540,8 +540,7 @@ variable_contracts_(m::ModelSpec) = variable_contracts_(model_(m)) _declared_contract_variable_names(spec::ModelSpec) = _declared_contract_variable_names(model_(spec)) -function _validate_variable_contract_names(spec::ModelSpec, schema) - declared = _declared_contract_variable_names(spec) +function _validate_variable_contract_names(spec::ModelSpec, schema, declared) unknown = sort!( Symbol[name for name in keys(schema) if Symbol(name) ∉ declared]; by=string, diff --git a/src/PlantSimEngine.jl b/src/PlantSimEngine.jl index e4523d7e5..93f824ca4 100644 --- a/src/PlantSimEngine.jl +++ b/src/PlantSimEngine.jl @@ -47,8 +47,7 @@ include("composite_model_api.jl") # Time-step table adapter: include("component_models/TimeStepTable.jl") -# Model application configuration: -include("ModelSpec.jl") +# CompositeModel display: include("composite_model/display.jl") # Model evaluation (statistics): diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl new file mode 100644 index 000000000..a7500e340 --- /dev/null +++ b/src/composite_model/authored_ports.jl @@ -0,0 +1,113 @@ +struct ScenarioPreparationFailure{E,B} + phase::Symbol + application_id::Union{Nothing,Symbol} + error::E + backtrace::B +end + +# Diagnostic exceptions may reference Modules/method frames. Keep the original +# exception and an independent trace while copying scientific owners normally. +function Base.deepcopy_internal(failure::ScenarioPreparationFailure, stack::IdDict) + return get!(stack, failure) do + ScenarioPreparationFailure(failure.phase, failure.application_id, + failure.error, copy(failure.backtrace)) + end +end + +struct AuthoredPortNames{NAMES} end +AuthoredPortNames(names::Tuple{Vararg{Symbol}}) = AuthoredPortNames{names}() +_authored_port_names(::AuthoredPortNames{NAMES}) where {NAMES} = NAMES +_authored_port_names(failure::ScenarioPreparationFailure) = throw(failure.error) + +struct AuthoredOutputPorts{ALL,LOCAL,DISTRIBUTED,CANONICAL} end +function AuthoredOutputPorts(all_names, local_names, distributed_names, canonical_names) + return AuthoredOutputPorts{all_names,local_names,distributed_names,canonical_names}() +end +_output_all_names(::AuthoredOutputPorts{ALL}) where {ALL} = ALL +_output_local_names(::AuthoredOutputPorts{ALL,LOCAL}) where {ALL,LOCAL} = LOCAL +_output_distributed_names(::AuthoredOutputPorts{ALL,LOCAL,DISTRIBUTED}) where {ALL,LOCAL,DISTRIBUTED} = DISTRIBUTED +_output_canonical_names(::AuthoredOutputPorts{ALL,LOCAL,DISTRIBUTED,CANONICAL}) where {ALL,LOCAL,DISTRIBUTED,CANONICAL} = CANONICAL +@inline function Base.getproperty(ports::AuthoredOutputPorts, name::Symbol) + name === :all_names && return _output_all_names(ports) + name === :local_names && return _output_local_names(ports) + name === :distributed_names && return _output_distributed_names(ports) + name === :canonical_names && return _output_canonical_names(ports) + return getfield(ports, name) +end +Base.propertynames(::AuthoredOutputPorts) = (:all_names, :local_names, :distributed_names, :canonical_names) + +# One stable owner is shared by the authored recipe and compiled application. +# Name carriers preserve static schemas without retaining initialization values. +mutable struct AuthoredPortInventory{I,O,EI,EO,C} + const inputs::I + const outputs::O + const environment_inputs::EI + const environment_outputs::EO + const contracts::C +end +@inline function Base.getproperty(ports::AuthoredPortInventory, name::Symbol) + name === :input_names && return _authored_port_names(getfield(ports, :inputs)) + name === :environment_input_names && return _authored_port_names(getfield(ports, :environment_inputs)) + name === :environment_output_names && return _authored_port_names(getfield(ports, :environment_outputs)) + return getfield(ports, name) +end +Base.propertynames(ports::AuthoredPortInventory) = + (fieldnames(typeof(ports))..., :input_names, :environment_input_names, :environment_output_names) + +_authored_metadata_value(value) = value +_authored_metadata_value(failure::ScenarioPreparationFailure) = throw(failure.error) + +function _capture_authored_metadata(operation, phase::Symbol, application_id::Symbol) + try + return operation() + catch error + error isa InterruptException && rethrow() + return ScenarioPreparationFailure(phase, application_id, error, catch_backtrace()) + end +end + +function _authored_output_ports(spec::ModelSpec) + schema = _output_schema(spec) + all_names = Tuple(Symbol(name) for name in keys(schema)) + local_names = Tuple(Symbol(name) for name in keys(schema) if !(schema[name] isa Distributed)) + distributed_names = Tuple(Symbol(name) for name in keys(schema) if schema[name] isa Distributed) + canonical_names = Tuple(name for name in local_names + if _publish_mode_for_output(spec, name) === :canonical) + return AuthoredOutputPorts(all_names, local_names, distributed_names, canonical_names) +end + +function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) + # This is the constructor's existing output read. A failed output hook + # retains its existing top-level authoring failure and application recovery. + output_ports = _authored_output_ports(spec) + model = model_(spec) + inputs = _capture_authored_metadata(:input_ports, application_id) do + AuthoredPortNames(Tuple(Symbol(name) for name in keys(_input_schema(model)))) + end + environment_inputs = _capture_authored_metadata(:environment_input_ports, application_id) do + AuthoredPortNames(Tuple(Symbol(name) for name in keys(environment_inputs_(model)))) + end + environment_outputs = _capture_authored_metadata(:environment_output_ports, application_id) do + AuthoredPortNames(Tuple(Symbol(name) for name in keys(environment_outputs_(model)))) + end + declared_contracts = _capture_authored_metadata(:variable_contracts, application_id) do + _variable_contract_declarations(spec) + end + # Shape validation precedes declared-name reads even for empty contracts. + # Keep original failures so later phases rethrow without a callback. + failed_names = findfirst(result -> result isa ScenarioPreparationFailure, + (inputs, environment_inputs, environment_outputs)) + contracts = if declared_contracts isa ScenarioPreparationFailure + declared_contracts + elseif !isnothing(failed_names) + (inputs, environment_inputs, environment_outputs)[failed_names] + else + _capture_authored_metadata(:variable_contract_names, application_id) do + declared = Set{Symbol}(_authored_port_names(inputs)) + union!(declared, output_ports.local_names, output_ports.distributed_names, + _authored_port_names(environment_inputs), _authored_port_names(environment_outputs)) + _validate_variable_contract_names(spec, declared_contracts, declared) + end + end + return AuthoredPortInventory(inputs, output_ports, environment_inputs, environment_outputs, contracts) +end diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 3370cda26..f10e4bef9 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2,7 +2,7 @@ Immutable scenario-level metadata for one model application. Runtime object membership is stored separately in [`CompiledModelApplication`](@ref). """ -struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,ON,CN,CP} +struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,P,CP} slot::Int id::Symbol spec::S @@ -13,8 +13,7 @@ struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,ON,CN,CP} timestep::TS clock::CL model_overrides::MO - output_names::ON - canonical_output_names::CN + ports::P call_plans::CP end @@ -659,7 +658,7 @@ end # Authoring records contain declarations, never current target identities, # status values, resolved overrides, clocks, or simulation-owned storage. -struct AuthoredApplicationRecipe{S,M,H,ON,CN,CP} +struct AuthoredApplicationRecipe{S,M,H,P,CP} slot::Int id::Symbol spec::S @@ -667,33 +666,14 @@ struct AuthoredApplicationRecipe{S,M,H,ON,CN,CP} name::Union{Nothing,Symbol} target_matcher::M environment_hint::H - output_names::ON - canonical_output_names::CN + ports::P call_plans::CP end function _application_recipe_with_calls(recipe::AuthoredApplicationRecipe, call_plans::Tuple) return AuthoredApplicationRecipe(recipe.slot, recipe.id, recipe.spec, recipe.process, recipe.name, recipe.target_matcher, recipe.environment_hint, - recipe.output_names, recipe.canonical_output_names, call_plans) -end - -struct ScenarioPreparationFailure{E,B} - phase::Symbol - application_id::Union{Nothing,Symbol} - error::E - backtrace::B -end - -# Exceptions and interpreter frames are diagnostic metadata, and may reference -# Modules or methods that cannot be deep-copied. Preserve the original exception -# for rethrowing; give the copied model a separate trace vector. Scientific -# models, statuses and defaults are copied through their ordinary owners. -function Base.deepcopy_internal(failure::ScenarioPreparationFailure, stack::IdDict) - return get!(stack, failure) do - ScenarioPreparationFailure(failure.phase, failure.application_id, - failure.error, copy(failure.backtrace)) - end + recipe.ports, call_plans) end mutable struct ScenarioPreparation{M,S,A,F} @@ -799,10 +779,10 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs) phase = :environment_hint hint = environment_hint(model_(spec)) phase = :output_ports - output_names, canonical_output_names = _compiled_output_names(spec) + ports = _prepare_authored_ports(spec, application_id) push!(authored, AuthoredApplicationRecipe( slot, application_id, spec, proc, name, matcher, hint, - output_names, canonical_output_names, (), + ports, (), )) catch err err isa InterruptException && rethrow() @@ -1044,7 +1024,7 @@ function _validate_initializer_call_plans!( "Targeted newborn initialization supports canonical local outputs only.", ) stream_only = Symbol[ - Symbol(variable) for variable in keys(_local_output_schema(callee.spec)) + variable for variable in _model_output_names(callee) if _publish_mode_for_output(callee.spec, Symbol(variable)) === :stream_only ] isempty(stream_only) || error( @@ -4788,9 +4768,9 @@ function explain_initialization(model::CompositeModel) rows = NamedTuple[] for application in compiled.applications model_outputs = _local_output_schema(application.spec) - environment_model_outputs = environment_outputs_(application.spec) - model_inputs = _input_schema(application.spec) - environment_inputs = environment_inputs_(application.spec) + environment_model_outputs = _model_environment_output_schema(application) + model_inputs = _model_input_schema(application) + environment_inputs = _model_environment_input_schema(application) generated = Set(Symbol.(keys(model_outputs))) for object_id in application.target_ids for variable in sort!(collect(generated); by=string) @@ -4916,7 +4896,7 @@ function explain_initialization(model::CompositeModel) nothing, )) end - for variable in sort!(Symbol.(collect(keys(environment_inputs_(application.spec)))); by=string) + for variable in sort!(collect(_model_environment_input_names(application)); by=string) environment_binding = get( environment_bindings, (application.id, object_id), @@ -4980,7 +4960,8 @@ function _resolve_application_recipes( sizehint!(target_ids, length(target_ids) + 1) spec = _model_spec_with_environment_hints( model, recipe.spec, _model_application_hint_scale(model, target_ids), - recipe.environment_hint; on_error=on_environment_error, + recipe.environment_hint, recipe.ports.environment_inputs; + on_error=on_environment_error, ) model_overrides = _compiled_object_model_overrides(spec, target_ids, recipe.id) push!(applications, CompiledModelApplication( @@ -4988,8 +4969,7 @@ function _resolve_application_recipes( recipe.slot, recipe.id, spec, recipe.process, recipe.name, selector, target_matcher, timestep(spec), _model_application_clock(model, spec, target_ids, timeline), - model_overrides, recipe.output_names, recipe.canonical_output_names, - recipe.call_plans, + model_overrides, recipe.ports, recipe.call_plans, ), target_ids, )) @@ -4998,14 +4978,17 @@ function _resolve_application_recipes( end function _model_spec_with_environment_hints( - model::CompositeModel, spec, scale::Symbol, authored_hint; on_error=nothing, + model::CompositeModel, spec, scale::Symbol, authored_hint, environment_input_names; + on_error=nothing, ) hint = _normalize_environment_hint(scale, process(spec), authored_hint) current_bindings = environment_bindings(spec) has_explicit_bindings = !(current_bindings isa NamedTuple && isempty(keys(current_bindings))) new_bindings = has_explicit_bindings || isnothing(hint.bindings) ? current_bindings : hint.bindings - new_bindings = _model_environment_bindings_with_environment_sources(spec, new_bindings; on_error) + new_bindings = _model_environment_bindings_with_environment_sources( + spec, new_bindings, environment_input_names; on_error, + ) # Only the diagnostic consumer records a rejected configuration and keeps # its actual authored spec visible. Strict compilation throws below. isnothing(new_bindings) && return spec @@ -5021,12 +5004,14 @@ function _model_spec_with_environment_hints( ) end -function _model_environment_bindings_with_environment_sources(spec, bindings; on_error=nothing) +function _model_environment_bindings_with_environment_sources( + spec, bindings, environment_input_names; on_error=nothing, +) sources = _environment_source_overrides(spec) isempty(keys(sources)) && return bindings bindings = bindings isa NamedTuple ? bindings : NamedTuple() - model_inputs = Set(Symbol.(keys(environment_inputs_(spec)))) + model_inputs = Set(_authored_port_names(environment_input_names)) unknown = Symbol[target for target in keys(sources) if !(Symbol(target) in model_inputs)] if !isempty(unknown) message = string( @@ -5082,21 +5067,27 @@ function _application_model(application::CompiledModelApplication, object_id::Ob ) end -function _compiled_output_names(spec) - # Port names belong to the immutable application schema. Reading a model's - # declarations again during growth can allocate fresh default arrays even - # though writer matching needs only their names. - names = Tuple(Symbol(var) for var in keys(_local_output_schema(spec))) - canonical = Tuple(variable for variable in names - if _publish_mode_for_output(spec, variable) === :canonical) - return names, canonical -end - -_model_output_names(application::CompiledModelApplication) = - getfield(application, :plan).output_names +_application_ports(application::CompiledModelApplication) = getfield(application, :plan).ports +_model_output_names(application::CompiledModelApplication) = _application_ports(application).outputs.local_names +_model_canonical_output_names(application::CompiledModelApplication) = _application_ports(application).outputs.canonical_names +_model_distributed_output_names(application::CompiledModelApplication) = _application_ports(application).outputs.distributed_names +_model_environment_input_names(application::CompiledModelApplication) = _application_ports(application).environment_input_names +_model_environment_output_names(application::CompiledModelApplication) = _application_ports(application).environment_output_names -_model_canonical_output_names(application::CompiledModelApplication) = - getfield(application, :plan).canonical_output_names +# Real-value initialization/inspection stays fresh; a hook already rejected at +# authoring must instead rethrow its captured failure without being replayed. +function _model_input_schema(application::CompiledModelApplication) + _model_input_names(application) + return _input_schema(application.spec) +end +function _model_environment_input_schema(application::CompiledModelApplication) + _model_environment_input_names(application) + return environment_inputs_(application.spec) +end +function _model_environment_output_schema(application::CompiledModelApplication) + _model_environment_output_names(application) + return environment_outputs_(application.spec) +end function _model_writer_groups(applications, skipped_application_ids=Set{Symbol}()) groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() @@ -6775,7 +6766,7 @@ function _prepare_model_input_defaults!( performance=nothing, ) for application in applications - schema = _input_schema(application.spec) + schema = _model_input_schema(application) defaults = _input_default_values(schema) for object_id in application.target_ids status = _ensure_model_object_status!(model, object_id) @@ -6908,7 +6899,7 @@ function _prepare_model_input_statuses_batched!( default_status_updates = Dict{Tuple{ObjectId,Symbol},Bool}() input_default_rewrites_avoided = 0 for application in applications - schema = _input_schema(application.spec) + schema = _model_input_schema(application) defaults = _input_default_values(schema) for object_id in application.target_ids preparation = _status_preparation_for_object!( @@ -7203,7 +7194,7 @@ function _validate_temporal_input_output_overlap!( temporal_bindings, ) isempty(temporal_bindings) && return nothing - output_names = Set(Symbol.(keys(_local_output_schema(application.spec)))) + output_names = Set(_model_output_names(application)) for binding in temporal_bindings binding.input in output_names || continue error( @@ -7669,7 +7660,7 @@ Base.@nospecializeinfer function _input_plan_variable_contracts!( application_id = application.id schema = get(contracts_by_application, application_id, nothing) isnothing(schema) || return schema - schema = _variable_contract_schema(application.spec) + schema = _authored_metadata_value(_application_ports(application).contracts) contracts_by_application[application_id] = schema return schema end @@ -7766,10 +7757,8 @@ function _compile_model_input_plans( applications_by_id = Dict( application.id => application for application in applications ) - # Output declarations can allocate fresh default arrays even when only - # their names are needed. Snapshot names for this planning pass only: - # neither declaration values nor runtime reference carriers are retained. - # Application IDs also support filtered lists with non-contiguous slots. + # The author owns value-free names; IDs also support diagnostic subsets + # with non-contiguous application slots. local_output_names = Dict( application.id => _model_output_names(application) for application in applications @@ -7789,11 +7778,8 @@ function _compile_model_input_plans( if _publish_mode_for_output(application.spec, variable) == :canonical ] for application in applications ) - # Contract-name validation reads full declarations, which may allocate - # array defaults. Validate each exact application once in this pass and - # reuse only its contract metadata for every producer/consumer comparison. - # Fill lazily to preserve declaration/endpoint error ordering. Do not retain - # initialization values or cache across compilations. + # Read saved pure contracts lazily at the existing endpoint positions. + # This preserves route/error ordering without replaying declaration hooks. variable_contracts_by_application = Dict{Symbol,NamedTuple}() for application in applications _input_plan_variable_contracts!(variable_contracts_by_application, application) @@ -7919,7 +7905,7 @@ function _compile_model_output_destination_plans( ) plans = CompiledModelOutputDestinationPlan[] for application in applications - distributed_names = _distributed_output_names(application.spec) + distributed_names = _model_distributed_output_names(application) destinations = _output_destination_layout(application.spec, distributed_names) if !isnothing(application.model_overrides) for replacement in values(application.model_overrides) @@ -7982,7 +7968,7 @@ end function _application_declares_output_name(application, variable::Symbol) variable in _model_output_names(application) && return true destinations = _output_destination_layout( - application.spec, _distributed_output_names(application.spec), + application.spec, _model_distributed_output_names(application), ) return any( destination -> variable in destination.variable_names, @@ -8385,9 +8371,7 @@ function _has_matching_distributed_input_writer( end end -function _model_input_names(application::CompiledModelApplication) - return Symbol[Symbol(var) for var in keys(_input_schema(application.spec))] -end +_model_input_names(application::CompiledModelApplication) = _application_ports(application).input_names function _validate_model_input_source!( model::CompositeModel, @@ -8444,7 +8428,7 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, i bound = _bound_model_inputs(input_bindings) missing = NamedTuple[] for application in applications - schema = _input_schema(application.spec) + schema = _model_input_schema(application) for object_id in application.target_ids for (input_, declaration) in pairs(schema) declaration isa Required || continue @@ -8925,12 +8909,12 @@ function explain_applications(compiled::CompiledCompositeModel) if !isnothing(_model_object(compiled.model, id).scale) ]); by=string), applies_to=application.applies_to, - inputs=Tuple(Symbol.(keys(_input_schema(application.spec)))), - outputs=Tuple(Symbol.(keys(_output_schema(application.spec)))), - local_outputs=Tuple(Symbol.(keys(_local_output_schema(application.spec)))), - distributed_outputs=Tuple(Symbol.(keys(_distributed_output_schema(application.spec)))), - environment_inputs=Tuple(Symbol.(keys(environment_inputs_(application.spec)))), - environment_outputs=Tuple(Symbol.(keys(environment_outputs_(application.spec)))), + inputs=_model_input_names(application), + outputs=_application_ports(application).outputs.all_names, + local_outputs=_model_output_names(application), + distributed_outputs=_model_distributed_output_names(application), + environment_inputs=_model_environment_input_names(application), + environment_outputs=_model_environment_output_names(application), timestep=application.timestep, clock=application.clock, model_type=typeof(_application_default_model(application)), diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 5664ee66d..0399cf535 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -199,18 +199,15 @@ function _compile_environment_application_plans( for application in applications config = environment_config(application.spec) backend = _environment_backend_from_config(model, config) - sampling_rules = Tuple(_environment_sampling_rules(application.spec)) + bindings, environment_sources = _environment_sampling_configuration(application.spec) + required_inputs = _model_environment_input_names(application) + sampling_rules = Tuple(_environment_sampling_rules(bindings, environment_sources, required_inputs)) compiled_sampling_rules = Tuple( CompiledEnvironmentSamplingRule(target, source) for (target, source) in sampling_rules ) - required_inputs = _environment_variable_names( - environment_inputs_(application.spec), - ) source_inputs = _environment_source_variable_names(sampling_rules) - produced_outputs = _environment_variable_names( - environment_outputs_(application.spec), - ) + produced_outputs = _model_environment_output_names(application) sampler = nothing prepared_source = nothing if prepare_runtime && backend isa GlobalConstant @@ -222,10 +219,8 @@ function _compile_environment_application_plans( _prepare_global_environment(source) end end - bindings = environment_bindings(application.spec) - has_bindings = bindings isa NamedTuple && !isempty(keys(bindings)) - has_source_overrides = - !isempty(keys(_environment_source_overrides(application.spec))) + has_bindings = !isempty(keys(bindings)) + has_source_overrides = !isempty(keys(environment_sources)) uses_raw_global_source = backend isa GlobalConstant && isnothing(sampler) && !has_bindings && !has_source_overrides diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 7aa9307da..9c3563924 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1808,7 +1808,7 @@ function _model_output_object_ids( (application.id, variable), nothing, ) - variable in keys(_local_output_schema(application.spec)) || + variable in _model_output_names(application) || return isnothing(destination_ids) ? ObjectId[] : destination_ids isnothing(destination_ids) && return application.target_ids object_ids = copy(application.target_ids) @@ -1832,7 +1832,7 @@ function _model_output_reference( object_id::ObjectId, variable::Symbol, ) - if variable in keys(_local_output_schema(application.spec)) && + if variable in _model_output_names(application) && haskey( compiled.status_views_by_target, (application.id, object_id), @@ -1919,7 +1919,7 @@ function _initialize_changed_model_output_streams!( ) isempty(variables) && continue _compiled_application_by_id(compiled, application_id) do application - model_outputs = keys(_local_output_schema(application.spec)) + model_outputs = _model_output_names(application) if haskey(compiled.status_views_by_target, (application_id, object_id)) for variable in variables variable in model_outputs || continue @@ -3175,7 +3175,7 @@ Base.@nospecializeinfer function _runtime_model_output_streams( isempty(variables) && return () # Assemble once without specializing a generator on the entire model/status. # The returned tuple still has concrete stream and reference types. - declared_outputs = keys(_local_output_schema(application.spec)) + declared_outputs = _model_output_names(application) runtime_streams = RuntimeOutputStream[] for variable in variables variable in declared_outputs || continue @@ -3779,7 +3779,7 @@ function _model_execution_outputs_match( nothing, ) for variable in variables - variable in keys(_local_output_schema(application.spec)) || continue + variable in _model_output_names(application) || continue output_index += 1 output_index <= length(runtime_outputs) || return false output = runtime_outputs[output_index] @@ -4698,7 +4698,7 @@ function _model_application_output_variables( application, ::NoCompiledDistributedOutputs, ) - return Tuple(Symbol(variable) for variable in keys(_local_output_schema(application.spec))) + return _model_output_names(application) end function _model_application_output_variables( @@ -4706,7 +4706,7 @@ function _model_application_output_variables( application, distributed_outputs::CompiledDistributedOutputs, ) - variables = Symbol[Symbol(variable) for variable in keys(_local_output_schema(application.spec))] + variables = Symbol[Symbol(variable) for variable in _model_output_names(application)] for ((application_id, variable), destination_ids) in distributed_outputs.destination_ids_by_application_variable application_id == application.id || continue @@ -6222,7 +6222,7 @@ function _environment_binding_for_current_context(context::RunContext) end function _validate_environment_commit(context::RunContext, state) - declared = Symbol.(collect(keys(environment_outputs_(context.application.spec)))) + declared = _model_environment_output_names(context.application) isempty(declared) && error( "Application `$(context.application.id)` cannot commit environment state because ", "its model declares no `environment_outputs_` variables.", @@ -7992,7 +7992,7 @@ function _model_request_application(model::CompositeModel, compiled::CompiledCom application.id == request.application || application.name == request.application || continue - local_output = request.var in keys(_local_output_schema(application.spec)) + local_output = request.var in _model_output_names(application) local_match = local_output && ( any(id -> id in requested_ids, application.target_ids) || (!isnothing(declared_scale) && diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index f5f93ab49..b7890a742 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -5,6 +5,9 @@ include("composite_model/status_conversion.jl") include("composite_model/registry_topology.jl") include("composite_model/status_construction.jl") include("composite_model/selectors.jl") +include("composite_model/scenario_dsl.jl") +include("ModelSpec.jl") +include("composite_model/authored_ports.jl") include("composite_model/execution_cohorts.jl") include("composite_model/execution_storage.jl") include("composite_model/execution_cohort_refresh.jl") @@ -16,4 +19,3 @@ include("composite_model/runtime_outputs.jl") include("composite_model/execution_dispatch.jl") include("composite_model/call_evaluations.jl") include("composite_model/source_compilation.jl") -include("composite_model/scenario_dsl.jl") diff --git a/src/native_compilation.jl b/src/native_compilation.jl index c1773e128..d450302f9 100644 --- a/src/native_compilation.jl +++ b/src/native_compilation.jl @@ -36,7 +36,7 @@ function _check_scenario(model, plan) end for application in plan.applications spec = application.spec - isempty(PSE.environment_outputs_(spec)) || + isempty(application.ports.environment_output_names) || _unsupported(application.id, "environment outputs are unsupported") backend = PSE._environment_backend_from_config(model, PSE.environment_config(spec)) _is_constant_environment(backend) || diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index 025baef27..5186e7497 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -356,12 +356,15 @@ function sample_environment(backend::GlobalConstant, handle, state, time, variab return _environment_row_at_step(state, Int(round(time))) end -function _environment_sampling_rules(model_spec::ModelSpec) +function _environment_sampling_configuration(model_spec::ModelSpec) bindings = environment_bindings(model_spec) bindings = bindings isa NamedTuple ? bindings : NamedTuple() - environment_sources = _environment_source_overrides(model_spec) + return bindings, _environment_source_overrides(model_spec) +end + +function _environment_sampling_rules(bindings, environment_sources, input_names) rules = Pair{Symbol,Symbol}[] - for target in keys(environment_inputs_(model_spec)) + for target in input_names source = target if haskey(bindings, target) rule = bindings[target] @@ -390,12 +393,12 @@ function _environment_source_overrides(model_spec::ModelSpec) end function PreparedEnvironmentInputs(model_spec::ModelSpec) - rules = _environment_sampling_rules(model_spec) + bindings, environment_sources = _environment_sampling_configuration(model_spec) + input_names = _environment_variable_names(environment_inputs_(model_spec)) + rules = _environment_sampling_rules(bindings, environment_sources, input_names) targets = Tuple(first(rule) for rule in rules) sources = Tuple(last(rule) for rule in rules) - bindings = environment_bindings(model_spec) - raw_global_source = !(bindings isa NamedTuple && !isempty(keys(bindings))) && - isempty(keys(_environment_source_overrides(model_spec))) + raw_global_source = isempty(keys(bindings)) && isempty(keys(environment_sources)) return PreparedEnvironmentInputs(targets, sources; raw_global_source) end diff --git a/src/variable_contracts.jl b/src/variable_contracts.jl index e161ce08f..a183c1061 100644 --- a/src/variable_contracts.jl +++ b/src/variable_contracts.jl @@ -87,8 +87,7 @@ function _declared_contract_variable_names(model) return declared end -function _validate_variable_contract_names(model, schema) - declared = _declared_contract_variable_names(model) +function _validate_variable_contract_names(model, schema, declared) unknown = Tuple(name for name in keys(schema) if name ∉ declared) isempty(unknown) || return _invalid_variable_contract_schema_error( model, @@ -103,7 +102,7 @@ end error("`variable_contracts_($(typeof(model)))` $(message)") end -function _variable_contract_schema(model) +function _variable_contract_declarations(model) schema = variable_contracts_(model) schema isa NamedTuple || return _invalid_variable_contract_schema_error( model, @@ -122,7 +121,12 @@ function _variable_contract_schema(model) ", ", ) * ".", ) - return _validate_variable_contract_names(model, schema) + return schema +end + +function _variable_contract_schema(model) + schema = _variable_contract_declarations(model) + return _validate_variable_contract_names(model, schema, _declared_contract_variable_names(model)) end function _variable_contract(model, variable::Symbol) diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index c01489306..384c836d9 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -795,6 +795,23 @@ function _model_graph_model_parameters(model) return parameters end +# Failed declaration hooks are already represented in the compilation report. +# Successful value inspection stays fresh; failed hooks must not be replayed. +_model_graph_name_result(::ScenarioPreparationFailure) = () +_model_graph_name_result(result::AuthoredPortNames) = _authored_port_names(result) +function _model_graph_input_schema(application) + _application_ports(application).inputs isa ScenarioPreparationFailure && return NamedTuple() + return _model_input_schema(application) +end +function _model_graph_environment_input_schema(application) + _application_ports(application).environment_inputs isa ScenarioPreparationFailure && return NamedTuple() + return _model_environment_input_schema(application) +end +function _model_graph_environment_output_schema(application) + _application_ports(application).environment_outputs isa ScenarioPreparationFailure && return NamedTuple() + return _model_environment_output_schema(application) +end + function _model_graph_port(application, role::Symbol, variable, declaration) name = Symbol(variable) is_input = role == :input @@ -818,9 +835,10 @@ function _model_graph_port(application, role::Symbol, variable, declaration) return port end -function _model_graph_output_destinations(spec) +function _model_graph_output_destinations(application) + spec = application.spec resolved = try - _output_destination_layout(spec, _distributed_output_names(spec)) + _output_destination_layout(spec, _model_distributed_output_names(application)) catch # Invalid declarations remain editable; compilation reports the error. nothing @@ -878,10 +896,10 @@ function _model_graph_application_dict( ) process_model = _application_default_model(application) spec = application.spec - inputs = _input_schema(application.spec) + inputs = _model_graph_input_schema(application) outputs = _output_schema(application.spec) - environment_inputs = environment_inputs_(application.spec) - environment_outputs = environment_outputs_(application.spec) + environment_inputs = _model_graph_environment_input_schema(application) + environment_outputs = _model_graph_environment_output_schema(application) target_objects = [_model_object(composite_model, id) for id in application.target_ids] environment = environment_config(spec) environment_payload = environment isa EnvironmentConfig ? environment.config : environment @@ -944,7 +962,7 @@ function _model_graph_application_dict( "environmentBindings" => _model_graph_json_value(environment_bindings(spec)), "environmentWindow" => _model_graph_period_dict(environment_window(spec)), "outputRouting" => _model_graph_json_value(output_routing(spec)), - "outputsTo" => _model_graph_output_destinations(spec), + "outputsTo" => _model_graph_output_destinations(application), "updates" => Dict{String,Any}[ Dict( "variables" => collect(string.(_update_variables(update))), @@ -1413,10 +1431,12 @@ function _model_graph_environment_edges(report, level, environment_catalog) end if isempty(environment_bindings) for application in report.applications - required_inputs = Symbol.(keys(environment_inputs_(application.spec))) - produced_outputs = Symbol.(keys(environment_outputs_(application.spec))) + ports = _application_ports(application) + required_inputs = _model_graph_name_result(ports.environment_inputs) + produced_outputs = _model_graph_name_result(ports.environment_outputs) isempty(required_inputs) && isempty(produced_outputs) && continue - sampling_rules = Tuple(_environment_sampling_rules(application.spec)) + bindings, environment_sources = _environment_sampling_configuration(application.spec) + sampling_rules = Tuple(_environment_sampling_rules(bindings, environment_sources, required_inputs)) source_inputs = _environment_source_variable_names(sampling_rules) config = environment_config(application.spec) backend = _environment_backend_from_config(report.model, config) @@ -1586,10 +1606,10 @@ function _model_graph_initialization(report) rows = Dict{String,Any}[] for application in report.applications - model_inputs = _input_schema(application.spec) + model_inputs = _model_graph_input_schema(application) model_outputs = _local_output_schema(application.spec) - model_environment_inputs = environment_inputs_(application.spec) - model_environment_outputs = environment_outputs_(application.spec) + model_environment_inputs = _model_graph_environment_input_schema(application) + model_environment_outputs = _model_graph_environment_output_schema(application) source_overrides = _environment_source_overrides(application.spec) for object_id in application.target_ids object = _model_object(report.model, object_id) diff --git a/test/runtests.jl b/test/runtests.jl index fd7ea0df6..6d43e292f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -82,6 +82,7 @@ else @testset "Reusable scenario plans" begin include("test-model-prepared-scenario.jl") include("test-model-scenario-authoring.jl") + include("test-model-authored-port-inventory.jl") include("test-model-prepared-authoring-owner.jl") include("test-model-public-refresh-owners.jl") include("test-model-authored-call-plans.jl") diff --git a/test/test-initial-status-preparation.jl b/test/test-initial-status-preparation.jl index beaca856f..4977ce285 100644 --- a/test/test-initial-status-preparation.jl +++ b/test/test-initial-status-preparation.jl @@ -374,10 +374,12 @@ end @testset "runtime output assembly preserves ordered stream and status references" begin object_id = ObjectId(:target) status = Status(first=7.0, second=Float32[2, 3]) - application = ( - id=:probe, - spec=ModelSpec(InitialStatusPreparationProbe(NamedTuple(), (first=0.0, second=Float32[]))), - ) + model = CompositeModel(Object(object_id; status); applications=( + ModelSpec(InitialStatusPreparationProbe(NamedTuple(), (first=0.0, second=Float32[])); + name=:probe, on=One(id=object_id)), + )) + application = only(Advanced.refresh_bindings!(model).applications) + @test model_status(model, object_id) === status retention = PlantSimEngine.OutputRetentionPlan( false, Set([(:probe, :second)]), diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl new file mode 100644 index 000000000..828e4115f --- /dev/null +++ b/test/test-model-authored-port-inventory.jl @@ -0,0 +1,463 @@ +module AuthoredPortInventoryChecks +using Dates, PlantSimEngine, Test +const PSE = PlantSimEngine +const hook_zero = (inputs=0, outputs=0, environment_inputs=0, environment_outputs=0, contracts=0) +PSE.@process "authored_port_inventory" verbose=false +PSE.@process "authored_port_bad_input" verbose=false +PSE.@process "authored_port_source" verbose=false +PSE.@process "authored_port_ordered" verbose=false + +function count_hook!(counter, name) + counter[] = merge(counter[], NamedTuple{(name,)}((getproperty(counter[], name) + 1,))) + return nothing +end +struct Probe{C,S} <: AbstractAuthored_Port_InventoryModel + key::Symbol + counter::C + seed::S +end +input_name(model::Probe) = Symbol(:buffer_, model.key) +output_name(model::Probe) = Symbol(:seen_, model.key) +distributed_name(model::Probe) = Symbol(:payload_, model.key) +environment_input_name(model::Probe) = Symbol(:T_, model.key) +environment_output_name(model::Probe) = Symbol(:flux_, model.key) +function PSE.inputs_(model::Probe) + count_hook!(model.counter, :inputs) + return NamedTuple{(input_name(model),)}((Default(fill(model.seed[], 2)),)) +end +function PSE.outputs_(model::Probe) + count_hook!(model.counter, :outputs) + return NamedTuple{(output_name(model), distributed_name(model))}(( + 0f0, Distributed(Default(fill(model.seed[], 3))), + )) +end +function PSE.environment_inputs_(model::Probe) + count_hook!(model.counter, :environment_inputs) + return NamedTuple{(environment_input_name(model),)}((0f0,)) +end +function PSE.environment_outputs_(model::Probe) + count_hook!(model.counter, :environment_outputs) + return NamedTuple{(environment_output_name(model),)}((0f0,)) +end +function PSE.variable_contracts_(model::Probe) + count_hook!(model.counter, :contracts) + names = (input_name(model), output_name(model), distributed_name(model), + environment_input_name(model), environment_output_name(model)) + return NamedTuple{names}(ntuple(_ -> VariableContract(unit=:probe), length(names))) +end +function PSE.run!(model::Probe, status, environment, constants, context) + value = sum(getproperty(status, input_name(model))) + getproperty(environment, environment_input_name(model)) + setproperty!(status, output_name(model), value) + return nothing +end +spec(model::Probe) = ModelSpec(model; name=model.key, on=Many(kind=model.key, scale=:Leaf), + outputs_to=(OutputTo(One(Self())),)) + +function inventory_is_value_free(value) + value isa Union{Nothing,Symbol,VariableContract} && return true + value isa Tuple && return all(inventory_is_value_free, value) + value isa NamedTuple && return all(inventory_is_value_free, values(value)) + value isa Union{Default,Required,Distributed,AbstractArray,Ref,AbstractModel} && return false + parentmodule(typeof(value)) === PSE || return false + return all(name -> inventory_is_value_free(getfield(value, name)), fieldnames(typeof(value))) +end + +@testset "constructor owns one instance-specific value-free port inventory" begin + a = Probe(:a, Ref(hook_zero), Ref(1f0)) + b = Probe(:b, Ref(hook_zero), Ref(2f0)) + @test typeof(a) === typeof(b) + model = CompositeModel(Object(:a1; scale=:Leaf, kind=:a), Object(:b1; scale=:Leaf, kind=:b); + applications=(spec(a), spec(b)), environment=(T_a=1f0, T_b=2f0, + flux_a=0f0, flux_b=0f0, duration=Hour(1))) + expected = map(_ -> 1, hook_zero) + @test a.counter[] == expected + @test b.counter[] == expected + recipes = model.scenario_plan_cache.authored + for (recipe, process_model) in zip(recipes, (a, b)) + has_inventory = hasproperty(recipe, :ports) + @test has_inventory + if has_inventory + ports = recipe.ports + @test (@inferred PSE._authored_port_names(ports.inputs)) === (input_name(process_model),) + @test ports.input_names === (input_name(process_model),) + @test ports.outputs.all_names === (output_name(process_model), distributed_name(process_model)) + @test ports.outputs.local_names === (output_name(process_model),) + @test ports.outputs.distributed_names === (distributed_name(process_model),) + @test ports.outputs.canonical_names === ports.outputs.local_names + @test ports.environment_input_names === (environment_input_name(process_model),) + @test ports.environment_output_names === (environment_output_name(process_model),) + @test keys(ports.contracts) == (input_name(process_model), output_name(process_model), + distributed_name(process_model), environment_input_name(process_model), + environment_output_name(process_model)) + @test inventory_is_value_free(ports) + end + end + # Compiler-only preparation must not replay any metadata getter. + before_a, before_b = a.counter[], b.counter[] + applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + destinations = PSE._compile_model_output_destination_plans(model, applications) + PSE._compile_model_input_plans(model, applications, destinations) + PSE._compile_environment_application_plans(model, applications; prepare_runtime=false) + @test a.counter[] == before_a + @test b.counter[] == before_b + if all(recipe -> hasproperty(recipe, :ports), recipes) + @test identity(applications[1].plan.ports === recipes[1].ports) + @test identity(applications[2].plan.ports === recipes[2].ports) + end + + a.seed[], b.seed[] = 7f0, 9f0 + simulation = run!(model; outputs=:all) + state_a, state_b = model_status(model, :a1), model_status(model, :b1) + @test state_a.buffer_a == fill(7f0, 2) + @test state_b.buffer_b == fill(9f0, 2) + @test state_a.payload_a == fill(7f0, 3) + @test state_b.payload_b == fill(9f0, 3) + @test state_a.seen_a === 15f0 + @test state_b.seen_b === 20f0 + @test a.counter[].inputs > before_a.inputs + @test a.counter[].outputs > before_a.outputs + @test a.counter[].environment_inputs == before_a.environment_inputs + @test a.counter[].environment_outputs == before_a.environment_outputs + @test a.counter[].contracts == before_a.contracts + a.seed[] = 11f0 + register_object!(model, Object(:a2; scale=:Leaf, kind=:a)) + step!(simulation) + newborn = model_status(model, :a2) + @test newborn.buffer_a == fill(11f0, 2) + @test newborn.payload_a == fill(11f0, 3) + @test identity(newborn.buffer_a !== state_a.buffer_a) + @test identity(newborn.payload_a !== state_a.payload_a) + @test newborn.seen_a === 23f0 + @test state_a.buffer_a == fill(7f0, 2) + @test state_a.payload_a == fill(7f0, 3) + before_ordinary_a, before_ordinary_b = a.counter[], b.counter[] + step!(simulation) + @test a.counter[] == before_ordinary_a + @test b.counter[] == before_ordinary_b + @test outputs(simulation)[(:a, ObjectId(:a1), :seen_a)] == [(1.0, 15f0), (2.0, 15f0), (3.0, 15f0)] + @test outputs(simulation)[(:a, ObjectId(:a2), :seen_a)] == [(2.0, 23f0), (3.0, 23f0)] + previous_contracts = a.counter[].contracts + previous_environment = a.counter[].environment_inputs + current = Advanced.refresh_bindings!(model; force=true) + @test identity(only(app for app in current.applications if app.id === :a).plan.ports !== recipes[1].ports) + @test a.counter[].contracts == previous_contracts + 1 + @test a.counter[].environment_inputs == previous_environment + 1 + step!(simulation) + @test identity(simulation.compiled === current) + @test a.counter[].contracts == previous_contracts + 1 + @test a.counter[].environment_inputs == previous_environment + 1 + @test state_a.buffer_a == fill(7f0, 2) + @test newborn.buffer_a == fill(11f0, 2) + @test outputs(simulation)[(:a, ObjectId(:a1), :seen_a)] == + [(1.0, 15f0), (2.0, 15f0), (3.0, 15f0), (4.0, 15f0)] +end + +const broken_input_calls = Ref(0) +struct BrokenInput{T} <: AbstractAuthored_Port_Bad_InputModel + token::T +end +function PSE.inputs_(::BrokenInput) + broken_input_calls[] += 1 + error("captured input declaration failure") +end +PSE.outputs_(::BrokenInput) = (bad_seen=0f0,) +PSE.run!(::BrokenInput, status, environment, constants, context) = nothing + +@testset "failed input metadata is frozen without hiding valid target applications" begin + broken_input_calls[] = 0 + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(BrokenInput(:application); name=:broken, on=One(id=:leaf)),)) + @test broken_input_calls[] == 1 + @test isnothing(model.scenario_plan_cache.failure) + @test hasproperty(only(model.scenario_plan_cache.authored), :ports) + for _ in 1:2 + report = PSE.compile_model_report(model) + @test [app.id for app in report.applications] == [:broken] + @test any(diagnostic -> occursin("captured input declaration failure", diagnostic.message), report.diagnostics) + @test broken_input_calls[] == 1 + @test_throws "captured input declaration failure" run!(model; steps=0) + @test broken_input_calls[] == 1 + end + view = try + PSE.GraphEditor.model_graph_view(model) + catch error + @info "failed port graph inspection" error=sprint(showerror, error) + nothing + end + @test !isnothing(view) + if !isnothing(view) + @test only(view.applications)["applicationId"] == "broken" + @test !isempty(view.diagnostics) + end + @test broken_input_calls[] == 1 + @test isnothing(model_status(model, :leaf)) +end + +@testset "live application Scope is repaired before a saved input failure is delivered" begin + broken_input_calls[] = 0 + model = CompositeModel(Object(:scene; scale=:Scene); applications=( + ModelSpec(BrokenInput(:application); name=:broken, + on=One(Scope(ObjectId(:future_root)); scale=:Leaf)),)) + @test broken_input_calls[] == 1 + @test isnothing(model.scenario_plan_cache.failure) + @test_throws "No instance or object ID" run!(model; steps=0) + @test broken_input_calls[] == 1 + register_object!(model, Object(:future_root; scale=:Plant)) + register_object!(model, Object(:future_leaf; scale=:Leaf, parent=:future_root)) + @test_throws "captured input declaration failure" run!(model; steps=0) + @test broken_input_calls[] == 1 + @test isnothing(model_status(model, :future_leaf)) +end + +struct Source{UNIT} <: AbstractAuthored_Port_SourceModel end +PSE.inputs_(::Source) = NamedTuple() +PSE.outputs_(::Source) = (value=0f0,) +PSE.variable_contracts_(::Source{UNIT}) where {UNIT} = (value=VariableContract(unit=UNIT),) +PSE.run!(::Source, status, environment, constants, context) = nothing +struct Ordered{C} <: AbstractAuthored_Port_OrderedModel + contracts::C +end +PSE.inputs_(::Ordered) = (first=Required(Float32), second=Required(Float32)) +PSE.outputs_(::Ordered) = (seen=0f0,) +function PSE.variable_contracts_(model::Ordered) + model.contracts[] += 1 + return (first=VariableContract(unit=:first), second=VariableContract(unit=:wrong)) +end +PSE.run!(::Ordered, status, environment, constants, context) = nothing + +@testset "earlier live route scope still wins over a later pure contract error" begin + calls = Ref(0) + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(Source{:first}(); name=:first_source, on=Many(scale=:FirstSource)), + ModelSpec(Source{:second}(); name=:second_source, on=Many(scale=:SecondSource)), + ModelSpec(Ordered(calls); name=:reader, on=One(id=:leaf), inputs=( + first=One(Scope(ObjectId(:future)); application=:first_source, var=:value), + second=One(application=:second_source, var=:value), + )), + )) + @test calls[] == 1 + @test_throws "No instance or object ID" run!(model; steps=0) + @test calls[] == 1 + register_object!(model, Object(:future; scale=:Plant)) + @test_throws "Incompatible variable contracts for input `second`" run!(model; steps=0) + @test calls[] == 1 + @test isnothing(model_status(model, :leaf)) +end +PSE.@process "authored_port_bad_environment" verbose=false +struct BrokenEnvironment{WHICH} <: AbstractAuthored_Port_Bad_EnvironmentModel end +const failed_environment_inputs = Ref(0) +const failed_environment_outputs = Ref(0) +PSE.inputs_(::BrokenEnvironment) = NamedTuple() +PSE.outputs_(::BrokenEnvironment) = (seen=0f0,) +PSE.run!(::BrokenEnvironment, status, environment, constants, context) = nothing +function PSE.environment_inputs_(::BrokenEnvironment{WHICH}) where {WHICH} + WHICH === :inputs || return NamedTuple() + failed_environment_inputs[] += 1 + error("captured environment input declaration failure") +end +function PSE.environment_outputs_(::BrokenEnvironment{WHICH}) where {WHICH} + WHICH === :outputs || return NamedTuple() + failed_environment_outputs[] += 1 + error("captured environment output declaration failure") +end + +@testset "empty remapping defers failed environment metadata without replay" begin + for which in (:inputs, :outputs) + failed_environment_inputs[] = failed_environment_outputs[] = 0 + declaration = which === :inputs ? BrokenEnvironment{:inputs}() : BrokenEnvironment{:outputs}() + counter = which === :inputs ? failed_environment_inputs : failed_environment_outputs + message = which === :inputs ? "captured environment input declaration failure" : + "captured environment output declaration failure" + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(declaration; name=:probe, on=One(id=:leaf), + environment=Environment(sources=NamedTuple())),)) + @test counter[] == 1 + @test isnothing(model.scenario_plan_cache.failure) + applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + @test counter[] == 1 # empty remap must not demand failed names early + destinations = PSE._compile_model_output_destination_plans(model, applications) + @test_throws message PSE._compile_model_input_plans(model, applications, destinations) + @test counter[] == 1 # even empty contracts validate all declared port names + @test_throws message PSE._compile_environment_application_plans(model, applications; prepare_runtime=false) + @test counter[] == 1 + @test_throws message run!(model; steps=0) + @test counter[] == 1 + report = PSE.compile_model_report(model) + @test [app.id for app in report.applications] == [:probe] + @test any(diagnostic -> occursin(message, diagnostic.message), report.diagnostics) + @test counter[] == 1 + end +end + +PSE.@process "authored_port_shape_before_names" verbose=false +struct BadShapeBeforeNames <: AbstractAuthored_Port_Shape_Before_NamesModel end +const shape_input_calls = Ref(0) +const shape_contract_calls = Ref(0) +function PSE.inputs_(::BadShapeBeforeNames) + shape_input_calls[] += 1 + error("input failure must not beat malformed contracts") +end +PSE.outputs_(::BadShapeBeforeNames) = (seen=0f0,) +function PSE.variable_contracts_(::BadShapeBeforeNames) + shape_contract_calls[] += 1 + return 42 +end +PSE.run!(::BadShapeBeforeNames, status, environment, constants, context) = nothing +@testset "contract shape errors keep precedence over saved port failures" begin + shape_input_calls[] = shape_contract_calls[] = 0 + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(BadShapeBeforeNames(); name=:probe, on=One(id=:leaf)),)) + @test shape_input_calls[] == shape_contract_calls[] == 1 + @test isnothing(model.scenario_plan_cache.failure) + @test_throws "must return a NamedTuple" run!(model; steps=0) + @test shape_input_calls[] == shape_contract_calls[] == 1 + @test isnothing(model_status(model, :leaf)) +end + +PSE.@process "authored_port_commit" verbose=false +PSE.@process "authored_port_capture" verbose=false +const EA = PSE.EnvironmentAPI +mutable struct CommitBackend{T} <: EA.AbstractEnvironmentBackend + value::T + writes::Vector{NamedTuple} +end +EA.base_step_seconds(::CommitBackend) = 3600.0 +EA.get_nsteps(::CommitBackend) = 4 +EA.environment_variables(::CommitBackend) = Set((:T,)) +EA.bind_environment(::CommitBackend, object::PSE.Object, context, config) = + (application=context.application, sink=isnothing(config) ? nothing : get(config, :sink, nothing)) +EA.sample(backend::CommitBackend, handle, ::Symbol, time) = backend.value +function EA.commit_environment!(backend::CommitBackend, handle, state, time) + handle.sink === :inventory_commit || error("missing inventory commit sink") + backend.value = state.T + push!(backend.writes, (application=handle.application, value=state.T, time=Float64(time))) + return nothing +end +struct CommitProbe{T,Q,F} <: AbstractAuthored_Port_CommitModel + zero_value::T + queries::Q + forbidden::F +end +PSE.inputs_(::CommitProbe) = NamedTuple() +PSE.outputs_(model::CommitProbe) = (seen=model.zero_value, calls=0) +PSE.environment_inputs_(model::CommitProbe) = (T=model.zero_value,) +function PSE.environment_outputs_(model::CommitProbe) + model.queries[] += 1 + model.forbidden[] && error("environment output metadata was replayed") + return (T=model.zero_value,) +end +function PSE.run!(::CommitProbe, status, environment, constants, context) + status.calls += 1 + status.seen = environment.T + one(status.seen) + commit_environment!(context, (T=status.seen,)) + return nothing +end +struct Capture{C} <: AbstractAuthored_Port_CaptureModel + capture::C +end +PSE.inputs_(::Capture) = NamedTuple() +PSE.outputs_(::Capture) = (owners=0,) +function PSE.run!(model::Capture, status, environment, constants, context) + model.capture[] = context + status.owners += 1 + return nothing +end + +@testset "commits use captured names with fresh state in scheduled and evaluated execution" begin + for T in (Float32, Float64) + queries, forbidden = Ref(0), Ref(false) + backend = CommitBackend(zero(T), NamedTuple[]) + probe = ModelSpec(CommitProbe(zero(T), queries, forbidden); name=:probe, + on=One(id=:leaf), environment=Environment(provider=:inventory_commit, sink=:inventory_commit)) + model = CompositeModel(Object(:leaf); applications=(probe,), environment=backend) + @test queries[] == 1 + forbidden[] = true + simulation = run!(model; steps=2, outputs=:all) + @test queries[] == 1 + @test backend.value === T(2) + @test [row.value for row in backend.writes] == T[1, 2] + @test outputs(simulation)[(:probe, ObjectId(:leaf), :seen)] == [(1.0, T(1)), (2.0, T(2))] + + queries, forbidden = Ref(0), Ref(false) + backend = CommitBackend(zero(T), NamedTuple[]) + capture = Ref{Any}() + model = CompositeModel(Object(:owner), Object(:leaf; parent=:owner); applications=( + ModelSpec(Capture(capture); name=:owner, on=One(id=:owner), calls=( + child=One(SceneScope(); id=:leaf, application=:probe),)), + ModelSpec(CommitProbe(zero(T), queries, forbidden); name=:probe, + on=One(id=:leaf), environment=Environment(provider=:inventory_commit, sink=:inventory_commit)), + ), environment=backend) + @test queries[] == 1 + forbidden[] = true + simulation = run!(model; outputs=:all) + target = only(call_targets(capture[], :child)) + run_call!(target; publish=false) + @test target.status.calls == 1 + @test isempty(backend.writes) + @test backend.value === zero(T) + evaluation = evaluate_call!(target; sampled_environment=(T=T(4),)) + @test target.status.calls == 2 + @test target.status.seen === T(5) + @test isempty(backend.writes) + @test identity(accept_call!(evaluation) === evaluation) + @test target.status.calls == 2 # acceptance never reruns its kernel + @test backend.value === T(5) + @test [row.value for row in backend.writes] == T[5] + run_call!(target; publish=true) + @test target.status.calls == 3 + @test backend.value === T(6) + @test [row.value for row in backend.writes] == T[5, 6] + run_call!(target; publish=false) + @test target.status.calls == 4 + @test target.status.seen === T(7) + @test backend.value === T(6) + @test length(backend.writes) == 2 + @test queries[] == 1 + @test outputs(simulation)[(:probe, ObjectId(:leaf), :seen)] == [(1.0, T(6))] + end +end + +PSE.@process "authored_port_native_metadata" verbose=false +struct NativeMetadataProbe{HAS_OUTPUT} <: AbstractAuthored_Port_Native_MetadataModel end +const native_metadata_queries = Ref(0) +const native_metadata_forbidden = Ref(false) +PSE.inputs_(::NativeMetadataProbe) = NamedTuple() +PSE.outputs_(::NativeMetadataProbe) = (seen=0f0,) +function PSE.environment_outputs_(::NativeMetadataProbe{HAS_OUTPUT}) where {HAS_OUTPUT} + native_metadata_queries[] += 1 + native_metadata_forbidden[] && error("native metadata was replayed") + return HAS_OUTPUT ? (T=0f0,) : NamedTuple() +end +PSE.run!(::NativeMetadataProbe, status, environment, constants, context) = (status.seen += 1f0; nothing) +@testset "public compilation admission consumes the same authored environment names" begin + for has_output in (false, true) + native_metadata_queries[] = 0 + native_metadata_forbidden[] = false + process_model = has_output ? NativeMetadataProbe{true}() : NativeMetadataProbe{false}() + model = CompositeModel(Object(:leaf); applications=( + ModelSpec(process_model; name=:probe, on=One(id=:leaf)),), + environment=(duration=Hour(1),)) + @test native_metadata_queries[] == 1 + native_metadata_forbidden[] = true + if has_output + rejection = try + PSE.Compilation.prepare(model) + nothing + catch error + error + end + @test rejection isa ArgumentError + message = rejection isa Exception ? sprint(showerror, rejection) : "accepted" + @test occursin("application :probe", message) + @test occursin("environment outputs are unsupported", message) + else + program = PSE.Compilation.prepare(model) + continue!(program; steps=2) + @test final_state(program).seen === 2f0 + end + @test native_metadata_queries[] == 1 + @test isnothing(model_status(model, :leaf)) + end +end + +end diff --git a/test/test-model-diagnostic-authoring-recovery.jl b/test/test-model-diagnostic-authoring-recovery.jl index 56b8d2713..5a86aaa62 100644 --- a/test/test-model-diagnostic-authoring-recovery.jl +++ b/test/test-model-diagnostic-authoring-recovery.jl @@ -189,10 +189,11 @@ end environment=Environment(sources=(T=:temperature,))), ModelSpec(Good{:later}(); name=:later, on=One(id=:root)), )) - for expected_reads in 1:2 + @test failed_environment_port_reads[] == 1 + for _ in 1:2 report = PSE.compile_model_report(model) @test [application.id for application in report.applications] == [:later] - @test failed_environment_port_reads[] == expected_reads + @test failed_environment_port_reads[] == 1 @test any(diagnostic -> diagnostic.application_ids == [:failed] && occursin("opaque declaration failed once", diagnostic.message), report.diagnostics) diff --git a/test/test-model-input-plan-output-metadata.jl b/test/test-model-input-plan-output-metadata.jl index 1ea011521..67b883683 100644 --- a/test/test-model-input-plan-output-metadata.jl +++ b/test/test-model-input-plan-output-metadata.jl @@ -106,19 +106,18 @@ plan_signature(plans) = [(plan.application_id, plan.input, plan.origin, @test length(plans) == count @test all(plan -> plan.potential_source_application_ids == (:source,), plans) @test all(plan -> plan.origin == (explicit ? :model_spec : :inferred_same_object), plans) - # Names already belong to the prepared application. Only contract - # validation reads declarations again, once per application; every real - # binding still compares the validated endpoint contracts. - @test queries.source == 1 - @test all(==(1), queries.readers) - @test queries.source_contracts == 1 - @test all(==(1), queries.reader_contracts) + # The constructor owns names and validated pure contracts. This + # planning pass still compares endpoints but replays no declaration. + @test queries.source == 0 + @test all(iszero, queries.readers) + @test queries.source_contracts == 0 + @test all(iszero, queries.reader_contracts) repeated, fresh_queries = planner_pass(data, applications, destinations) @test plan_signature(repeated) == plan_signature(plans) - @test fresh_queries.source == 1 - @test all(==(1), fresh_queries.readers) - @test fresh_queries.source_contracts == 1 - @test all(==(1), fresh_queries.reader_contracts) + @test fresh_queries.source == 0 + @test all(iszero, fresh_queries.readers) + @test fresh_queries.source_contracts == 0 + @test all(iszero, fresh_queries.reader_contracts) simulation = run!(data.model; steps=1, outputs=:all) for index in 1:count @@ -139,11 +138,11 @@ end @test getproperty.(selected, :slot) == [1, 9] plans, queries = planner_pass(data, selected, PSE.NoCompiledDistributedOutputPlans()) @test plan_signature(plans) == [(:reader_8, :signal, :inferred_same_object, (:source,))] - @test queries.source <= 3 - @test queries.readers[end] <= 3 + @test queries.source == 0 + @test queries.readers[end] == 0 @test all(iszero, queries.readers[1:end-1]) - @test queries.source_contracts == 1 - @test queries.reader_contracts[end] == 1 + @test queries.source_contracts == 0 + @test queries.reader_contracts[end] == 0 @test all(iszero, queries.reader_contracts[1:end-1]) end @@ -393,7 +392,7 @@ end @test final_state(first).observed === T(4) @test data.source.queries[] == data.reader.queries[] == 1 - # A compile-local snapshot must not survive a forced compile of the + # An authored snapshot must not survive an explicit author refresh of the # same model/application instances, including a failed compile. data.source.contracts[] = (signal=VariableContract(unit=:changed_signal),) @test_throws "Incompatible variable contracts" Advanced.refresh_bindings!(data.model; force=true) @@ -417,8 +416,9 @@ end data.model.applications..., ModelSpec(later; name=:later_invalid, on=Many(scale=:Other)), ), environment=(duration=Hour(1),)) + @test later.queries[] == 1 # constructor captures later results for diagnostics @test_throws "Incompatible variable contracts" Advanced.refresh_bindings!(model) - @test later.queries[] == 0 + @test later.queries[] == 1 # earlier endpoint error still wins without replay end end diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl index d4df6f0be..fed0887a3 100644 --- a/test/test-model-scenario-authoring.jl +++ b/test/test-model-scenario-authoring.jl @@ -53,8 +53,8 @@ end @test preparation.authored isa Tuple recipe = only(preparation.authored) @test recipe isa PSE.AuthoredApplicationRecipe - @test recipe.output_names == (:value, :scratch, :visits) - @test recipe.canonical_output_names == recipe.output_names + @test recipe.ports.outputs.local_names == (:value, :scratch, :visits) + @test recipe.ports.outputs.canonical_names == recipe.ports.outputs.local_names @test recipe.spec === only(model.applications) @test declarations[] == hints[] == 1 @test conversions == [:seed] diff --git a/test/test-model-spec-normalization.jl b/test/test-model-spec-normalization.jl index 5eac2ea21..595fab985 100644 --- a/test/test-model-spec-normalization.jl +++ b/test/test-model-spec-normalization.jl @@ -170,7 +170,7 @@ end environment=(air=17f0, explicit_air=23f0, duration=Hour(1))) forbidden[] = true hint = (bindings=(T=(source=:air, reducer=MeanWeighted()),), window=TestWindow) - resolved = PSE._model_spec_with_environment_hints(model, spec, :Leaf, hint) + resolved = PSE._model_spec_with_environment_hints(model, spec, :Leaf, hint, PSE.AuthoredPortNames((:T,))) @test calls[] == 1 @test resolved.environment_bindings.T.source === :explicit_air @test resolved.environment_window isa TestWindow @@ -182,16 +182,16 @@ end explicit = ModelSpec(source; environment_bindings=(T=(source=:chosen,),), environment_window=explicit_window) forbidden[] = true - resolved = PSE._model_spec_with_environment_hints(model, explicit, :Leaf, hint) + resolved = PSE._model_spec_with_environment_hints(model, explicit, :Leaf, hint, PSE.AuthoredPortNames((:T,))) @test resolved.environment_bindings.T.source === :chosen @test resolved.environment_window === explicit_window @test calls[] == 2 invalid = ModelSpec(Leaf(); environment=Environment(sources=(unknown=:air,))) @test_throws "unknown model-facing environment input" PSE._model_spec_with_environment_hints( - model, invalid, :Leaf, nothing) + model, invalid, :Leaf, nothing, PSE.AuthoredPortNames(())) errors = Any[] - diagnostic = PSE._model_spec_with_environment_hints(model, invalid, :Leaf, nothing; + diagnostic = PSE._model_spec_with_environment_hints(model, invalid, :Leaf, nothing, PSE.AuthoredPortNames(()); on_error=error -> push!(errors, error)) @test diagnostic === invalid @test length(errors) == 1 From b9e8692dadfd734fdbb715132e7d38351ecddb0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 03:26:51 +0100 Subject: [PATCH 019/324] Prepare logical dependencies once in CompositeModel --- docs/src/model_execution.md | 11 +- src/composite_model/authored_ports.jl | 2 +- src/composite_model/compilation.jl | 573 +++++++++--------- src/visualization/model_graph_view.jl | 78 +-- test/runtests.jl | 1 + test/test-model-authored-input-graph.jl | 308 ++++++++++ test/test-model-authored-port-inventory.jl | 8 +- .../test-model-distributed-route-ownership.jl | 2 +- test/test-model-initializers.jl | 13 +- test/test-model-input-plan-output-metadata.jl | 21 +- test/test-model-input-recipes.jl | 7 +- test/test-model-previous-timestep-views.jl | 6 +- 12 files changed, 667 insertions(+), 363 deletions(-) create mode 100644 test/test-model-authored-input-graph.jl diff --git a/docs/src/model_execution.md b/docs/src/model_execution.md index ff5344a78..5d73ad622 100644 --- a/docs/src/model_execution.md +++ b/docs/src/model_execution.md @@ -69,9 +69,10 @@ other simulations with different choices. ## Compilation Before Runtime `CompositeModel` prepares the application declarations when you construct it: -application identifiers, selector rules, output-port names, environment hints, -and declared calls between models. It registers the objects you supplied without -running their equations. +application identifiers, input/output and environment port names, variable +contracts, selector rules, declared value and call connections, and the dependency +order between applications. Objects and weather rows can be added later. The +constructor registers the objects you supplied without running their equations. Starting a simulation resolves those declarations against the current objects and environment. This preparation is called **compilation**. It: @@ -84,8 +85,8 @@ and environment. This preparation is called **compilation**. It: models that run at different time steps; 5. lists the models that each controller can call through `calls`; 6. finds the weather source, cell, or layer that supplies each object; -7. puts applications in order so their inputs are available when needed, - including any order specified by `Updates`; +7. prepares a schedule from the dependency order, including `Updates`, and + each application's actual cadence; 8. groups objects with matching model, status, and environment types so Julia can run them efficiently. diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl index a7500e340..dbb8c05bf 100644 --- a/src/composite_model/authored_ports.jl +++ b/src/composite_model/authored_ports.jl @@ -57,7 +57,7 @@ Base.propertynames(ports::AuthoredPortInventory) = _authored_metadata_value(value) = value _authored_metadata_value(failure::ScenarioPreparationFailure) = throw(failure.error) -function _capture_authored_metadata(operation, phase::Symbol, application_id::Symbol) +function _capture_authored_metadata(operation, phase::Symbol, application_id::Union{Nothing,Symbol}) try return operation() catch error diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f10e4bef9..44548e80c 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -676,11 +676,29 @@ function _application_recipe_with_calls(recipe::AuthoredApplicationRecipe, call_ recipe.ports, call_plans) end -mutable struct ScenarioPreparation{M,S,A,F} +# Logical declarations have no resolved object identity, clock, scientific +# default, live carrier or simulation owner. Keep one durable typed owner. +mutable struct AuthoredScenarioProgram{D,I,CP,G} + const output_records::D + const input_records::I + const call_plans::CP + const graph::G +end + +mutable struct AuthoredScenarioGraph{CO,MA,AC,AO,F} + const call_owners::CO + const manual_application_ids::MA + const application_children::AC + const application_order::AO + const failures::F +end + +mutable struct ScenarioPreparation{M,S,A,F,P} const owner::M const source_specs::S const authored::A const failure::F + const program::P resolved::Any end @@ -810,7 +828,11 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs) end failure_index = findfirst(record -> record isa ScenarioPreparationFailure, authored) failure = isnothing(failure_index) ? nothing : authored[failure_index] - return ScenarioPreparation(model, source_specs, Tuple(authored), failure, nothing) + authored_records = Tuple(authored) + recipes = Tuple(record for record in authored_records + if record isa AuthoredApplicationRecipe) + program = _prepare_authored_scenario_program(recipes) + return ScenarioPreparation(model, source_specs, authored_records, failure, program, nothing) end function _model_owned_scenario_preparation(model::CompositeModel, preparation::ScenarioPreparation) @@ -818,7 +840,7 @@ function _model_owned_scenario_preparation(model::CompositeModel, preparation::S # Internal reconstruction can share authored metadata, never the mutable # resolved target snapshot. This check is O(1) on lifecycle invalidation. owned = ScenarioPreparation(model, preparation.source_specs, - preparation.authored, preparation.failure, nothing) + preparation.authored, preparation.failure, preparation.program, nothing) model.scenario_plan_cache = owned return owned end @@ -1258,8 +1280,8 @@ function _scenario_update_order_edges!( previous_application, ) || continue _selector_labels_may_overlap( - previous_application.applies_to, - application.applies_to, + applies_to(previous_application.spec), + applies_to(application.spec), ) || continue any( label -> _update_matches_application( @@ -1287,7 +1309,7 @@ function _application_output_selectors( ) selectors = Any[] variable in _model_canonical_output_names(application) && - push!(selectors, application.applies_to) + push!(selectors, applies_to(application.spec)) for plan in _application_plans(plans.by_application, application.id) variable in plan.variable_names || continue push!(selectors, plan.selector) @@ -1360,29 +1382,83 @@ function _freeze_scenario_application_children(applications, children) ) end -function _compile_scenario_application_children( - applications, - input_plans, - call_plans, - call_owners, - manual_application_ids, - distributed_output_plans, -) +function _prepare_authored_scenario_graph(applications, input_plans, call_plans, + distributed_output_plans) + call_owners = _scenario_call_owners(applications, call_plans) + manual_application_ids = Tuple(application.id for application in applications + if !isempty(call_owners[application.id])) + ownership_failure = _capture_authored_metadata(:call_ownership, nothing) do + _validate_scenario_call_ownership!(call_owners, manual_application_ids) + end children = Dict{Symbol,Set{Symbol}}() - _scenario_input_order_edges!(children, input_plans, call_owners) - _scenario_initializer_order_edges!( - children, - input_plans, - call_plans, - call_owners, - ) - _scenario_update_order_edges!( - children, - applications, - manual_application_ids, - distributed_output_plans, - ) - return _freeze_scenario_application_children(applications, children) + dependency_failure = _capture_authored_metadata(:dependency_inputs, nothing) do + _scenario_input_order_edges!(children, input_plans, call_owners) + _scenario_initializer_order_edges!(children, input_plans, call_plans, call_owners) + nothing + end + update_failure = _capture_authored_metadata(:update_order, nothing) do + _scenario_update_order_edges!(children, applications, manual_application_ids, + distributed_output_plans) + nothing + end + frozen_children = _freeze_scenario_application_children(applications, children) + order_result = _capture_authored_metadata(:schedule, nothing) do + Tuple(_stable_topological_application_order(applications, frozen_children)) + end + order = order_result isa ScenarioPreparationFailure ? () : order_result + failures = (call_ownership=ownership_failure, dependency_inputs=dependency_failure, + update_order=update_failure, + schedule=order_result isa ScenarioPreparationFailure ? order_result : nothing) + return AuthoredScenarioGraph(call_owners, manual_application_ids, + frozen_children, order, failures) +end + +function _prepare_authored_scenario_program(applications) + output_records = _prepare_authored_output_records(applications) + destinations = _authored_distributed_output_plans(applications, output_records) + input_records = _prepare_authored_input_records(applications, destinations) + inputs = Tuple(record for record in input_records if record isa CompiledModelInputPlan) + calls = Tuple(plan for application in applications for plan in application.call_plans) + graph = _prepare_authored_scenario_graph(applications, inputs, calls, destinations) + return AuthoredScenarioProgram(output_records, input_records, calls, graph) +end + +function _authored_input_graph_matches(records::Tuple, plans) + length(records) == length(plans) || return false + return all(zip(records, plans)) do (authored, resolved) + authored isa CompiledModelInputPlan && + authored.application_id === resolved.application_id && + authored.input === resolved.input && authored.selector === resolved.selector && + authored.origin === resolved.origin && + authored.potential_source_application_ids === resolved.potential_source_application_ids && + authored.order_after_application_ids === resolved.order_after_application_ids + end +end + +function _authored_call_graph_matches(records::Tuple, plans) + length(records) == length(plans) || return false + return all(zip(records, plans)) do (authored, resolved) + authored.application_id === resolved.application_id && + authored.call === resolved.call && authored.selector === resolved.selector && + _compiled_call_mode(authored) === _compiled_call_mode(resolved) && + authored.potential_callee_application_ids === resolved.potential_callee_application_ids + end +end + +function _resolved_scenario_graph(preparation::ScenarioPreparation, applications, + input_plans, call_plans, distributed_output_plans) + program = preparation.program + if _authored_program_matches(program, applications, distributed_output_plans) && + _authored_input_graph_matches(program.input_records, input_plans) && + _authored_call_graph_matches(program.call_plans, call_plans) + return program.graph + end + # Diagnostics can deliberately omit applications or replace one failed + # phase by empty metadata. Reuse the exact constructor graph factory for + # that projected declaration set, with no author callback or fake object. + return _prepare_authored_scenario_graph( + _project_authored_applications(preparation, applications), + input_plans, call_plans, distributed_output_plans) end function _compiled_scenario_plan( @@ -1403,27 +1479,16 @@ function _compiled_scenario_plan( call_plans, distributed_output_plans, ) - call_owners = _scenario_call_owners(applications, call_plans) - manual_application_ids = Tuple( - application.id for application in applications - if !isempty(call_owners[application.id]) - ) - _validate_scenario_call_ownership!( - call_owners, - manual_application_ids, - ) - application_children = _compile_scenario_application_children( - applications, - input_plans, - call_plans, - call_owners, - manual_application_ids, - distributed_output_plans, - ) - application_order = _stable_topological_application_order( - applications, - application_children, - ) + graph = _resolved_scenario_graph(preparation, applications, + input_plans, call_plans, distributed_output_plans) + _authored_metadata_value(graph.failures.call_ownership) + _authored_metadata_value(graph.failures.dependency_inputs) + _authored_metadata_value(graph.failures.update_order) + _authored_metadata_value(graph.failures.schedule) + call_owners = graph.call_owners + manual_application_ids = graph.manual_application_ids + application_children = graph.application_children + application_order = graph.application_order application_plans_by_id = CompiledMetadataTable(NamedTuple{application_ids}(application_plans)) application_schedule = _compiled_application_schedule( application_plans_by_id, @@ -2185,12 +2250,9 @@ function _compile_resolved_scenario_plan( model::CompositeModel, preparation::ScenarioPreparation, applications, timeline, ) distributed_output_plans = - _compile_model_output_destination_plans(model, applications) - input_plans = _compile_model_input_plans( - model, - applications, - distributed_output_plans, - ) + _resolve_model_output_destination_plans(model, preparation, applications) + input_plans = _resolve_model_input_plans(model, preparation, + applications, distributed_output_plans) call_plans = _compile_model_call_plans(model, applications) return _compiled_scenario_plan( model, @@ -5068,11 +5130,12 @@ function _application_model(application::CompiledModelApplication, object_id::Ob end _application_ports(application::CompiledModelApplication) = getfield(application, :plan).ports -_model_output_names(application::CompiledModelApplication) = _application_ports(application).outputs.local_names -_model_canonical_output_names(application::CompiledModelApplication) = _application_ports(application).outputs.canonical_names -_model_distributed_output_names(application::CompiledModelApplication) = _application_ports(application).outputs.distributed_names -_model_environment_input_names(application::CompiledModelApplication) = _application_ports(application).environment_input_names -_model_environment_output_names(application::CompiledModelApplication) = _application_ports(application).environment_output_names +_application_ports(application::AuthoredApplicationRecipe) = getfield(application, :ports) +_model_output_names(application) = _application_ports(application).outputs.local_names +_model_canonical_output_names(application) = _application_ports(application).outputs.canonical_names +_model_distributed_output_names(application) = _application_ports(application).outputs.distributed_names +_model_environment_input_names(application) = _application_ports(application).environment_input_names +_model_environment_output_names(application) = _application_ports(application).environment_output_names # Real-value initialization/inspection stays fresh; a hook already rejected at # authoring must instead rethrow its captured failure without being replayed. @@ -5108,7 +5171,7 @@ function _application_match_labels(application::CompiledModelApplication) return labels end -_update_matches_application(label::Symbol, application::CompiledModelApplication) = +_update_matches_application(label::Symbol, application) = label == application.id function _update_variables(update) @@ -7539,7 +7602,7 @@ function _potential_input_source_application_ids( ) _selector_from_status(selector) && return () source_selector = origin == :inferred_same_object ? - consumer_application.applies_to : selector + applies_to(consumer_application.spec) : selector return Tuple( application.id for application in get(writer_applications, source_var, ()) if (isnothing(process_filter) || @@ -7561,10 +7624,10 @@ function _input_plan_writer_applications( local_output_names, distributed_output_plans, ) - writers = Dict{Symbol,Vector{CompiledModelApplication}}() + writers = Dict{Symbol,Vector{AuthoredApplicationRecipe}}() for application in applications for variable in local_output_names[application.id] - push!(get!(Vector{CompiledModelApplication}, writers, variable), application) + push!(get!(Vector{AuthoredApplicationRecipe}, writers, variable), application) end distributed_output_plans isa NoCompiledDistributedOutputPlans && continue for plan in get( @@ -7573,7 +7636,7 @@ function _input_plan_writer_applications( (), ) for variable in plan.variable_names - candidates = get!(Vector{CompiledModelApplication}, writers, variable) + candidates = get!(Vector{AuthoredApplicationRecipe}, writers, variable) # An application can write the same name through several # destination plans. Keep it once, in application order. (isempty(candidates) || last(candidates).id != application.id) && @@ -7594,7 +7657,7 @@ function _application_may_output_variable( return variable in local_output_names && _selector_labels_may_overlap( source_selector, - application.applies_to, + applies_to(application.spec), ) end @@ -7608,7 +7671,7 @@ function _application_may_output_variable( variable in local_output_names && _selector_labels_may_overlap( source_selector, - application.applies_to, + applies_to(application.spec), ) && return true return any( plan -> variable in plan.variable_names && @@ -7666,8 +7729,7 @@ Base.@nospecializeinfer function _input_plan_variable_contracts!( end Base.@nospecializeinfer function _compiled_model_input_plan( - plans, - model, + slot::Int, writer_applications, application, input::Symbol, @@ -7727,12 +7789,12 @@ Base.@nospecializeinfer function _compiled_model_input_plan( route = InputRouteTag{input,source_var,_selector_from_status(selector)}() return CompiledModelInputPlan( route, - length(plans) + 1, - application.plan.slot, + slot, + application.slot, application.id, input, selector, - _compile_selector_matcher(model, selector), + _authored_selector_matcher(selector), origin, Tuple(order_after_application_ids), source_var, @@ -7745,111 +7807,94 @@ Base.@nospecializeinfer function _compiled_model_input_plan( ) end -function _compile_model_input_plans( - model::CompositeModel, - applications, - distributed_output_plans=_compile_model_output_destination_plans( - model, - applications, - ), -) +function _prepare_authored_input_records(applications, distributed_output_plans) plans = CompiledModelInputPlan[] - applications_by_id = Dict( - application.id => application for application in applications - ) - # The author owns value-free names; IDs also support diagnostic subsets - # with non-contiguous application slots. - local_output_names = Dict( - application.id => _model_output_names(application) - for application in applications - ) - # Restrict producer scans by declared variable, before applying selectors - # and process/application filters. This remains a compile-pass inventory: - # retain empty applications, stream-only local outputs, and distributed - # declarations regardless of their current destination membership. + records = Any[] + applications_by_id = Dict(application.id => application for application in applications) + local_output_names = Dict(application.id => _model_output_names(application) + for application in applications) writer_applications = _input_plan_writer_applications( - applications, - local_output_names, - distributed_output_plans, - ) - canonical_output_names = Dict( - application.id => Symbol[ - variable for variable in local_output_names[application.id] - if _publish_mode_for_output(application.spec, variable) == :canonical - ] for application in applications - ) - # Read saved pure contracts lazily at the existing endpoint positions. - # This preserves route/error ordering without replaying declaration hooks. + applications, local_output_names, distributed_output_plans) + canonical_output_names = Dict(application.id => _model_canonical_output_names(application) + for application in applications) variable_contracts_by_application = Dict{Symbol,NamedTuple}() for application in applications - _input_plan_variable_contracts!(variable_contracts_by_application, application) + preflight = _capture_authored_metadata(:input_plans, application.id) do + _input_plan_variable_contracts!(variable_contracts_by_application, application) + end + if preflight isa ScenarioPreparationFailure + push!(records, preflight) + continue + end declared_inputs = value_inputs(application.spec) declared_inputs isa NamedTuple || (declared_inputs = NamedTuple()) declared_names = Set(Symbol.(keys(declared_inputs))) for (input_name, selector) in pairs(declared_inputs) input = Symbol(input_name) - _validate_declared_model_input_name!(application, input) - selector isa AbstractObjectMultiplicity || error( - "Input binding `$(input)` on application `$(application.id)` must use an object selector." - ) - push!( - plans, - _compiled_model_input_plan( - plans, - model, - writer_applications, - application, - input, - selector, + record = _capture_authored_metadata(:input_plans, application.id) do + _validate_declared_model_input_name!(application, input) + selector isa AbstractObjectMultiplicity || error( + "Input binding `$(input)` on application `$(application.id)` must use an object selector.") + _compiled_model_input_plan(length(plans) + 1, writer_applications, + application, input, selector, get(input_origins(application.spec), input, :model_spec), - applications_by_id, - distributed_output_plans, - local_output_names, - variable_contracts_by_application, - ), - ) + applications_by_id, distributed_output_plans, local_output_names, + variable_contracts_by_application) + end + push!(records, record) + record isa CompiledModelInputPlan && push!(plans, record) end for input in _model_input_names(application) input in declared_names && continue for producer in get(writer_applications, input, ()) producer.id == application.id && continue local_output = input in canonical_output_names[producer.id] && - _selector_labels_may_overlap( - application.applies_to, - producer.applies_to, - ) + _selector_labels_may_overlap(applies_to(application.spec), applies_to(producer.spec)) distributed_output = _application_declares_distributed_output( - producer, - input, - application.applies_to, - distributed_output_plans, - ) + producer, input, applies_to(application.spec), distributed_output_plans) (local_output || distributed_output) || continue - selector = One( - within=Self(), - process=producer.process, - application=producer.id, - var=input, - ) - push!( - plans, - _compiled_model_input_plan( - plans, - model, - writer_applications, - application, - input, - selector, - :inferred_same_object, - applications_by_id, - distributed_output_plans, - local_output_names, - variable_contracts_by_application, - ), - ) + selector = One(within=Self(), process=producer.process, + application=producer.id, var=input) + record = _capture_authored_metadata(:input_plans, application.id) do + _compiled_model_input_plan(length(plans) + 1, writer_applications, + application, input, selector, :inferred_same_object, + applications_by_id, distributed_output_plans, local_output_names, + variable_contracts_by_application) + end + push!(records, record) + record isa CompiledModelInputPlan && push!(plans, record) end end end + return Tuple(records) +end + +function _resolve_model_input_plan(model, plan::CompiledModelInputPlan, slot::Int) + matcher = _resolve_selector_matcher(model, plan.matcher) + matcher === plan.matcher && slot == plan.slot && return plan + return CompiledModelInputPlan(plan.route, slot, plan.application_slot, + plan.application_id, plan.input, plan.selector, matcher, plan.origin, + plan.order_after_application_ids, plan.source_var, plan.process, + plan.application, plan.multiplicity, plan.potential_source_application_ids, + plan.breaks_same_step_cycle, plan.window) +end + +function _resolve_model_input_plans(model, preparation::ScenarioPreparation, + applications, distributed_output_plans) + program = preparation.program + records = if _authored_program_matches(program, applications, distributed_output_plans) + program.input_records + else + # A partial report is a different declaration set. Project the real + # recipes through the SAME pure factory, without replaying a hook. + _prepare_authored_input_records(_project_authored_applications(preparation, applications), + distributed_output_plans) + end + plans = CompiledModelInputPlan[] + for record in records + plan = _authored_metadata_value(record) + push!(plans, _resolve_model_input_plan(model, plan, length(plans) + 1)) + end return plans end @@ -7899,50 +7944,112 @@ function _compile_model_call_plans(model::CompositeModel, applications) return plans end -function _compile_model_output_destination_plans( - model::CompositeModel, - applications, -) +function _distributed_output_plans(applications, plans) + isempty(plans) && return NoCompiledDistributedOutputPlans() + return CompiledDistributedOutputPlans(Tuple(plans), _plans_by_application(applications, plans)) +end + +function _prepare_authored_output_records(applications) + records = Any[] + slot = 0 + for application in applications + layout = _capture_authored_metadata(:output_destination_plans, application.id) do + _output_destination_layout(application.spec, + _model_distributed_output_names(application)) + end + if layout isa ScenarioPreparationFailure + push!(records, layout) + continue + end + routes = Any[] + for (destination_slot, destination) in enumerate(layout) + record = _capture_authored_metadata(:output_destination_plans, application.id) do + group = Symbol("output_", destination_slot) + selector = destination.selector + selector isa AbstractObjectMultiplicity || error( + "Output destination `$(group)` on application `$(application.id)` must use an object selector.") + CompiledModelOutputDestinationPlan(slot + 1, + application.slot, application.id, group, selector, + _authored_selector_matcher(selector), destination.variable_names, + multiplicity(selector), destination.coverage) + end + push!(routes, record) + record isa ScenarioPreparationFailure || (slot += 1) + end + push!(records, Tuple(routes)) + end + ids = Tuple(application.id for application in applications) + return CompiledMetadataTable(NamedTuple{ids}(Tuple(records))) +end + +function _authored_distributed_output_plans(applications, output_records) + plans = CompiledModelOutputDestinationPlan[] + for application in applications + records = output_records[application.id] + records isa ScenarioPreparationFailure && continue + for record in records + record isa CompiledModelOutputDestinationPlan && push!(plans, record) + end + end + return _distributed_output_plans(applications, plans) +end + +function _resolve_model_output_destination_plans(model::CompositeModel, + preparation::ScenarioPreparation, applications) plans = CompiledModelOutputDestinationPlan[] for application in applications + # Deliver each saved partition error before this application's real + # override validation and Scope resolution, retaining phase order. + authored = _authored_metadata_value(preparation.program.output_records[application.id]) distributed_names = _model_distributed_output_names(application) - destinations = _output_destination_layout(application.spec, distributed_names) if !isnothing(application.model_overrides) for replacement in values(application.model_overrides) replacement_names = _distributed_output_names(replacement) _output_destination_layout(application.spec, replacement_names, replacement) - Set(replacement_names) == Set(distributed_names) || - error("Object override for application `$(application.id)` has incompatible distributed output names.") + Set(replacement_names) == Set(distributed_names) || error( + "Object override for application `$(application.id)` has incompatible distributed output names.") end end - for (destination_slot, destination) in enumerate(destinations) - group_name = Symbol("output_", destination_slot) - selector = getproperty(destination, :selector) - selector isa AbstractObjectMultiplicity || error( - "Output destination `$(group_name)` on application `$(application.id)` " * - "must use an object selector.", - ) - push!( - plans, - CompiledModelOutputDestinationPlan( - length(plans) + 1, - application.plan.slot, - application.id, - Symbol(group_name), - selector, - _compile_selector_matcher(model, selector), - getproperty(destination, :variable_names), - multiplicity(selector), - getproperty(destination, :coverage), - ), - ) + for record in authored + plan = _authored_metadata_value(record) + matcher = _resolve_selector_matcher(model, plan.matcher) + push!(plans, CompiledModelOutputDestinationPlan(length(plans) + 1, + plan.application_slot, plan.application_id, plan.group, + plan.selector, matcher, plan.variable_names, plan.multiplicity, + plan.coverage)) end end - isempty(plans) && return NoCompiledDistributedOutputPlans() - return CompiledDistributedOutputPlans( - Tuple(plans), - _plans_by_application(applications, plans), - ) + return _distributed_output_plans(applications, plans) +end + +function _project_authored_applications(preparation::ScenarioPreparation, applications) + by_id = Dict(recipe.id => recipe for recipe in preparation.authored + if recipe isa AuthoredApplicationRecipe) + return Tuple(by_id[application.id] for application in applications) +end + +function _authored_program_matches(program::AuthoredScenarioProgram, + applications, distributed_output_plans) + ids = Tuple(application.id for application in applications) + ids === keys(program.output_records) || return false + resolved = distributed_output_plans isa NoCompiledDistributedOutputPlans ? + () : distributed_output_plans.plans + index = 0 + for application in applications + records = program.output_records[application.id] + records isa ScenarioPreparationFailure && return false + for authored in records + authored isa ScenarioPreparationFailure && return false + index += 1 + index <= length(resolved) || return false + plan = resolved[index] + authored.application_id === plan.application_id && + authored.group === plan.group && authored.selector === plan.selector && + authored.variable_names === plan.variable_names && + authored.coverage === plan.coverage || return false + end + end + return index == length(resolved) end _application_plans(plans_by_application, application_id::Symbol) = @@ -8026,15 +8133,10 @@ end function _compile_model_input_bindings( model::CompositeModel, applications, - manual_application_ids=Set{Symbol}(), - input_recipes_by_application=nothing, + manual_application_ids, + input_recipes_by_application, distributed_outputs=NoCompiledDistributedOutputs(), ) - if isnothing(input_recipes_by_application) - plans = _compile_model_input_plans(model, applications) - input_recipes_by_application = _compiled_application_input_recipes( - _plans_by_application(applications, plans)) - end bindings = CompiledModelInputBinding[] by_object = _applications_by_object(applications, model.registry.objects) by_id = _applications_by_id(applications) @@ -8371,7 +8473,7 @@ function _has_matching_distributed_input_writer( end end -_model_input_names(application::CompiledModelApplication) = _application_ports(application).input_names +_model_input_names(application) = _application_ports(application).input_names function _validate_model_input_source!( model::CompositeModel, @@ -8396,7 +8498,7 @@ function _validate_model_input_source!( ) end -function _validate_declared_model_input_name!(application::CompiledModelApplication, input_sym::Symbol) +function _validate_declared_model_input_name!(application, input_sym::Symbol) input_names = Set(_model_input_names(application)) input_sym in input_names && return nothing error( @@ -8749,59 +8851,12 @@ function _compile_model_call_bindings( return bindings end -function _model_call_owners(call_bindings) - owners = Dict{Symbol,Set{Symbol}}() - for binding in call_bindings - _compiled_call_mode(binding) === :manual || continue - for callee_id in binding.callee_application_ids - push!(get!(owners, callee_id, Set{Symbol}()), binding.application_id) - end - end - return owners -end - function _add_model_application_edge!(children, parent::Symbol, child::Symbol) parent == child && return nothing push!(get!(children, parent, Set{Symbol}()), child) return nothing end -function _model_input_order_edges!(children, input_bindings, call_owners) - for binding in input_bindings - binding.policy isa PreviousTimeStep && continue - ordering_sources = ( - binding.source_application_ids..., - binding.order_after_application_ids..., - ) - for source_id in ordering_sources - owners = get(call_owners, source_id, nothing) - if isnothing(owners) - _add_model_application_edge!(children, source_id, binding.application_id) - else - for owner_id in owners - _add_model_application_edge!(children, owner_id, binding.application_id) - end - end - end - end - return children -end - -function _model_update_order_edges!(children, applications) - any(application -> !isempty(updates(application.spec)), applications) || - return children - for indexed_writers in values(_model_writer_groups(applications)) - length(indexed_writers) > 1 || continue - sort!(indexed_writers; by=first) - for index in 2:length(indexed_writers) - previous_application = indexed_writers[index - 1][2] - application = indexed_writers[index][2] - _add_model_application_edge!(children, previous_application.id, application.id) - end - end - return children -end - function _stable_topological_application_order(applications, children) application_ids = Symbol[application.id for application in applications] positions = Dict(application_id => index for (index, application_id) in pairs(application_ids)) @@ -8833,34 +8888,6 @@ function _stable_topological_application_order(applications, children) return order end -function _compile_model_application_children( - applications, - input_bindings, - call_bindings, - call_owners, -) - children = Dict{Symbol,Set{Symbol}}() - _model_input_order_edges!(children, input_bindings, call_owners) - _scenario_initializer_order_edges!( - children, - input_bindings, - call_bindings, - call_owners, - ) - _model_update_order_edges!(children, applications) - return children -end - -function _compile_model_application_order(applications, input_bindings, call_bindings) - children = _compile_model_application_children( - applications, - input_bindings, - call_bindings, - _model_call_owners(call_bindings), - ) - return _stable_topological_application_order(applications, children) -end - function _ordered_model_applications(compiled::CompiledCompositeModel) return compiled.ordered_applications end diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 384c836d9..0ef3457ea 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -92,34 +92,6 @@ function _model_graph_phase!(operation, diagnostics, phase::Symbol, fallback) end end -function _model_graph_dependency_children( - applications, - input_bindings, - call_bindings, - distributed_output_plans=NoCompiledDistributedOutputPlans(), -) - children = Dict{Symbol,Set{Symbol}}() - call_owners = _model_call_owners(call_bindings) - _model_input_order_edges!( - children, - input_bindings, - call_owners, - ) - _scenario_initializer_order_edges!( - children, - input_bindings, - call_bindings, - call_owners, - ) - _scenario_update_order_edges!( - children, - applications, - _manual_call_application_ids(call_bindings), - distributed_output_plans, - ) - return children -end - function _model_graph_dependency_children(compiled::CompiledCompositeModel) return Dict{Symbol,Set{Symbol}}( application_id => Set{Symbol}(children) @@ -378,18 +350,14 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) :output_destination_plans, NoCompiledDistributedOutputPlans(), ) do - _compile_model_output_destination_plans(model, applications) + _resolve_model_output_destination_plans(model, preparation, applications) end input_plans = _model_graph_phase!( diagnostics, :input_plans, CompiledModelInputPlan[], ) do - _compile_model_input_plans( - model, - applications, - distributed_output_plans, - ) + _resolve_model_input_plans(model, preparation, applications, distributed_output_plans) end call_plans = _model_graph_phase!( diagnostics, @@ -398,11 +366,10 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) ) do _compile_model_call_plans(model, applications) end - scenario_call_owners = _scenario_call_owners(applications, call_plans) - manual_application_ids = Tuple( - application.id for application in applications - if !isempty(scenario_call_owners[application.id]) - ) + graph = _resolved_scenario_graph(preparation, applications, + input_plans, call_plans, distributed_output_plans) + scenario_call_owners = graph.call_owners + manual_application_ids = graph.manual_application_ids _model_graph_phase!(diagnostics, :call_ownership, nothing) do _validate_initializer_call_plans!( model, @@ -411,10 +378,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) call_plans, distributed_output_plans, ) - _validate_scenario_call_ownership!( - scenario_call_owners, - manual_application_ids, - ) + _authored_metadata_value(graph.failures.call_ownership) end call_bindings = _model_graph_phase!(diagnostics, :calls, CompiledModelCallBinding[]) do @@ -464,33 +428,21 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) _wire_model_input_carriers!(model, input_bindings) end - children = Dict{Symbol,Set{Symbol}}() + children = Dict{Symbol,Set{Symbol}}( + application_id => Set(child_ids) + for (application_id, child_ids) in pairs(graph.application_children) if !isempty(child_ids)) _model_graph_phase!(diagnostics, :dependency_inputs, nothing) do - _scenario_input_order_edges!( - children, - input_plans, - scenario_call_owners, - ) - _scenario_initializer_order_edges!( - children, - input_plans, - call_plans, - scenario_call_owners, - ) + _authored_metadata_value(graph.failures.dependency_inputs) end _model_graph_phase!(diagnostics, :update_order, nothing) do - _scenario_update_order_edges!( - children, - applications, - manual_application_ids, - distributed_output_plans, - ) + _authored_metadata_value(graph.failures.update_order) end cycles = _model_graph_cycle_components(applications, children) application_order = Symbol[] if isempty(cycles) application_order = _model_graph_phase!(diagnostics, :schedule, Symbol[]) do - _stable_topological_application_order(applications, children) + _authored_metadata_value(graph.failures.schedule) + Symbol[graph.application_order...] end else for cycle in cycles @@ -1705,7 +1657,7 @@ end function _model_graph_distributed_initialization!(rows, report) destinations = try - plans = _compile_model_output_destination_plans(report.model, report.applications) + plans = _resolve_model_output_destination_plans(report.model, _scenario_preparation(report.model), report.applications) _resolve_model_output_destinations(report.model, _applications_by_id(report.applications), plans) catch # A binding error is already in the report. Valid destinations can still diff --git a/test/runtests.jl b/test/runtests.jl index 6d43e292f..f069fd38c 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -83,6 +83,7 @@ else include("test-model-prepared-scenario.jl") include("test-model-scenario-authoring.jl") include("test-model-authored-port-inventory.jl") + include("test-model-authored-input-graph.jl") include("test-model-prepared-authoring-owner.jl") include("test-model-public-refresh-owners.jl") include("test-model-authored-call-plans.jl") diff --git a/test/test-model-authored-input-graph.jl b/test/test-model-authored-input-graph.jl new file mode 100644 index 000000000..6c0b6a342 --- /dev/null +++ b/test/test-model-authored-input-graph.jl @@ -0,0 +1,308 @@ +module AuthoredInputGraphChecks +using Dates, DataFrames, PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "authored_graph_source" verbose=false +PSE.@process "authored_graph_sink" verbose=false +PSE.@process "authored_graph_writer" verbose=false +PSE.@process "authored_graph_update" verbose=false +PSE.@process "authored_graph_child" verbose=false +PSE.@process "authored_graph_owner" verbose=false +PSE.@process "authored_graph_consumer" verbose=false +PSE.@process "authored_graph_previous" verbose=false +PSE.@process "authored_graph_broken" verbose=false + +struct Source{C,Q} <: AbstractAuthored_Graph_SourceModel + runs::C + declarations::Q +end +Source(runs) = Source(runs, Ref(0)) +PSE.inputs_(::Source) = NamedTuple() +function PSE.outputs_(model::Source) + model.declarations[] += 1 + return (value=0f0,) +end +function PSE.run!(model::Source, status, environment, constants, context) + model.runs[] += 1 + status.value += 1f0 + return nothing +end +struct Sink <: AbstractAuthored_Graph_SinkModel end +PSE.inputs_(::Sink) = (value=Required(Float32),) +PSE.outputs_(::Sink) = (seen=0f0,) +PSE.run!(::Sink, status, environment, constants, context) = (status.seen = status.value; nothing) + +function authored_program(model) + preparation = model.scenario_plan_cache + @test preparation isa PSE.ScenarioPreparation + ready = hasproperty(preparation, :program) + @test ready + return ready ? preparation.program : nothing +end + +@testset "constructor prepares complete explicit and inferred dependencies before weather or objects" begin + for explicit in (false, true) + weather = DataFrame(duration=Hour[]) + runs = Ref(0) + source = Source(runs) + target = Many(Scope(ObjectId(:future_root)); scale=:Leaf) + model = CompositeModel(Object(:scene; scale=:Scene); environment=weather, + applications=( + ModelSpec(Sink(); name=:sink, on=target, + inputs=explicit ? (value=One(Self(); application=:source),) : NamedTuple()), + ModelSpec(source; name=:source, on=target), + )) + preparation = model.scenario_plan_cache + program = authored_program(model) + @test isempty(weather) + @test runs[] == 0 + @test source.declarations[] == 1 + @test model.binding_cache === nothing + @test preparation.resolved === nothing + @test model_status(model, :scene) === nothing + if !isnothing(program) + route = only(program.input_records) + @test route isa PSE.CompiledModelInputPlan + @test route.application_id === :sink + @test route.origin === (explicit ? :model_spec : :inferred_same_object) + @test route.potential_source_application_ids === (:source,) + @test program.graph.application_children.source === (:sink,) + @test program.graph.application_order === (:source, :sink) + @test isempty(program.graph.manual_application_ids) + end + # Physical roots, membership, weather duration and history dimensions + # are supplied only after the constructor has prepared the graph. + register_object!(model, Object(:future_root; scale=:Plant, parent=:scene)) + register_object!(model, Object(:a; scale=:Leaf, parent=:future_root)) + append!(weather, DataFrame(duration=fill(Hour(1), 3))) + simulation = run!(model; steps=2, outputs=:all) + if !isnothing(program) + plan = simulation.compiled.scenario_plan + @test PSE._resolved_scenario_graph(preparation, simulation.compiled.applications, + plan.input_plans, plan.call_plans, plan.distributed_output_plans) === program.graph + end + @test source.declarations[] > 1 # real status initialization remains fresh + @test model_status(model, :a).seen === 2f0 + @test runs[] == 2 + register_object!(model, Object(:b; scale=:Leaf, parent=:future_root)) + step!(simulation) + @test runs[] == 4 + @test model_status(model, :a).seen === 3f0 + @test model_status(model, :b).seen === 1f0 + @test outputs(simulation)[(:sink, ObjectId(:a), :seen)] == [(1.0, 1f0), (2.0, 2f0), (3.0, 3f0)] + @test outputs(simulation)[(:sink, ObjectId(:b), :seen)] == [(3.0, 1f0)] + @test model.scenario_plan_cache === preparation + if !isnothing(program) + @test model.scenario_plan_cache.program === program + end + end +end + +struct Writer <: AbstractAuthored_Graph_WriterModel end +PSE.inputs_(::Writer) = NamedTuple() +PSE.outputs_(::Writer) = (signal=Distributed(Default(0f0)),) +function PSE.run!(::Writer, status, environment, constants, context) + targets = output_targets(context, (:signal,)) + for index in eachindex(targets.columns.signal) + targets.columns.signal[index] = 2f0 + end + return nothing +end +struct Updater <: AbstractAuthored_Graph_UpdateModel end +PSE.inputs_(::Updater) = NamedTuple() +PSE.outputs_(::Updater) = (signal=0f0,) +PSE.run!(::Updater, status, environment, constants, context) = (status.signal += 1f0; nothing) +struct Child <: AbstractAuthored_Graph_ChildModel end +PSE.inputs_(::Child) = NamedTuple() +PSE.outputs_(::Child) = (manual_value=0f0, manual_calls=0) +function PSE.run!(::Child, status, environment, constants, context) + status.manual_value += 2f0 + status.manual_calls += 1 + return nothing +end +struct Owner <: AbstractAuthored_Graph_OwnerModel end +PSE.inputs_(::Owner) = NamedTuple() +PSE.outputs_(::Owner) = (manual_seen=0f0,) +function PSE.run!(::Owner, status, environment, constants, context) + child = only(run_call!(context, :child; publish=true)) + status.manual_seen = child.status.manual_value + return nothing +end +struct Consumer <: AbstractAuthored_Graph_ConsumerModel end +PSE.inputs_(::Consumer) = (signal=Required(Float32), manual_value=Required(Float32)) +PSE.outputs_(::Consumer) = (total=0f0,) +PSE.run!(::Consumer, status, environment, constants, context) = (status.total = status.signal + status.manual_value; nothing) +struct Previous <: AbstractAuthored_Graph_PreviousModel end +PSE.inputs_(::Previous) = (lagged=Required(Float32),) +PSE.outputs_(::Previous) = (previous=0f0,) +PSE.run!(::Previous, status, environment, constants, context) = (status.previous = status.lagged; nothing) + +@testset "one authored graph contains distributed writes Updates manual ownership and PreviousTimeStep" begin + weather = DataFrame(duration=Hour[]) + model = CompositeModel(Object(:scene; scale=:Scene); environment=weather, + applications=( + ModelSpec(Consumer(); name=:consumer, on=Many(scale=:Leaf)), + ModelSpec(Previous(); name=:previous, on=Many(scale=:Leaf), + inputs=(PreviousTimeStep(:lagged) => One(Self(); application=:updater, var=:signal),)), + ModelSpec(Writer(); name=:writer, on=One(id=:scene), + outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope())),)), + ModelSpec(Updater(); name=:updater, on=Many(scale=:Leaf), updates=Updates(:signal; after=:writer)), + ModelSpec(Owner(); name=:owner, on=One(id=:scene), + calls=(child=One(id=:leaf, application=:child, within=SceneScope()),)), + ModelSpec(Child(); name=:child, on=Many(scale=:Leaf)), + )) + program = authored_program(model) + @test model_status(model, :scene) === nothing + @test model.binding_cache === nothing + @test model.scenario_plan_cache.resolved === nothing + if !isnothing(program) + destination = only(program.output_records[:writer]) + @test destination.variable_names === (:signal,) + @test !hasproperty(destination, :declarations) + @test program.graph.manual_application_ids === (:child,) + children = program.graph.application_children + @test :updater in children.writer + @test :consumer in children.updater + @test :consumer in children.owner + @test !(:previous in children.updater) + previous = only(filter(route -> route.application_id === :previous, program.input_records)) + @test previous.breaks_same_step_cycle + @test previous.potential_source_application_ids === (:updater,) + end + register_object!(model, Object(:leaf; scale=:Leaf, parent=:scene, + status=Status(signal=10f0, lagged=10f0))) + append!(weather, DataFrame(duration=fill(Hour(1), 2))) + simulation = run!(model; steps=2, outputs=:all) + state = model_status(model, :leaf) + @test state.signal === 3f0 + @test state.manual_value === 4f0 + @test state.manual_calls == 2 + @test state.total === 7f0 + @test state.previous === 3f0 + @test outputs(simulation)[(:consumer, ObjectId(:leaf), :total)] == [(1.0, 5f0), (2.0, 7f0)] + @test outputs(simulation)[(:previous, ObjectId(:leaf), :previous)] == [(1.0, 10f0), (2.0, 3f0)] + @test outputs(simulation)[(:child, ObjectId(:leaf), :manual_value)] == [(1.0, 2f0), (2.0, 4f0)] + if !isnothing(program) + @test model.scenario_plan_cache.program === program + end +end + +struct Broken <: AbstractAuthored_Graph_BrokenModel + token::Symbol +end +PSE.outputs_(::Broken) = error("authored graph deliberately invalid output") + +@testset "filtered diagnostics project the same authored input factory without renumbering slots" begin + source = Source(Ref(0)) + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(source; name=:source, on=One(id=:leaf)), + ModelSpec(Broken(:once); name=:broken, on=One(id=:leaf)), + ModelSpec(Sink(); name=:sink, on=One(id=:leaf), + inputs=(value=One(Self(); application=:source),)), + )) + program = authored_program(model) + report = PSE.compile_model_report(model) + @test [app.id for app in report.applications] == [:source, :sink] + @test [app.slot for app in report.applications] == [1, 3] + @test any(diagnostic -> occursin("deliberately invalid output", diagnostic.message), report.diagnostics) + @test !any(diagnostic -> occursin("BoundsError", diagnostic.message), report.diagnostics) + @test length(report.input_bindings) == 1 + @test only(report.input_bindings).application_id === :sink + @test only(report.input_bindings).source_application_ids == [:source] + @test model_status(model, :leaf) === nothing + @test source.runs[] == 0 + if !isnothing(program) + @test model.scenario_plan_cache.program === program + end +end + +PSE.@process "authored_graph_contract_source" verbose=false +PSE.@process "authored_graph_contract_sink" verbose=false +struct ContractSource{UNIT} <: AbstractAuthored_Graph_Contract_SourceModel end +PSE.inputs_(::ContractSource) = NamedTuple() +PSE.outputs_(::ContractSource) = (value=0f0,) +PSE.variable_contracts_(::ContractSource{UNIT}) where {UNIT} = (value=VariableContract(unit=UNIT),) +PSE.run!(::ContractSource, status, environment, constants, context) = nothing +struct OrderedSink{C} <: AbstractAuthored_Graph_Contract_SinkModel + declarations::C +end +PSE.inputs_(::OrderedSink) = (first=Required(Float32), second=Required(Float32)) +PSE.outputs_(::OrderedSink) = (seen=0f0,) +function PSE.variable_contracts_(model::OrderedSink) + model.declarations[] += 1 + return (first=VariableContract(unit=:first), second=VariableContract(unit=:wrong)) +end +PSE.run!(::OrderedSink, status, environment, constants, context) = nothing + +@testset "saved route failures retain physical Scope error order" begin + calls = Ref(0) + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(ContractSource{:first}(); name=:first, on=Many(scale=:First)), + ModelSpec(ContractSource{:second}(); name=:second, on=Many(scale=:Second)), + ModelSpec(OrderedSink(calls); name=:sink, on=One(id=:leaf), inputs=( + first=One(Scope(ObjectId(:future)); application=:first, var=:value), + second=One(application=:second, var=:value), + )), + )) + program = authored_program(model) + @test calls[] == 1 + if !isnothing(program) + @test length(program.input_records) == 2 + @test first(program.input_records) isa PSE.CompiledModelInputPlan + @test last(program.input_records) isa PSE.ScenarioPreparationFailure + @test last(program.input_records).application_id === :sink + end + @test_throws "No instance or object ID" run!(model; steps=0) + @test calls[] == 1 + register_object!(model, Object(:future; scale=:Plant)) + @test_throws "Incompatible variable contracts for input `second`" run!(model; steps=0) + @test calls[] == 1 + @test model_status(model, :leaf) === nothing +end + +@testset "earlier output Scope wins over a later captured output partition error" begin + model = CompositeModel(Object(:scene; scale=:Scene); applications=( + ModelSpec(Writer(); name=:first, on=One(id=:scene), + outputs_to=(OutputTo(Many(Scope(ObjectId(:future)); scale=:Leaf)),)), + ModelSpec(Writer(); name=:second, on=One(id=:scene), + outputs_to=(OutputTo(Many(scale=:Leaf); vars=(:unknown,)),)), + )) + program = authored_program(model) + if !isnothing(program) + @test only(program.output_records[:first]) isa PSE.CompiledModelOutputDestinationPlan + @test program.output_records[:second] isa PSE.ScenarioPreparationFailure + end + @test_throws "No instance or object ID" run!(model; steps=0) + register_object!(model, Object(:future; scale=:Plant)) + @test_throws "not declared as a Distributed output" run!(model; steps=0) + @test model_status(model, :scene) === nothing +end + +struct ContractSink <: AbstractAuthored_Graph_SinkModel end +PSE.inputs_(::ContractSink) = (value=Default(7f0),) +PSE.outputs_(::ContractSink) = (seen=0f0,) +PSE.variable_contracts_(::ContractSink) = (value=VariableContract(unit=:sink),) +PSE.run!(::ContractSink, status, environment, constants, context) = (status.seen=status.value; nothing) + +@testset "a removed diagnostic producer cannot leave a captured endpoint mismatch behind" begin + model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( + ModelSpec(ContractSource{:wrong}(); name=:source, + on=One(Scope(ObjectId(:missing)); scale=:Leaf)), + ModelSpec(Broken(:keep_slots); name=:broken, on=One(id=:leaf)), + ModelSpec(ContractSink(); name=:sink, on=One(id=:leaf), + inputs=(value=OptionalOne(Self(); application=:source),)), + )) + program = authored_program(model) + if !isnothing(program) + @test any(record -> record isa PSE.ScenarioPreparationFailure && + occursin("Incompatible variable contracts", sprint(showerror, record.error)), program.input_records) + end + report = PSE.compile_model_report(model) + @test [app.id for app in report.applications] == [:sink] + @test only(report.applications).slot == 3 + @test any(diagnostic -> occursin("No instance or object ID", diagnostic.message), report.diagnostics) + @test !any(diagnostic -> occursin("Incompatible variable contracts", diagnostic.message), report.diagnostics) + @test !any(diagnostic -> occursin("BoundsError", diagnostic.message), report.diagnostics) + @test model_status(model, :leaf) === nothing +end + +end diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index 828e4115f..f18b1823c 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -95,8 +95,8 @@ end # Compiler-only preparation must not replay any metadata getter. before_a, before_b = a.counter[], b.counter[] applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) - destinations = PSE._compile_model_output_destination_plans(model, applications) - PSE._compile_model_input_plans(model, applications, destinations) + destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) + PSE._resolve_model_input_plans(model, PSE._scenario_preparation(model), applications, destinations) PSE._compile_environment_application_plans(model, applications; prepare_runtime=false) @test a.counter[] == before_a @test b.counter[] == before_b @@ -275,8 +275,8 @@ end @test isnothing(model.scenario_plan_cache.failure) applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) @test counter[] == 1 # empty remap must not demand failed names early - destinations = PSE._compile_model_output_destination_plans(model, applications) - @test_throws message PSE._compile_model_input_plans(model, applications, destinations) + destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) + @test_throws message PSE._resolve_model_input_plans(model, PSE._scenario_preparation(model), applications, destinations) @test counter[] == 1 # even empty contracts validate all declared port names @test_throws message PSE._compile_environment_application_plans(model, applications; prepare_runtime=false) @test counter[] == 1 diff --git a/test/test-model-distributed-route-ownership.jl b/test/test-model-distributed-route-ownership.jl index 23c7c8663..053615e1d 100644 --- a/test/test-model-distributed-route-ownership.jl +++ b/test/test-model-distributed-route-ownership.jl @@ -105,7 +105,7 @@ end Object(:leaf; scale=:Leaf); applications=(spec,)) applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) - destinations = PSE._compile_model_output_destination_plans(model, applications) + destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) plan = only(destinations.plans) @test (@inferred PSE._output_destination_variable_names(plan)) === (:payload,) @test !hasproperty(plan, :declarations) diff --git a/test/test-model-initializers.jl b/test/test-model-initializers.jl index 260e43637..783cf15e1 100644 --- a/test/test-model-initializers.jl +++ b/test/test-model-initializers.jl @@ -543,6 +543,7 @@ PlantSimEngine.outputs_(::InitializerCacheMutatorModel) = ( targeted_value=-1.0, refreshed_plan=false, cache_invalidated=false, + cache_preserved_for_adoption=false, bindings_remained_dirty=false, ) @@ -568,6 +569,7 @@ function PlantSimEngine.run!( ) run_call!(context, :manual_leaf; objects=leaf, publish=false) elseif object_id(context) == ObjectId(:cache_creator_b) + previous_cache = PlantSimEngine.lifecycle_delta(runtime).targeted_topology_runtime leaf = register_object!( runtime, Object( @@ -579,8 +581,15 @@ function PlantSimEngine.run!( ), ) reparent_object!(runtime, :cache_leaf_a, :plant_b) + delta = PlantSimEngine.lifecycle_delta(runtime) + # Keep the real newborn execution stamps until ordinary views adopt + # them, while rejecting this cache for a mixed structural event. + status.cache_preserved_for_adoption = !isnothing(previous_cache) && + delta.targeted_topology_runtime === previous_cache status.cache_invalidated = isnothing( - PlantSimEngine.lifecycle_delta(runtime).targeted_topology_runtime, + PlantSimEngine._targeted_new_object_call_targets( + context, :manual_leaf, (leaf.id,), only(context.calls), + ), ) target = only( run_call!( @@ -1423,6 +1432,8 @@ end @test model_status(model, :cache_creator_b).targeted_value == 7.0 @test model_status(model, :cache_creator_b).refreshed_plan @test model_status(model, :cache_creator_b).cache_invalidated + @test model_status(model, :cache_creator_b).cache_preserved_for_adoption + @test isnothing(PlantSimEngine.lifecycle_delta(model).targeted_topology_runtime) @test !model_status(model, :cache_creator_b).bindings_remained_dirty @test simulation.compiled.applications_by_id[:cache_manual_target].target_ids == [ObjectId(:cache_leaf_b)] diff --git a/test/test-model-input-plan-output-metadata.jl b/test/test-model-input-plan-output-metadata.jl index 67b883683..7de713376 100644 --- a/test/test-model-input-plan-output-metadata.jl +++ b/test/test-model-input-plan-output-metadata.jl @@ -86,7 +86,7 @@ function planner_pass(data, applications, destinations) data.source.contract_queries[] = 0 foreach(reader -> reader.queries[] = 0, data.readers) foreach(reader -> reader.contract_queries[] = 0, data.readers) - plans = PSE._compile_model_input_plans(data.model, applications, destinations) + plans = PSE._resolve_model_input_plans(data.model, PSE._scenario_preparation(data.model), applications, destinations) queries = (source=data.source.queries[], readers=[reader.queries[] for reader in data.readers], source_contracts=data.source.contract_queries[], reader_contracts=[reader.contract_queries[] for reader in data.readers]) @@ -101,7 +101,7 @@ plan_signature(plans) = [(plan.application_id, plan.input, plan.origin, data = query_scene(T, count; explicit) applications = PSE._compile_model_applications(data.model, data.model.applications, PSE._model_timeline(data.model)) - destinations = PSE._compile_model_output_destination_plans(data.model, applications) + destinations = PSE._resolve_model_output_destination_plans(data.model, PSE._scenario_preparation(data.model), applications) plans, queries = planner_pass(data, applications, destinations) @test length(plans) == count @test all(plan -> plan.potential_source_application_ids == (:source,), plans) @@ -439,20 +439,23 @@ end ), environment=(duration=Hour(1),)) applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) - destinations = PSE._compile_model_output_destination_plans(model, applications) + preparation = PSE._scenario_preparation(model) + authored = PSE._project_authored_applications(preparation, applications) + destinations = PSE._resolve_model_output_destination_plans(model, preparation, applications) local_names = Dict(application.id => PSE._model_output_names(application) for application in applications) queries_before = [source.queries[] for source in (first_source, last_source, noise...)] - writers = PSE._input_plan_writer_applications(applications, local_names, destinations) + writers = PSE._input_plan_writer_applications(authored, local_names, destinations) @test [source.queries[] for source in (first_source, last_source, noise...)] == queries_before @test getproperty.(writers[:sent], :id) == [:local_first, :distributed, :local_last] # Each explicit or inferred scan for :sent now visits three declarations, # regardless of the 32 unrelated-variable applications. @test length(writers[:sent]) == 3 < length(applications) @test !haskey(writers, :missing) - @test all(isempty(application.target_ids) for application in writers[:sent] - if application.id != :distributed) - consumer = last(applications) + @test all(isempty(application.target_ids) for application in applications + if application.id in (:local_first, :local_last)) + @test all(!hasproperty(recipe, :target_ids) for recipe in writers[:sent]) + consumer = last(authored) potential(selector; process_filter=nothing, application_filter=nothing, origin=:model_spec) = PSE._potential_input_source_application_ids( writers, consumer, selector, :sent, process_filter, application_filter, @@ -472,7 +475,7 @@ end # The pass also supports application subsets whose slots belong to the # original full graph, including distributed declaration lookup by ID. - selected = applications[[1, length(applications) - 2, length(applications)]] + selected = [authored[index] for index in (1, length(authored) - 2, length(authored))] subset = PSE._input_plan_writer_applications(selected, local_names, destinations) @test getproperty.(subset[:sent], :id) == [:local_first, :distributed] @test getproperty.(selected, :slot) == [1, 34, 36] @@ -490,7 +493,7 @@ end @test model_status(model, :last).observed === 14.0 refreshed = Advanced.refresh_bindings!(model; force=true) @test plan_signature(refreshed.scenario_plan.input_plans) == signature - @test PSE._input_plan_writer_applications(applications, local_names, destinations) !== writers + @test PSE._input_plan_writer_applications(authored, local_names, destinations) !== writers end end # module diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 811006bfa..91bc7864a 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -103,9 +103,10 @@ end @test input_carrier(binding) === PSE.refvalue(model_status(model, 1), source) @test fieldtype(typeof(binding), :consumer_id) === ObjectId{Int} end - # Exercise the canonical default preparation entry, without supplying the - # prebuilt recipe table. It must derive the same routes and exact carriers. - fresh = PSE._compile_model_input_bindings(model, compiled.applications) + # Binding consumes the one prepared recipe table. It never reconstructs + # logical routes while obtaining the same canonical reference carriers. + fresh = PSE._compile_model_input_bindings(model, compiled.applications, + scenario.manual_application_ids, scenario.input_recipes_by_application) @test binding_signature(fresh) == binding_signature(compiled.input_bindings) @test all(input_carrier(binding) === PSE.refvalue(model_status(model, 1), binding.input === :left ? :x : :y) for binding in fresh) diff --git a/test/test-model-previous-timestep-views.jl b/test/test-model-previous-timestep-views.jl index 3e4b62aa3..5b3ae34a8 100644 --- a/test/test-model-previous-timestep-views.jl +++ b/test/test-model-previous-timestep-views.jl @@ -233,10 +233,10 @@ end binding.input == :signal ) children = Dict{Symbol,Set{Symbol}}() - PlantSimEngine._model_input_order_edges!( + PlantSimEngine._scenario_input_order_edges!( children, - (lagged_binding,), - Dict{Symbol,Set{Symbol}}(), + (lagged_binding.plan,), + NamedTuple(), ) @test isempty(children) From 96d0d795aa7155a52cb0961b9e8274767e2e0ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 04:06:55 +0100 Subject: [PATCH 020/324] Preserve concrete cohort and call schemas in the shared engine --- .../execution_batch_schemas.jl | 611 ++++++++ .../execution_cohort_refresh.jl | 275 ++-- src/composite_model/execution_cohorts.jl | 182 ++- src/composite_model/execution_dispatch.jl | 3 +- .../execution_extension_intents.jl | 274 ++++ src/composite_model/execution_storage.jl | 10 +- src/composite_model/runtime_outputs.jl | 1259 +++++++++-------- test/runtests.jl | 15 + test/test-model-call-context-cloning.jl | 2 +- test/test-model-closed-cohort-schemas.jl | 345 +++++ ...est-model-closed-group-layout-preflight.jl | 96 ++ test/test-model-closed-group-refresh.jl | 240 ++++ ...est-model-finite-call-extension-intents.jl | 287 ++++ test/test-model-hard-calls.jl | 2 +- test/test-model-prepared-call-schemas.jl | 320 +++++ test/test-model-prepared-call-vector-api.jl | 141 ++ test/test-model-prepared-growth-schemas.jl | 216 +++ ...st-model-prepared-missing-future-schema.jl | 56 + test/test-model-slot-group-refresh.jl | 16 +- 19 files changed, 3644 insertions(+), 706 deletions(-) create mode 100644 src/composite_model/execution_batch_schemas.jl create mode 100644 src/composite_model/execution_extension_intents.jl create mode 100644 test/test-model-closed-cohort-schemas.jl create mode 100644 test/test-model-closed-group-layout-preflight.jl create mode 100644 test/test-model-closed-group-refresh.jl create mode 100644 test/test-model-finite-call-extension-intents.jl create mode 100644 test/test-model-prepared-call-schemas.jl create mode 100644 test/test-model-prepared-call-vector-api.jl create mode 100644 test/test-model-prepared-growth-schemas.jl create mode 100644 test/test-model-prepared-missing-future-schema.jl diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl new file mode 100644 index 000000000..bbc224b64 --- /dev/null +++ b/src/composite_model/execution_batch_schemas.jl @@ -0,0 +1,611 @@ +# Explicit preparation contracts live at the application/call owner. They are +# type-only metadata, never a catalogue in the scene or runtime storage. +abstract type ExecutionBatchSchema end +struct OpenExecutionBatchSchema <: ExecutionBatchSchema end + +function _prepared_execution_batch_types(::Type{BT}) where {BT} + isconcretetype(BT) || throw(ArgumentError("Prepared execution batches need a concrete finite container type.")) + batches = if BT <: Vector + Tuple(Base.uniontypes(eltype(BT))) + elseif BT <: Tuple + fieldtypes(BT) + else + throw(ArgumentError("Prepared execution batches require Vector{B}, Vector{Union{B...}} or a fixed Tuple.")) + end + isempty(batches) && throw(ArgumentError("An empty batch family needs explicit future batch types.")) + for B in batches + isconcretetype(B) && B <: CompiledExecutionBatch || + throw(ArgumentError("Prepared batch families must be concrete canonical execution batches.")) + Rows = fieldtype(B, :targets) + Rows <: ExecutionCohortRows && isconcretetype(Rows) || + throw(ArgumentError("Prepared batches must use concrete canonical cohort rows.")) + Target = eltype(Rows) + isconcretetype(Target) && Target <: CompiledExecutionTarget || + throw(ArgumentError("Prepared rows require an explicit concrete execution-target type.")) + Context = fieldtype(Target, :context) + isconcretetype(Context) && Context <: RunContext || + throw(ArgumentError("Prepared execution targets require a real concrete RunContext schema.")) + fieldtype(B, :application) === fieldtype(Context, :application) || + throw(ArgumentError("Prepared batch and context application schemas differ.")) + for name in (:object_id, :bound_inputs, :output_targets) + fieldtype(Target, name) === fieldtype(Context, name) || + throw(ArgumentError("Prepared target and context fields disagree.")) + end + _validate_prepared_context_calls(fieldtype(Context, :calls)) + end + return batches +end + +struct PreparedExecutionBatchSchema{BT} <: ExecutionBatchSchema + function PreparedExecutionBatchSchema{BT}() where {BT} + _prepared_execution_batch_types(BT) + return new{BT}() + end +end + +abstract type ContextCallSchema end +struct OpenContextCallSchema <: ContextCallSchema end +struct PreparedContextCallSchema{C<:Tuple} <: ContextCallSchema + PreparedContextCallSchema{C}() where {C<:Tuple} = new{C}() +end + +_prepared_call_mode(::Type{<:CompiledModelCallBinding{P}}) where {P} = _prepared_call_plan_mode(P) +_prepared_call_plan_mode(::Type{<:CompiledModelCallPlan{NAME,MODE}}) where {NAME,MODE} = MODE + +function _validate_prepared_context_calls(::Type{C}) where {C<:Tuple} + isconcretetype(C) || throw(ArgumentError("Prepared context calls require a concrete finite tuple.")) + for CT in fieldtypes(C) + CT <: CallTargets && isconcretetype(CT) || throw(ArgumentError("A prepared context contains a non-concrete CallTargets schema.")) + S = fieldtype(CT, :batch_schema) + S <: PreparedExecutionBatchSchema || throw(ArgumentError("Every prepared call needs an explicit current/future batch schema.")) + BT = only(S.parameters) + _prepared_execution_batch_types(BT) + actual = fieldtype(CT, :execution_batches) + expected = _prepared_call_mode(fieldtype(CT, :binding)) === :initializer ? Tuple{} : BT + actual === expected || throw(ArgumentError("Prepared call container and explicit batch schema disagree.")) + end + return nothing +end + +@generated function _execution_cohort_schema(::PreparedExecutionBatchSchema{BT}) where {BT} + targets = unique(eltype(fieldtype(B, :targets)) for B in _prepared_execution_batch_types(BT)) + return :(_closed_execution_cohort_schema($(Tuple{targets...}))) +end + +_execution_batch_buffer(::OpenExecutionBatchSchema) = AbstractExecutionBatch[] +@generated function _execution_batch_buffer(::PreparedExecutionBatchSchema{BT}) where {BT} + batches = _prepared_execution_batch_types(BT) + return :(Vector{$(Union{batches...})}()) +end + +_finish_execution_batches(::OpenExecutionBatchSchema, batches) = Tuple(batches) +@generated function _finish_execution_batches(::PreparedExecutionBatchSchema{BT}, batches) where {BT} + if BT <: Vector + return :(batches::$BT) + end + entries = [gensym(:batch) for _ in 1:fieldcount(BT)] + checks = Any[] + for (index, B) in enumerate(fieldtypes(BT)) + push!(checks, :($(entries[index]) = batches[$index])) + push!(checks, :($(entries[index]) isa $B || throw(ArgumentError("A batch is outside its prepared ordered schema.")))) + end + result = Expr(:tuple, [:($(entries[index])::$(fieldtype(BT, index))) for index in eachindex(entries)]...) + return quote + length(batches) == $(fieldcount(BT)) || throw(ArgumentError("Prepared ordered batch count changed.")) + $(checks...) + return $result + end +end + +@inline _with_execution_batch(f, ::OpenExecutionBatchSchema, batch) = f(batch) +@generated function _with_execution_batch(f, ::PreparedExecutionBatchSchema{BT}, batch) where {BT} + branches = [:(batch isa $B && return f(batch::$B)) for B in _prepared_execution_batch_types(BT)] + return quote + $(branches...) + throw(ArgumentError("The execution batch is outside its prepared application schema.")) + end +end + +@inline _with_new_execution_batch(f, ::OpenExecutionBatchSchema, application, rows, provider, publication) = + f(CompiledExecutionBatch(application, rows, provider, publication)) +@generated function _with_new_execution_batch(f, ::PreparedExecutionBatchSchema{BT}, application, rows, provider, publication) where {BT} + branches = Expr[] + for B in _prepared_execution_batch_types(BT) + A, R, P, O = (fieldtype(B, name) for name in (:application, :targets, :environment_provider, :output_publication)) + push!(branches, quote + if application isa $A && rows isa $R && provider isa $P && publication isa $O + return f(CompiledExecutionBatch(application::$A, rows::$R, provider::$P, publication::$O)) + end + end) + end + return quote + $(branches...) + throw(ArgumentError("The real batch fields do not match an admitted execution schema.")) + end +end + +@inline _context_call_schema(::Nothing) = OpenContextCallSchema() +@generated function _context_call_schema(context::RunContext{CS,A,C}) where {CS,A,C} + closed = any(fieldtype(CT, :batch_schema) <: PreparedExecutionBatchSchema for CT in fieldtypes(C)) + return closed ? :(PreparedContextCallSchema{$C}()) : :(OpenContextCallSchema()) +end + +@inline _with_execution_target_type(f, ::OpenExecutionCohortSchema, application, fields, owners) = f(nothing, application, fields, owners, OpenContextCallSchema()) +@generated function _with_execution_target_type(f, ::ClosedExecutionCohortSchema{T}, application, fields, owners) where {T} + branches = Expr[] + names = (:object_id, :model, :status_view, :bound_inputs, + :output_targets, :call_bindings, :environment_binding) + for Target in fieldtypes(T) + Target <: CompiledExecutionTarget || error("Closed target factory needs canonical execution-target schemas.") + Context = fieldtype(Target, :context) + Context <: RunContext && isconcretetype(Context) || error("A prepared target requires a real concrete context.") + Calls = fieldtype(Context, :calls) + closed_calls = any(fieldtype(CT,:batch_schema) <: PreparedExecutionBatchSchema for CT in fieldtypes(Calls)) + closed_calls && _validate_prepared_context_calls(Calls) + CallSchema = closed_calls ? PreparedContextCallSchema{Calls} : OpenContextCallSchema + checks = Expr[:(application isa $(fieldtype(Context, :application)))] + for name in names + push!(checks, :(getproperty(fields, $(QuoteNode(name))) isa $(fieldtype(Target, name)))) + end + for name in (:compiled, :temporal_streams, :output_retention, :constants, :environment) + push!(checks, :(getproperty(owners, $(QuoteNode(name))) isa $(fieldtype(Context, name)))) + end + condition = foldl((a,b) -> :($a && $b), checks) + values = Expr(:tuple, [:(getproperty(fields, $(QuoteNode(name)))::$(fieldtype(Target,name))) for name in names]...) + owner_names = (:compiled, :temporal_streams, :output_retention, :constants, :environment) + owner_values = Expr(:tuple, [:(getproperty(owners, $(QuoteNode(name)))::$(fieldtype(Context,name))) for name in owner_names]...) + A = fieldtype(Context, :application) + push!(branches, quote + if $condition + actual_fields = NamedTuple{$(QuoteNode(names))}($values) + actual_owners = NamedTuple{$(QuoteNode(owner_names))}($owner_values) + return f($Target, application::$A, actual_fields, actual_owners, + $CallSchema()) + end + end) + end + return quote + $(branches...) + throw(ArgumentError("The real target fields are outside the prepared execution schema.")) + end +end + +# Validate the type-only application tree in the already validated call DAG's +# bottom-up order. call_owners already maps callee -> callers; reuse the one +# canonical topological ordering operation, without discovering another graph. +function _prepared_application_schema_order(compiled::CompiledCompositeModel, schemas::NamedTuple) + order = _stable_topological_application_order(compiled.applications, + compiled.scenario_plan.call_owners) + for application_id in order + haskey(schemas, application_id) || throw(ArgumentError("An application lacks an explicit execution batch schema.")) + schema = getproperty(schemas, application_id) + schema isa PreparedExecutionBatchSchema || throw(ArgumentError("Prepared applications require explicit batch schemas.")) + application = compiled.applications_by_id[application_id] + for B in _prepared_execution_batch_types(only(typeof(schema).parameters)) + fieldtype(B, :application) === typeof(application) || throw(ArgumentError("Prepared application and batch types disagree.")) + end + end + return Tuple(order) +end + +Base.@nospecializeinfer function _call_execution_batches_for_schema( + ::OpenExecutionBatchSchema, compiled, environment_bindings, binding, + temporal_streams, output_retention, constants, tracks_full_membership, +) + @nospecialize compiled environment_bindings binding + if _compiled_call_mode(binding) === :initializer + return () + elseif binding.multiplicity === :many + return LazyCallExecutionBatches() + end + return _compiled_call_execution_batches(compiled, environment_bindings, + binding, temporal_streams, output_retention, constants) +end + +function _call_execution_batches_for_schema(schema::PreparedExecutionBatchSchema, + compiled, environment_bindings, binding, temporal_streams, + output_retention, constants, tracks_full_membership, +) + _compiled_call_mode(binding) === :initializer && return () + if tracks_full_membership + _observe_compiled_call_membership!(compiled, binding; + resolve_current=!bindings_dirty(compiled.model)) + end + return _compiled_call_execution_batches(compiled, environment_bindings, + binding, temporal_streams, output_retention, constants; + cohort_schema=_execution_cohort_schema(schema), batch_schema=schema) +end + +@inline _assemble_runtime_call_targets(::OpenContextCallSchema, compiled, + environment_bindings, ::Tuple{}, args...) = () + +Base.@nospecializeinfer function _assemble_runtime_call_targets( + ::OpenContextCallSchema, compiled, environment_bindings, bindings::Tuple, + temporal_streams, output_retention, time, constants, publication_allowed, + environment, +) + @nospecialize compiled environment_bindings bindings + targets = CallTargets[] + for binding in bindings + push!(targets, CallTargets(compiled, environment_bindings, binding, + temporal_streams, output_retention, time, constants, + publication_allowed, environment)) + end + return Tuple(targets) +end + +@generated function _assemble_runtime_call_targets(::PreparedContextCallSchema{C}, + compiled, environment_bindings, bindings::Tuple, temporal_streams, + output_retention, time, constants, publication_allowed, environment, +) where {C} + _validate_prepared_context_calls(C) + bindings_vars = [gensym(:binding) for _ in 1:fieldcount(C)] + checks = Any[] + constructions = Any[] + for (index, CT) in enumerate(fieldtypes(C)) + Binding = fieldtype(CT, :binding) + Schema = fieldtype(CT, :batch_schema) + binding = bindings_vars[index] + push!(checks, :($binding = getfield(bindings, $index))) + push!(checks, :($binding isa $Binding || throw(ArgumentError("A call declaration is outside its prepared context schema.")))) + for (argument, field) in ((:compiled,:compiled), (:environment_bindings,:environment_bindings), + (:temporal_streams,:temporal_streams), (:output_retention,:output_retention), (:constants,:constants)) + push!(checks, :($argument isa $(fieldtype(CT, field)) || throw(ArgumentError("A call owner is outside its prepared context schema.")))) + end + push!(constructions, :(CallTargets(compiled::$(fieldtype(CT,:compiled)), + environment_bindings::$(fieldtype(CT,:environment_bindings)), $binding::$Binding, + temporal_streams::$(fieldtype(CT,:temporal_streams)), output_retention::$(fieldtype(CT,:output_retention)), + time, constants::$(fieldtype(CT,:constants)), publication_allowed, environment; + batch_schema=$(QuoteNode(Schema())))::$CT)) + end + result = Expr(:tuple, constructions...) + return quote + length(bindings) == $(fieldcount(C)) || throw(ArgumentError("Prepared context call count changed.")) + # Validate ALL declarations and owners before constructing a child. + $(checks...) + return $result + end +end + +@inline _clone_call_execution_batches(batches::Vector{B}) where {B<:CompiledExecutionBatch} = copy(batches) + +function _materialize_prepared_call_execution_batches!(schema::PreparedExecutionBatchSchema, + targets::CallTargets, +) + if targets.tracks_full_membership + _synchronize_tracked_call_targets!(targets) + end + _call_targets_preparation_is_current(targets, targets.compiled, + targets.environment_bindings, targets.temporal_streams, + targets.output_retention, targets.constants) && return targets.execution_batches + if targets.tracks_full_membership + _observe_compiled_call_membership!(targets.compiled, targets.binding; + resolve_current=!bindings_dirty(targets.compiled.model)) + end + batches = _compiled_call_execution_batches(targets.compiled, + targets.environment_bindings, targets.binding, targets.temporal_streams, + targets.output_retention, targets.constants; + cohort_schema=_execution_cohort_schema(schema), batch_schema=schema) + if targets.tracks_full_membership + _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches; + schema=_execution_cohort_schema(schema)) + end + # Publish a complete validated replacement, preserving retained lease shells. + targets.execution_batches = batches + targets.last_single_snapshot = nothing + targets.preparation = _call_targets_preparation(targets.compiled, + targets.environment_bindings, targets.binding, targets.temporal_streams, + targets.output_retention, targets.constants) + return batches +end + +@generated function _prepared_runtime_temporal_inputs(::Type{I}, inputs::Tuple, streams) where {I<:Tuple} + entries = Expr[] + for (index, R) in enumerate(fieldtypes(I)) + if R <: CompiledTemporalInput + push!(entries, :(getfield(inputs, $index)::$R)) + else + R <: RuntimeTemporalInput || error("Invalid prepared temporal-input schema.") + C, S = fieldtype(R, :compiled), fieldtype(R, :source_streams) + push!(entries, :(_prepared_runtime_temporal_input($R, + getfield(inputs, $index)::$C, streams))) + end + end + return quote + length(inputs) == $(fieldcount(I)) || throw(ArgumentError("Prepared temporal-input count changed.")) + return $(Expr(:tuple, entries...)) + end +end + +function _prepared_runtime_temporal_input(::Type{R}, input::C, streams) where {C,S,R<:RuntimeTemporalInput{C,S}} + sources = if input.binding.multiplicity === :many + _prepared_temporal_sources(S, streams, input) + else + source = _runtime_temporal_source_stream(streams, input, 1) + source isa S || throw(ArgumentError("A temporal producer stream is outside its prepared schema.")) + source::S + end + return R(input, sources) +end + +function _prepared_temporal_sources(::Type{Vector{S}}, streams, input) where {S} + all(isconcretetype,Base.uniontypes(S)) || throw(ArgumentError("Many temporal inputs need explicit producer stream types.")) + sources = Vector{S}() + sizehint!(sources, length(input.binding.source_ids)) + for index in eachindex(input.binding.source_ids) + source = _runtime_temporal_source_stream(streams, input, index) + source isa S || throw(ArgumentError("A temporal producer stream is outside its prepared schema.")) + push!(sources, source::S) + end + return sources +end + +@generated function _prepared_temporal_sources(::Type{S}, streams, input) where {S<:Tuple} + entries = [quote + source = _runtime_temporal_source_stream(streams, input, $index) + source isa $(fieldtype(S,index)) || throw(ArgumentError("A temporal producer stream is outside its prepared schema.")) + source::$(fieldtype(S,index)) + end for index in 1:fieldcount(S)] + return quote + length(input.binding.source_ids) == $(fieldcount(S)) || + throw(ArgumentError("An ordered temporal source schema changed its runtime cardinality.")) + return $(Expr(:tuple, entries...)) + end +end + +function _prepared_local_runtime_output(::Type{O}, status, application, object_id, + streams, retention, initialize_missing, +) where {V,S,R,O<:RuntimeOutputStream{V,S,R}} + key = _model_stream_key(application.id, object_id, V) + stream = get(streams, key, nothing) + if isnothing(stream) + initialize_missing || throw(ArgumentError("A prepared retained output has no initialized stream.")) + stream = _model_new_output_stream(getproperty(status,V), retention, application.id, V) + stream isa S || throw(ArgumentError("A newborn output stream is outside its prepared schema.")) + streams[key] = stream + end + reference = refvalue(status,V) + stream isa S && reference isa R || throw(ArgumentError("A retained output reference is outside its prepared schema.")) + return O(stream::S, reference::R, + get(retention.dependency_horizons,(application.id,V),0.0)) +end + +function _prepared_distributed_runtime_output(::Type{O}, output_targets, application, + streams, retention, +) where {V,B,S,R,O<:RuntimeDistributedOutputStream{V,B,S,R}} + target = getproperty(output_targets,V) + binding = target.binding + binding isa B || throw(ArgumentError("A distributed output owner is outside its prepared schema.")) + references = getproperty(binding.columns,V) + references isa R || throw(ArgumentError("A distributed output column is outside its prepared schema.")) + sources = _prepared_distributed_output_sources(S, streams, binding, application.id, V) + return O(binding::B, sources::S, references::R, + get(retention.dependency_horizons,(application.id,V),0.0)) +end + +function _prepared_distributed_output_sources(::Type{Vector{S}}, streams, binding, application_id, variable) where {S} + sources = Vector{S}() + sizehint!(sources,length(binding.destination_ids)) + for object_id in binding.destination_ids + source = get(streams,_model_stream_key(application_id,object_id,variable),nothing) + !isnothing(source) && source isa S || throw(ArgumentError("A distributed retained stream is outside its prepared schema.")) + push!(sources,source::S) + end + return sources +end + +@generated function _prepared_distributed_output_sources(::Type{S}, streams, binding, application_id, variable) where {S<:Tuple} + entries = [quote + source = get(streams,_model_stream_key(application_id,binding.destination_ids[$index],variable),nothing) + !isnothing(source) && source isa $(fieldtype(S,index)) || throw(ArgumentError("A distributed retained stream is outside its prepared schema.")) + source::$(fieldtype(S,index)) + end for index in 1:fieldcount(S)] + return quote + length(binding.destination_ids) == $(fieldcount(S)) || throw(ArgumentError("An ordered distributed stream schema changed cardinality.")) + return $(Expr(:tuple,entries...)) + end +end + +@generated function _prepared_runtime_outputs(::Type{O}, status, output_targets, + application, object_id, compiled, streams, retention, initialize_missing, +) where {O<:Tuple} + entries = Expr[] + for R in fieldtypes(O) + if R <: RuntimeOutputStream + push!(entries,:(_prepared_local_runtime_output($R,status,application, + object_id,streams,retention,initialize_missing))) + elseif R <: RuntimeDistributedOutputStream + push!(entries,:(_prepared_distributed_runtime_output($R,output_targets, + application,streams,retention))) + else + error("Invalid prepared output-binding schema.") + end + end + return quote + outputs = $(Expr(:tuple,entries...)) + if initialize_missing + # Targeted newborns own a pre-barrier private view: it is not in + # compiled.status_views_by_target yet. Validate this real view's + # local output names here; each exact Ref/stream was checked above. + expected = isnothing(retention) ? () : get(retention.retained_outputs_by_application,application.id,()) + local_count = 0 + for variable in expected + variable in _model_output_names(application) || continue + local_count += 1 + local_count <= length(outputs) && + _runtime_output_variable(outputs[local_count]) === variable || + throw(ArgumentError("Prepared newborn retained output names changed.")) + end + local_count == length(outputs) || + throw(ArgumentError("Prepared newborn retained output count changed.")) + else + _model_execution_outputs_match(outputs,compiled,application,object_id, + retention,streams) || throw(ArgumentError("Prepared retained output names or ownership changed.")) + end + return outputs + end +end + +function _call_cohort_admission(::OpenExecutionBatchSchema, schema) + return schema +end +function _call_cohort_admission(batch_schema::PreparedExecutionBatchSchema, schema) + expected = _execution_cohort_schema(batch_schema) + schema isa OpenExecutionCohortSchema || typeof(schema) === typeof(expected) || + throw(ArgumentError("Prepared call batch and cohort schemas disagree.")) + return expected +end + +@inline _call_batch_schema_for_application(::OpenExecutionBatchSchema, application) = OpenExecutionBatchSchema() +@generated function _call_batch_schema_for_application(::PreparedExecutionBatchSchema{BT}, application::A) where {BT,A} + batches = [B for B in _prepared_execution_batch_types(BT) if fieldtype(B,:application) === A] + isempty(batches) && return :(throw(ArgumentError("A callee application is outside its prepared batch schema."))) + schema = PreparedExecutionBatchSchema{Vector{Union{batches...}}}() + return QuoteNode(schema) +end + +@generated function _execution_group_batch_schema(group::G) where {G<:CompiledApplicationExecutionGroup} + M = fieldtype(G,:membership) + if !(fieldtype(M,:schema) <: ClosedExecutionCohortSchema) + return :(OpenExecutionBatchSchema()) + end + BT = fieldtype(G,:batches) + candidates = BT <: Vector ? Base.uniontypes(eltype(BT)) : fieldtypes(BT) + for B in candidates + isconcretetype(B) && B <: CompiledExecutionBatch || return :(OpenExecutionBatchSchema()) + Target = eltype(fieldtype(B,:targets)) + Context = fieldtype(Target,:context) + Context <: RunContext || return :(OpenExecutionBatchSchema()) + Calls = fieldtype(Context,:calls) + for CT in fieldtypes(Calls) + fieldtype(CT,:batch_schema) <: PreparedExecutionBatchSchema || return :(OpenExecutionBatchSchema()) + end + end + return QuoteNode(PreparedExecutionBatchSchema{BT}()) +end +_execution_group_batch_schema(::Nothing) = OpenExecutionBatchSchema() + + +function _prepared_execution_group(application, schema::PreparedExecutionBatchSchema{BT}, cohorts) where {BT} + BT <: Vector || throw(ArgumentError("A growing prepared group needs a finite Vector batch schema.")) + membership = _new_execution_cohort_membership(cohorts,nothing,application.id,0, + _execution_cohort_schema(schema)) + return CompiledApplicationExecutionGroup(application,BT(),membership) +end + +# This is a host preparation over actual, already initialized objects at step0. +# The transient whole-application schema map is discarded after compilation. +function _prepare_execution_batch_schemas(simulation::Simulation, schemas::NamedTuple) + iszero(simulation.current_step) || throw(ArgumentError("Execution batch schemas must be prepared before the first step.")) + bindings_dirty(simulation.model) && throw(ArgumentError("Prepare current bindings before admitting execution schemas.")) + _prepared_application_schema_order(simulation.compiled,schemas) + for location in values(simulation.temporal_streams.cohorts.locations) + target = _execution_cohort_target(location) + cache = target.call_context_cache + !cache.in_use && isnothing(cache.evaluation) && iszero(cache.execution_stamp[]) || + throw(ArgumentError("Execution schemas cannot replace a used or leased timeline.")) + end + storage = RuntimeStorage(simulation.temporal_streams.streams) + plan = compile_model_execution_plan(simulation.compiled,simulation.environment_bindings, + storage,simulation.output_retention,simulation.constants; batch_schemas=schemas) + closed_groups = Tuple(plan.groups) + closed_slots = Tuple(plan.groups_by_application_slot) + closed = CompiledExecutionPlan(plan.cohorts,plan.topology,closed_groups, + plan.batches,closed_slots,plan.schedule,plan.model_revision,plan.environment_revision) + return Simulation(simulation.model,simulation.compiled,simulation.environment_bindings, + closed,simulation.output_retention,storage,simulation.output_datetimes, + simulation.output_requests,simulation.output_request_matchers, + simulation.output_request_targets,simulation.output_request_model_revision, + simulation.runtime_revision,simulation.current_step,simulation.constants, + simulation.performance) +end + +_batch_output_publication(::OpenExecutionBatchSchema,retention,application) = + _compiled_output_publication(retention,application) + +@generated function _batch_output_publication(::PreparedExecutionBatchSchema{BT}, retention, + application::A, +) where {BT,A} + publications = unique(fieldtype(B,:output_publication) for B in _prepared_execution_batch_types(BT) + if fieldtype(B,:application) === A) + branches = Expr[] + for O in publications + V = fieldtype(O,:variables) + isconcretetype(V) && V <: Tuple || error("Prepared publication variables need a fixed tuple schema.") + names = Expr(:tuple, [:(variables[$index]::$(fieldtype(V,index))) for index in 1:fieldcount(V)]...) + push!(branches, :(length(variables) == $(fieldcount(V)) && + return $O($names,$(!iszero(fieldcount(V)))))) + end + return quote + variables = isnothing(retention) ? () : + get(retention.retained_outputs_by_application,application.id,()) + $(branches...) + throw(ArgumentError("Retained publication shape is outside its prepared batch schema.")) + end +end + +@inline function _compatible_execution_batch(schema,batch,application,provider,publication) + isnothing(batch) && return nothing + return _with_execution_batch(schema,batch) do actual + _execution_batch_matches(actual,application,provider,publication) ? actual : nothing + end +end + +_prepared_call_name(::Type{<:CompiledModelCallBinding{P}}) where {P} = _prepared_call_plan_name(P) +_prepared_call_plan_name(::Type{<:CompiledModelCallPlan{NAME}}) where {NAME} = NAME + +# Host-only type lowering of an OBSERVED real batch's context. No current +# target, callback, status value or model parameter is sampled or reconstructed. +function _execution_batch_type_with_call_schemas(::Type{B}, schemas::NamedTuple) where {B<:CompiledExecutionBatch} + Target = eltype(fieldtype(B,:targets)) + Context = fieldtype(Target,:context) + Context <: RunContext || throw(ArgumentError("Prepared calls need a real context type.")) + calls = fieldtype(Context,:calls) + names = Tuple(_prepared_call_name(fieldtype(CT,:binding)) for CT in fieldtypes(calls)) + Set(keys(schemas)) == Set(names) || throw(ArgumentError("Provide one explicit schema for each declared call.")) + prepared_calls = map(fieldtypes(calls)) do CT + Binding = fieldtype(CT,:binding) + schema = getproperty(schemas,_prepared_call_name(Binding)) + schema isa PreparedExecutionBatchSchema || throw(ArgumentError("Calls need explicit batch schemas.")) + BT = only(typeof(schema).parameters) + actual_batches = _prepared_call_mode(Binding) === :initializer ? Tuple{} : BT + return CallTargets{fieldtype(CT,:compiled),fieldtype(CT,:environment_bindings),Binding, + fieldtype(CT,:temporal_streams),fieldtype(CT,:output_retention), + fieldtype(CT,:constants),actual_batches,typeof(schema)} + end + C = Tuple{prepared_calls...} + parameters = collect(Context.parameters) + parameters[3] = C + prepared_context = Core.apply_type(RunContext,parameters...) + parameters = collect(Target.parameters) + parameters[9] = prepared_context + prepared_target = Core.apply_type(CompiledExecutionTarget,parameters...) + I = fieldtype(prepared_target,:object_id) + Rows = ExecutionCohortRows{prepared_target,ExecutionCohort{prepared_target,I}} + return CompiledExecutionBatch{fieldtype(B,:application),Rows, + fieldtype(B,:environment_provider),fieldtype(B,:output_publication)} +end + +@generated function _current_call_binding_for_application(compiled, + application::CompiledModelApplication{P}, binding::B, +) where {P,B<:CompiledModelCallBinding} + plans = fieldtype(P,:call_plans) + Plan = fieldtype(B,:plan) + index = findfirst(==(Plan),collect(fieldtypes(plans))) + isnothing(index) && return :(throw(ArgumentError("A retained call no longer has its prepared declaration."))) + Bindings = Tuple{[CompiledModelCallBinding{T} for T in fieldtypes(plans)]...} + return quote + bindings = get(compiled.call_bindings_by_target, + (binding.application_id,binding.consumer_id),()) + bindings isa $Bindings || _unprepared_runtime_configuration() + return getfield(bindings::$Bindings,$index)::$B + end +end + +@inline _admit_newborn_context_cache(::Nothing,cache) = cache +@inline function _admit_newborn_context_cache(::Type{T},cache) where {T<:CompiledExecutionTarget} + isnothing(cache) && return nothing + Cache = CallContextCache{fieldtype(T,:context)} + cache isa Cache || throw(ArgumentError("A retained newborn context is outside its prepared schema.")) + return cache::Cache +end diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index 8f82baa78..dbd79093f 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -1,11 +1,12 @@ """Ordered schedule membership, separate from persistent execution payloads.""" -struct ExecutionCohortMembership +struct ExecutionCohortMembership{S<:ExecutionCohortSchema,I<:ObjectId,L<:ExecutionCohortLocation,R<:ExecutionCohortRows} store::ExecutionCohortStore owner::Any application_id::Symbol - object_ids::Vector{ObjectId} - locations::Vector{ExecutionCohortLocation} - runs::Vector{ExecutionCohortRows} + schema::S + object_ids::Vector{I} + locations::Vector{L} + runs::Vector{R} run_starts::Vector{Int} end @@ -33,48 +34,64 @@ function _shift_execution_run_starts!(membership, first_run, delta) return nothing end +function _execution_membership_location_has_cohort(membership, position, cohort) + object_id = membership.object_ids[position] + return _with_execution_cohort_location(membership.schema, membership.locations[position], + membership.owner, membership.application_id, object_id) do location + location.cohort === cohort + end +end + +function _execution_membership_run_has_cohort(membership, index, cohort) + return _with_execution_membership_run(membership, index) do rows + rows.cohort === cohort + end +end + function _insert_execution_membership_row!(membership, position, object_id, location) count = length(membership.object_ids) runs = membership.runs starts = membership.run_starts if isempty(runs) || position == count + 1 - if !isempty(runs) && last(runs).cohort === location.cohort - push!(last(runs).indices, location.row) + if !isempty(runs) && _execution_membership_run_has_cohort(membership, length(runs), location.cohort) + _with_execution_membership_run(membership, length(runs)) do rows + push!(rows.indices, location.row) + end else push!(runs, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) push!(starts, position) end else run_index = searchsortedlast(starts, position) - rows = runs[run_index] - local_index = position - starts[run_index] + 1 - if rows.cohort === location.cohort - insert!(rows.indices, local_index, location.row) - _shift_execution_run_starts!(membership, run_index + 1, 1) - elseif local_index == 1 && run_index > 1 && - runs[run_index - 1].cohort === location.cohort - push!(runs[run_index - 1].indices, location.row) - _shift_execution_run_starts!(membership, run_index, 1) - elseif local_index == 1 - insert!(runs, run_index, _execution_cohort_rows( - membership.store, location.cohort, Int[location.row], - )) - insert!(starts, run_index, position) - _shift_execution_run_starts!(membership, run_index + 1, 1) - else - # A new family inside a run needs one additional view of its right - # part. Other runs and all scientific payloads retain identity. - right_indices = rows.indices[local_index:end] - sizehint!(right_indices, length(right_indices) + max(16, length(right_indices) ÷ 4)) - right = _execution_cohort_rows(membership.store, rows.cohort, right_indices) - resize!(rows.indices, local_index - 1) - insert!(runs, run_index + 1, _execution_cohort_rows( - membership.store, location.cohort, Int[location.row], - )) - insert!(starts, run_index + 1, position) - insert!(runs, run_index + 2, right) - insert!(starts, run_index + 2, position + 1) - _shift_execution_run_starts!(membership, run_index + 3, 1) + _with_execution_membership_run(membership, run_index) do rows + local_index = position - starts[run_index] + 1 + if rows.cohort === location.cohort + insert!(rows.indices, local_index, location.row) + _shift_execution_run_starts!(membership, run_index + 1, 1) + elseif local_index == 1 && run_index > 1 && + _execution_membership_run_has_cohort(membership, run_index - 1, location.cohort) + _with_execution_membership_run(membership, run_index - 1) do previous_rows + push!(previous_rows.indices, location.row) + end + _shift_execution_run_starts!(membership, run_index, 1) + elseif local_index == 1 + insert!(runs, run_index, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) + insert!(starts, run_index, position) + _shift_execution_run_starts!(membership, run_index + 1, 1) + else + # This is the same ordered reconciliation algorithm: split only + # membership indices; retain payloads and scientific references. + right_indices = rows.indices[local_index:end] + sizehint!(right_indices, length(right_indices) + max(16, length(right_indices) ÷ 4)) + right = _execution_cohort_rows(membership.store, rows.cohort, right_indices) + resize!(rows.indices, local_index - 1) + insert!(runs, run_index + 1, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) + insert!(starts, run_index + 1, position) + insert!(runs, run_index + 2, right) + insert!(starts, run_index + 2, position + 1) + _shift_execution_run_starts!(membership, run_index + 3, 1) + end + return nothing end end insert!(membership.object_ids, position, object_id) @@ -86,17 +103,26 @@ function _delete_execution_membership_row!(membership, position) runs = membership.runs starts = membership.run_starts run_index = searchsortedlast(starts, position) - rows = runs[run_index] - deleteat!(rows.indices, position - starts[run_index] + 1) + run_empty = _with_execution_membership_run(membership, run_index) do rows + deleteat!(rows.indices, position - starts[run_index] + 1) + isempty(rows.indices) + end _shift_execution_run_starts!(membership, run_index + 1, -1) - if isempty(rows.indices) + if run_empty deleteat!(runs, run_index) deleteat!(starts, run_index) - if run_index > 1 && run_index <= length(runs) && - runs[run_index - 1].cohort === runs[run_index].cohort - append!(runs[run_index - 1].indices, runs[run_index].indices) - deleteat!(runs, run_index) - deleteat!(starts, run_index) + if run_index > 1 && run_index <= length(runs) + merged = _with_execution_membership_run(membership, run_index - 1) do left + _with_execution_membership_run(membership, run_index) do right + left.cohort === right.cohort || return false + append!(left.indices, right.indices) + return true + end + end + if merged + deleteat!(runs, run_index) + deleteat!(starts, run_index) + end end end deleteat!(membership.object_ids, position) @@ -119,20 +145,64 @@ function _check_execution_cohort_target(target, object_id) return nothing end -function _new_execution_cohort_membership(store, owner, application_id, count) - ids = ObjectId[] - locations = ExecutionCohortLocation[] - # Reserve initial spare capacity once. Ordinary push!/insert! growth then - # remains amortized; requesting exactly one spare slot on every refresh - # would itself force repeated allocations proportional to live object count. +function _new_execution_cohort_membership(store, owner, application_id, count, schema=OpenExecutionCohortSchema()) + types = _execution_cohort_types(schema) + ids = Vector{types.identity}() + locations = Vector{types.location}() capacity = count + max(16, count ÷ 4) sizehint!(ids, capacity) sizehint!(locations, capacity) return ExecutionCohortMembership( - store, owner, application_id, ids, locations, ExecutionCohortRows[], Int[], + store, owner, application_id, schema, ids, locations, Vector{types.rows}(), Int[], ) end +# Host-only schema closure, before a plan's container types are fixed. Metadata +# vectors become finite unions; all cohort payloads, references and run views +# retain identity. No models, defaults, samplers or callbacks are invoked. +function _close_execution_cohort_membership(previous::ExecutionCohortMembership, schema::ClosedExecutionCohortSchema) + types = _execution_cohort_types(schema) + for (object_id, location) in zip(previous.object_ids, previous.locations) + object_id isa types.identity || throw(ArgumentError("An object identity is outside the prepared cohort schema.")) + _with_execution_cohort_location(identity, schema, location, previous.owner, previous.application_id, object_id) + end + for rows in previous.runs + _with_execution_cohort_rows(schema, rows) do admitted + _check_execution_cohort_rows_owner(admitted, previous.store, previous.owner, previous.application_id) + end + end + typeof(previous.schema) === typeof(schema) && return previous + membership = _new_execution_cohort_membership(previous.store, previous.owner, + previous.application_id, length(previous.object_ids), schema) + append!(membership.object_ids, previous.object_ids) + append!(membership.locations, previous.locations) + # Close once with the same spare-capacity policy as initial preparation. + # Exact-length copies would force an O(n) resize on the first real birth. + run_count = length(previous.runs) + run_capacity = run_count + max(16, run_count ÷ 4) + sizehint!(membership.runs, run_capacity) + sizehint!(membership.run_starts, run_capacity) + append!(membership.runs, previous.runs) + append!(membership.run_starts, previous.run_starts) + return membership +end + +function _check_execution_cohort_rows_owner(rows, store, owner, application_id) + rows.store === store && isequal(rows.cohort.owner, owner) && + rows.cohort.application_id === application_id || throw(ArgumentError( + "The execution run belongs to another store, owner or application.", + )) + return nothing +end + +@inline function _with_execution_membership_run(f, membership, index) + return _with_execution_cohort_rows(membership.schema, membership.runs[index]) do rows + _check_execution_cohort_rows_owner(rows, membership.store, membership.owner, membership.application_id) + f(rows) + end +end + + """ refresh_cohort_membership!(build_target, store, application_id, current_ids, changed_ids; previous=nothing, owner=nothing) @@ -162,28 +232,40 @@ function refresh_cohort_membership!( changed_ids; previous::Union{Nothing,ExecutionCohortMembership}=nothing, owner=nothing, + schema=isnothing(previous) ? OpenExecutionCohortSchema() : previous.schema, ) if !isnothing(previous) previous.store === store && previous.application_id === application_id && isequal(previous.owner, owner) || throw(ArgumentError( "Previous execution membership belongs to a different store or execution owner.", )) + typeof(schema) === typeof(previous.schema) || throw(ArgumentError( + "Close the application membership before entering its prepared refresh boundary.", + )) end - staged_targets = Tuple{ObjectId,Any}[] - removed_ids = ObjectId[] + types = _execution_cohort_types(schema) + staged_targets = Vector{Tuple{types.identity,types.target}}() + removed_ids = Vector{types.identity}() checked_ids = isnothing(previous) || isnothing(changed_ids) ? current_ids : changed_ids for object_id in checked_ids + object_id isa types.identity || throw(ArgumentError("An object identity is outside the prepared cohort schema.")) location = cohort_location(store, application_id, object_id; owner) is_current = isnothing(previous) || isnothing(changed_ids) || first(_sorted_object_id_position(current_ids, object_id)) - if !is_current - push!(removed_ids, object_id) - continue + _with_execution_cohort_location(schema, location, owner, application_id, object_id) do admitted + if !is_current + push!(removed_ids, object_id) + return nothing + end + previous_target = isnothing(admitted) ? nothing : _execution_cohort_target(admitted) + target = build_target(object_id, previous_target) + _with_execution_cohort_target(schema, target) do accepted + _check_execution_cohort_target(accepted, object_id) + accepted === previous_target || push!(staged_targets, (object_id, accepted)) + return nothing + end + return nothing end - previous_target = isnothing(location) ? nothing : _execution_cohort_target(location) - target = build_target(object_id, previous_target) - _check_execution_cohort_target(target, object_id) - target === previous_target || push!(staged_targets, (object_id, target)) end if !isnothing(previous) && isnothing(changed_ids) current_index = firstindex(current_ids) @@ -198,8 +280,14 @@ function refresh_cohort_membership!( end end + # Discovering removals may bypass checked_ids. Validate every old location + # and every run before the first clear/splice, including a fully empty result. + for object_id in removed_ids + location = cohort_location(store, application_id, object_id; owner) + _with_execution_cohort_location(identity, schema, location, owner, application_id, object_id) + end membership = isnothing(previous) ? - _new_execution_cohort_membership(store, owner, application_id, length(current_ids)) : + _new_execution_cohort_membership(store, owner, application_id, length(current_ids), schema) : previous membership_changed = isnothing(previous) targets_removed = 0 @@ -211,42 +299,53 @@ function refresh_cohort_membership!( targets_removed += 1 membership_changed = true end - remove_cohort_target!(store, application_id, object_id; owner) + remove_cohort_target!(store, application_id, object_id; owner, schema) end for (object_id, target) in staged_targets - cohort = _execution_cohort(store, owner, application_id, typeof(target)) - _store_execution_cohort_target!(store, cohort, target) - isnothing(previous) && continue - location = cohort_location(store, application_id, object_id; owner) - found, position = if isempty(membership.object_ids) || - _object_id_isless(last(membership.object_ids), object_id) - (false, length(membership.object_ids) + 1) - else - _sorted_object_id_position(membership.object_ids, object_id) - end - if !found - _insert_execution_membership_row!(membership, position, object_id, location) - membership_changed = true - elseif membership.locations[position].cohort !== location.cohort - _delete_execution_membership_row!(membership, position) - _insert_execution_membership_row!(membership, position, object_id, location) - membership_changed = true - else - membership.locations[position] = location + changed = _with_execution_cohort_target(schema, target) do accepted + cohort = _execution_cohort(store, owner, application_id, typeof(accepted)) + old_location = cohort_location(store, application_id, object_id; owner) + return _with_execution_cohort_location(schema, old_location, owner, application_id, object_id) do admitted + slot = _store_execution_cohort_target!(store, cohort, accepted, admitted) + isnothing(previous) && return false + location = ExecutionCohortLocation(cohort, slot) + found, position = if isempty(membership.object_ids) || + _object_id_isless(last(membership.object_ids), object_id) + (false, length(membership.object_ids) + 1) + else + _sorted_object_id_position(membership.object_ids, object_id) + end + if !found + _insert_execution_membership_row!(membership, position, object_id, location) + return true + elseif !_execution_membership_location_has_cohort(membership, position, location.cohort) + _delete_execution_membership_row!(membership, position) + _insert_execution_membership_row!(membership, position, object_id, location) + return true + else + membership.locations[position] = location + return false + end + end end + membership_changed |= changed end if isnothing(previous) for object_id in current_ids location = cohort_location(store, application_id, object_id; owner) - _insert_execution_membership_row!( - membership, length(membership.object_ids) + 1, object_id, location, - ) + _with_execution_cohort_location(schema, location, owner, application_id, object_id) do admitted + _insert_execution_membership_row!( + membership, length(membership.object_ids) + 1, object_id, admitted, + ) + end end - for rows in membership.runs - count = length(rows) - sizehint!(rows.indices, count + max(16, count ÷ 4)) - family_count = length(rows.cohort.rows) - sizehint!(rows.cohort.rows, family_count + max(16, family_count ÷ 4)) + for index in eachindex(membership.runs) + _with_execution_membership_run(membership, index) do rows + count = length(rows) + sizehint!(rows.indices, count + max(16, count ÷ 4)) + family_count = length(rows.cohort.rows) + sizehint!(rows.cohort.rows, family_count + max(16, family_count ÷ 4)) + end end end return ( diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 2ffff5656..69b81c610 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -11,8 +11,8 @@ mutable struct ExecutionCohort{T,I<:ObjectId} <: AbstractExecutionCohort new{T,I}(owner, application_id, rows, indices) end -struct ExecutionCohortLocation - cohort::AbstractExecutionCohort +struct ExecutionCohortLocation{C<:AbstractExecutionCohort} + cohort::C row::Int end @@ -37,6 +37,126 @@ end ExecutionCohortRows{T}(store::ExecutionCohortStore, cohort::C, indices::Vector{Int}) where {T,C<:ExecutionCohort{T}} = ExecutionCohortRows{T,C}(store, cohort, indices) +# The finite witness belongs to one application/owner boundary, never to the +# runtime store. In particular Target -> RunContext -> RuntimeStorage does not +# acquire a recursive catalogue of Target types. +abstract type ExecutionCohortSchema end +struct OpenExecutionCohortSchema <: ExecutionCohortSchema end +struct ClosedExecutionCohortSchema{T<:Tuple} <: ExecutionCohortSchema end + +function _closed_execution_cohort_schema(::Type{T}) where {T<:Tuple} + isconcretetype(T) || throw(ArgumentError("A closed cohort schema needs a finite tuple of concrete target types.")) + iszero(fieldcount(T)) && throw(ArgumentError("An empty cohort needs an explicit future target type witness.")) + for Target in fieldtypes(T) + isconcretetype(Target) && hasfield(Target, :object_id) || + throw(ArgumentError("A closed cohort schema requires concrete execution target types.")) + I = fieldtype(Target, :object_id) + isconcretetype(I) && I <: ObjectId || + throw(ArgumentError("A closed cohort schema requires concrete object identity types.")) + end + return ClosedExecutionCohortSchema{T}() +end + +_execution_cohort_schema(::Nothing) = OpenExecutionCohortSchema() +_execution_cohort_schema(::AbstractVector) = OpenExecutionCohortSchema() + +# Pure type-only recipe shared by current batches and an explicit future B. +# Generated wrappers keep each finite operation inside its concrete branch; +# the recipe never reads scientific values or invokes model declarations. +function _execution_cohort_schema_expression(B, require_witness) + invalid = require_witness ? + :(throw(ArgumentError("A closed cohort needs explicit concrete canonical batch witnesses."))) : + :(OpenExecutionCohortSchema()) + isconcretetype(B) || return invalid + targets = Any[] + for Batch in fieldtypes(B) + isconcretetype(Batch) && hasfield(Batch, :targets) || return invalid + Rows = fieldtype(Batch, :targets) + Rows <: ExecutionCohortRows || return invalid + Target = eltype(Rows) + Target in targets || push!(targets, Target) + end + isempty(targets) && return invalid + T = Tuple{targets...} + return :(_closed_execution_cohort_schema($T)) +end + +@generated function _execution_cohort_schema(batches::B) where {B<:Tuple} + return _execution_cohort_schema_expression(B, false) +end + +@generated function _execution_cohort_schema(::Type{B}) where {B<:Tuple} + return _execution_cohort_schema_expression(B, true) +end + +function _check_execution_cohort_location(location, owner, application_id, object_id) + cohort = location.cohort + isequal(cohort.owner, owner) && cohort.application_id === application_id && + get(cohort.indices, object_id, 0) == location.row || throw(ArgumentError( + "The execution location belongs to another owner, application or object.", + )) + return nothing +end + +@inline _with_execution_cohort_location(f, schema::ExecutionCohortSchema, ::Nothing, owner, application_id, object_id) = f(nothing) +@inline function _with_execution_cohort_location(f, ::OpenExecutionCohortSchema, location::ExecutionCohortLocation, owner, application_id, object_id) + _check_execution_cohort_location(location, owner, application_id, object_id) + return f(location) +end + +# Select the actual cohort before invoking the operation. An assertion after a +# dynamic read/clear would leave the abstract operation reachable by JuliaC. +@generated function _with_execution_cohort_location(f, ::ClosedExecutionCohortSchema{T}, location::ExecutionCohortLocation, owner, application_id, object_id) where {T} + branches = Expr[] + for Target in fieldtypes(T) + I = fieldtype(Target, :object_id) + L = ExecutionCohortLocation{ExecutionCohort{Target,I}} + push!(branches, quote + if location isa $L + _check_execution_cohort_location(location, owner, application_id, object_id) + return f(location) + end + end) + end + return quote + $(branches...) + throw(ArgumentError("The existing execution payload is outside its prepared application schema.")) + end +end + +@inline _with_execution_cohort_target(f, ::OpenExecutionCohortSchema, target) = f(target) +@generated function _with_execution_cohort_target(f, ::ClosedExecutionCohortSchema{T}, target) where {T} + branches = [:(target isa $Target && return f(target)) for Target in fieldtypes(T)] + return quote + $(branches...) + throw(ArgumentError("The new execution payload is outside its prepared application schema.")) + end +end + +_execution_cohort_types(::OpenExecutionCohortSchema) = + (identity=ObjectId, target=Any, location=ExecutionCohortLocation, rows=ExecutionCohortRows) +@generated function _execution_cohort_types(::ClosedExecutionCohortSchema{T}) where {T} + targets = collect(fieldtypes(T)) + ids = unique([fieldtype(Target, :object_id) for Target in targets]) + locations = [ExecutionCohortLocation{ExecutionCohort{Target,fieldtype(Target,:object_id)}} for Target in targets] + rows = [ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id)}} for Target in targets] + I, U, L, R = Union{ids...}, Union{targets...}, Union{locations...}, Union{rows...} + return :((identity=$I, target=$U, location=$L, rows=$R)) +end + +@inline _with_execution_cohort_rows(f, ::OpenExecutionCohortSchema, rows::ExecutionCohortRows) = f(rows) +@generated function _with_execution_cohort_rows(f, ::ClosedExecutionCohortSchema{T}, rows::ExecutionCohortRows) where {T} + branches = Expr[] + for Target in fieldtypes(T) + R = ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id)}} + push!(branches, :(rows isa $R && return f(rows))) + end + return quote + $(branches...) + throw(ArgumentError("The execution run is outside its prepared application schema.")) + end +end + Base.IndexStyle(::Type{<:ExecutionCohortRows}) = IndexLinear() Base.size(rows::ExecutionCohortRows) = size(rows.indices) Base.length(rows::ExecutionCohortRows) = length(rows.indices) @@ -72,14 +192,22 @@ function _clear_execution_cohort_row!(cohort::ExecutionCohort, row::Int) return nothing end +function _store_execution_cohort_target!(store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T) where {T} + object_id = ObjectId(target.object_id) + previous = cohort_location(store, cohort.application_id, object_id; owner=cohort.owner) + return _with_execution_cohort_location(OpenExecutionCohortSchema(), previous, + cohort.owner, cohort.application_id, object_id) do location + _store_execution_cohort_target!(store, cohort, target, location) + end +end + function _store_execution_cohort_target!( - store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T, + store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T, previous, ) where {T} object_id = ObjectId(target.object_id) - key = (cohort.owner, cohort.application_id, object_id) - previous = get(store.locations, key, nothing) - if !isnothing(previous) && previous.cohort !== cohort - _clear_execution_cohort_row!(previous.cohort, previous.row) + if !isnothing(previous) + _check_execution_cohort_location(previous, cohort.owner, cohort.application_id, object_id) + previous.cohort === cohort || _clear_execution_cohort_row!(previous.cohort, previous.row) end slot = get(cohort.indices, object_id, 0) if iszero(slot) @@ -89,10 +217,34 @@ function _store_execution_cohort_target!( else cohort.rows[slot] = target end - store.locations[key] = ExecutionCohortLocation(cohort, slot) + store.locations[(cohort.owner, cohort.application_id, object_id)] = ExecutionCohortLocation(cohort, slot) return slot end +# Appending a prepared homogeneous call batch cannot replace another family. +# Prove that before writing either payloads or membership. General replacement +# is handled by refresh_cohort_membership!, with the whole application witness. +function _check_execution_cohort_append(rows::ExecutionCohortRows{T}, target::T) where {T} + location = cohort_location(rows.store, rows.cohort.application_id, target.object_id; owner=rows.cohort.owner) + isnothing(location) && return nothing + location.cohort === rows.cohort || throw(ArgumentError( + "Appending an execution batch cannot replace another payload family; reconcile its application membership first.", + )) + return nothing +end +_check_execution_cohort_append(rows::AbstractVector, target) = nothing +function _append_execution_cohort_target!(rows::ExecutionCohortRows{T}, target::T) where {T} + _check_execution_cohort_append(rows, target) + # The old row is absent or in this exact concrete cohort; no erased cohort + # clear remains reachable from the admitted pure-addition operation. + object_id = target.object_id + slot = get(rows.cohort.indices, object_id, 0) + previous = iszero(slot) ? nothing : ExecutionCohortLocation(rows.cohort, slot) + push!(rows.indices, _store_execution_cohort_target!(rows.store, rows.cohort, target, previous)) + return rows +end +_append_execution_cohort_target!(rows::AbstractVector, target) = push!(rows, target) + """ cohort_rows!(store, application_id, targets::AbstractVector{T}; owner=nothing) @@ -175,10 +327,14 @@ cohort_location(store::ExecutionCohortStore, application_id::Symbol, object_id; get(store.locations, (owner, application_id, ObjectId(object_id)), nothing) """Remove an execution payload without renumbering any cohort's row slots.""" -function remove_cohort_target!(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing) - key = (owner, application_id, ObjectId(object_id)) - location = pop!(store.locations, key, nothing) +function remove_cohort_target!(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing, schema=OpenExecutionCohortSchema()) + object_id = ObjectId(object_id) + key = (owner, application_id, object_id) + location = get(store.locations, key, nothing) isnothing(location) && return false - _clear_execution_cohort_row!(location.cohort, location.row) - return true + return _with_execution_cohort_location(schema, location, owner, application_id, object_id) do admitted + _clear_execution_cohort_row!(admitted.cohort, admitted.row) + delete!(store.locations, key) + return true + end end diff --git a/src/composite_model/execution_dispatch.jl b/src/composite_model/execution_dispatch.jl index a00fb0065..d802152dd 100644 --- a/src/composite_model/execution_dispatch.jl +++ b/src/composite_model/execution_dispatch.jl @@ -28,8 +28,7 @@ end """Close schedule container schemas without copying the live execution payloads.""" function _fixed_execution_plan(plan::CompiledExecutionPlan) - groups = Tuple(CompiledApplicationExecutionGroup(group.application, Tuple(group.batches), group.membership) - for group in plan.groups) + groups = Tuple(_close_execution_group_cohorts(group; batches=Tuple(group.batches)) for group in plan.groups) groups_by_id = Dict(group.application.id => group for group in groups) groups_by_slot = Tuple(isnothing(group) ? nothing : groups_by_id[group.application.id] for group in plan.groups_by_application_slot) diff --git a/src/composite_model/execution_extension_intents.jl b/src/composite_model/execution_extension_intents.jl new file mode 100644 index 000000000..9a4558d45 --- /dev/null +++ b/src/composite_model/execution_extension_intents.jl @@ -0,0 +1,274 @@ +# Ephemeral staging metadata for the existing call-extension algorithm. These +# buffers never belong to the scene, runtime store, targets or call contexts. +struct AppendIntent{Rows,T} + rows::Rows + target::T +end + +struct BindingIntent{CT,B} + targets::CT + binding::B +end + +_prepared_intent_batch_container(::Type{<:PreparedExecutionBatchSchema{BT}}) where {BT} = BT + +# Pure type recipe. Initializers keep their binding update, but cannot append +# manual-call batches: their actual execution_batches is the genuine empty (). +function _execution_extension_intent_layout(::Type{C}) where {C<:Tuple} + _validate_prepared_context_calls(C) + append_types = Any[] + binding_types = Any[] + append_cases = Any[] + for CT in fieldtypes(C) + B = fieldtype(CT, :binding) + Binding = BindingIntent{CT,B} + Binding in binding_types || push!(binding_types, Binding) + _prepared_call_mode(B) === :initializer && continue + BT = _prepared_intent_batch_container(fieldtype(CT, :batch_schema)) + for Batch in _prepared_execution_batch_types(BT) + Rows = fieldtype(Batch, :targets) + Target = eltype(Rows) + Intent = AppendIntent{Rows,Target} + Intent in append_types || push!(append_types, Intent) + case = (CT, B, Rows, Target) + case in append_cases || push!(append_cases, case) + end + end + return (; append_types, binding_types, append_cases) +end + +_execution_append_intent_buffer(::OpenContextCallSchema) = Tuple{Any,Any}[] +_execution_binding_intent_buffer(::OpenContextCallSchema) = Tuple{Any,Any}[] +@generated function _execution_append_intent_buffer(::PreparedContextCallSchema{C}) where {C} + types = _execution_extension_intent_layout(C).append_types + return :(Vector{$(Union{types...})}()) +end +@generated function _execution_binding_intent_buffer(::PreparedContextCallSchema{C}) where {C} + types = _execution_extension_intent_layout(C).binding_types + return :(Vector{$(Union{types...})}()) +end + +@inline function _execution_extension_binding_owner_matches(targets, binding) + return isequal(_execution_call_owner(targets.binding), _execution_call_owner(binding)) +end + +# Closed admission also proves the real namespace, independent of matching +# target/row types. Distinct callers may have identical concrete target schemas. +@inline function _execution_extension_append_owner_matches(targets, binding, rows, target) + storage = targets.temporal_streams + storage isa RuntimeStorage || return false + expected_owner = _execution_call_owner(binding) + stored_owner = rows.cohort.owner + stored_owner isa typeof(expected_owner) || return false + return _execution_extension_binding_owner_matches(targets, binding) && + rows.store === storage.cohorts && + isequal(stored_owner::typeof(expected_owner), expected_owner) && + rows.cohort.application_id === target.context.application.id && + target.context.object_id == target.object_id && + target.context.temporal_streams === storage +end + +@inline function _stage_execution_append!(buffer, ::OpenContextCallSchema, + targets, binding, rows, target) + push!(buffer, (rows, target)) + return true +end +@inline function _stage_execution_binding!(buffer, ::OpenContextCallSchema, targets, binding) + push!(buffer, (targets, binding)) + return true +end + +@generated function _stage_execution_append!(buffer, ::PreparedContextCallSchema{C}, + targets, binding, rows, target) where {C} + branches = Expr[] + for (CT, B, Rows, T) in _execution_extension_intent_layout(C).append_cases + Intent = AppendIntent{Rows,T} + push!(branches, quote + if targets isa $CT && binding isa $B && rows isa $Rows && target isa $T + _execution_extension_append_owner_matches(targets, binding, rows, target) || return false + push!(buffer, $Intent(rows::$Rows, target::$T)) + return true + end + end) + end + return quote + $(branches...) + return false + end +end + +@generated function _stage_execution_binding!(buffer, ::PreparedContextCallSchema{C}, + targets, binding) where {C} + branches = Expr[] + for Intent in _execution_extension_intent_layout(C).binding_types + CT, B = fieldtypes(Intent) + push!(branches, quote + if targets isa $CT && binding isa $B + _execution_extension_binding_owner_matches(targets, binding) || return false + push!(buffer, $Intent(targets::$CT, binding::$B)) + return true + end + end) + end + return quote + $(branches...) + return false + end +end + +@inline _with_execution_append_intent(f, ::OpenContextCallSchema, intent) = f(intent[1], intent[2]) +@inline _with_execution_binding_intent(f, ::OpenContextCallSchema, intent) = f(intent[1], intent[2]) +@generated function _with_execution_append_intent(f, ::PreparedContextCallSchema{C}, intent) where {C} + branches = [:(intent isa $I && return f(intent.rows, intent.target)) + for I in _execution_extension_intent_layout(C).append_types] + return quote + $(branches...) + throw(ArgumentError("An append intent is outside its prepared call schema.")) + end +end +@generated function _with_execution_binding_intent(f, ::PreparedContextCallSchema{C}, intent) where {C} + branches = [:(intent isa $I && return f(intent.targets, intent.binding)) + for I in _execution_extension_intent_layout(C).binding_types] + return quote + $(branches...) + throw(ArgumentError("A binding intent is outside its prepared call schema.")) + end +end + +@inline function _execution_binding_commit_admitted(::PreparedContextCallSchema, + targets::CT, binding, compiled, environment_bindings) where {CT} + return binding isa fieldtype(CT, :binding) && + compiled isa fieldtype(CT, :compiled) && + environment_bindings isa fieldtype(CT, :environment_bindings) && + _execution_extension_binding_owner_matches(targets, binding) +end + +@inline _preflight_execution_binding_intents(::OpenContextCallSchema, bindings, compiled, environment_bindings) = true +function _preflight_execution_binding_intents(scope::PreparedContextCallSchema, + bindings, compiled, environment_bindings) + for intent in bindings + admitted = _with_execution_binding_intent(scope, intent) do targets, binding + _execution_binding_commit_admitted(scope, targets, binding, compiled, environment_bindings) + end + admitted || return false + end + return true +end + +# Stage callers retain the compiler's unique application/owner/object order. +# All live-row checks AND all binding/stamp type checks precede the first write. +# This is schema admission, not rollback for a later unexpected runtime error. +function _commit_execution_call_extension!(scope, appends, bindings, compiled, environment_bindings) + _preflight_execution_binding_intents(scope, bindings, compiled, environment_bindings) || return false + for intent in appends + _with_execution_append_intent(scope, intent) do rows, target + _check_execution_cohort_append(rows, target) + end + end + for intent in appends + _with_execution_append_intent(scope, intent) do rows, target + _append_execution_cohort_target!(rows, target) + end + end + for intent in bindings + _with_execution_binding_intent(scope, intent) do targets, binding + targets.binding = binding + _record_extended_call_execution_batch_cache!(targets, compiled, environment_bindings, binding) + end + end + return true +end + +# The dictionary keeps the outer tuple erased. Prove the complete target field +# schema before staging, so the final assignment/signature also stay concrete. +@inline _admitted_current_execution_call_bindings(::OpenContextCallSchema, target, bindings) = bindings +@generated function _admitted_current_execution_call_bindings(::PreparedContextCallSchema, + target::T, bindings) where {T<:CompiledExecutionTarget} + B = fieldtype(T, :call_bindings) + return :(bindings isa $B ? bindings::$B : nothing) +end + +# Admit every current declaration before constructing any replacement child. +# A later incompatible binding must not fail after an earlier child owner writes. +@inline _preflight_current_execution_calls(::OpenContextCallSchema, calls, bindings, compiled, environment_bindings) = true +@generated function _preflight_current_execution_calls(scope::PreparedContextCallSchema{C}, + calls::C, bindings::Tuple, compiled, environment_bindings) where {C} + _validate_prepared_context_calls(C) + checks = Expr[] + for (index, CT) in enumerate(fieldtypes(C)) + B = fieldtype(CT, :binding) + value = gensym(:binding) + push!(checks, :($value = getfield(bindings, $index))) + push!(checks, :($value isa $B || return false)) + push!(checks, :(_execution_binding_commit_admitted(scope, getfield(calls, $index), + $value::$B, compiled, environment_bindings) || return false)) + end + return quote + length(bindings) == $(fieldcount(C)) || return false + $(checks...) + return true + end +end + +@inline _with_current_execution_call(f, ::OpenContextCallSchema, calls::Tuple, + bindings::Tuple, index::Int) = f(calls[index], bindings[index]) +@generated function _with_current_execution_call(f, ::PreparedContextCallSchema{C}, + calls::C, bindings::Tuple, index::Int) where {C} + _validate_prepared_context_calls(C) + branches = Expr[] + for (slot, CT) in enumerate(fieldtypes(C)) + B = fieldtype(CT, :binding) + push!(branches, quote + if index == $slot + binding = getfield(bindings, $slot) + binding isa $B || throw(ArgumentError("A current call binding is outside its admitted context schema.")) + return f(getfield(calls, $slot), binding::$B) + end + end) + end + return quote + length(bindings) == $(fieldcount(C)) || throw(ArgumentError("The current call count differs from its admitted context schema.")) + $(branches...) + throw(BoundsError(calls, index)) + end +end + +function _execution_call_batches_match_applications(schema, batches, application_ids) + for raw_batch in batches + matches = _with_execution_batch(schema, raw_batch) do batch + batch.application.id in application_ids + end + matches || return false + end + return true +end + +function _execution_call_batches_for_application(schema, application_schema, batches, application_id) + selected = _execution_batch_buffer(application_schema) + for raw_batch in batches + _with_execution_batch(schema, raw_batch) do batch + batch.application.id == application_id || return nothing + _with_execution_batch(application_schema, batch) do admitted + push!(selected, admitted) + end + return nothing + end + end + return selected +end + +# Keep the running count in this typed operation. The outer loop receives only +# a scalar result, avoiding a captured mutable counter across batch callbacks. +function _execution_call_prefix_end(schema, raw_batch, current_ids, previous_count, + changed_target_ids, application_id) + return _with_execution_batch(schema, raw_batch) do batch + count = previous_count + for execution_target in batch.targets + count += 1 + count <= length(current_ids) || return nothing + execution_target.object_id == current_ids[count] || return nothing + (application_id, execution_target.object_id) in changed_target_ids && return nothing + end + return count + end +end diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl index 0728aea20..3ddcae69c 100644 --- a/src/composite_model/execution_storage.jl +++ b/src/composite_model/execution_storage.jl @@ -36,7 +36,7 @@ _execution_cohort_store(::Nothing) = ExecutionCohortStore() _insert_with_spare_capacity!(rows::ExecutionCohortRows, position::Integer, target) = insert!(rows, position, target) -function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches) +function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches; schema=OpenExecutionCohortSchema()) store = storage.cohorts owner = _execution_call_owner(binding) current = Set((batch.application.id, target.object_id) @@ -47,12 +47,16 @@ function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches) (application_id, object_id) in current || push!(obsolete, (application_id, object_id)) end for (application_id, object_id) in obsolete - remove_cohort_target!(store, application_id, object_id; owner) + location = cohort_location(store, application_id, object_id; owner) + _with_execution_cohort_location(identity, schema, location, owner, application_id, object_id) + end + for (application_id, object_id) in obsolete + remove_cohort_target!(store, application_id, object_id; owner, schema) end return nothing end -_retire_call_cohort_targets!(::Nothing, binding, batches) = nothing +_retire_call_cohort_targets!(::Nothing, binding, batches; schema=OpenExecutionCohortSchema()) = nothing _execution_call_owner(binding) = ( binding.application_id, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 9c3563924..7d30b041a 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -544,15 +544,9 @@ abstract type AbstractExecutionBatch end mutable struct LazyCallExecutionBatches <: AbstractVector{AbstractExecutionBatch} owner::Any batches::Any - tracks_full_membership::Bool end -LazyCallExecutionBatches(; tracks_full_membership::Bool=true) = - LazyCallExecutionBatches( - nothing, - nothing, - tracks_full_membership, - ) +LazyCallExecutionBatches() = LazyCallExecutionBatches(nothing, nothing) struct _TrackedCallExecutionBatchCache # Keep the already-boxed runtime values behind `Any` fields. This cache is @@ -626,7 +620,7 @@ types widen as needed. Empty collections have element type `CallTarget`. Use target types. Each view captures its caller metadata and shares the live status references; collecting does not copy numerical state. """ -mutable struct CallTargets{CS,EB,B,TS,OR,C,BT} <: AbstractVector{CallTarget} +mutable struct CallTargets{CS,EB,B,TS,OR,C,BT,S} <: AbstractVector{CallTarget} compiled::CS environment_bindings::EB binding::B @@ -640,6 +634,8 @@ mutable struct CallTargets{CS,EB,B,TS,OR,C,BT} <: AbstractVector{CallTarget} # may legitimately change its concrete type between invocations. environment::Any execution_batches::BT + const batch_schema::S + const tracks_full_membership::Bool preparation::CallTargetsPreparation{CS,EB,TS,OR,C} evaluation::Union{Nothing,CallEvaluationFrame} target_buffer_cache::Union{Nothing,_CallTargetBufferCache} @@ -660,55 +656,18 @@ end return nothing end -Base.@nospecializeinfer function CallTargets( - compiled, - environment_bindings, - binding, - temporal_streams, - output_retention, - time, - constants, - publication_allowed, - environment, - ; +function CallTargets( + compiled, environment_bindings, binding, temporal_streams, output_retention, + time, constants, publication_allowed, environment; tracks_full_membership::Bool=true, + batch_schema=OpenExecutionBatchSchema(), ) - # Cold construction returns concrete targets without specializing the - # assembly method on the entire compiled scene for every call binding. - @nospecialize compiled environment_bindings binding - execution_batches = if _compiled_call_mode(binding) === :initializer - () - elseif binding.multiplicity === :many - # Large `Many` bindings are commonly executed with an object filter - # while organs are emitted. Defer their complete batch construction - # until an unfiltered view or execution actually needs it. - LazyCallExecutionBatches( - ; tracks_full_membership=tracks_full_membership, - ) - else - # Preserve the concrete, allocation-free lookup path promised by - # `call_model` for `One` and `OptionalOne` bindings. - _compiled_call_execution_batches( - compiled, - environment_bindings, - binding, - temporal_streams, - output_retention, - constants, - ) - end - return _prepared_call_targets( - compiled, - environment_bindings, - binding, - temporal_streams, - output_retention, - time, - constants, - publication_allowed, - environment, - execution_batches, - ) + execution_batches = _call_execution_batches_for_schema(batch_schema, + compiled, environment_bindings, binding, temporal_streams, + output_retention, constants, tracks_full_membership) + return _prepared_call_targets(compiled, environment_bindings, binding, + temporal_streams, output_retention, time, constants, publication_allowed, + environment, execution_batches, batch_schema, tracks_full_membership) end # Both graph preparation and a leased context's clone use this fully specified @@ -717,10 +676,12 @@ end @inline function _prepared_call_targets( compiled, environment_bindings, binding, temporal_streams, output_retention, time, constants, publication_allowed, environment, execution_batches, + batch_schema, tracks_full_membership::Bool, ) targets = CallTargets( compiled, environment_bindings, binding, temporal_streams, output_retention, float(time), constants, publication_allowed, environment, execution_batches, + batch_schema, tracks_full_membership, _call_targets_preparation( compiled, environment_bindings, binding, temporal_streams, output_retention, constants, ), @@ -770,7 +731,7 @@ end # A lazy wrapper points at its owning CallTargets. Share its prepared state, # never its owner link; cloning must leave a cold Many membership cold. return LazyCallExecutionBatches( - nothing, batches.batches, batches.tracks_full_membership, + nothing, batches.batches, ) end @@ -785,6 +746,7 @@ end compiled, environment_bindings, prototype.binding, temporal_streams, output_retention, time, constants, publication_allowed, environment, _clone_call_execution_batches(prototype.execution_batches), + prototype.batch_schema, prototype.tracks_full_membership, ) remaining = _clone_runtime_call_targets( Base.tail(calls), compiled, environment_bindings, temporal_streams, @@ -793,27 +755,12 @@ end return (targets, remaining...) end -function _current_call_binding_for_retained_view( - compiled::CompiledCompositeModel, +function _current_call_binding_for_retained_view(compiled::CompiledCompositeModel, binding::CompiledModelCallBinding, ) - bindings = get( - compiled.call_bindings_by_target, - (binding.application_id, binding.consumer_id), - (), - ) - binding_index = findfirst( - candidate -> - _compiled_call_name(candidate) === _compiled_call_name(binding) && - _compiled_call_mode(candidate) === _compiled_call_mode(binding), - bindings, - ) - isnothing(binding_index) && error( - "Retained hard-call view `$(_compiled_call_name(binding))` no longer has " * - "a compiled binding for application `$(binding.application_id)` on " * - "object `$(binding.consumer_id.value)`.", - ) - return bindings[binding_index] + return _compiled_application_by_id(compiled,binding.application_id) do application + _current_call_binding_for_application(compiled,application,binding) + end end @inline function _environment_bindings_match_compiled( @@ -837,41 +784,30 @@ function _prebarrier_environment_bindings( return nothing end -function _synchronize_tracked_call_targets!(targets::CallTargets) +function _synchronize_tracked_call_targets!(targets::CallTargets{CS,EB}) where {CS,EB} binding = targets.binding model = targets.compiled.model topology_dirty = bindings_dirty(model) - current_compiled = if topology_dirty - cached = getfield(model, :binding_cache) - cached isa CompiledCompositeModel ? cached : targets.compiled - else - cached = compiled_bindings(model) - isnothing(cached) ? targets.compiled : cached - end - current_environment_bindings = if topology_dirty - _prebarrier_environment_bindings( - model, - current_compiled, - targets.environment_bindings, - ) + cached = getfield(model,:binding_cache) + current_compiled = if isnothing(cached) + targets.compiled else - refresh_environment_bindings!(model, current_compiled) + cached isa CS || _unprepared_runtime_configuration() + cached::CS end - if isnothing(current_environment_bindings) - # A dirty lifecycle may temporarily expose a newer structural cache - # without a matching pre-barrier environment cache. Keep the last - # internally coherent runtime shell instead of mixing generations. + candidate_environment = topology_dirty ? + _prebarrier_environment_bindings(model,current_compiled,targets.environment_bindings) : + refresh_environment_bindings!(model,current_compiled) + if isnothing(candidate_environment) current_compiled = targets.compiled current_environment_bindings = targets.environment_bindings + else + candidate_environment isa EB || _unprepared_runtime_configuration() + current_environment_bindings = candidate_environment::EB end - _invalidate_single_call_snapshot!( - targets, current_compiled, current_environment_bindings, - ) + _invalidate_single_call_snapshot!(targets,current_compiled,current_environment_bindings) if current_compiled !== targets.compiled - current_binding = _current_call_binding_for_retained_view( - current_compiled, - binding, - ) + current_binding = _current_call_binding_for_retained_view(current_compiled,binding) targets.compiled = current_compiled targets.binding = current_binding end @@ -885,7 +821,7 @@ end ) state = cached.batches isnothing(state) && return false - cached.tracks_full_membership || return true + targets.tracks_full_membership || return true state isa _TrackedCallExecutionBatchCache || return false return state.binding === targets.binding && state.membership_generation == @@ -925,10 +861,14 @@ end function _record_call_execution_batch_cache!( cached::LazyCallExecutionBatches, targets::CallTargets, - batches, + batches; + cohort_schema=OpenExecutionCohortSchema(), ) + if targets.tracks_full_membership + _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches; schema=cohort_schema) + end targets.last_single_snapshot = nothing - cached.batches = if cached.tracks_full_membership + cached.batches = if targets.tracks_full_membership _TrackedCallExecutionBatchCache( batches, targets.binding, @@ -946,9 +886,6 @@ function _record_call_execution_batch_cache!( # Explicit `objects=` selections share the call owner's payloads with its # complete cached view. Only that complete membership can retire rows; # absence from one selection does not remove a target from the call. - if cached.tracks_full_membership - _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches) - end return batches end @@ -965,7 +902,7 @@ function _record_extended_call_execution_batch_cache!( ) cached = targets.execution_batches cached isa LazyCallExecutionBatches || return targets - cached.tracks_full_membership || return targets + targets.tracks_full_membership || return targets batches = _cached_call_execution_batches(targets) isnothing(batches) && return targets cached.batches = _TrackedCallExecutionBatchCache( @@ -979,9 +916,11 @@ function _record_extended_call_execution_batch_cache!( end function _materialize_call_execution_batches!(targets::CallTargets) + targets.batch_schema isa PreparedExecutionBatchSchema && + return _materialize_prepared_call_execution_batches!(targets.batch_schema, targets) cached = targets.execution_batches cached isa LazyCallExecutionBatches || return cached - if cached.tracks_full_membership + if targets.tracks_full_membership _tracked_call_execution_batch_cache_can_reuse(cached, targets) && return _cached_call_execution_batches(targets) _synchronize_tracked_call_targets!(targets) @@ -993,7 +932,7 @@ function _materialize_call_execution_batches!(targets::CallTargets) # A complete manual `Many` view becomes lifecycle-tracked only here. Merely # retrieving the cached CallTargets wrapper, diagnostics, and targeted # `objects=` calls leave the full membership cold. - if cached.tracks_full_membership + if targets.tracks_full_membership _observe_compiled_call_membership!( targets.compiled, targets.binding; @@ -1036,37 +975,14 @@ Base.iterate(batches::LazyCallExecutionBatches, state...) = Base.IndexStyle(::Type{<:CallTargets}) = IndexLinear() Base.eltype(::Type{<:CallTargets}) = CallTarget -_runtime_call_targets(compiled, environment_bindings, ::Tuple{}, args...) = () - -Base.@nospecializeinfer function _runtime_call_targets( - compiled, - environment_bindings, - bindings::Tuple, - temporal_streams, - output_retention, - time, - constants, - publication_allowed, - environment, +function _runtime_call_targets( + compiled, environment_bindings, bindings::Tuple, temporal_streams, + output_retention, time, constants, publication_allowed, environment; + call_schema=OpenContextCallSchema(), ) - @nospecialize compiled environment_bindings bindings - # Assemble once instead of specializing recursively on each tuple suffix. - # The final tuple retains each target's concrete type and original order. - targets = CallTargets[] - for binding in bindings - push!(targets, CallTargets( - compiled, - environment_bindings, - binding, - temporal_streams, - output_retention, - float(time), - constants, - publication_allowed, - environment, - )) - end - return Tuple(targets) + return _assemble_runtime_call_targets(call_schema, compiled, environment_bindings, + bindings, temporal_streams, output_retention, time, constants, + publication_allowed, environment) end @inline _prepare_runtime_call_targets!( @@ -1213,13 +1129,19 @@ CompiledExecutionBatch( ExecutionBatchContextState(nothing, nothing), ) -mutable struct CompiledApplicationExecutionGroup{A,B} +mutable struct CompiledApplicationExecutionGroup{A,B,M<:ExecutionCohortMembership} application::A batches::B - membership::ExecutionCohortMembership + membership::M end -function _compiled_application_execution_group(application, batches, membership) +function _compiled_application_execution_group(application, batches, membership; + batch_schema=OpenExecutionBatchSchema(), +) + if batch_schema isa PreparedExecutionBatchSchema + return CompiledApplicationExecutionGroup(application, + _finish_execution_batches(batch_schema,batches),membership) + end if !isempty(batches) batch_type = typeof(first(batches)) eltype(batches) === batch_type && @@ -1245,8 +1167,21 @@ function _empty_model_execution_group(application, ::Type{B}, cohorts::Execution Rows = fieldtype(B, :targets) Rows <: ExecutionCohortRows || throw(ArgumentError("Prepared batches require canonical cohort rows.")) _execution_cohort(cohorts, nothing, application.id, eltype(Rows)) - membership = _new_execution_cohort_membership(cohorts, nothing, application.id, 0) - return CompiledApplicationExecutionGroup(application, B[], membership) + schema = _execution_cohort_schema(Tuple{B}) + membership = _new_execution_cohort_membership(cohorts,nothing,application.id,0,schema) + return CompiledApplicationExecutionGroup(application,B[],membership) +end + +# Prepare the membership witness before fixing the group's container types. +# Batch/Rows/Target/context schemas are unchanged: only metadata vectors close. +function _close_execution_group_cohorts(group::CompiledApplicationExecutionGroup; batches=group.batches) + schema = group.membership.schema isa ClosedExecutionCohortSchema ? + group.membership.schema : _execution_cohort_schema(Tuple(group.batches)) + schema isa ClosedExecutionCohortSchema || throw(ArgumentError( + "An empty group needs an explicit future batch witness before closure.", + )) + membership = _close_execution_cohort_membership(group.membership, schema) + return CompiledApplicationExecutionGroup(group.application, batches, membership) end # Same-schema metadata refresh keeps the existing owner, including its formerly @@ -1435,8 +1370,15 @@ function _execution_groups_by_application_slot(groups, application_count::Int) ), nothing, ) - for group in groups - groups_by_slot[group.application.slot] = group + for index in eachindex(groups) + _with_metadata_entry(groups, index) do group + slot = group.application.slot + 1 <= slot <= application_count || throw(ArgumentError( + "An execution group selected a slot outside the prepared application layout.", + )) + groups_by_slot[slot] = group + return nothing + end end return groups_by_slot end @@ -1465,6 +1407,9 @@ mutable struct Simulation{S,CS,EB,EP,OR,TS,DT,R,RM,RT,C,P} performance::P end +include("execution_batch_schemas.jl") +include("execution_extension_intents.jl") + function Base.show(io::IO, simulation::Simulation) print( io, @@ -2803,6 +2748,7 @@ end publication_allowed::Bool, environment; fresh::Bool=false, + call_schema=_context_call_schema(context), ) if isnothing(context) || fresh calls = if context isa RunContext && _call_context_clone_is_current( @@ -2816,7 +2762,8 @@ end else _runtime_call_targets( compiled, environment_bindings, call_bindings, temporal_streams, - output_retention, time, constants, publication_allowed, environment, + output_retention, time, constants, publication_allowed, environment; + call_schema, ) end return RunContext( @@ -3407,99 +3354,82 @@ function _compiled_model_execution_target( output_retention=nothing, constants=nothing; owner=nothing, + cohort_schema=OpenExecutionCohortSchema(), ) if temporal_streams isa RuntimeStorage location = cohort_location(temporal_streams.cohorts, application.id, object_id; owner) - if !isnothing(location) - previous = location.cohort.rows[location.row] - if !isnothing(previous) && isnothing(_model_execution_target_change_reason( - previous, compiled, env_bindings, application, output_retention, temporal_streams, - )) - return previous - end + return _with_execution_cohort_location(cohort_schema, location, owner, application.id, object_id) do admitted + previous = isnothing(admitted) ? nothing : _execution_cohort_target(admitted) + _compiled_model_execution_target_from_previous(previous, compiled, env_bindings, + application, object_id, temporal_streams, output_retention, constants; + target_schema=cohort_schema) end end - return _new_model_execution_target( - compiled, env_bindings, application, object_id, - temporal_streams, output_retention, constants, - ) + return _new_model_execution_target(compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants; target_schema=cohort_schema) +end + +function _compiled_model_execution_target_from_previous(previous, compiled, env_bindings, + application, object_id, temporal_streams, output_retention, constants; + target_schema=OpenExecutionCohortSchema()) + if !isnothing(previous) && isnothing(_model_execution_target_change_reason( + previous, compiled, env_bindings, application, output_retention, temporal_streams, + )) + return previous + end + return _new_model_execution_target(compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants; target_schema) end function _new_model_execution_target( - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - application::CompiledModelApplication, - object_id::ObjectId, - temporal_streams, - output_retention, - constants, + compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, + application::CompiledModelApplication, object_id::ObjectId, + temporal_streams, output_retention, constants; + target_schema=OpenExecutionCohortSchema(), ) - status_view = _model_status_view_for_application( - compiled, - application, - object_id, - ) + status_view = _model_status_view_for_application(compiled, application, object_id) model = _application_model(application, object_id) - bound_inputs = status_view.bound_inputs - distributed_targets = _runtime_model_output_targets( - compiled, - application, - object_id, - ) - call_bindings = get( - compiled.call_bindings_by_target, - (application.id, object_id), - (), - ) - environment_binding = _environment_binding_for( - env_bindings, - application.id, - object_id, - ) - context = if isnothing(temporal_streams) && isempty(distributed_targets) - nothing - else - _prepare_model_execution_context!( - nothing, compiled, env_bindings, application, object_id, - bound_inputs, distributed_targets, call_bindings, temporal_streams, - output_retention, 0.0, constants, true, _NO_ENVIRONMENT_OVERRIDE, - ) + distributed_targets = _runtime_model_output_targets(compiled, application, object_id) + call_bindings = get(compiled.call_bindings_by_target, (application.id, object_id), ()) + environment_binding = _environment_binding_for(env_bindings, application.id, object_id) + fields = (object_id=object_id, model=model, status_view=status_view, + bound_inputs=status_view.bound_inputs, output_targets=distributed_targets, + call_bindings=call_bindings, environment_binding=environment_binding) + owners = (compiled=compiled, temporal_streams=temporal_streams, + output_retention=output_retention, constants=constants, + environment=_NO_ENVIRONMENT_OVERRIDE) + return _with_execution_target_type(target_schema, application, fields, owners) do Target, actual_application, actual, owner, call_schema + input_bindings = isnothing(Target) ? + _runtime_model_temporal_inputs(actual.status_view.temporal_inputs, owner.temporal_streams) : + _prepared_runtime_temporal_inputs(fieldtype(Target,:input_bindings), + actual.status_view.temporal_inputs,owner.temporal_streams) + output_bindings = if isnothing(Target) + local_outputs = _runtime_model_output_streams(actual.status_view.status, + actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) + distributed_outputs = _runtime_model_distributed_output_streams(owner.compiled, + actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) + (local_outputs...,distributed_outputs...) + else + _prepared_runtime_outputs(fieldtype(Target,:output_bindings),actual.status_view.status, + actual.output_targets,actual_application,actual.object_id,owner.compiled, + owner.temporal_streams,owner.output_retention,false) + end + context = if isnothing(owner.temporal_streams) && isempty(actual.output_targets) + nothing + else + _prepare_model_execution_context!(nothing, owner.compiled, env_bindings, + actual_application, actual.object_id, actual.bound_inputs, + actual.output_targets, actual.call_bindings, owner.temporal_streams, + owner.output_retention, 0.0, owner.constants, true, owner.environment; + call_schema) + end + target = _compiled_execution_target(actual.object_id, actual.model, + actual.status_view, input_bindings, actual.bound_inputs, + actual.output_targets, output_bindings, actual.call_bindings, + actual.environment_binding, context, + CallContextCache(context, actual.status_view.execution_stamp)) + return isnothing(Target) ? target : target::Target end - local_output_bindings = _runtime_model_output_streams( - status_view.status, - application, - object_id, - temporal_streams, - output_retention, - ) - distributed_output_bindings = - _runtime_model_distributed_output_streams( - compiled, - application, - object_id, - temporal_streams, - output_retention, - ) - output_bindings = ( - local_output_bindings..., - distributed_output_bindings..., - ) - return _compiled_execution_target( - object_id, - model, - status_view, - _runtime_model_temporal_inputs( - status_view.temporal_inputs, - temporal_streams, - ), - bound_inputs, - distributed_targets, - output_bindings, - call_bindings, - environment_binding, - context, - CallContextCache(context, status_view.execution_stamp), - ) end function _compiled_model_execution_environment_provider( @@ -3546,128 +3476,134 @@ end # their providers and publication contract before allocating reconciliation # indexes; an unchanged layout needs no new batch-list owner. function _execution_batches_match_membership( - env_bindings, application, membership, output_publication, previous_group, + env_bindings,application,membership,publication,previous_group,batch_schema, ) isnothing(previous_group) && return false previous_group.application === application || return false batches = previous_group.batches length(batches) == length(membership.runs) || return false for index in eachindex(membership.runs) - rows = membership.runs[index] - batch = batches[index] - batch.targets === rows || return false - provider = _compiled_model_execution_environment_provider( - env_bindings, application, first(rows), - ) - _execution_batch_matches(batch, application, provider, output_publication) || return false + matches = _with_execution_cohort_rows(membership.schema,membership.runs[index]) do rows + _with_execution_batch(batch_schema,batches[index]) do batch + batch.targets === rows || return false + provider = _compiled_model_execution_environment_provider(env_bindings, + application,first(rows)) + return _execution_batch_matches(batch,application,provider,publication) + end + end + matches || return false end return true end function _model_execution_batches( - env_bindings::CompiledEnvironmentBindings, - application::CompiledModelApplication, - membership::ExecutionCohortMembership, - output_retention, - previous_group=nothing, + env_bindings::CompiledEnvironmentBindings,application::CompiledModelApplication, + membership::ExecutionCohortMembership,output_retention,previous_group=nothing; + batch_schema=OpenExecutionBatchSchema(), ) - output_publication = _compiled_output_publication(output_retention, application) - if _execution_batches_match_membership( - env_bindings, application, membership, output_publication, previous_group, - ) - return (batches=previous_group.batches, batches_constructed=0) + publication = _batch_output_publication(batch_schema,output_retention,application) + if _execution_batches_match_membership(env_bindings,application,membership, + publication,previous_group,batch_schema) + return (batches=previous_group.batches,batches_constructed=0) end live_views = IdDict{ExecutionCohortRows,Nothing}(rows => nothing for rows in membership.runs) previous_by_view = IdDict{ExecutionCohortRows,Any}() spare_by_cohort = IdDict{AbstractExecutionCohort,Vector{Any}}() next_spare = IdDict{AbstractExecutionCohort,Int}() if !isnothing(previous_group) && previous_group.application === application - for batch in previous_group.batches - previous_by_view[batch.targets] = batch - if !haskey(live_views, batch.targets) - candidates = get!(spare_by_cohort, batch.targets.cohort) do - Any[] + for index in eachindex(previous_group.batches) + _with_execution_batch(batch_schema,previous_group.batches[index]) do batch + previous_by_view[batch.targets] = batch + if !haskey(live_views,batch.targets) + candidates = get!(spare_by_cohort,batch.targets.cohort) do + Any[] + end + push!(candidates,batch) end - push!(candidates, batch) + return nothing end end end - batches = AbstractExecutionBatch[] + batches = _execution_batch_buffer(batch_schema) batches_constructed = 0 - for (index, rows) in pairs(membership.runs) - provider = _compiled_model_execution_environment_provider( - env_bindings, application, first(rows), - ) - reused = get(previous_by_view, rows, nothing) - if !isnothing(reused) && - !_execution_batch_matches(reused, application, provider, output_publication) - reused = nothing - end - if isnothing(reused) - candidates = get(spare_by_cohort, rows.cohort, ()) - candidate_index = get(next_spare, rows.cohort, 1) - while candidate_index <= length(candidates) - candidate = candidates[candidate_index] - candidate_index += 1 - if _execution_batch_matches(candidate, application, provider, output_publication) - reused = candidate - break + for index in eachindex(membership.runs) + constructed = _with_execution_cohort_rows(membership.schema,membership.runs[index]) do rows + provider = _compiled_model_execution_environment_provider(env_bindings, + application,first(rows)) + reused = _compatible_execution_batch(batch_schema, + get(previous_by_view,rows,nothing),application,provider,publication) + if isnothing(reused) + candidates = get(spare_by_cohort,rows.cohort,()) + candidate_index = get(next_spare,rows.cohort,1) + while candidate_index <= length(candidates) + candidate = _compatible_execution_batch(batch_schema, + candidates[candidate_index],application,provider,publication) + candidate_index += 1 + if !isnothing(candidate) + reused = candidate + break + end end + next_spare[rows.cohort] = candidate_index end - next_spare[rows.cohort] = candidate_index - end - if isnothing(reused) - push!(batches, CompiledExecutionBatch( - application, rows, provider, output_publication, - )) - batches_constructed += 1 - else - if reused.targets !== rows - # Never consume a view still reserved for a later ordered run. - # Spares are retired views, and shared index vectors need no copy. - if reused.targets.indices !== rows.indices - empty!(reused.targets.indices) - append!(reused.targets.indices, rows.indices) + if isnothing(reused) + _with_new_execution_batch(batch_schema,application,rows,provider,publication) do batch + push!(batches,batch) + return nothing + end + return 1 + end + _with_execution_batch(batch_schema,reused) do batch + if batch.targets !== rows + if batch.targets.indices !== rows.indices + empty!(batch.targets.indices) + append!(batch.targets.indices,rows.indices) + end + membership.runs[index] = batch.targets end - membership.runs[index] = reused.targets + push!(batches,batch) + return nothing end - push!(batches, reused) + return 0 end + batches_constructed += constructed end - return (batches=batches, batches_constructed=batches_constructed) + return (batches=batches,batches_constructed=batches_constructed) end function _compiled_call_execution_batches( - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - binding, - temporal_streams, - output_retention, - constants, + compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, + binding, temporal_streams, output_retention, constants; + cohort_schema=OpenExecutionCohortSchema(), + batch_schema=OpenExecutionBatchSchema(), ) cohorts = _execution_cohort_store(temporal_streams) owner = _execution_call_owner(binding) - batches = AbstractExecutionBatch[] + admission = _call_cohort_admission(batch_schema,cohort_schema) + batches = _execution_batch_buffer(batch_schema) for application_id in binding.callee_application_ids - application = _compiled_application_by_id(compiled, application_id) - current_ids = ObjectId[ - object_id for object_id in binding.callee_object_ids - if _call_binding_target_matches(binding, application, object_id) - ] - refreshed = refresh_cohort_membership!( - cohorts, application.id, current_ids, nothing; owner, - ) do object_id, previous_target - _compiled_model_execution_target( - compiled, env_bindings, application, object_id, - temporal_streams, output_retention, constants; owner, - ) + _compiled_application_by_id(compiled,application_id) do application + application_schema = _call_batch_schema_for_application(batch_schema,application) + current_ids = ObjectId[object_id for object_id in binding.callee_object_ids + if _call_binding_target_matches(binding,application,object_id)] + refreshed = refresh_cohort_membership!(cohorts,application.id,current_ids, + nothing;owner,schema=admission) do object_id, previous_target + _compiled_model_execution_target_from_previous(previous_target, + compiled,env_bindings,application,object_id,temporal_streams, + output_retention,constants;target_schema=admission) + end + assembled = _model_execution_batches(env_bindings,application, + refreshed.membership,output_retention;batch_schema=application_schema) + for index in eachindex(assembled.batches) + _with_execution_batch(application_schema,assembled.batches[index]) do batch + push!(batches,batch) + return nothing + end + end + return nothing end - assembled = _model_execution_batches( - env_bindings, application, refreshed.membership, output_retention, - ) - append!(batches, assembled.batches) end - return Tuple(batches) + return _finish_execution_batches(batch_schema,batches) end function compile_model_execution_plan( @@ -3675,16 +3611,20 @@ function compile_model_execution_plan( env_bindings::CompiledEnvironmentBindings, temporal_streams=nothing, output_retention=nothing, - constants=nothing, + constants=nothing; + batch_schemas=nothing, ) + isnothing(batch_schemas) || _prepared_application_schema_order(compiled,batch_schemas) cohorts = _execution_cohort_store(temporal_streams) manual_application_ids = _manual_call_application_ids(compiled) groups = CompiledApplicationExecutionGroup[] batches = AbstractExecutionBatch[] for application in _ordered_model_applications(compiled) application.id in manual_application_ids && continue + previous_group = isnothing(batch_schemas) ? nothing : + _prepared_execution_group(application,getproperty(batch_schemas,application.id),cohorts) refreshed = _refresh_model_execution_group!( - nothing, cohorts, compiled, env_bindings, application, + previous_group, cohorts, compiled, env_bindings, application, temporal_streams, output_retention, constants, nothing, nothing, ) isnothing(refreshed.group) && continue @@ -4008,13 +3948,19 @@ function _model_execution_target_change_reason( target.call_bindings_signature == _call_bindings_signature(target.call_bindings) || return :call_bindings - any( - binding -> _manual_call_binding_has_changed_target( - binding, - compiled, - ), - target.call_bindings, - ) && return :call_bindings + if any(binding -> _manual_call_binding_has_changed_target(binding,compiled), + target.call_bindings) + context = target.context + # Delta markers describe changes entering this compiled owner. A child + # already prepared against that exact owner must not replay the delta. + # Reuse the same owner/binding/stamp proof as ordinary context cloning; + # a stale child still reaches the existing rebuild below. + current = context isa RunContext && _call_context_clone_is_current( + context,compiled,env_bindings,application,object_id,target.bound_inputs, + target.output_targets,target.call_bindings,temporal_streams, + output_retention,context.constants) + current || return :call_bindings + end return nothing end @@ -4086,88 +4032,74 @@ function _extend_execution_target_call_batches_by_prefix!( (context.application.id, target.object_id), (), ) + scope = _context_call_schema(context) + current_call_bindings = _admitted_current_execution_call_bindings(scope, + target, current_call_bindings) + isnothing(current_call_bindings) && return false length(context.calls) == length(current_call_bindings) || return false - staged = Tuple{Any,Any}[] - staged_bindings = Tuple{Any,Any}[] - for (call_targets, binding) in zip(context.calls, current_call_bindings) - _compiled_call_name(call_targets.binding) == - _compiled_call_name(binding) || return false - push!(staged_bindings, (call_targets, binding)) - _compiled_call_mode(binding) === :initializer && continue - execution_batches = _cached_call_execution_batches(call_targets) - isnothing(execution_batches) && continue - all( - batch -> batch.application.id in binding.callee_application_ids, - execution_batches, - ) || return false - for application_id in binding.callee_application_ids - application = _compiled_application_by_id(compiled, application_id) - batches = AbstractExecutionBatch[ - batch for batch in execution_batches - if batch.application.id == application_id - ] - isempty(batches) && return false - current_ids = ObjectId[ - object_id for object_id in binding.callee_object_ids - if _call_binding_target_matches(binding, application, object_id) - ] - # Call batches are compiled by walking the sorted callee IDs and - # only split when their concrete target type changes. A monotonic - # lifecycle addition therefore preserves the flattened old target - # sequence as an exact prefix. Any removal, reordering, or target - # replacement falls back to the general rebuild path. - existing_count = 0 - for batch in batches - for execution_target in batch.targets - existing_count += 1 - existing_count <= length(current_ids) || return false - execution_target.object_id == current_ids[existing_count] || - return false - ( - application.id, - execution_target.object_id, - ) in compiled.changed_execution_target_ids && return false + _preflight_current_execution_calls(scope, context.calls, current_call_bindings, + compiled, env_bindings) || return false + staged = _execution_append_intent_buffer(scope) + staged_bindings = _execution_binding_intent_buffer(scope) + for call_index in eachindex(context.calls) + extended = _with_current_execution_call(scope, context.calls, + current_call_bindings, call_index) do call_targets, binding + _compiled_call_name(call_targets.binding) == _compiled_call_name(binding) || return false + _stage_execution_binding!(staged_bindings, scope, call_targets, binding) || return false + _compiled_call_mode(binding) === :initializer && return true + execution_batches = _cached_call_execution_batches(call_targets) + isnothing(execution_batches) && return true + schema = call_targets.batch_schema + _execution_call_batches_match_applications(schema, execution_batches, + binding.callee_application_ids) || return false + for application_id in binding.callee_application_ids + matched = _compiled_application_by_id(compiled, application_id) do application + application_schema = _call_batch_schema_for_application(schema, application) + batches = _execution_call_batches_for_application(schema, application_schema, + execution_batches, application_id) + isempty(batches) && return false + current_ids = ObjectId[object_id for object_id in binding.callee_object_ids + if _call_binding_target_matches(binding, application, object_id)] + # Preserve the existing ordered-prefix algorithm. Only the + # count leaves each admitted concrete batch operation. + existing_count = 0 + for raw_batch in batches + next_count = _execution_call_prefix_end(application_schema, + raw_batch, current_ids, existing_count, + compiled.changed_execution_target_ids, application.id) + isnothing(next_count) && return false + existing_count = next_count + end + existing_count == length(current_ids) && return true + admission = _call_cohort_admission(application_schema, OpenExecutionCohortSchema()) + return _with_execution_batch(application_schema, last(batches)) do destination_batch + for index in (existing_count + 1):lastindex(current_ids) + object_id = current_ids[index] + execution_target = _compiled_model_execution_target( + compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants; + owner=_execution_call_owner(binding), cohort_schema=admission) + accepted = _with_execution_cohort_target(admission, execution_target) do actual + _model_execution_batch_accepts_target(destination_batch, + actual, env_bindings, application) || return false + return _stage_execution_append!(staged, scope, call_targets, + binding, destination_batch.targets, actual) + end + accepted || return false + end + return true + end end + matched || return false end - existing_count == length(current_ids) && continue - destination_batch = last(batches) - for index in (existing_count + 1):lastindex(current_ids) - object_id = current_ids[index] - execution_target = _compiled_model_execution_target( - compiled, - env_bindings, - application, - object_id, - temporal_streams, - output_retention, - constants; - owner=_execution_call_owner(binding), - ) - _model_execution_batch_accepts_target( - destination_batch, - execution_target, - env_bindings, - application, - ) || return false - push!(staged, (destination_batch.targets, execution_target)) - end + return true end + extended || return false end - for (targets, execution_target) in staged - push!(targets, execution_target) - end - for (call_targets, binding) in staged_bindings - call_targets.binding = binding - _record_extended_call_execution_batch_cache!( - call_targets, - compiled, - env_bindings, - binding, - ) - end + _commit_execution_call_extension!(scope, staged, staged_bindings, + compiled, env_bindings) || return false target.call_bindings = current_call_bindings - target.call_bindings_signature = - _call_bindings_signature(current_call_bindings) + target.call_bindings_signature = _call_bindings_signature(current_call_bindings) target.call_context_cache.transient = nothing return true end @@ -4187,13 +4119,10 @@ function _pure_addition_changed_call_target_ids( object_id, ), ) || continue - application = _compiled_application_by_id(compiled, application_id) - first( - _sorted_object_id_position( - application.target_ids, - object_id, - ), - ) || continue + matches_application = _compiled_application_by_id(compiled, application_id) do application + first(_sorted_object_id_position(application.target_ids, object_id)) + end + matches_application || continue push!(changed_ids, object_id) application_id in affected_application_ids || push!(affected_application_ids, application_id) @@ -4219,103 +4148,74 @@ function _extend_execution_target_call_batches_for_pure_addition!( (context.application.id, target.object_id), (), ) + scope = _context_call_schema(context) + current_call_bindings = _admitted_current_execution_call_bindings(scope, + target, current_call_bindings) + isnothing(current_call_bindings) && return nothing length(context.calls) == length(current_call_bindings) || return nothing - staged = Tuple{Any,Any}[] - staged_bindings = Tuple{Any,Any}[] - for (call_targets, binding) in zip(context.calls, current_call_bindings) - _compiled_call_name(call_targets.binding) == - _compiled_call_name(binding) || return nothing - push!(staged_bindings, (call_targets, binding)) - _compiled_call_mode(binding) === :initializer && continue - execution_batches = _cached_call_execution_batches(call_targets) - isnothing(execution_batches) && continue - all( - batch -> batch.application.id in binding.callee_application_ids, - execution_batches, - ) || return nothing - changed_ids, affected_application_ids = - _pure_addition_changed_call_target_ids(binding, compiled) - isempty(changed_ids) && continue - length(affected_application_ids) == 1 || return nothing - length(binding.callee_application_ids) == 1 || return nothing - application_id = only(affected_application_ids) - application = _compiled_application_by_id(compiled, application_id) - batches = AbstractExecutionBatch[ - batch for batch in execution_batches - if batch.application.id == application_id - ] - isempty(batches) && return false - last_old_id = last(last(batches).targets).object_id - all( - object_id -> _object_id_isless(last_old_id, object_id), - changed_ids, - ) || return false - found_boundary, boundary = _sorted_object_id_position( - binding.callee_object_ids, - last_old_id, - ) - found_boundary || return false - for index in (boundary + 1):lastindex(binding.callee_object_ids) - object_id = binding.callee_object_ids[index] - first( - _sorted_object_id_position( - application.target_ids, - object_id, - ), - ) || continue - first( - _sorted_object_id_position( - changed_ids, - object_id, - ), - ) || return false - end - destination_batch = last(batches) - for object_id in changed_ids - execution_target = _compiled_model_execution_target( - compiled, - env_bindings, - application, - object_id, - temporal_streams, - output_retention, - constants; - owner=_execution_call_owner(binding), - ) - _model_execution_batch_accepts_target( - destination_batch, - execution_target, - env_bindings, - application, - ) || return false - push!(staged, (destination_batch.targets, execution_target)) + _preflight_current_execution_calls(scope, context.calls, current_call_bindings, + compiled, env_bindings) || return nothing + staged = _execution_append_intent_buffer(scope) + staged_bindings = _execution_binding_intent_buffer(scope) + for call_index in eachindex(context.calls) + extended = _with_current_execution_call(scope, context.calls, + current_call_bindings, call_index) do call_targets, binding + _compiled_call_name(call_targets.binding) == _compiled_call_name(binding) || return nothing + _stage_execution_binding!(staged_bindings, scope, call_targets, binding) || return nothing + _compiled_call_mode(binding) === :initializer && return true + execution_batches = _cached_call_execution_batches(call_targets) + isnothing(execution_batches) && return true + schema = call_targets.batch_schema + _execution_call_batches_match_applications(schema, execution_batches, + binding.callee_application_ids) || return nothing + changed_ids, affected_application_ids = _pure_addition_changed_call_target_ids(binding, compiled) + isempty(changed_ids) && return true + length(affected_application_ids) == 1 || return nothing + length(binding.callee_application_ids) == 1 || return nothing + application_id = only(affected_application_ids) + return _compiled_application_by_id(compiled, application_id) do application + application_schema = _call_batch_schema_for_application(schema, application) + batches = _execution_call_batches_for_application(schema, application_schema, + execution_batches, application_id) + isempty(batches) && return false + admission = _call_cohort_admission(application_schema, OpenExecutionCohortSchema()) + return _with_execution_batch(application_schema, last(batches)) do destination_batch + last_old_id = last(destination_batch.targets).object_id + all(object_id -> _object_id_isless(last_old_id, object_id), changed_ids) || return false + found_boundary, boundary = _sorted_object_id_position(binding.callee_object_ids, last_old_id) + found_boundary || return false + for index in (boundary + 1):lastindex(binding.callee_object_ids) + object_id = binding.callee_object_ids[index] + first(_sorted_object_id_position(application.target_ids, object_id)) || continue + first(_sorted_object_id_position(changed_ids, object_id)) || return false + end + for object_id in changed_ids + execution_target = _compiled_model_execution_target( + compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants; + owner=_execution_call_owner(binding), cohort_schema=admission) + accepted = _with_execution_cohort_target(admission, execution_target) do actual + _model_execution_batch_accepts_target(destination_batch, + actual, env_bindings, application) || return false + return _stage_execution_append!(staged, scope, call_targets, + binding, destination_batch.targets, actual) + end + accepted || return false + end + return true + end + end end + isnothing(extended) && return nothing + extended || return false end - for (targets, execution_target) in staged - push!(targets, execution_target) - end - for (call_targets, binding) in staged_bindings - call_targets.binding = binding - _record_extended_call_execution_batch_cache!( - call_targets, - compiled, - env_bindings, - binding, - ) - end + _commit_execution_call_extension!(scope, staged, staged_bindings, + compiled, env_bindings) || return false target.call_bindings = current_call_bindings - target.call_bindings_signature = - _call_bindings_signature(current_call_bindings) + target.call_bindings_signature = _call_bindings_signature(current_call_bindings) target.call_context_cache.transient = nothing - _runtime_performance_count!( - performance, - :execution_target_call_delta_extensions, - ) - _runtime_performance_count!( - performance, - :execution_target_call_delta_targets_added, - length(staged), - ) + _runtime_performance_count!(performance, :execution_target_call_delta_extensions) + _runtime_performance_count!(performance, :execution_target_call_delta_targets_added, length(staged)) return true end @@ -4367,6 +4267,7 @@ function _refresh_model_execution_group!( changed_object_ids, ) previous_membership = isnothing(previous_group) ? nothing : previous_group.membership + target_schema = isnothing(previous_membership) ? OpenExecutionCohortSchema() : previous_membership.schema calls_extended = Ref(false) refreshed = refresh_cohort_membership!( cohorts, application.id, application.target_ids, changed_object_ids; @@ -4388,14 +4289,15 @@ function _refresh_model_execution_group!( end target = _new_model_execution_target( compiled, env_bindings, application, object_id, - temporal_streams, output_retention, constants, + temporal_streams, output_retention, constants; target_schema, ) _count_model_execution_target_rebuild!(performance, reason) return target end assembled = _model_execution_batches( env_bindings, application, refreshed.membership, - output_retention, previous_group, + output_retention, previous_group; + batch_schema=_execution_group_batch_schema(previous_group), ) reused_group = !isnothing(previous_group) && previous_group.application === application && @@ -4416,7 +4318,8 @@ function _refresh_model_execution_group!( previous_group else _retain_execution_group(previous_group, _compiled_application_execution_group( - application, assembled.batches, refreshed.membership, + application, assembled.batches, refreshed.membership; + batch_schema=_execution_group_batch_schema(previous_group), )) end if !isnothing(group) && group === previous_group && group_changed @@ -4444,28 +4347,108 @@ function _changed_execution_target_ids_by_application(changed_execution_target_i return changed_by_application end -# Prefer the existing authored position without building a Dict of group -# objects. Reordered application metadata still matches the old owner by id. -# Only scalar refresh counts leave the concrete group callback, never a group. -function _with_previous_execution_group(f, slots, application_id::Symbol, - preferred_slot::Int, visited::BitVector, +# The ordinary open representation can learn a new group schema. A closed +# tuple must enter the worker with an already admitted application witness. +function _with_matching_previous_execution_group(f, group, application::A, + ::Tuple, +) where {A<:CompiledModelApplication} + group isa CompiledApplicationExecutionGroup{A} || return nothing + group.application.id === application.id || return nothing + group.application.slot == application.slot || return nothing + return f(group)::NTuple{3,Int} +end + +function _with_matching_previous_execution_group(f, group, application, + ::AbstractVector, ) + isnothing(group) && return nothing + group.application.id === application.id || return nothing + return f(group)::NTuple{3,Int} +end + +_missing_previous_execution_group(f, ::AbstractVector, application) = + f(nothing)::NTuple{3,Int} + +function _missing_previous_execution_group(f, ::Tuple, application) + throw(ArgumentError( + "The prepared execution-group schema has no matching application " * + "`$(application.id)` at slot $(application.slot). Prepare its group before execution.", + )) +end + +# Prefer the current authored position, then search the existing owners by id. +# Only scalar counts leave the concrete callback; there is one lookup loop for +# both representations. Incompatible closed application types never enter f. +function _with_previous_execution_group(f, slots, application::CompiledModelApplication, + visited::BitVector, +) + preferred_slot = application.slot for candidate in 0:length(slots) slot = iszero(candidate) ? preferred_slot : candidate (slot < 1 || slot > length(slots) || (!iszero(candidate) && slot == preferred_slot)) && continue counts = _with_metadata_entry(slots, slot) do group - if !isnothing(group) && group.application.id === application_id - return f(group)::NTuple{3,Int} - end - return nothing + _with_matching_previous_execution_group(f, group, application, slots) end if !isnothing(counts) visited[slot] = true return counts end end - return f(nothing)::NTuple{3,Int} + return _missing_previous_execution_group(f, slots, application) +end + +# Validate each CURRENT entry before it reaches metadata readers. Literal +# tuple fields close the container without constructing Tuple(values) with a +# runtime arity, reordering application ids, or recreating any live group. +_execution_groups_in_schema(::AbstractVector, groups) = groups + +@generated function _execution_groups_in_schema(::G, groups) where {G<:Tuple} + count = fieldcount(G) + values = [gensym(:group) for _ in 1:count] + statements = Any[] + for (index, (value, type)) in enumerate(zip(values, fieldtypes(G))) + push!(statements, :($value = groups[$index])) + push!(statements, :($value isa $type || throw(ArgumentError( + "A refreshed execution group is outside the prepared tuple schema at position " * + string($index) * ".", + )))) + end + result = Expr(:tuple, [:( $(values[index])::$(fieldtype(G, index)) ) + for index in 1:count]...) + return quote + length(groups) == $count || throw(ArgumentError( + "The refreshed execution-group count differs from its prepared tuple schema.", + )) + $(statements...) + return $result + end +end + +# A known closed layout mismatch is an admission error. Validate metadata +# coverage and CURRENT schedule order before any membership/cohort worker runs. +# This does not promise rollback of earlier lifecycle or binding preparation. +_preflight_execution_group_layout!(previous, compiled, ::AbstractVector) = nothing + +function _preflight_execution_group_layout!(previous, compiled, slots::Tuple) + witnesses = CompiledApplicationExecutionGroup[] + visited = falses(length(slots)) + for entry in compiled.scenario_plan.application_schedule.entries + _with_metadata_entry(compiled.applications_by_id,entry.application_id) do application + _with_previous_execution_group(slots,application,visited) do group + push!(witnesses,group) + return (0,0,0) + end + return nothing + end + end + # The witnesses remain the actual old owners in the NEW scheduler order. + # Never reorder them back to the prepared ids to make a cast succeed. + groups = _execution_groups_in_schema(previous.groups,witnesses) + current_slots = _execution_groups_by_application_slot(groups, + length(compiled.scenario_plan.applications)) + _execution_groups_in_schema(slots,current_slots) + return nothing end function _refresh_model_execution_plan( @@ -4484,6 +4467,7 @@ function _refresh_model_execution_plan( changed_execution_target_ids, ) previous_slots = previous.groups_by_application_slot + _preflight_execution_group_layout!(previous,compiled,previous_slots) visited_slots = falses(length(previous_slots)) groups = CompiledApplicationExecutionGroup[] batches = AbstractExecutionBatch[] @@ -4496,8 +4480,8 @@ function _refresh_model_execution_plan( # call-only applications are already excluded by that same schedule. for entry in compiled.scenario_plan.application_schedule.entries counts = _with_metadata_entry(compiled.applications_by_id, entry.application_id) do application - _with_previous_execution_group(previous_slots, application.id, - application.slot, visited_slots, + _with_previous_execution_group(previous_slots, application, + visited_slots, ) do previous_group if !isnothing(previous_group) && !isnothing(changed_application_ids) && !(application.id in changed_application_ids) @@ -4530,25 +4514,29 @@ function _refresh_model_execution_plan( _with_metadata_entry(previous_slots, slot) do group isnothing(group) && return nothing for object_id in group.membership.object_ids - remove_cohort_target!(previous.cohorts, group.application.id, object_id) + remove_cohort_target!(previous.cohorts, group.application.id, object_id; schema=group.membership.schema) end return nothing end end - same_groups = _same_execution_members(previous.groups, groups) + groups_in_schema = _execution_groups_in_schema(previous.groups, groups) + same_groups = _same_execution_members(previous.groups, groups_in_schema) same_batches = _same_execution_members(previous.batches, batches) application_count = length(compiled.scenario_plan.applications) groups_by_slot = same_groups && length(previous.groups_by_application_slot) == application_count ? previous.groups_by_application_slot : - _execution_groups_by_application_slot(groups, application_count) + _execution_groups_by_application_slot(groups_in_schema, application_count) + slots_in_schema = _execution_groups_in_schema( + previous.groups_by_application_slot, groups_by_slot, + ) return ( plan=CompiledExecutionPlan( previous.cohorts, previous.topology, - same_groups ? previous.groups : groups, + same_groups ? previous.groups : groups_in_schema, same_batches ? previous.batches : batches, - groups_by_slot, + slots_in_schema, _refreshed_runtime_application_schedule(previous.schedule, compiled.scenario_plan.application_schedule), compiled.revision, @@ -4941,11 +4929,19 @@ end _call_target_matches(targets::CallTargets, application, object_id::ObjectId) = _call_binding_target_matches(targets.binding, application, object_id) +@inline function _with_call_execution_batch(f::F, targets::CallTargets, batches, index::Int) where {F} + return _with_metadata_entry(batches, index) do batch + _with_execution_batch(f, targets.batch_schema, batch) + end +end + function Base.length(targets::CallTargets) count = 0 batches = _materialize_call_execution_batches!(targets) - for batch in batches - count += length(batch.targets) + for index in eachindex(batches) + count += _with_call_execution_batch(targets, batches, index) do batch + length(batch.targets) + end end return count end @@ -4989,7 +4985,8 @@ end _runtime_call_targets( targets.compiled, targets.environment_bindings, target.call_bindings, targets.temporal_streams, targets.output_retention, targets.time, - targets.constants, targets.publication_allowed, environment, + targets.constants, targets.publication_allowed, environment; + call_schema=_context_call_schema(context), ) end else @@ -5037,13 +5034,18 @@ end function Base.getindex(targets::CallTargets, requested::Int) batches = _materialize_call_execution_batches!(targets) - current = 0 - for batch in batches - for target in batch.targets - current += 1 - current == requested && - return _materialize_call(targets, batch.application, target) + remaining = requested + for index in eachindex(batches) + count, selected = let position=remaining + _with_call_execution_batch(targets, batches, index) do batch + batch_count = length(batch.targets) + target = 1 <= position <= batch_count ? + _materialize_call(targets, batch.application, batch.targets[position]) : nothing + return batch_count, target + end end + isnothing(selected) || return selected + remaining -= count end throw(BoundsError(targets, (requested,))) end @@ -5052,14 +5054,15 @@ function Base.iterate(targets::CallTargets, state::Tuple{Int,Int}=(1, 1)) batch_index, target_index = state batches = _materialize_call_execution_batches!(targets) while batch_index <= length(batches) - batch = batches[batch_index] - if target_index <= length(batch.targets) - target = batch.targets[target_index] - return ( - _materialize_call(targets, batch.application, target), - (batch_index, target_index + 1), - ) + selected = let batch_position=batch_index, target_position=target_index + _with_call_execution_batch(targets, batches, batch_position) do batch + target_position <= length(batch.targets) || return nothing + target = batch.targets[target_position] + return (_materialize_call(targets, batch.application, target), + (batch_position, target_position + 1)) + end end + isnothing(selected) || return selected batch_index += 1 target_index = 1 end @@ -5103,26 +5106,34 @@ end return entry end -function _refill_call_target_buffer!(values::Vector{V}, targets, batches::Tuple) where {V} +function _refill_call_target_buffer!(values::Vector{V}, targets::CallTargets, + batches::Union{Tuple,AbstractVector}, +) where {V} count = 0 - for batch in batches - count += length(batch.targets) + for index in eachindex(batches) + count += _with_call_execution_batch(targets, batches, index) do batch + length(batch.targets) + end end resize!(values, count) - index = 0 - for batch in batches - for target in batch.targets - index += 1 - # A concrete constructor lets Julia write immutable views directly - # into inline vector storage, without a boxed temporary per target. - # Mixed collections keep Base's widened element type instead. - view = if isconcretetype(V) - _materialize_call(V, targets, batch.application, target) - else - _materialize_call(targets, batch.application, target) + written = 0 + for index in eachindex(batches) + next_count = let offset=written + _with_call_execution_batch(targets, batches, index) do batch + for (local_index, target) in enumerate(batch.targets) + # Keep the same concrete snapshot constructor for inline + # homogeneous buffers; heterogeneous vectors widen normally. + view = if isconcretetype(V) + _materialize_call(V, targets, batch.application, target) + else + _materialize_call(targets, batch.application, target) + end + @inbounds values[offset + local_index] = view + end + return length(batch.targets) end - @inbounds values[index] = view end + written += next_count end return values end @@ -5363,17 +5374,22 @@ end return _single_call_target_snapshot(targets, batch.application, batch.targets[1]) end -function _only_call_target(targets::CallTargets, batches::Tuple) +function _only_call_target(targets::CallTargets, batches::Union{Tuple,AbstractVector}) count = 0 - selected_batch = nothing - for batch in batches - isempty(batch.targets) && continue - count += length(batch.targets) + selected_index = 0 + for index in eachindex(batches) + next_count = _with_call_execution_batch(targets, batches, index) do batch + length(batch.targets) + end + iszero(next_count) && continue + count += next_count count == 1 || _only_call_target_count_error(count) - selected_batch = batch + selected_index = index end iszero(count) && _only_call_target_count_error(count) - return _single_call_target_snapshot(targets, selected_batch.application, selected_batch.targets[1]) + return _with_call_execution_batch(targets, batches, selected_index) do batch + _single_call_target_snapshot(targets, batch.application, batch.targets[1]) + end end # Reuse only indistinguishable immutable snapshots; all numerical state is @@ -5417,12 +5433,25 @@ Base.@constprop :aggressive function call_targets( return _with_named_call(_selected_call_targets, context.calls, name, context, requested_ids) end -@inline function _single_call_model(batches::Tuple{B}) where {B} +@inline function _single_call_model(targets::CallTargets, batches::Tuple{B}) where {B} # The caller has already checked singular membership. Index directly rather # than allocating the Vector iterator's (target, state) tuple on this path. return first(batches).targets[1].model end +function _single_call_model(targets::CallTargets, batches::Union{Tuple,AbstractVector}) + # Singular membership was checked by call_model. Empty retained runs do not + # choose a model; every real payload remains in its admitted batch branch. + for index in eachindex(batches) + model = _with_call_execution_batch(targets, batches, index) do batch + isempty(batch.targets) && return nothing + return batch.targets[1].model + end + isnothing(model) || return model + end + _only_call_target_count_error(0) +end + """ call_model(context::RunContext, name::Symbol) @@ -5458,7 +5487,7 @@ end _compiled_call_mode(targets.binding) === :manual || _initializer_requires_dedicated_api(context, name) length(targets) == 1 || _call_model_target_count_error(name, targets) - return _single_call_model(_materialize_call_execution_batches!(targets)) + return _single_call_model(targets, _materialize_call_execution_batches!(targets)) end @inline Base.@constprop :aggressive function call_model(context::RunContext, name::Symbol) @@ -5866,6 +5895,7 @@ function _targeted_new_object_call_targets( return _prepare_targeted_newborn_targets( context, name, targeted_runtime, application_set, callee_applications, initializer, + cached_targets.batch_schema, ) end @@ -5879,6 +5909,7 @@ function _prepare_targeted_newborn_targets( application_set::_TargetedApplicationSet, callee_applications::Tuple, initializer::Bool, + batch_schema::ExecutionBatchSchema, ) model = runtime_model(context) compiled = context.compiled @@ -5951,7 +5982,7 @@ function _prepare_targeted_newborn_targets( for partial_application in callee_applications _append_targeted_newborn_targets!( targets, context, targeted_runtime, partial_application, - targeted_input_bindings, environment_bindings, + targeted_input_bindings, environment_bindings, batch_schema, ) end if initializer @@ -5970,42 +6001,60 @@ function _append_targeted_newborn_targets!( partial_application::CompiledModelApplication, targeted_input_bindings, environment_bindings::CompiledEnvironmentBindings, + batch_schema::ExecutionBatchSchema, ) compiled = context.compiled - # A partial application preserves its exact plan type. Recover that type - # after the heterogeneous application index before constructing its rows. - application = compiled.applications_by_id[partial_application.id]::typeof(partial_application) - for object_id in partial_application.target_ids - key = (application.id, object_id) - cache = get(targeted_runtime.call_context_caches, key, nothing)::Union{Nothing,CallContextCache} - stamp = isnothing(cache) ? Ref(UInt64(0)) : - (getfield(cache, :execution_stamp)::Base.RefValue{UInt64}) - status_view = _compile_model_status_view( - runtime_model(context), partial_application, object_id, - get(targeted_input_bindings, key, ()), compiled.applications_by_id, - targeted_runtime.application_positions, compiled.distributed_outputs; - execution_stamp=stamp, - ) - outputs = _runtime_model_output_streams( - status_view.status, application, object_id, context.temporal_streams, - context.output_retention, true, - ) - output_targets = _runtime_model_output_targets(compiled, application, object_id) - environment_binding = _environment_binding_for(environment_bindings, application.id, object_id) - # Targeted admission has already resolved this callee without nested - # calls. The general payload/cache helper accepts the actual tuple; - # nested manual newborns retain their existing full-refresh path. - call_bindings = () - if isnothing(cache) - cache = _newborn_call_context_cache(context, application, object_id, - status_view.bound_inputs, output_targets, call_bindings, environment_bindings, stamp) - targeted_runtime.call_context_caches[key] = cache + # Partial applications share the genuine authored application plan. + _compiled_application_by_id(compiled,partial_application.id) do application + application_schema = _call_batch_schema_for_application(batch_schema,application) + admission = _call_cohort_admission(application_schema,OpenExecutionCohortSchema()) + for object_id in partial_application.target_ids + key = (application.id,object_id) + cache = get(targeted_runtime.call_context_caches,key,nothing)::Union{Nothing,CallContextCache} + stamp = isnothing(cache) ? Ref(UInt64(0)) : + (getfield(cache,:execution_stamp)::Base.RefValue{UInt64}) + status_view = _compile_model_status_view(runtime_model(context),partial_application, + object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, + targeted_runtime.application_positions,compiled.distributed_outputs; + execution_stamp=stamp) + output_targets = _runtime_model_output_targets(compiled,application,object_id) + environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) + call_bindings = () # targeted admission has rejected nested callees + fields = (object_id=object_id,model=_application_model(application,object_id), + status_view=status_view,bound_inputs=status_view.bound_inputs, + output_targets=output_targets,call_bindings=call_bindings, + environment_binding=environment_binding) + owners = (compiled=compiled,temporal_streams=context.temporal_streams, + output_retention=context.output_retention,constants=context.constants, + environment=context.environment) + _with_execution_target_type(admission,application,fields,owners) do Target,actual_application,actual,owner,call_schema + outputs = isnothing(Target) ? + _runtime_model_output_streams(actual.status_view.status,actual_application, + actual.object_id,owner.temporal_streams,owner.output_retention,true) : + _prepared_runtime_outputs(fieldtype(Target,:output_bindings), + actual.status_view.status,actual.output_targets,actual_application, + actual.object_id,owner.compiled,owner.temporal_streams, + owner.output_retention,true) + # Narrow a retained cache before use; no new owner is published + # until all real fields have passed the same target admission. + prepared_cache = _admit_newborn_context_cache(Target,cache) + if isnothing(prepared_cache) + prepared_cache = _newborn_call_context_cache(context,actual_application, + actual.object_id,actual.bound_inputs,actual.output_targets, + actual.call_bindings,environment_bindings,stamp;call_schema) + end + result = _targeted_newborn_call_target(context,actual_application, + actual.object_id,actual.model,actual.status_view,outputs, + actual.output_targets,actual.call_bindings,environment_bindings, + actual.environment_binding,prepared_cache) + isnothing(Target) || result.execution_target isa Target || + throw(ArgumentError("A newborn execution target is outside its prepared schema.")) + targeted_runtime.call_context_caches[key] = prepared_cache + push!(targets,result) + return nothing + end end - push!(targets, _targeted_newborn_call_target( - context, application, object_id, _application_model(application, object_id), - status_view, outputs, output_targets, call_bindings, - environment_bindings, environment_binding, cache, - )) + return nothing end return targets end @@ -6027,13 +6076,14 @@ end # Call bindings come from resolution, not from the shape of a cached prototype. function _newborn_call_context_cache(context::RunContext, application, object_id, bound_inputs, output_targets, call_bindings::Tuple, environment_bindings, - stamp::Base.RefValue{UInt64}, + stamp::Base.RefValue{UInt64}; + call_schema=OpenContextCallSchema(), ) prepared = _prepare_model_execution_context!( nothing, context.compiled, environment_bindings, application, object_id, bound_inputs, output_targets, call_bindings, context.temporal_streams, context.output_retention, context.time, context.constants, - context.publication_allowed, context.environment, + context.publication_allowed, context.environment;call_schema, ) return CallContextCache(prepared, stamp) end @@ -6201,6 +6251,7 @@ function _current_topology_call_targets( context.environment, ; tracks_full_membership=false, + batch_schema=cached_targets.batch_schema, ) end @@ -6691,6 +6742,26 @@ end return nothing end +# Prepared Many keeps an ordered runtime vector. Both representations enter +# the same batch and target executor after their normal metadata admission. +@inline function _run_compiled_call_batches!( + targets::CallTargets, + batches::AbstractVector, + publish::Bool, + sampled_environment, + environment, + frame, +) + for index in eachindex(batches) + _with_call_execution_batch(targets, batches, index) do batch + _run_compiled_call_batch!( + targets, batch, publish, sampled_environment, environment, frame, + ) + end + end + return nothing +end + function _run_call_targets!( targets::CallTargets, publish::Bool, diff --git a/test/runtests.jl b/test/runtests.jl index f069fd38c..c85e12c0f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -26,6 +26,10 @@ if length(ARGS) == 1 && endswith(only(ARGS), ".jl") focused_path = joinpath(@__DIR__, focused_file) isfile(focused_path) || error("Unknown focused test file `$(focused_file)`.") @testset "Focused: $(focused_file)" begin + if focused_file in ("test-model-prepared-call-vector-api.jl", + "test-model-prepared-missing-future-schema.jl") + include("test-model-prepared-call-schemas.jl") + end include(focused_path) end else @@ -54,6 +58,17 @@ else include("test-model-slot-group-refresh.jl") end + @testset "Prepared execution schemas" begin + include("test-model-closed-cohort-schemas.jl") + include("test-model-closed-group-refresh.jl") + include("test-model-closed-group-layout-preflight.jl") + include("test-model-prepared-call-schemas.jl") + include("test-model-prepared-call-vector-api.jl") + include("test-model-prepared-growth-schemas.jl") + include("test-model-prepared-missing-future-schema.jl") + include("test-model-finite-call-extension-intents.jl") + end + @testset "Organ creation allocations" begin include("test-organ-creation-allocation.jl") end diff --git a/test/test-model-call-context-cloning.jl b/test/test-model-call-context-cloning.jl index 2d998939e..a9f5e87e9 100644 --- a/test/test-model-call-context-cloning.jl +++ b/test/test-model-call-context-cloning.jl @@ -175,7 +175,7 @@ end @test cloned.execution_batches !== original.execution_batches @test cloned.execution_batches.owner === cloned @test original.execution_batches.owner === original - @test cloned.execution_batches.tracks_full_membership + @test cloned.tracks_full_membership @test isnothing(cloned.execution_batches.batches) end end diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl new file mode 100644 index 000000000..8db6c793c --- /dev/null +++ b/test/test-model-closed-cohort-schemas.jl @@ -0,0 +1,345 @@ +module ClosedCohortSchemaChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine + +mutable struct Target{I,S,C} + object_id::I + status::S + context::C +end +make_target(id, value) = Target(ObjectId(id), Status(value=value), Ref(0)) +ids(values) = ObjectId{Int}[ObjectId(value) for value in values] +flatten(membership) = [target for rows in membership.runs for target in rows] +schema_for(targets...) = PSE._closed_execution_cohort_schema(Tuple{map(typeof, targets)...}) + +function refresh(store, targets, current, changed=nothing; previous=nothing, owner=nothing, schema=PSE.OpenExecutionCohortSchema()) + PSE.refresh_cohort_membership!(store, :growth, ids(current), isnothing(changed) ? nothing : ids(changed); + previous, owner, schema) do object_id, old + targets[object_id] + end +end + +@testset "closed replacement admits old and new payloads before clearing" begin + store = PSE.ExecutionCohortStore() + first, last = make_target(1, 1.0), make_target(3, 3.0) + changed = make_target(1, 5.0f0) + schema = schema_for(first, changed) + targets = Dict{ObjectId,Any}(first.object_id => first, last.object_id => last) + membership = refresh(store, targets, (1, 3); schema).membership + old_rows = only(membership.runs) + first_location = PSE.cohort_location(store, :growth, first.object_id) + last_location = PSE.cohort_location(store, :growth, last.object_id) + last_reference = PSE.refvalue(last.status, :value) + @test isconcretetype(fieldtype(typeof(first_location), :cohort)) + @test eltype(membership.object_ids) === ObjectId{Int} + @test eltype(membership.locations) !== PSE.ExecutionCohortLocation + @test eltype(membership.runs) !== PSE.ExecutionCohortRows + + targets[first.object_id] = changed + replaced = refresh(store, targets, (1, 3), (1,); previous=membership, schema) + @test replaced.membership === membership + @test flatten(membership) == [changed, last] + @test isnothing(first_location.cohort.rows[first_location.row]) + @test Base.last(membership.runs) === old_rows + @test old_rows.indices == [last_location.row] + @test only(old_rows) === last + @test_throws ArgumentError PSE._execution_cohort_target(first_location) + @test PSE.cohort_location(store, :growth, last.object_id) === last_location + @test PSE.refvalue(last.status, :value) === last_reference + + targets[first.object_id] = first + restored = refresh(store, targets, (1, 3), (1,); previous=membership, schema) + @test flatten(restored.membership) == [first, last] + @test PSE.cohort_location(store, :growth, first.object_id) === first_location + @test PSE.refvalue(last.status, :value) === last_reference +end + +@testset "root and distinct calls keep separate execution owners" begin + store = PSE.ExecutionCohortStore() + root = make_target(1, 2.0) + first_call = Target(root.object_id, root.status, Ref(1)) + second_call = Target(root.object_id, root.status, Ref(2)) + owners = (nothing, + (:first, ObjectId(10), :call, :manual), + (:second, ObjectId(20), :call, :manual)) + schema = schema_for(root) + memberships = map(zip(owners, (root, first_call, second_call))) do (owner, target) + refresh(store, Dict{ObjectId,Any}(target.object_id => target), (1,); owner, schema).membership + end + @test length(unique([only(membership.runs).cohort for membership in memberships])) == 3 + @test all(membership -> only(flatten(membership)).status === root.status, memberships) + @test collect(map(membership -> only(flatten(membership)).context[], memberships)) == [0, 1, 2] + called = Ref(false) + foreign = PSE.cohort_location(store, :growth, root.object_id; owner=owners[2]) + @test_throws ArgumentError PSE._with_execution_cohort_location(schema, foreign, + owners[3], :growth, root.object_id) do admitted + called[] = true + end + @test !called[] + @test PSE.remove_cohort_target!(store, :growth, root.object_id; owner=owners[2], schema) + @test only(flatten(memberships[1])) === root + @test only(flatten(memberships[3])) === second_call +end + +@testset "removing an interleaved family preserves order and merges runs" begin + store = PSE.ExecutionCohortStore() + first, middle, last = make_target(1, 1.0), make_target(2, 2.0f0), make_target(3, 3.0) + targets = Dict{ObjectId,Any}(target.object_id => target for target in (first, middle, last)) + schema = schema_for(first, middle) + membership = refresh(store, targets, 1:3; schema).membership + @test length(membership.runs) == 3 + original_left = Base.first(membership.runs) + original_last = PSE.cohort_location(store, :growth, last.object_id) + removed = refresh(store, targets, (1, 3), (2,); previous=membership, schema) + @test removed.targets_removed == 1 + @test only(membership.runs) === original_left + @test membership.run_starts == [1] + @test flatten(membership) == [first, last] + @test PSE.cohort_location(store, :growth, last.object_id) === original_last + @test getproperty.(flatten(membership), :object_id) == ids((1, 3)) +end + +@testset "an empty future schema creates no target or scientific default" begin + S = Status{(:value,),Tuple{Base.RefValue{Float64}}} + T = Target{ObjectId{Int},S,Base.RefValue{Int}} + schema = PSE._closed_execution_cohort_schema(Tuple{T}) + store = PSE.ExecutionCohortStore() + calls = Ref(0) + created = Ref{Any}() + builder = (object_id, old) -> begin + calls[] += 1 + created[] = make_target(object_id.value, 3.0) + end + membership = PSE.refresh_cohort_membership!(builder, store, :growth, ids(()), nothing; schema).membership + @test calls[] == 0 + @test !isassigned(created) + @test isempty(store.cohorts) && isempty(store.locations) + @test isempty(membership.runs) && isempty(membership.locations) + @test eltype(membership.object_ids) === ObjectId{Int} + added = PSE.refresh_cohort_membership!(builder, store, :growth, ids((7,)), ids((7,)); previous=membership) + @test calls[] == 1 + witness = created[] + location = PSE.cohort_location(store, :growth, witness.object_id) + @test only(flatten(added.membership)) === witness + PSE.refresh_cohort_membership!(builder, store, :growth, ids(()), ids((7,)); previous=membership) + @test isempty(membership.runs) + @test isnothing(location.cohort.rows[location.row]) + PSE.refresh_cohort_membership!(builder, store, :growth, ids((7,)), ids((7,)); previous=membership) + @test calls[] == 2 + @test PSE.cohort_location(store, :growth, witness.object_id) === location + @test only(flatten(membership)) === created[] + @test created[] !== witness +end + +@testset "schema and identity admission precede any removal or splice" begin + store = PSE.ExecutionCohortStore() + first, second = make_target(1, 1.0), make_target(2, 2.0) + schema = schema_for(first) + targets = Dict{ObjectId,Any}(first.object_id => first, second.object_id => second) + membership = refresh(store, targets, (1, 2); schema).membership + original_ids = copy(membership.object_ids) + original_runs = copy(membership.runs) + original_locations = copy(membership.locations) + targets[second.object_id] = make_target(2, 2.0f0) + @test_throws ArgumentError refresh(store, targets, (2,), (1, 2); previous=membership, schema) + @test membership.object_ids == original_ids + @test all(a === b for (a, b) in zip(membership.runs, original_runs)) + @test membership.locations == original_locations + @test flatten(membership) == [first, second] + @test length(store.locations) == 2 + @test_throws ArgumentError PSE.refresh_cohort_membership!((id, old) -> first, + store, :growth, ObjectId[ObjectId(:foreign)], nothing; schema) + @test flatten(membership) == [first, second] + + # A same-family append must never silently clear a different family. + changed = make_target(1, 4.0f0) + changed_rows = PSE.cohort_rows!(store, :growth, [changed]) + rows = original_runs[1] + @test_throws ArgumentError PSE._append_execution_cohort_target!(rows, first) + @test length(rows) == 2 + @test changed_rows[1] === changed + @test isnothing(original_locations[1].cohort.rows[original_locations[1].row]) +end + +PSE.@process "closed_cohort_owner" verbose=false +PSE.@process "closed_cohort_middle" verbose=false +PSE.@process "closed_cohort_leaf" verbose=false +struct Owner{C} <: AbstractClosed_Cohort_OwnerModel + capture::C +end +struct Middle <: AbstractClosed_Cohort_MiddleModel end +struct Leaf <: AbstractClosed_Cohort_LeafModel end +PSE.outputs_(::Owner) = (owner_visits=0,) +PSE.outputs_(::Middle) = (middle_visits=0,) +PSE.outputs_(::Leaf) = (leaf_visits=0,) +function PSE.run!(model::Owner, status, environment, constants, context) + model.capture[] = context + run_call!(context, :middle; publish=true) + status.owner_visits += 1 + return nothing +end +function PSE.run!(::Middle, status, environment, constants, context) + run_call!(context, :leaf; publish=true) + status.middle_visits += 1 + return nothing +end +PSE.run!(::Leaf, status, environment, constants, context) = (status.leaf_visits += 1; nothing) + +@testset "real two-level calls remain outside the runtime store type" begin + capture = Ref{Any}() + model = CompositeModel(Object(:plant; scale=:Plant); applications=( + ModelSpec(Owner(capture); name=:owner, on=One(id=:plant), + calls=(middle=One(within=Self(), application=:middle),)), + ModelSpec(Middle(); name=:middle, on=One(id=:plant), + calls=(leaf=One(within=Self(), application=:leaf),)), + ModelSpec(Leaf(); name=:leaf, on=One(id=:plant)), + )) + simulation = run!(model; steps=1, outputs=:all) + state = model_status(model, :plant) + @test (state.owner_visits, state.middle_visits, state.leaf_visits) == (1, 1, 1) + middle = only(call_targets(capture[], :middle)) + batches = capture[].calls[1].execution_batches + schema = PSE._execution_cohort_schema(batches) + @test schema isa PSE.ClosedExecutionCohortSchema + @test fieldtype(typeof(only(batches).targets), :store) === PSE.ExecutionCohortStore + @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === PSE.ExecutionCohortStore + @test typeof(simulation.temporal_streams.cohorts) === PSE.ExecutionCohortStore + owner = PSE._execution_call_owner(capture[].calls[1].binding) + location = PSE.cohort_location(simulation.temporal_streams.cohorts,:middle, + ObjectId(:plant);owner) + @test PSE._execution_cohort_target(location) === middle.execution_target + original_context = middle.context_cache.default + original_stamp = middle.context_cache.execution_stamp + middle_reference = PSE.refvalue(state,:middle_visits) + leaf_reference = PSE.refvalue(state,:leaf_visits) + @test isnothing(PSE._model_execution_target_change_reason(middle.execution_target, + middle.compiled,middle.environment_bindings,middle.application, + middle.output_retention,middle.temporal_streams)) + rebuilt = PSE._compiled_call_execution_batches(middle.compiled, middle.environment_bindings, + capture[].calls[1].binding, middle.temporal_streams, middle.output_retention, middle.constants; + cohort_schema=schema) + @test only(only(rebuilt).targets) === middle.execution_target + @test only(only(rebuilt).targets).context === original_context + @test only(only(rebuilt).targets).call_context_cache === middle.context_cache + @test middle.context_cache.execution_stamp === original_stamp + @test PSE.refvalue(state,:middle_visits) === middle_reference + @test PSE.refvalue(state,:leaf_visits) === leaf_reference + @test (state.owner_visits,state.middle_visits,state.leaf_visits) == (1,1,1) + prototype = middle.context_cache.default + leased = PSE._prepare_cached_call_context!( + middle.context_cache, false, middle.compiled, middle.environment_bindings, + middle.application, middle.object_id, middle.bound_inputs, middle.output_targets, + middle.execution_target.call_bindings, middle.temporal_streams, + middle.output_retention, middle.time, middle.constants, + middle.publication_allowed, middle.environment, + ) + @test leased !== prototype + original_leaf = call_targets(prototype, :leaf) + leased_leaf = call_targets(leased, :leaf) + @test leased_leaf !== original_leaf + @test leased_leaf.execution_batches === original_leaf.execution_batches + original_leaf.last_single_snapshot = (:private_borrowing_marker,) + @test isnothing(leased_leaf.last_single_snapshot) + original_leaf.last_single_snapshot = nothing + @test only(leased_leaf).execution_target === only(original_leaf).execution_target + # This tests the common factory under a supplied witness, not automatic + # closure of cold/lazy calls; that admission boundary remains explicit. + middle_stream = outputs(simulation)[(:middle, ObjectId(:plant), :middle_visits)] + leaf_stream = outputs(simulation)[(:leaf, ObjectId(:plant), :leaf_visits)] + before_middle, before_leaf = collect(middle_stream), collect(leaf_stream) + evaluation = evaluate_call!(middle) + @test (state.middle_visits, state.leaf_visits) == (2, 2) + @test collect(middle_stream) == before_middle + @test collect(leaf_stream) == before_leaf + accept_call!(evaluation) + @test (state.middle_visits, state.leaf_visits) == (2, 2) + @test length(middle_stream) == length(before_middle) + @test length(leaf_stream) == length(before_leaf) + @test last(middle_stream) == (last(before_middle)[1], 2) + @test last(leaf_stream) == (last(before_leaf)[1], 2) + continue!(simulation; steps=1) + @test (state.owner_visits, state.middle_visits, state.leaf_visits) == (2, 3, 3) + @test [sample[2] for sample in middle_stream] == [2, 3] + @test [sample[2] for sample in leaf_stream] == [2, 3] +end + +function closed_append_allocations(count) + store = PSE.ExecutionCohortStore() + first = make_target(1, 1.0) + schema = schema_for(first) + builder = (object_id, old) -> make_target(object_id.value, Float64(object_id.value)) + current = ids(1:count) + membership = PSE.refresh_cohort_membership!(builder, store, :growth, current, nothing; schema).membership + push!(current, ObjectId(count + 1)) + changed = ids((count + 1,)) + return @allocated PSE.refresh_cohort_membership!(builder, store, :growth, current, changed; previous=membership) +end + +@testset "closed append keeps the existing membership allocation budget" begin + closed_append_allocations(8) + small = minimum(closed_append_allocations(8) for _ in 1:2) + large = minimum(closed_append_allocations(4096) for _ in 1:2) + @test large <= small + 4096 +end + +function closed_from_open_append_allocations(count) + store = PSE.ExecutionCohortStore() + builder = (object_id, old) -> make_target(object_id.value, Float64(object_id.value)) + current = ids(1:count) + opened = PSE.refresh_cohort_membership!(builder, store, :growth, current, nothing).membership + original_last = flatten(opened)[end] + original_reference = PSE.refvalue(original_last.status, :value) + original_context = original_last.context + original_run = only(opened.runs) + schema = schema_for(original_last) + closed = PSE._close_execution_cohort_membership(opened, schema) + @test closed !== opened + @test closed.object_ids !== opened.object_ids + @test closed.locations !== opened.locations + @test closed.runs !== opened.runs + @test closed.run_starts !== opened.run_starts + @test only(closed.runs) === original_run + @test flatten(closed) == flatten(opened) + @test PSE._close_execution_cohort_membership(closed, schema) === closed + push!(current, ObjectId(count + 1)) + changed = ids((count + 1,)) + allocated = @allocated PSE.refresh_cohort_membership!(builder, + store, :growth, current, changed; previous=closed) + targets = flatten(closed) + @test closed.object_ids == current + @test getproperty.(targets, :object_id) == current + @test [target.status.value for target in targets] == Float64.(1:(count + 1)) + @test targets[count] === original_last + @test PSE.refvalue(targets[count].status, :value) === original_reference + @test targets[count].context === original_context + @test only(closed.runs) === original_run + return allocated +end + +@testset "host Open to closed preparation preserves the append capacity budget" begin + closed_from_open_append_allocations(8) + small = minimum(closed_from_open_append_allocations(8) for _ in 1:2) + large = minimum(closed_from_open_append_allocations(4096) for _ in 1:2) + @test large <= small + 4096 +end + +@testset "same-schema close validates ownership before reusing its owner" begin + store = PSE.ExecutionCohortStore() + target = make_target(1, 1.0) + schema = schema_for(target) + closed = refresh(store, Dict{ObjectId,Any}(target.object_id => target), (1,); schema).membership + wrong_owner = PSE.ExecutionCohortMembership(closed.store, + (:foreign, ObjectId(99), :call, :manual), closed.application_id, + closed.schema, closed.object_ids, closed.locations, closed.runs, closed.run_starts) + wrong_store = PSE.ExecutionCohortMembership(PSE.ExecutionCohortStore(), + closed.owner, closed.application_id, closed.schema, + closed.object_ids, closed.locations, closed.runs, closed.run_starts) + @test_throws ArgumentError PSE._close_execution_cohort_membership(wrong_owner, schema) + @test_throws ArgumentError PSE._close_execution_cohort_membership(wrong_store, schema) + @test PSE._close_execution_cohort_membership(closed, schema) === closed + @test only(flatten(closed)) === target +end + +end diff --git a/test/test-model-closed-group-layout-preflight.jl b/test/test-model-closed-group-layout-preflight.jl new file mode 100644 index 000000000..d7a1a5608 --- /dev/null +++ b/test/test-model-closed-group-layout-preflight.jl @@ -0,0 +1,96 @@ +module ClosedGroupLayoutPreflightTests +using PlantSimEngine, Test +const PSE = PlantSimEngine +@process "closed_layout_count" verbose=false +struct Count{T} <: AbstractClosed_Layout_CountModel + increment::T +end +PSE.inputs_(::Count) = NamedTuple() +PSE.outputs_(model::Count) = (count=zero(model.increment),) +PSE.run!(model::Count,status,environment,constants,context) = (status.count += model.increment; nothing) + +function fixture() + model = CompositeModel(Object(:a;scale=:A,status=Status(count=0f0)), + Object(:b;scale=:B,status=Status(count=0.0)), + Object(:c;scale=:C,status=Status(count=0f0)); applications=( + ModelSpec(Count(1f0);name=:a,on=Many(scale=:A)), + ModelSpec(Count(1.0);name=:b,on=Many(scale=:B)), + ModelSpec(Count(1f0);name=:c,on=Many(scale=:C)))) + simulation = run!(model;steps=0,outputs=:none) + plan = simulation.execution_plan + closed = PSE.CompiledExecutionPlan(plan.cohorts,plan.topology,Tuple(plan.groups), + plan.batches,Tuple(plan.groups_by_application_slot),plan.schedule, + plan.model_revision,plan.environment_revision) + return simulation,closed +end + +# Host-only metadata projection uses the canonical scheduler definition and the +# genuine application plans. Scientific objects, statuses and refs are shared. +function with_order(compiled,order) + order = Tuple(order) # canonical D application-order representation + scenario = compiled.scenario_plan + definition = PSE._compiled_application_schedule(compiled.applications_by_id, + order,scenario.manual_application_ids) + plans = Tuple(compiled.applications_by_id[id].plan for id in order) + fields = ntuple(fieldcount(typeof(scenario))) do index + name = fieldname(typeof(scenario),index) + name === :application_schedule && return definition + name === :application_order && return order + name === :ordered_application_plans && return plans + return getfield(scenario,index) + end + current_scenario = PSE.CompiledScenarioPlan(fields...) + fields = ntuple(fieldcount(typeof(compiled))) do index + name = fieldname(typeof(compiled),index) + name === :scenario_plan && return current_scenario + name === :application_order && return order + name === :ordered_applications && return Tuple(compiled.applications_by_id[id] for id in order) + return getfield(compiled,index) + end + return PSE.CompiledCompositeModel(fields...) +end + +function membership_snapshot(plan) + return [(membership=group.membership,ids=copy(group.membership.object_ids), + locations=copy(group.membership.locations), + runs=copy(group.membership.runs), + indices=[copy(run.indices) for run in group.membership.runs], + refs=[PSE.refvalue(target.status_view.status,:count) + for run in group.membership.runs for target in run]) for group in plan.groups] +end + +@testset "known incompatible closed layout rejects before a newborn changes live rows" begin + simulation,previous = fixture() + before = membership_snapshot(previous) + locations = copy(previous.cohorts.locations) + newborn = register_object!(simulation.model, + Object(:newborn;scale=:A,status=Status(count=7f0))) + current = PSE.Advanced.refresh_bindings!(simulation.model) + incompatible = with_order(current,[:a,:c,:b]) + @test_throws "prepared tuple schema" PSE._refresh_model_execution_plan(previous, + incompatible,simulation.environment_bindings,simulation.temporal_streams, + simulation.output_retention,simulation.constants) + @test previous.cohorts.locations == locations + @test newborn.status.count == 7f0 + for (group,snapshot) in zip(previous.groups,before) + @test group.membership === snapshot.membership + @test group.membership.object_ids == snapshot.ids + @test group.membership.locations == snapshot.locations + @test group.membership.runs == snapshot.runs + @test [run.indices for run in group.membership.runs] == snapshot.indices + current_refs = [PSE.refvalue(target.status_view.status,:count) + for run in group.membership.runs for target in run] + @test length(current_refs) == length(snapshot.refs) + @test all(first === second for (first,second) in zip(current_refs,snapshot.refs)) + end + # A compatible CURRENT A/B/A permutation is admitted and keeps that order. + compatible = with_order(current,[:c,:b,:a]) + environment = PSE.Advanced.refresh_environment_bindings!(simulation.model,current) + result = PSE._refresh_model_execution_plan(previous,compatible, + environment,simulation.temporal_streams, + simulation.output_retention,simulation.constants) + @test [group.application.id for group in result.plan.groups] == [:c,:b,:a] + @test only(group for group in result.plan.groups if group.application.id === :a).membership.object_ids == + [ObjectId(:a),ObjectId(:newborn)] +end +end diff --git a/test/test-model-closed-group-refresh.jl b/test/test-model-closed-group-refresh.jl new file mode 100644 index 000000000..2b07a034e --- /dev/null +++ b/test/test-model-closed-group-refresh.jl @@ -0,0 +1,240 @@ +module ClosedGroupRefreshChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "closed_group_counter" verbose=false +struct Counter{T} <: AbstractClosed_Group_CounterModel + increment::T + trace::Vector{Symbol} + declarations::Base.RefValue{Int} +end +PSE.inputs_(::Counter) = NamedTuple() +function PSE.outputs_(model::Counter) + model.declarations[] += 1 + return (count=zero(model.increment),) +end +function PSE.run!(model::Counter, status, environment, constants, context) + push!(model.trace, context.application.id) + status.count += model.increment + return nothing +end + +function three_groups() + trace, declarations = Symbol[], Ref(0) + increments = (1f0, 1.0, 1f0) + ids = (:a1, :b, :a2) + specs = ntuple(index -> ModelSpec(Counter(increments[index], trace, declarations); + name=ids[index], on=One(id=ids[index])), 3) + objects = ntuple(index -> Object(ids[index]; + status=Status(count=zero(increments[index]))), 3) + simulation = run!(CompositeModel(objects...; applications=specs); + steps=0, outputs=:none) + return (; simulation, trace, declarations) +end + +function closed_plan(plan) + return PSE.CompiledExecutionPlan(plan.cohorts, plan.topology, + Tuple(plan.groups), plan.batches, Tuple(plan.groups_by_application_slot), + plan.schedule, plan.model_revision, plan.environment_revision) +end + +@testset "closed A/B/A groups retain current scheduler order and slot ownership" begin + fixture = three_groups() + simulation = fixture.simulation + previous = closed_plan(simulation.execution_plan) + @test typeof(previous.groups[1]) === typeof(previous.groups[3]) + @test typeof(previous.groups[1]) !== typeof(previous.groups[2]) + @test [group.application.id for group in previous.groups] == [:a1, :b, :a2] + current = reverse(collect(previous.groups)) + admitted = @inferred PSE._execution_groups_in_schema(previous.groups, current) + @test [group.application.id for group in admitted] == [:a2, :b, :a1] + @test admitted[1] === previous.groups[3] + @test admitted[3] === previous.groups[1] + @test_throws "prepared tuple schema" PSE._execution_groups_in_schema( + previous.groups, [previous.groups[2], previous.groups[1], previous.groups[3]]) + @test_throws "count differs" PSE._execution_groups_in_schema( + previous.groups, current[1:2]) + @test_throws "prepared tuple schema" PSE._execution_groups_in_schema( + (previous.groups[1], nothing, previous.groups[3]), previous.groups) + repeated = PSE._execution_groups_in_schema(previous.groups, + [previous.groups[1], previous.groups[2], previous.groups[1]]) + repeated_slots = PSE._execution_groups_by_application_slot(repeated, 3) + @test_throws "prepared tuple schema" PSE._execution_groups_in_schema( + previous.groups_by_application_slot, repeated_slots) + + # Build a CURRENT schedule definition with the canonical compiler, keeping + # authored slots and all real application/group owners. A/B/A makes both + # dependency-order representations inhabit the same actual tuple types. + compiled = simulation.compiled + old_scenario = compiled.scenario_plan + order = reverse(old_scenario.application_order) + definition = PSE._compiled_application_schedule(compiled.applications_by_id, + order, old_scenario.manual_application_ids) + current_plans = Tuple(compiled.applications_by_id[id].plan for id in order) + fields = ntuple(fieldcount(typeof(old_scenario))) do index + name = fieldname(typeof(old_scenario), index) + name === :application_schedule && return definition + name === :application_order && return order + name === :ordered_application_plans && return current_plans + return getfield(old_scenario, index) + end + compiled.scenario_plan = typeof(old_scenario)(fields...) + compiled.application_order = order + compiled.ordered_applications = Tuple(compiled.applications_by_id[id] for id in order) + refreshed = PSE._refresh_model_execution_plan(previous, compiled, + simulation.environment_bindings, simulation.temporal_streams, + simulation.output_retention, simulation.constants, nothing, Set{Symbol}()) + @test typeof(refreshed.plan) === typeof(previous) + @test [group.application.id for group in refreshed.plan.groups] == [:a2, :b, :a1] + @test [group.application.id for group in refreshed.plan.groups_by_application_slot] == [:a1, :b, :a2] + @test refreshed.targets_constructed == 0 + @test refreshed.batches_constructed == 0 + @test refreshed.groups_reused == 3 + @test isempty(fixture.trace) + simulation = PSE._simulation_with_execution_plan(simulation, refreshed.plan) + step!(simulation) + @test fixture.trace == [:a2, :b, :a1] + @test all(id -> model_status(simulation.model, id).count == 1, (:a1, :b, :a2)) +end + +@testset "closed lookup requires an existing id, application type and authored slot" begin + fixture = three_groups() + simulation = fixture.simulation + slots = Tuple(simulation.execution_plan.groups_by_application_slot) + application = slots[1].application + invoked = Ref(false) + counts = PSE._with_previous_execution_group(slots, application, falses(3)) do group + invoked[] = true + @test group === slots[1] + return (0, 0, 1) + end + @test invoked[] && counts === (0, 0, 1) + # A real same-typed application is absent, rather than a fabricated group + # or a placeholder Status supplied only to satisfy inference. + other = run!(CompositeModel(Object(:other; status=Status(count=0f0)); + applications=(ModelSpec(Counter(1f0, Symbol[], Ref(0)); + name=:other, on=One(id=:other)),)); steps=0, outputs=:none) + missing = only(other.compiled.applications) + @test typeof(missing) === typeof(application) + invoked[] = false + @test_throws "prepared execution-group schema" PSE._with_previous_execution_group( + group -> (invoked[] = true; (0, 0, 0)), slots, missing, falses(3)) + @test !invoked[] + + # Public force can legitimately reorder ordinary authored application slots. + reverse!(simulation.model.applications) + PSE.Advanced.refresh_bindings!(simulation.model; force=true) + moved = PSE.Advanced.compiled_bindings(simulation.model).applications_by_id[:a1] + @test moved.slot == 3 + @test typeof(moved) === typeof(application) + @test_throws "prepared execution-group schema" PSE._with_previous_execution_group( + group -> (invoked[] = true; (0, 0, 0)), slots, moved, falses(3)) + @test !invoked[] + open_counts = PSE._with_previous_execution_group(collect(slots), moved, falses(3)) do group + @test group === slots[1] + return (0, 0, 1) + end + @test open_counts === (0, 0, 1) + # Reordering authored ids also changes the metadata table's tuple type; + # the existing outer C witness requires a new timeline for that edit. + current_simulation = run!(simulation.model; steps=0, outputs=:none) + step!(current_simulation) + @test fixture.trace == [:a2, :b, :a1] +end + +@testset "open lookup admits a same-id application-type replacement" begin + trace, declarations = Symbol[], Ref(0) + status = Status(count=0f0) + model = CompositeModel(Object(:leaf; status); + applications=(ModelSpec(Counter(1f0, trace, declarations); + name=:counter, on=One(id=:leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + previous = only(simulation.execution_plan.groups) + model.applications[1] = ModelSpec(Counter(2.0, trace, declarations); + name=:counter, on=One(id=:leaf)) + PSE.Advanced.refresh_bindings!(model; force=true) + current = PSE.Advanced.compiled_bindings(model).applications_by_id[:counter] + @test typeof(current) !== typeof(previous.application) + invoked = Ref(false) + @test_throws "prepared execution-group schema" PSE._with_previous_execution_group( + group -> (invoked[] = true; (0, 0, 0)), (previous,), current, falses(1)) + @test !invoked[] + counts = PSE._with_previous_execution_group([previous], current, falses(1)) do group + @test group === previous + return (0, 0, 1) + end + @test counts === (0, 0, 1) + # A different authored CS needs a new Simulation under the existing outer + # runtime contract. This tests the OPEN group container, not a new API for + # changing a running Simulation's parametric compiled field. + current_simulation = run!(model; steps=0, outputs=:none) + current_groups = current_simulation.execution_plan.groups + @test PSE._execution_groups_in_schema([previous], current_groups) === current_groups + step!(current_simulation) + @test status.count === 2f0 + @test model_status(model, :leaf) === status + @test trace == [:counter] +end + +@testset "ordinary heterogeneous overrides and public force retain full execution" begin + trace, declarations = Symbol[], Ref(0) + plain = Status(count=0f0) + alternate = Status(count=0.0) + template = CompositeModelTemplate((ModelSpec(Counter(1f0, trace, declarations); + name=:counter, on=Many(scale=:Leaf)),)) + instance = ObjectInstance(:plant, template; + root=Object(:plant; scale=:Plant), + objects=(Object(:plain; scale=:Leaf, parent=:plant, status=plain), + Object(:alternate; scale=:Leaf, parent=:plant, status=alternate)), + object_overrides=(Override(object=:alternate, application=:counter, + model=Counter(2.0, trace, declarations)),)) + model = CompositeModel(instance) + simulation = run!(model; steps=1, outputs=:none) + @test simulation.execution_plan.groups isa AbstractVector + @test plain.count === 1f0 && alternate.count === 2.0 + PSE.Advanced.refresh_bindings!(model; force=true) + step!(simulation) + @test plain.count === 2f0 && alternate.count === 4.0 + @test model_status(model, :plain) === plain + @test model_status(model, :alternate) === alternate + group = only(simulation.execution_plan.groups) + @test length(group.batches) == 2 + @test trace == fill(:plant__counter, 4) +end + +@testset "a real learned batch schema admits an empty future group without probing defaults" begin + trace, declarations = Symbol[], Ref(0) + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:first; scale=:Leaf, status=Status(count=0)); + applications=(ModelSpec(Counter(1, trace, declarations); + name=:counter, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + Batch = typeof(only(only(simulation.execution_plan.groups).batches)) + removed_status = model_status(model, :first) + remove_object!(model, :first) + step!(simulation) + application = simulation.compiled.applications_by_id[:counter] + before = declarations[] + future = PSE._empty_model_execution_group(application, Batch, + simulation.execution_plan.cohorts) + @test declarations[] == before + @test isempty(future.batches) && isempty(future.membership.object_ids) + @test length(model.registry.objects) == 1 + @test isempty(trace) + old = simulation.execution_plan + plan = PSE.CompiledExecutionPlan(old.cohorts, old.topology, + (future,), old.batches, (future,), old.schedule, + old.model_revision, old.environment_revision) + simulation = PSE._simulation_with_execution_plan(simulation, plan) + newborn = register_object!(model, Object(:next; scale=:Leaf, status=Status(count=7))) + step!(simulation) + @test newborn.status.count == 8 + @test removed_status.count == 0 + @test only(simulation.execution_plan.groups) === future + @test only(simulation.execution_plan.groups_by_application_slot) === future + @test typeof(simulation.execution_plan) === typeof(plan) + @test only(only(future.batches).targets).status_view.status === newborn.status + @test trace == [:counter] +end + +end diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl new file mode 100644 index 000000000..115509f1e --- /dev/null +++ b/test/test-model-finite-call-extension-intents.jl @@ -0,0 +1,287 @@ +module FiniteCallExtensionIntentChecks + +using PlantSimEngine, Random, Test +const PSE = PlantSimEngine +const MANUAL_NAMES = (:a, :alias_a, :b, :c, :d, :e, :f) +const APP_NAMES = (:leaf_a, :leaf_b, :leaf_c, :leaf_d, :leaf_e, :leaf_f) + +PSE.@process "finite_extension_root" verbose=false +PSE.@process "finite_extension_leaf" verbose=false +struct Root{Names} <: AbstractFinite_Extension_RootModel end +struct Leaf{N,R} <: AbstractFinite_Extension_LeafModel + rng::R +end +PSE.inputs_(::Union{Root,Leaf}) = NamedTuple() +PSE.outputs_(::Root) = (root_visits=0,) +PSE.outputs_(::Leaf) = (visits=0, value=0.0) +function PSE.run!(::Root{Names}, status, environment, constants, context) where {Names} + status.root_visits += 1 + for name in Names + run_call!(context, name; publish=false) + end + return nothing +end +function PSE.run!(model::Leaf, status, environment, constants, context) + status.visits += 1 + status.value = rand(model.rng) + return nothing +end + +root_target(simulation) = only(only(only(group for group in simulation.execution_plan.groups + if group.application.id === :root).batches).targets) + +# Every batch witness comes from these real objects and the canonical factories. +# Six distinct models exceed the compiler's small-union splitting heuristic; +# alias_a also supplies two same-type batches with different execution owners. +function fixture(; prepared=true, wide=false) + rng = Xoshiro(4031) + objects = Object[Object(1; scale=:Scene, status=Status(root_visits=0))] + for (index, kind) in enumerate((:a, :b, :c, :d, :e, :f, :seed)) + push!(objects, Object(100index; kind, scale=index == 7 ? :Seed : :Leaf, parent=1, + status=Status(visits=0, value=0.0))) + end + manual = (a=Many(scale=:Leaf, kind=:a, application=:leaf_a), + alias_a=Many(scale=:Leaf, kind=:a, application=:leaf_a), + b=Many(scale=:Leaf, kind=:b, application=:leaf_b), + c=Many(scale=:Leaf, kind=:c, application=:leaf_c), + d=Many(scale=:Leaf, kind=:d, application=:leaf_d), + e=Many(scale=:Leaf, kind=:e, application=:leaf_e), + f=Many(scale=:Leaf, kind=:f, application=:leaf_f)) + names = wide ? (MANUAL_NAMES..., :all) : MANUAL_NAMES + manual = wide ? (; manual..., all=Many(scale=:Leaf)) : manual + specs = ntuple(6) do index + ModelSpec(Leaf{index,typeof(rng)}(rng); name=APP_NAMES[index], + on=Many(scale=:Leaf, kind=(:a, :b, :c, :d, :e, :f)[index])) + end + model = CompositeModel(objects...; applications=( + ModelSpec(Root{names}(); name=:root, on=One(id=1, scale=:Scene), calls=(; manual..., + initialize=Initializer(One(scale=:Seed, kind=:seed, application=:seed)))), + specs..., + ModelSpec(Leaf{7,typeof(rng)}(rng); name=:seed, on=Many(scale=:Seed, kind=:seed)), + )) + simulation = run!(model; steps=0, outputs=:none) + target = root_target(simulation) + manual_bindings = filter(binding -> PSE._compiled_call_mode(binding) === :manual, + target.call_bindings) + @test Set(id for binding in manual_bindings for id in binding.callee_application_ids) == Set(APP_NAMES) + @test all(binding -> !(:seed in binding.plan.potential_callee_application_ids), manual_bindings) + initializer_binding = only(binding for binding in target.call_bindings + if PSE._compiled_call_mode(binding) === :initializer) + @test initializer_binding.callee_application_ids == [:seed] + @test !(:visits in keys(PSE.outputs_(Root{names}()))) + call_schemas = map(names) do name + calls = call_targets(target.context, name) + batches = PSE._materialize_call_execution_batches!(calls) + Batch = Union{map(typeof, batches)...} + PSE.PreparedExecutionBatchSchema{Vector{Batch}}() + end + seed_batch = only(only(group for group in simulation.execution_plan.groups + if group.application.id === :seed).batches) + seed_schema = PSE.PreparedExecutionBatchSchema{Vector{typeof(seed_batch)}}() + schemas = NamedTuple{(names..., :initialize)}((call_schemas..., seed_schema)) + RootB = PSE._execution_batch_type_with_call_schemas( + typeof(only(only(group for group in simulation.execution_plan.groups + if group.application.id === :root).batches)), schemas) + application_schemas = (root=PSE.PreparedExecutionBatchSchema{Vector{RootB}}(), + leaf_a=schemas.a, leaf_b=schemas.b, leaf_c=schemas.c, + leaf_d=schemas.d, leaf_e=schemas.e, leaf_f=schemas.f, seed=seed_schema) + result = prepared ? PSE._prepare_execution_batch_schemas(simulation, application_schemas) : simulation + return (; model, simulation=result, rng) +end + +function add_leaves!(data) + for (index, kind) in enumerate((:a, :b, :c, :d, :e, :f)) + register_object!(data.model, Object(100index + 1; kind, scale=:Leaf, parent=1, + status=Status(visits=0, value=0.0))) + end + return nothing +end + +function refreshed_owners(data) + compiled = PSE.Advanced.refresh_bindings!(data.model) + environment = PSE.Advanced.refresh_environment_bindings!(data.model, compiled) + return (; compiled, environment) +end + +function extend!(algorithm, target, owners, simulation) + function_ = algorithm === :prefix ? PSE._extend_execution_target_call_batches_by_prefix! : + PSE._extend_execution_target_call_batches_for_pure_addition! + return function_(target, owners.compiled, owners.environment, + simulation.temporal_streams, simulation.output_retention, simulation.constants) +end + +function call_snapshot(simulation) + target = root_target(simulation) + return [(calls=calls, binding=calls.binding, preparation=calls.preparation, + batches=calls.execution_batches, + rows=[(rows=batch.targets, indices=copy(batch.targets.indices), + payloads=collect(batch.targets)) for batch in PSE._cached_call_execution_batches(calls)]) + for calls in target.context.calls if PSE._compiled_call_mode(calls.binding) === :manual] +end + +function assert_snapshot(snapshot) + for old in snapshot + @test old.calls.binding === old.binding + @test old.calls.preparation === old.preparation + @test old.calls.execution_batches === old.batches + for entry in old.rows + @test entry.rows.indices == entry.indices + @test all(a === b for (a, b) in zip(entry.rows, entry.payloads)) + end + end +end + +state(model) = Dict(object.id => deepcopy(NamedTuple(object.status)) for object in model_objects(model)) +random_state(rng) = rand(copy(rng), UInt64, 8) + +@testset "both canonical extensions keep finite intents, order and real references" begin + for algorithm in (:prefix, :pure_addition) + wide = algorithm === :prefix + ordinary, data = fixture(; prepared=false, wide), fixture(; wide) + simulation = data.simulation + target = root_target(simulation) + scope = PSE._context_call_schema(target.context) + @test scope isa PSE.PreparedContextCallSchema + append_buffer = PSE._execution_append_intent_buffer(scope) + binding_buffer = PSE._execution_binding_intent_buffer(scope) + @test length(Base.uniontypes(eltype(append_buffer))) == 6 + @test length(Base.uniontypes(eltype(binding_buffer))) == (wide ? 9 : 8) + if wide + all_calls = call_targets(target.context, :all) + @test length(Base.uniontypes(eltype(all_calls.execution_batches))) == 6 + @test length(all_calls.execution_batches) == 6 + end + @test eltype(append_buffer) !== Tuple{Any,Any} + @test eltype(binding_buffer) !== Tuple{Any,Any} + initializer = only(calls for calls in target.context.calls + if PSE._compiled_call_mode(calls.binding) === :initializer) + @test PSE._compiled_call_name(initializer.binding) === :initialize + @test_throws ArgumentError call_targets(target.context, :initialize) + @test initializer.execution_batches === () + @test PSE._stage_execution_binding!(binding_buffer, scope, initializer, initializer.binding) + @test length(binding_buffer) == 1 + @test isempty(append_buffer) + original_rows = [only(call_targets(target.context, name).execution_batches).targets + for name in MANUAL_NAMES] + original_targets = [only(rows) for rows in original_rows] + original_cells = [PSE.refvalue(child.status_view.status, :value) for child in original_targets] + before_random = random_state(data.rng) + add_leaves!(data) + add_leaves!(ordinary) + owners = refreshed_owners(data) + @test owners.compiled.status_view_refresh_is_pure_addition + before_state = state(data.model) + @test extend!(algorithm, target, owners, simulation) === true + @test state(data.model) == before_state + @test random_state(data.rng) == before_random + @test all(isempty, values(outputs(simulation))) + for (index, name) in enumerate(MANUAL_NAMES) + calls = call_targets(target.context, name) + rows = only(calls.execution_batches).targets + @test rows === original_rows[index] + @test first(rows) === original_targets[index] + @test PSE.refvalue(first(rows).status_view.status, :value) === original_cells[index] + kind_index = name === :alias_a ? 1 : findfirst(==(name), (:a,:b,:c,:d,:e,:f)) + @test getproperty.(collect(rows), :object_id) == [ObjectId(100kind_index), ObjectId(100kind_index + 1)] + @test last(rows).status_view.canonical_status === model_status(data.model, 100kind_index + 1) + @test last(rows).context.temporal_streams === simulation.temporal_streams + @test !last(rows).call_context_cache.in_use + end + left = only(call_targets(target.context, :a).execution_batches).targets + right = only(call_targets(target.context, :alias_a).execution_batches).targets + @test left.cohort !== right.cohort + @test last(left) !== last(right) + @test last(left).context !== last(right).context + @test PSE.refvalue(last(left).status_view.status, :value) === + PSE.refvalue(last(right).status_view.status, :value) + continue!(simulation; steps=2) + continue!(ordinary.simulation; steps=2) + @test state(data.model) == state(ordinary.model) + @test random_state(data.rng) == random_state(ordinary.rng) + @test collect_outputs(simulation) == collect_outputs(ordinary.simulation) + end +end + +@testset "a later inadmissible binding rejects before any earlier append" begin + for algorithm in (:prefix, :pure_addition), mismatch in (:type, :owner) + data = fixture() + simulation = data.simulation + target = root_target(simulation) + before = call_snapshot(simulation) + original_bindings = target.call_bindings + locations = copy(simulation.temporal_streams.cohorts.locations) + add_leaves!(data) + owners = refreshed_owners(data) + key = (:root, ObjectId(1)) + current = owners.compiled.call_bindings_by_target[key] + # Either a different real call declaration type, or the same exact + # declaration schema with a foreign execution owner. No Status, model + # default or kernel is constructed to exercise either negative. + last_binding = last(current) + wrong = mismatch === :type ? first(current) : PSE.CompiledModelCallBinding( + last_binding.plan, ObjectId(999), copy(last_binding.callee_object_ids), + copy(last_binding.callee_application_ids)) + incompatible = (Base.front(current)..., wrong) + scope = PSE._context_call_schema(target.context) + if mismatch === :type + @test isnothing(PSE._admitted_current_execution_call_bindings(scope, target, incompatible)) + else + @test typeof(incompatible) === typeof(target.call_bindings) + @test !PSE._preflight_current_execution_calls(scope, target.context.calls, + incompatible, owners.compiled, owners.environment) + end + before_random = random_state(data.rng) + before_state = state(data.model) + owners.compiled.call_bindings_by_target[key] = incompatible + try + expected = algorithm === :prefix ? false : nothing + @test extend!(algorithm, target, owners, simulation) === expected + finally + owners.compiled.call_bindings_by_target[key] = current + end + @test target.call_bindings === original_bindings + @test simulation.temporal_streams.cohorts.locations == locations + assert_snapshot(before) + @test state(data.model) == before_state + @test random_state(data.rng) == before_random + end +end + +@testset "multi-application pure addition retains its prefix fallback without writes" begin + data = fixture(; wide=true) + simulation = data.simulation + target = root_target(simulation) + before = call_snapshot(simulation) + locations = copy(simulation.temporal_streams.cohorts.locations) + add_leaves!(data) + owners = refreshed_owners(data) + @test extend!(:pure_addition, target, owners, simulation) === nothing + assert_snapshot(before) + @test simulation.temporal_streams.cohorts.locations == locations + @test extend!(:prefix, target, owners, simulation) === true + all_calls = call_targets(target.context, :all) + @test length(all_calls.execution_batches) == 6 + @test all(length(batch.targets) == 2 for batch in all_calls.execution_batches) +end + +@testset "same-type rows from a different call owner cannot be staged" begin + data = fixture() + target = root_target(data.simulation) + scope = PSE._context_call_schema(target.context) + left, right = call_targets(target.context, :a), call_targets(target.context, :alias_a) + rows = only(right.execution_batches).targets + candidate = only(only(left.execution_batches).targets) + staged = PSE._execution_append_intent_buffer(scope) + @test !PSE._stage_execution_append!(staged, scope, left, left.binding, rows, candidate) + @test isempty(staged) + @test length(rows) == 1 + # The ordinary path retains its existing tuple representation and does not + # introduce closed admission into a dynamic scene. + open = PSE.OpenContextCallSchema() + raw = PSE._execution_append_intent_buffer(open) + @test eltype(raw) === Tuple{Any,Any} + @test PSE._stage_execution_append!(raw, open, left, left.binding, rows, candidate) + @test only(raw) == (rows, candidate) +end + +end # module FiniteCallExtensionIntentChecks diff --git a/test/test-model-hard-calls.jl b/test/test-model-hard-calls.jl index 56c8e40c7..755759479 100644 --- a/test/test-model-hard-calls.jl +++ b/test/test-model-hard-calls.jl @@ -1535,7 +1535,7 @@ end @test only(selected).object_id == ObjectId(:callable_leaf) @test selected.execution_batches isa PlantSimEngine.LazyCallExecutionBatches - @test !selected.execution_batches.tracks_full_membership + @test !selected.tracks_full_membership @test !PlantSimEngine._compiled_call_membership_is_observed(binding) end diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl new file mode 100644 index 000000000..e6776e62a --- /dev/null +++ b/test/test-model-prepared-call-schemas.jl @@ -0,0 +1,320 @@ +module ColdCallSchemaActivationChecks + +using PlantSimEngine, Random, Test +const PSE = PlantSimEngine + +PSE.@process "cold_schema_activation_root" verbose=false +PSE.@process "cold_schema_activation_middle" verbose=false +PSE.@process "cold_schema_activation_leaf" verbose=false + +struct Root <: AbstractCold_Schema_Activation_RootModel + capture::Base.RefValue{Any} + kernels::Dict{Symbol,Int} +end +struct Middle <: AbstractCold_Schema_Activation_MiddleModel + contexts::Dict{Symbol,Any} + kernels::Dict{Symbol,Int} +end +struct Leaf{R} <: AbstractCold_Schema_Activation_LeafModel + rng::R + kernels::Dict{Symbol,Int} +end + +PSE.inputs_(::Root) = NamedTuple() +PSE.inputs_(::Middle) = NamedTuple() +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Root) = (visits=0,) +PSE.outputs_(::Middle) = (visits=0, total=0.0) +PSE.outputs_(::Leaf) = (visits=0, value=0.0, payload=zeros(2)) + +function PSE.run!(model::Root, status, environment, constants, context) + model.kernels[:root] += 1 + model.capture[] = context + status.visits += 1 + return nothing +end +function PSE.run!(model::Middle, status, environment, constants, context) + model.kernels[:middle] += 1 + model.contexts[context.object_id.value] = context + status.visits += 1 + children = run_call!(context, :leaf; publish=true) + status.total = sum(child.status.value for child in children; init=0.0) + return nothing +end +function PSE.run!(model::Leaf, status, environment, constants, context) + model.kernels[:leaf] += 1 + status.visits += 1 + status.value = rand(model.rng) + status.payload[1] = status.value + status.payload[2] = status.visits + return nothing +end + +# All statuses below belong to real scenario objects. No kernel or callback is +# executed to manufacture a status, a future organ, or an execution batch type. +function fixture(; leaves=true) + capture = Ref{Any}(nothing) + contexts = Dict{Symbol,Any}() + kernels = Dict(:root => 0, :middle => 0, :leaf => 0) + rng = Xoshiro(917) + objects = Object[ + Object(:root; scale=:Scene, status=Status(visits=0)), + Object(:middle_a; scale=:Branch, parent=:root, + status=Status(visits=0, total=0.0)), + Object(:middle_b; scale=:Branch, parent=:root, + status=Status(visits=0, total=0.0)), + ] + if leaves + append!(objects, ( + Object(:leaf_a; scale=:Leaf, parent=:middle_a, + status=Status(visits=0, value=0.0, payload=zeros(2))), + Object(:leaf_b; scale=:Leaf, parent=:middle_b, + status=Status(visits=0, value=0.0, payload=zeros(2))), + )) + end + model = CompositeModel(objects...; applications=( + ModelSpec(Root(capture, kernels); name=:root, on=One(id=:root), + calls=(middle=Many(scale=:Branch, within=Subtree(), application=:middle),)), + ModelSpec(Middle(contexts, kernels); name=:middle, on=Many(scale=:Branch), + calls=(leaf=Many(scale=:Leaf, within=Subtree(), application=:leaf),)), + ModelSpec(Leaf(rng, kernels); name=:leaf, on=Many(scale=:Leaf)), + )) + simulation = run!(model; steps=0, outputs=:all) + return (; model, simulation, capture, contexts, kernels, rng) +end + +root_target(simulation) = only(only(only(simulation.execution_plan.groups).batches).targets) +status_cells(model) = Dict((object.id, name) => PSE.refvalue(object.status, name) + for object in model_objects(model) for name in keys(object.status)) +scientific_state(model) = Dict(object.id => deepcopy(NamedTuple(object.status)) + for object in model_objects(model)) +rng_probe(rng) = rand(copy(rng), UInt64, 8) +history(simulation) = Dict(key => [(time, deepcopy(value)) for (time, value) in stream] + for (key, stream) in outputs(simulation)) +raw(simulation, application, object, variable) = + get(outputs(simulation), (application, ObjectId(object), variable), ()) + +function assert_same_cells(model, before) + current = status_cells(model) + @test Set(keys(current)) == Set(keys(before)) + @test all(current[key] === reference for (key, reference) in before) +end + +# Materialize the ordinary cached Many metadata at step zero, without invoking +# the models. A borrowed LeafB, when supplied, comes from another REAL scene. +function observed_schemas(simulation; borrowed_leaf_batch=nothing) + root = root_target(simulation) + middle_calls = call_targets(root.context, :middle) + @test middle_calls.execution_batches isa PSE.LazyCallExecutionBatches + @test isnothing(middle_calls.execution_batches.batches) + middle_batch = only(PSE._materialize_call_execution_batches!(middle_calls)) + leaf_calls = call_targets(first(middle_batch.targets).context, :leaf) + @test leaf_calls.execution_batches isa PSE.LazyCallExecutionBatches + @test isnothing(leaf_calls.execution_batches.batches) + leaf_batches = PSE._materialize_call_execution_batches!(leaf_calls) + LeafB = if isnothing(borrowed_leaf_batch) + typeof(only(leaf_batches)) + else + @test isempty(leaf_batches) + borrowed_leaf_batch + end + LeafTarget = eltype(fieldtype(LeafB, :targets)) + LeafContext = fieldtype(LeafTarget, :context) + @test fieldtype(LeafB, :application) === typeof(simulation.compiled.applications_by_id[:leaf]) + @test fieldtype(LeafContext, :compiled) === typeof(simulation.compiled) + @test fieldtype(LeafContext, :temporal_streams) === typeof(simulation.temporal_streams) + @test fieldtype(LeafContext, :output_retention) === typeof(simulation.output_retention) + @test fieldtype(LeafContext, :constants) === typeof(simulation.constants) + leaf_schema = PSE.PreparedExecutionBatchSchema{Vector{LeafB}}() + MiddleB = PSE._execution_batch_type_with_call_schemas(typeof(middle_batch), + (leaf=leaf_schema,)) + middle_schema = PSE.PreparedExecutionBatchSchema{Vector{MiddleB}}() + RootB = PSE._execution_batch_type_with_call_schemas( + typeof(only(only(simulation.execution_plan.groups).batches)), + (middle=middle_schema,)) + root_schema = PSE.PreparedExecutionBatchSchema{Vector{RootB}}() + return (; schemas=(root=root_schema, middle=middle_schema, leaf=leaf_schema), + LeafB, MiddleB, RootB) +end + +function assert_prepared_tree(simulation) + root = root_target(simulation) + @test root.status_view.canonical_status === model_status(simulation.model, :root) + middle_calls = call_targets(root.context, :middle) + @test middle_calls.batch_schema isa PSE.PreparedExecutionBatchSchema + @test middle_calls.execution_batches isa Vector + @test middle_calls.tracks_full_membership + for middle_batch in middle_calls.execution_batches, middle in middle_batch.targets + @test middle_batch.targets.store === simulation.execution_plan.cohorts + @test middle.status_view.canonical_status === model_status(simulation.model, middle.object_id) + @test !middle.call_context_cache.in_use + leaves = call_targets(middle.context, :leaf) + @test leaves.batch_schema isa PSE.PreparedExecutionBatchSchema + @test leaves.execution_batches isa Vector + @test leaves.tracks_full_membership + for leaf_batch in leaves.execution_batches, leaf in leaf_batch.targets + @test leaf_batch.targets.store === simulation.execution_plan.cohorts + @test leaf.status_view.canonical_status === model_status(simulation.model, leaf.object_id) + @test PSE.refvalue(leaf.status_view.status, :value) === + PSE.refvalue(model_status(simulation.model, leaf.object_id), :value) + @test !leaf.call_context_cache.in_use + end + end + return nothing +end + +@testset "bottom-up call activation changes metadata without science or references" begin + data = fixture() + before = scientific_state(data.model) + cells = status_cells(data.model) + random_state = rng_probe(data.rng) + original_root = root_target(data.simulation) + streams = Dict(key => stream for (key, stream) in outputs(data.simulation)) + learned = observed_schemas(data.simulation) + @test data.kernels == Dict(:root => 0, :middle => 0, :leaf => 0) + @test scientific_state(data.model) == before + @test rng_probe(data.rng) == random_state + @test data.capture[] === nothing && isempty(data.contexts) + assert_same_cells(data.model, cells) + prepared = PSE._prepare_execution_batch_schemas(data.simulation, learned.schemas) + @test prepared !== data.simulation + @test prepared.temporal_streams !== data.simulation.temporal_streams + @test prepared.temporal_streams.streams === data.simulation.temporal_streams.streams + @test prepared.execution_plan.cohorts !== data.simulation.execution_plan.cohorts + @test root_target(prepared) !== original_root + @test prepared.execution_plan.groups isa Tuple + @test prepared.execution_plan.groups_by_application_slot isa Tuple + @test current_step(prepared) == 0 + @test isempty(prepared.execution_plan.schedule.due_entry_indices) + @test data.kernels == Dict(:root => 0, :middle => 0, :leaf => 0) + @test scientific_state(data.model) == before + @test rng_probe(data.rng) == random_state + @test data.capture[] === nothing && isempty(data.contexts) + @test all(isempty, values(outputs(prepared))) + @test Set(keys(outputs(prepared))) == Set(keys(streams)) + @test all(outputs(prepared)[key] === stream for (key, stream) in streams) + assert_same_cells(data.model, cells) + assert_prepared_tree(prepared) + @test typeof(root_target(prepared)) === eltype(fieldtype(learned.RootB, :targets)) +end + +@testset "cold real Many calls retain public evaluation, history and lease behavior" begin + ordinary, activated = fixture(), fixture() + learned = observed_schemas(activated.simulation) + prepared = PSE._prepare_execution_batch_schemas(activated.simulation, learned.schemas) + simulations = (ordinary.simulation, prepared) + fixtures = (ordinary, activated) + cells = map(data -> status_cells(data.model), fixtures) + + # The root scheduler runs normally. Call-only applications remain cold. + for (data, simulation) in zip(fixtures, simulations) + step!(simulation) + @test data.kernels == Dict(:root => 1, :middle => 0, :leaf => 0) + @test data.capture[] isa PSE.RunContext + run_call!(data.capture[], :middle; publish=false) + @test data.kernels == Dict(:root => 1, :middle => 2, :leaf => 2) + @test all(isempty(raw(simulation, :leaf, id, :value)) for id in (:leaf_a, :leaf_b)) + @test all(isempty(raw(simulation, :middle, id, :total)) for id in (:middle_a, :middle_b)) + end + @test scientific_state(ordinary.model) == scientific_state(activated.model) + @test rng_probe(ordinary.rng) == rng_probe(activated.rng) + @test history(ordinary.simulation) == history(prepared) + + for (data, simulation) in zip(fixtures, simulations) + evaluation = evaluate_call!(data.capture[], :middle) + @test Set(target.object_id for target in call_targets(evaluation)) == + Set((ObjectId(:middle_a), ObjectId(:middle_b))) + @test all(isempty(raw(simulation, :leaf, id, :value)) for id in (:leaf_a, :leaf_b)) + counts = copy(data.kernels) + state = scientific_state(data.model) + random_state = rng_probe(data.rng) + @test accept_call!(evaluation) === evaluation + @test data.kernels == counts + @test scientific_state(data.model) == state + @test rng_probe(data.rng) == random_state + @test_throws ArgumentError accept_call!(evaluation) + for id in (:leaf_a, :leaf_b) + leaf = model_status(data.model, id) + @test leaf.visits == 2 + @test raw(simulation, :leaf, id, :value) == [(1.0, leaf.value)] + payload = deepcopy(only(raw(simulation, :leaf, id, :payload))[2]) + leaf.payload .= -999.0 + @test only(raw(simulation, :leaf, id, :payload))[2] == payload + end + end + @test scientific_state(ordinary.model) == scientific_state(activated.model) + @test rng_probe(ordinary.rng) == rng_probe(activated.rng) + @test history(ordinary.simulation) == history(prepared) + + # A descendant reexecution invalidates a pending parent evaluation. Its + # already accepted histories survive, and every acquired lease is released. + for (data, simulation) in zip(fixtures, simulations) + step!(simulation) + previous_history = history(simulation) + pending = evaluate_call!(data.capture[], :middle) + held_leaf = only(call_targets(data.contexts[:middle_a], :leaf)) + run_call!(held_leaf; publish=false) + @test_throws ArgumentError accept_call!(pending) + @test history(simulation) == previous_history + selected = only(call_targets(data.capture[], :middle; objects=(:middle_a,))) + latest = evaluate_call!(selected) + counts = copy(data.kernels) + random_state = rng_probe(data.rng) + accept_call!(latest) + @test data.kernels == counts + @test rng_probe(data.rng) == random_state + @test !selected.context_cache.in_use + @test !held_leaf.context_cache.in_use + @test first.(raw(simulation, :leaf, :leaf_a, :value)) == [1.0, 2.0] + @test first.(raw(simulation, :leaf, :leaf_b, :value)) == [1.0] + end + for (data, before_cells) in zip(fixtures, cells) + assert_same_cells(data.model, before_cells) + end + assert_prepared_tree(prepared) + @test scientific_state(ordinary.model) == scientific_state(activated.model) + @test rng_probe(ordinary.rng) == rng_probe(activated.rng) + @test history(ordinary.simulation) == history(prepared) +end + +@testset "initially empty Many admits an observed real future leaf batch" begin + witness = fixture() + witness_before = scientific_state(witness.model) + witness_random = rng_probe(witness.rng) + real_leaf_batch = observed_schemas(witness.simulation).LeafB + @test witness.kernels == Dict(:root => 0, :middle => 0, :leaf => 0) + @test scientific_state(witness.model) == witness_before + @test rng_probe(witness.rng) == witness_random + + empty = fixture(; leaves=false) + before = scientific_state(empty.model) + cells = status_cells(empty.model) + random_state = rng_probe(empty.rng) + learned = observed_schemas(empty.simulation; borrowed_leaf_batch=real_leaf_batch) + prepared = PSE._prepare_execution_batch_schemas(empty.simulation, learned.schemas) + @test scientific_state(empty.model) == before + @test rng_probe(empty.rng) == random_state + @test empty.kernels == Dict(:root => 0, :middle => 0, :leaf => 0) + @test isempty(object_ids(empty.model; scale=:Leaf)) + assert_same_cells(empty.model, cells) + assert_prepared_tree(prepared) + for batch in call_targets(root_target(prepared).context, :middle).execution_batches, + target in batch.targets + leaves = call_targets(target.context, :leaf) + @test isempty(leaves.execution_batches) + @test eltype(leaves.execution_batches) === real_leaf_batch + end + step!(prepared) + evaluation = evaluate_call!(empty.capture[], :middle) + @test empty.kernels == Dict(:root => 1, :middle => 2, :leaf => 0) + @test rng_probe(empty.rng) == random_state + counts = copy(empty.kernels) + accept_call!(evaluation) + @test empty.kernels == counts + @test all(model_status(empty.model, id).total == 0.0 for id in (:middle_a, :middle_b)) + @test isempty(object_ids(empty.model; scale=:Leaf)) + assert_same_cells(empty.model, cells) + assert_prepared_tree(prepared) +end + +end # module ColdCallSchemaActivationChecks diff --git a/test/test-model-prepared-call-vector-api.jl b/test/test-model-prepared-call-vector-api.jl new file mode 100644 index 000000000..3d093a6c2 --- /dev/null +++ b/test/test-model-prepared-call-vector-api.jl @@ -0,0 +1,141 @@ +module PreparedCallVectorAPIChecks + +using PlantSimEngine, Random, Test +const PSE = PlantSimEngine +const Scene = getfield(parentmodule(@__MODULE__), :ColdCallSchemaActivationChecks) + +ids(values) = [target.object_id for target in values] + +function inspect_calls(data, simulation; prepared) + # Capture a genuine context by running its real root kernel. No synthetic + # context or private execution object is supplied to the public accessors. + step!(simulation) + root_context = data.capture[] + @test root_context isa PSE.RunContext + middles = call_targets(root_context, :middle) + @test (middles.execution_batches isa Vector) == prepared + @test length(middles) == 2 + @test size(middles) == (2,) + @test ids(middles) == [ObjectId(:middle_a), ObjectId(:middle_b)] + @test ids(collect(middles)) == ids(middles) + @test middles[1].object_id == ObjectId(:middle_a) + @test middles[2].object_id == ObjectId(:middle_b) + @test_throws BoundsError middles[0] + @test_throws BoundsError middles[3] + @test_throws ArgumentError only(middles) + @test_throws ArgumentError call_model(root_context, :middle) + + counts = copy(data.kernels) + before = Scene.scientific_state(data.model) + random_state = Scene.rng_probe(data.rng) + cells = Scene.status_cells(data.model) + buffer_id = with_call_targets(middles) do values + @test ids(values) == [ObjectId(:middle_a), ObjectId(:middle_b)] + first_id = objectid(values) + reverse!(values) + with_call_targets(middles) do nested + @test objectid(nested) != first_id + @test ids(nested) == [ObjectId(:middle_a), ObjectId(:middle_b)] + end + @test ids(values) == [ObjectId(:middle_b), ObjectId(:middle_a)] + return first_id + end + with_call_targets(middles) do values + @test objectid(values) == buffer_id + @test ids(values) == [ObjectId(:middle_a), ObjectId(:middle_b)] + end + @test data.kernels == counts + @test Scene.scientific_state(data.model) == before + @test Scene.rng_probe(data.rng) == random_state + Scene.assert_same_cells(data.model, cells) + + run_call!(root_context, :middle; publish=false) + @test data.kernels == Dict(:root => 1, :middle => 2, :leaf => 2) + # Middle records the context supplied to its actual invocation. Each leaf + # CallTargets is a one-element prepared Vector in the activated scene. + for name in (:middle_a, :middle_b) + context = data.contexts[name] + leaves = call_targets(context, :leaf) + @test (leaves.execution_batches isa Vector) == prepared + leaf = only(leaves) + @test length(leaves) == 1 + @test leaf.object_id == ObjectId(name === :middle_a ? :leaf_a : :leaf_b) + @test call_model(context, :leaf) === leaf.model + @test leaves[1].status === leaf.status + @test only(collect(leaves)).status === leaf.status + with_call_targets(leaves) do values + @test only(values).status === leaf.status + end + with_call_targets(leaves) do values + @test only(values).status === leaf.status + end + @test !leaf.context_cache.in_use + end + pending = evaluate_call!(root_context, :middle) + counts = copy(data.kernels) + before = Scene.scientific_state(data.model) + random_state = Scene.rng_probe(data.rng) + accept_call!(pending) + @test data.kernels == counts + @test Scene.scientific_state(data.model) == before + @test Scene.rng_probe(data.rng) == random_state + @test_throws ArgumentError accept_call!(pending) + return nothing +end + +@testset "public prepared Vector collection APIs keep ordinary semantics" begin + ordinary, activated = Scene.fixture(), Scene.fixture() + schemas = Scene.observed_schemas(activated.simulation).schemas + prepared = PSE._prepare_execution_batch_schemas(activated.simulation, schemas) + inspect_calls(ordinary, ordinary.simulation; prepared=false) + inspect_calls(activated, prepared; prepared=true) + @test Scene.scientific_state(ordinary.model) == Scene.scientific_state(activated.model) + @test Scene.rng_probe(ordinary.rng) == Scene.rng_probe(activated.rng) + @test Scene.history(ordinary.simulation) == Scene.history(prepared) +end + +@testset "empty prepared Vector preserves public count and buffer contracts" begin + witness = Scene.fixture() + leaf_batch_type = Scene.observed_schemas(witness.simulation).LeafB + data = Scene.fixture(; leaves=false) + schemas = Scene.observed_schemas(data.simulation; + borrowed_leaf_batch=leaf_batch_type).schemas + simulation = PSE._prepare_execution_batch_schemas(data.simulation, schemas) + step!(simulation) + run_call!(data.capture[], :middle; publish=false) + @test data.kernels == Dict(:root => 1, :middle => 2, :leaf => 0) + before = Scene.scientific_state(data.model) + random_state = Scene.rng_probe(data.rng) + cells = Scene.status_cells(data.model) + for context in values(data.contexts) + leaves = call_targets(context, :leaf) + @test leaves.execution_batches isa Vector + @test isempty(leaves.execution_batches) + @test isempty(leaves) + @test size(leaves) == (0,) + @test iterate(leaves) === nothing + @test isempty(collect(leaves)) + @test_throws BoundsError leaves[1] + @test_throws ArgumentError only(leaves) + @test_throws ArgumentError call_model(context, :leaf) + buffer_id = with_call_targets(leaves) do targets + @test isempty(targets) + objectid(targets) + end + with_call_targets(leaves) do targets + @test isempty(targets) + @test objectid(targets) == buffer_id + end + evaluation = evaluate_call!(context, :leaf) + @test isempty(call_targets(evaluation)) + counts = copy(data.kernels) + accept_call!(evaluation) + @test data.kernels == counts + @test_throws ArgumentError accept_call!(evaluation) + end + @test Scene.scientific_state(data.model) == before + @test Scene.rng_probe(data.rng) == random_state + Scene.assert_same_cells(data.model, cells) +end + +end # module PreparedCallVectorAPIChecks diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl new file mode 100644 index 000000000..8e633e7aa --- /dev/null +++ b/test/test-model-prepared-growth-schemas.jl @@ -0,0 +1,216 @@ +module PreparedExecutionSchemaGrowthTests + +using Test + +using PlantSimEngine +const PSE = PlantSimEngine + +@process "closure_pulse" verbose=false +@process "closure_controller" verbose=false +@process "closure_leaf" verbose=false + +struct Pulse <: AbstractClosure_PulseModel end +struct HardController <: AbstractClosure_ControllerModel end +struct GrowthController <: AbstractClosure_ControllerModel + birth_day::Base.RefValue{Int} + seed::Base.RefValue{Float64} +end +struct LeafState <: AbstractClosure_LeafModel end + +PSE.inputs_(::Pulse) = NamedTuple() +PSE.outputs_(::Pulse) = (rate=0.0,) +PSE.inputs_(::Union{HardController,GrowthController}) = (rate=Default(0.0),) +PSE.outputs_(::HardController) = (ticks=0, pulse_total=0.0) +PSE.outputs_(::GrowthController) = ( + ticks=0, pulse_total=0.0, created=false, births=0, born_value=0.0, +) +PSE.inputs_(::LeafState) = (seed=Required(Real),) +PSE.outputs_(::LeafState) = (value=0.0, visits=0) + +function PSE.run!(::Pulse, status, environment, constants, context) + status.rate += 2.0 + return nothing +end + +function PSE.run!(::HardController, status, environment, constants, context) + run_call!(context, :pulse; publish=true) + status.ticks += 1 + status.pulse_total += status.rate + return nothing +end + +function PSE.run!(model::GrowthController, status, environment, constants, context) + run_call!(context, :pulse; publish=true) + status.ticks += 1 + status.pulse_total += status.rate + if !status.created && status.ticks >= model.birth_day[] + leaf = register_object!(runtime_model(context), Object(:leaf; + scale=:Leaf, parent=:owner, status=Status(seed=model.seed[]))) + run_initializer!(context, :initialize, leaf) + status.created = true + status.births += 1 + end + if status.created + status.born_value = model_status(runtime_model(context), :leaf).value + end + return nothing +end + +function PSE.run!(::LeafState, status, environment, constants, context) + status.value += status.seed + status.visits += 1 + return nothing +end + +function make_hardcall() + return CompositeModel(Object(:owner; scale=:Scene, + status=Status(rate=0.0, ticks=0, pulse_total=0.0)); + applications=( + ModelSpec(HardController(); name=:controller, on=One(id=:owner), + inputs=(rate=One(within=Self(), application=:pulse, var=:rate),), + calls=(pulse=One(within=Self(), application=:pulse),)), + ModelSpec(Pulse(); name=:pulse, on=One(id=:owner)), + ), + ) +end + +function make_growth() + birth_day = Ref(2) + seed = Ref(3.0) + model = CompositeModel(Object(:owner; scale=:Scene, + status=Status(rate=0.0, ticks=0, pulse_total=0.0, + created=false, births=0, born_value=0.0)); + applications=( + ModelSpec(GrowthController(birth_day, seed); + name=:controller, on=One(id=:owner), + inputs=(rate=One(within=Self(), application=:pulse, var=:rate),), + calls=( + pulse=One(within=Self(), application=:pulse), + initialize=Initializer(One(within=Subtree(), scale=:Leaf, application=:leaf)), + )), + ModelSpec(LeafState(); name=:leaf, on=Many(scale=:Leaf)), + ModelSpec(Pulse(); name=:pulse, on=One(id=:owner)), + ), + ) + return (; model, birth_day, seed) +end + +# Exact reference-field types required by this deliberately finite fixture. +# These are empty family descriptors, never fake scientific statuses or values. +const LeafSeedStatus = Status{(:seed,),Tuple{Base.RefValue{Float64}}} +const LeafFullStatus = Status{(:seed,:value,:visits), + Tuple{Base.RefValue{Float64},Base.RefValue{Float64},Base.RefValue{Int}}} + +empty_family(::Type{S}) where {S} = PSE.ObjectFamily{ObjectId{Symbol},S}( + Union{Nothing,PSE.ObjectFamilyRow{ObjectId{Symbol},S}}[]) + +function with_closed_registry(model::PSE.CompositeModel; future=()) + previous = model.registry + closed = PSE._closed_object_family_store(previous.objects) + families = (closed.catalog.families..., map(empty_family, future)...) + store = PSE.ObjectFamilyStore(PSE.ClosedObjectFamilyCatalog(families), + closed.locations, closed.status_owners, copy(closed.layout_cache)) + registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + return PSE.CompositeModel( + registry, model.applications, model.environment, model.instances, + model.source_adapter, model.status_conversion, model.status_conversion_records, + model.status_source_owners, model.status_source_identities, + model.scenario_plan_cache, model.binding_cache, model.environment_binding_cache, + model.bindings_dirty, model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, model.revision, + model.environment_revision, + ) +end + +function future_leaf_batch_type(simulation) + compiled = simulation.compiled + application = compiled.applications_by_id[:leaf] + environment_plan = simulation.environment_bindings.application_plans_by_id[:leaf] + @assert environment_plan.backend isa PSE.GlobalConstant{Nothing} + @assert environment_plan.uses_raw_global_source + @assert isempty(application.target_ids) + Empty = NamedTuple{(),Tuple{}} + I = ObjectId{Symbol} + # This descriptor is explicitly admitted alongside LeafSeedStatus above. + # No Leaf, Status, scientific default, or callback is instantiated here. + View = PSE.CompiledModelStatusView{LeafFullStatus,LeafFullStatus,Tuple{},Empty,Empty} + Context = PSE.RunContext{typeof(compiled),typeof(application),Tuple{},Empty,Empty, + typeof(simulation.temporal_streams),typeof(simulation.output_retention), + typeof(simulation.constants),PSE.NoEnvironmentOverride,I} + Binding = PSE.CompiledEnvironmentBinding{typeof(environment_plan),Nothing,PSE.EnvironmentContext{I}} + Target = PSE.CompiledExecutionTarget{typeof(PSE.model_(application.spec)),View, + Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} + Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I}} + return PSE.CompiledExecutionBatch{typeof(application),Rows, + PSE.RawGlobalModelEnvironment{Nothing},PSE.CompiledOutputPublication{Tuple{}}} +end + +function prepare_schema_growth() + setup = make_growth() + model = with_closed_registry(setup.model;future=(LeafSeedStatus,LeafFullStatus)) + simulation = run!(model;steps=0,outputs=:none) + controller = only(simulation.execution_plan.groups) + controller_batch = only(controller.batches) + context = only(controller_batch.targets).context + pulse = only(target for target in context.calls if PSE._compiled_call_name(target.binding) === :pulse) + @test PSE._compiled_call_mode(pulse.binding) === :manual + PulseBatch = typeof(only(PSE._materialize_call_execution_batches!(pulse))) + pulse_schema = PSE.PreparedExecutionBatchSchema{Vector{PulseBatch}}() + LeafBatch = future_leaf_batch_type(simulation) + leaf_schema = PSE.PreparedExecutionBatchSchema{Vector{LeafBatch}}() + ControllerBatch = PSE._execution_batch_type_with_call_schemas(typeof(controller_batch), + (pulse=pulse_schema,initialize=leaf_schema)) + controller_schema = PSE.PreparedExecutionBatchSchema{Vector{ControllerBatch}}() + before_status = model_status(model,:owner) + before_reference = PSE.refvalue(before_status,:ticks) + original_store = simulation.execution_plan.cohorts + prepared = PSE._prepare_execution_batch_schemas(simulation, + (controller=controller_schema,leaf=leaf_schema,pulse=pulse_schema)) + @test prepared.temporal_streams.streams === simulation.temporal_streams.streams + @test prepared.execution_plan.cohorts !== original_store + @test before_reference === PSE.refvalue(model_status(model,:owner),:ticks) + @test current_step(prepared) == 0 + @test before_status.ticks == 0 + @test before_status.rate == 0.0 + @test !before_status.created + return (;simulation=prepared,owner=before_status,setup.birth_day,setup.seed,LeafBatch) +end + +@testset "explicit future Leaf metadata uses the canonical initializer and growth engine" begin + for (steps,birth,seed,visits) in ((0,2,3.0,0),(1,2,3.0,0),(2,2,3.0,1),(4,2,3.0,3)) + state = prepare_schema_growth() + state.birth_day[] = birth + state.seed[] = seed + leaf_group = only(group for group in state.simulation.execution_plan.groups + if group.application.id === :leaf) + @test isempty(leaf_group.batches) + @test isempty(leaf_group.membership.object_ids) + @test eltype(leaf_group.batches) === state.LeafBatch + @test state.simulation.execution_plan.topology isa PSE.DynamicExecution + continue!(state.simulation;steps) + @test state.owner.ticks == steps + @test state.owner.rate == 2.0steps + @test state.owner.pulse_total == steps*(steps+1) + @test state.owner.births == (steps >= birth ? 1 : 0) + @test state.owner.created == (steps >= birth) + if steps >= birth + status = model_status(state.simulation.model,:leaf) + @test status.visits == visits + @test status.value == seed*visits + @test state.owner.born_value == seed*visits + current = only(group for group in state.simulation.execution_plan.groups + if group.application.id === :leaf) + @test current === leaf_group + batch = only(current.batches) + @test typeof(batch) === state.LeafBatch + payload = only(batch.targets) + @test payload.status_view.canonical_status === status + @test PSE.refvalue(payload.status_view.status,:value) === PSE.refvalue(status,:value) + @test only(batch.targets).call_context_cache.execution_stamp === + payload.status_view.execution_stamp + end + end +end + +end diff --git a/test/test-model-prepared-missing-future-schema.jl b/test/test-model-prepared-missing-future-schema.jl new file mode 100644 index 000000000..efa9018a2 --- /dev/null +++ b/test/test-model-prepared-missing-future-schema.jl @@ -0,0 +1,56 @@ +module PreparedExecutionMissingFutureSchemaTests +using PlantSimEngine, Test +const PSE = PlantSimEngine +const Fixtures = getfield(parentmodule(@__MODULE__),:ColdCallSchemaActivationChecks) + +function recorded_views(simulation) + views = PSE.ExecutionCohortRows[] + function visit(batch) + push!(views,batch.targets) + for target in batch.targets, calls in target.context.calls + batches = PSE._cached_call_execution_batches(calls) + isnothing(batches) && continue + for child in batches + visit(child) + end + end + end + for group in simulation.execution_plan.groups, batch in group.batches + visit(batch) + end + return [(view=view,indices=copy(view.indices)) for view in views] +end + +@testset "a genuine unadmitted reference family rejects before changing live cohort rows" begin + data = Fixtures.fixture() + schemas = Fixtures.observed_schemas(data.simulation).schemas + simulation = PSE._prepare_execution_batch_schemas(data.simulation,schemas) + step!(simulation) + cells = Fixtures.status_cells(data.model) + science = Fixtures.scientific_state(data.model) + random_state = Fixtures.rng_probe(data.rng) + store = simulation.execution_plan.cohorts + locations = copy(store.locations) + payloads = Dict(key=>PSE._execution_cohort_target(location) for (key,location) in locations) + views = recorded_views(simulation) + # An output declaration is not a supplied-reference storage constraint. + # This is a real registered organ with a Float32 Ref, not a dummy witness. + newborn = register_object!(data.model,Object(:leaf_bad;scale=:Leaf, + parent=:middle_a,status=Status(visits=0,value=0f0,payload=zeros(2)))) + @test newborn.status.value isa Float32 + @test_throws "prepared execution schema" call_targets(data.capture[],:middle; + objects=(:middle_a,)) + @test Set(keys(store.locations)) == Set(keys(locations)) + @test all(store.locations[key] === location for (key,location) in locations) + @test all(PSE._execution_cohort_target(store.locations[key]) === target for (key,target) in payloads) + @test all(snapshot.view.indices == snapshot.indices for snapshot in views) + for ((id,name),reference) in cells + @test PSE.refvalue(model_status(data.model,id),name) === reference + end + @test all(NamedTuple(model_status(data.model,id)) == value for (id,value) in science) + @test Fixtures.rng_probe(data.rng) == random_state + @test data.kernels == Dict(:root=>1,:middle=>0,:leaf=>0) + @test newborn.status.value === 0f0 + @test newborn.status.visits == 0 +end +end diff --git a/test/test-model-slot-group-refresh.jl b/test/test-model-slot-group-refresh.jl index ecf861096..7260358ba 100644 --- a/test/test-model-slot-group-refresh.jl +++ b/test/test-model-slot-group-refresh.jl @@ -62,23 +62,31 @@ end reordered = (second_group, nothing, first_group) visited = falses(3) counts = PSE._with_previous_execution_group(reordered, - first_group.application.id, 1, visited) do group + first_group.application, visited) do group @test group === first_group return (2, 3, 1) end @test counts === (2, 3, 1) @test visited == Bool[false, false, true] preferred_counts = PSE._with_previous_execution_group(reordered, - second_group.application.id, 1, visited) do group + second_group.application, visited) do group @test group === second_group return (0, 0, 1) end @test preferred_counts === (0, 0, 1) @test visited == Bool[true, false, true] + missing_application = simulation.execution_plan.groups[3].application missing_visited = falses(3) - missing_counts = PSE._with_previous_execution_group(reordered, - :missing, 9, missing_visited) do group + invoked = Ref(false) + @test_throws "prepared execution-group schema" PSE._with_previous_execution_group( + group -> (invoked[] = true; (0, 0, 0)), reordered, + missing_application, missing_visited, + ) + @test !invoked[] + @test !any(missing_visited) + missing_counts = PSE._with_previous_execution_group(collect(reordered), + missing_application, missing_visited) do group @test isnothing(group) return (0, 0, 0) end From 8010ab3140e5647de6b8041d48fec464445a5317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 04:57:37 +0100 Subject: [PATCH 021/324] Preserve identity families through calls and lifecycle metadata --- src/composite_model/compilation.jl | 74 ++-- src/composite_model/environment_bindings.jl | 5 +- .../execution_batch_schemas.jl | 6 +- src/composite_model/execution_cohorts.jl | 16 +- src/composite_model/execution_storage.jl | 80 +++- src/composite_model/runtime_outputs.jl | 36 +- test/runtests.jl | 1 + test/test-model-call-cohort-retirement.jl | 346 ++++++++++++++++++ 8 files changed, 491 insertions(+), 73 deletions(-) create mode 100644 test/test-model-call-cohort-retirement.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 44548e80c..cfc0a096a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -20,9 +20,23 @@ end """ Object-dependent runtime state for one compiled application. """ -mutable struct CompiledModelApplication{P} +mutable struct CompiledModelApplication{P,I<:ObjectId} const plan::P - target_ids::Vector{ObjectId} + target_ids::Vector{I} +end + +# Ordinary registries admit future identity types. Explicitly closed registries +# retain their finite identity family in the same mutable membership vectors. +_application_target_ids(::Type{I}, ids::Vector{I}) where {I<:ObjectId} = ids +_application_target_ids(::Type{I}, ids::AbstractVector{<:ObjectId}) where {I<:ObjectId} = + I[object_id::I for object_id in ids] +_application_target_ids(model::CompositeModel, ids) = + _application_target_ids(keytype(model.registry.objects), ids) + +function _partial_model_application(application::CompiledModelApplication{P,I}, + target_ids::AbstractVector{<:ObjectId}, +) where {P,I} + return CompiledModelApplication(application.plan, _application_target_ids(I, target_ids)) end @inline function Base.getproperty( @@ -903,9 +917,14 @@ end # The snapshot owns its target lists. Runtime application membership can # change during growth, so each binding compilation takes a private copy. -struct PreparedScenario{P} +struct PreparedScenario{P,I<:ObjectId} plan::P - target_ids::Vector{Vector{ObjectId}} + target_ids::Vector{Vector{I}} +end + +function _prepared_application_targets(model, applications; copy_targets=false) + T = Vector{keytype(model.registry.objects)} + return T[copy_targets ? copy(app.target_ids) : app.target_ids for app in applications] end Base.@nospecializeinfer function _scenario_applications(prepared::PreparedScenario) @@ -1596,10 +1615,10 @@ mutable struct CompiledModelStatusView{S,C,T,P,BI} const bound_inputs::BI end -struct CompiledModelCallBinding{P} +struct CompiledModelCallBinding{P,I<:ObjectId,J<:ObjectId} plan::P - consumer_id::ObjectId - callee_object_ids::Vector{ObjectId} + consumer_id::I + callee_object_ids::Vector{J} callee_application_ids::Vector{Symbol} # The binding stays immutable while lifecycle refreshes extend or rebuild # its shared target vectors in place. Keep the corresponding generation in @@ -1615,11 +1634,11 @@ end function CompiledModelCallBinding( plan::P, - consumer_id::ObjectId, - callee_object_ids::Vector{ObjectId}, + consumer_id::I, + callee_object_ids::Vector{J}, callee_application_ids::Vector{Symbol}, -) where {P} - return CompiledModelCallBinding{P}( +) where {P,I<:ObjectId,J<:ObjectId} + return CompiledModelCallBinding{P,I,J}( plan, consumer_id, callee_object_ids, @@ -1841,7 +1860,7 @@ function refresh_bindings!( model, preparation, _model_timeline(model); performance, ) prepared = PreparedScenario(plan, - Vector{ObjectId}[application.target_ids for application in applications]) + _prepared_application_targets(model, applications)) end end end @@ -2324,13 +2343,13 @@ function _prepare_scenario_plan( compiled.scenario_plan.authoring.preparation === preparation && compiled.scenario_plan.timeline.base_step_seconds == timeline.base_step_seconds prepared = PreparedScenario(compiled.scenario_plan, - Vector{ObjectId}[copy(app.target_ids) for app in compiled.applications]) + _prepared_application_targets(model, compiled.applications; copy_targets=true)) preparation.resolved = prepared return prepared end end plan, applications = _resolve_prepared_scenario(model, preparation, timeline; performance) - prepared = PreparedScenario(plan, Vector{ObjectId}[app.target_ids for app in applications]) + prepared = PreparedScenario(plan, _prepared_application_targets(model, applications)) # A running simulation still needs its pending topology refresh. Give # an adapter the requested snapshot without replacing that live plan. if !force && model.bindings_dirty && !isnothing(model.binding_cache) @@ -3959,10 +3978,7 @@ function _refresh_scene_call_bindings!( _sort_object_ids!(target_ids) push!( affected_call_applications, - CompiledModelApplication( - application.plan, - target_ids, - ), + _partial_model_application(application, target_ids), ) end end @@ -4159,10 +4175,7 @@ function _extend_compiled_scene( started_at = _runtime_performance_start(performance) added_applications = CompiledModelApplication[ - CompiledModelApplication( - application.plan, - new_targets[application.id], - ) + _partial_model_application(application, new_targets[application.id]) for application in new_target_applications ] new_call_bindings, changed_call_target_keys, observed_manual_call_binding_indices_by_callee_target = @@ -4464,10 +4477,7 @@ function _extend_compiled_scene( _sort_object_ids!(target_ids) push!( rewired_applications, - CompiledModelApplication( - application.plan, - target_ids, - ), + _partial_model_application(application, target_ids), ) end (added_applications..., rewired_applications...) @@ -5018,7 +5028,7 @@ function _resolve_application_recipes( for recipe in recipes target_matcher = _resolve_selector_matcher(model, recipe.target_matcher) selector = applies_to(recipe.spec) - target_ids = _resolve_object_ids(model, selector, target_matcher) + target_ids = _application_target_ids(model, _resolve_object_ids(model, selector, target_matcher)) sizehint!(target_ids, length(target_ids) + 1) spec = _model_spec_with_environment_hints( model, recipe.spec, _model_application_hint_scale(model, target_ids), @@ -5474,14 +5484,14 @@ function _validate_model_writers_for_objects!( return _validate_model_writer_groups!(groups) end -function _model_application_hint_scale(model::CompositeModel, target_ids::Vector{ObjectId}) +function _model_application_hint_scale(model::CompositeModel, target_ids::AbstractVector{<:ObjectId}) isempty(target_ids) && return :Scene scales = unique!([_model_object(model, object_id).scale for object_id in target_ids]) length(scales) == 1 && return something(only(scales), :Default) return :Mixed end -function _model_application_clock(model::CompositeModel, spec, target_ids::Vector{ObjectId}, timeline) +function _model_application_clock(model::CompositeModel, spec, target_ids::AbstractVector{<:ObjectId}, timeline) process_model = model_(spec) source = _runtime_clock_source_for_spec(spec) source == :environment_base_step || return _model_clock(spec, process_model, timeline) @@ -8674,12 +8684,12 @@ function _resolved_compiled_call_membership( binding::CompiledModelCallBinding, ) model = compiled.model - object_ids = _dependency_object_ids( + object_ids = _application_target_ids(model, _dependency_object_ids( model, binding.selector, binding.matcher, binding.consumer_id, - ) + )) if bindings_dirty(model) && !isempty(lifecycle_delta(model).added) # A newborn has no compiled application/status/environment target until # the safe refresh barrier. Keep it out of a first complete view so the @@ -8841,7 +8851,7 @@ function _compile_model_call_bindings( CompiledModelCallBinding( plan, consumer_id, - callee_object_ids, + _application_target_ids(model, callee_object_ids), callee_application_ids, ), ) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 0399cf535..2b2da9372 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -612,10 +612,7 @@ function _refresh_environment_bindings_for_objects( haskey(model.registry.objects, object_id) || continue for slot in current_applications _with_metadata_entry(current_applications.applications, slot) do application - partial_application = CompiledModelApplication( - application.plan, - ObjectId[object_id], - ) + partial_application = _partial_model_application(application, ObjectId[object_id]) for binding in _compile_environment_bindings_for_applications( model, (partial_application,), diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index bbc224b64..22e69f5c3 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -288,7 +288,7 @@ function _materialize_prepared_call_execution_batches!(schema::PreparedExecution cohort_schema=_execution_cohort_schema(schema), batch_schema=schema) if targets.tracks_full_membership _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches; - schema=_execution_cohort_schema(schema)) + schema=_execution_cohort_schema(schema), batch_schema=schema) end # Publish a complete validated replacement, preserving retained lease shells. targets.execution_batches = batches @@ -593,7 +593,9 @@ end Plan = fieldtype(B,:plan) index = findfirst(==(Plan),collect(fieldtypes(plans))) isnothing(index) && return :(throw(ArgumentError("A retained call no longer has its prepared declaration."))) - Bindings = Tuple{[CompiledModelCallBinding{T} for T in fieldtypes(plans)]...} + CallerId = fieldtype(B,:consumer_id) + CalleeId = eltype(fieldtype(B,:callee_object_ids)) + Bindings = Tuple{[CompiledModelCallBinding{T,CallerId,CalleeId} for T in fieldtypes(plans)]...} return quote bindings = get(compiled.call_bindings_by_target, (binding.application_id,binding.consumer_id),()) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 69b81c610..6c09932d5 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -89,9 +89,17 @@ end return _execution_cohort_schema_expression(B, true) end -function _check_execution_cohort_location(location, owner, application_id, object_id) +# Ordinary stores may use arbitrary owner values. Closed execution first +# admits the stored owner to the concrete expected type, before comparison. +@inline _execution_cohort_owner_matches(::OpenExecutionCohortSchema, stored, expected) = isequal(stored, expected) +@inline function _execution_cohort_owner_matches(::ClosedExecutionCohortSchema, stored, expected::O) where {O} + return stored isa O && isequal(stored::O, expected) +end + +function _check_execution_cohort_location(location, owner, application_id, object_id, + schema=OpenExecutionCohortSchema()) cohort = location.cohort - isequal(cohort.owner, owner) && cohort.application_id === application_id && + _execution_cohort_owner_matches(schema, cohort.owner, owner) && cohort.application_id === application_id && get(cohort.indices, object_id, 0) == location.row || throw(ArgumentError( "The execution location belongs to another owner, application or object.", )) @@ -106,14 +114,14 @@ end # Select the actual cohort before invoking the operation. An assertion after a # dynamic read/clear would leave the abstract operation reachable by JuliaC. -@generated function _with_execution_cohort_location(f, ::ClosedExecutionCohortSchema{T}, location::ExecutionCohortLocation, owner, application_id, object_id) where {T} +@generated function _with_execution_cohort_location(f, schema::ClosedExecutionCohortSchema{T}, location::ExecutionCohortLocation, owner, application_id, object_id) where {T} branches = Expr[] for Target in fieldtypes(T) I = fieldtype(Target, :object_id) L = ExecutionCohortLocation{ExecutionCohort{Target,I}} push!(branches, quote if location isa $L - _check_execution_cohort_location(location, owner, application_id, object_id) + _check_execution_cohort_location(location, owner, application_id, object_id, schema) return f(location) end end) diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl index 3ddcae69c..d9610a761 100644 --- a/src/composite_model/execution_storage.jl +++ b/src/composite_model/execution_storage.jl @@ -36,27 +36,87 @@ _execution_cohort_store(::Nothing) = ExecutionCohortStore() _insert_with_spare_capacity!(rows::ExecutionCohortRows, position::Integer, target) = insert!(rows, position, target) -function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches; schema=OpenExecutionCohortSchema()) +# The caller identity and the callee identity schema are independent. The +# latter comes only from this already admitted application's target families. +@generated function _execution_retirement_key_type(::ClosedExecutionCohortSchema{T}) where {T} + ids = unique(fieldtype(Target, :object_id) for Target in fieldtypes(T)) + Key = Tuple{Symbol,Union{ids...}} + return :($Key) +end + +@inline _with_execution_retirement_id(f, ::OpenExecutionCohortSchema, id) = f(id) +@generated function _with_execution_retirement_id(f, ::ClosedExecutionCohortSchema{T}, id) where {T} + ids = unique(fieldtype(Target, :object_id) for Target in fieldtypes(T)) + branches = [:(id isa $I && return f(id::$I)) for I in ids] + return quote + $(branches...) + throw(ArgumentError("The retired target identity is outside its prepared callee schema.")) + end +end + +# Keep the ordinary representation and its equality behavior unchanged. +_call_retirement_current(::OpenExecutionCohortSchema, batches, batch_schema) = + Set((batch.application.id, target.object_id) for batch in batches for target in batch.targets) +_call_retirement_obsolete(::OpenExecutionCohortSchema) = Tuple{Symbol,ObjectId}[] +_call_retirement_obsolete(schema::ClosedExecutionCohortSchema) = Vector{_execution_retirement_key_type(schema)}() + +function _collect_call_retirement_current!(current, schema, batch) + for raw_target in batch.targets + _with_execution_cohort_target(schema, raw_target) do target + # Selection of the concrete target precedes pair construction. + push!(current, (batch.application.id, target.object_id)) + end + end + return nothing +end + +function _call_retirement_current(schema::ClosedExecutionCohortSchema, batches, batch_schema) + current = Set{_execution_retirement_key_type(schema)}() + for batch in batches + if isnothing(batch_schema) + _collect_call_retirement_current!(current, schema, batch) + else + _with_execution_batch(batch_schema, batch) do actual + _collect_call_retirement_current!(current, schema, actual) + end + end + end + return current +end + +function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches; + schema=OpenExecutionCohortSchema(), batch_schema=nothing) store = storage.cohorts owner = _execution_call_owner(binding) - current = Set((batch.application.id, target.object_id) - for batch in batches for target in batch.targets) - obsolete = Tuple{Symbol,ObjectId}[] + current = _call_retirement_current(schema, batches, batch_schema) + obsolete = _call_retirement_obsolete(schema) for (candidate_owner, application_id, object_id) in keys(store.locations) - isequal(owner, candidate_owner) || continue - (application_id, object_id) in current || push!(obsolete, (application_id, object_id)) + # Preserve the original argument order for arbitrary ordinary owners. + matches = schema isa OpenExecutionCohortSchema ? isequal(owner, candidate_owner) : + _execution_cohort_owner_matches(schema, candidate_owner, owner) + matches || continue + _with_execution_retirement_id(schema, object_id) do admitted_id + key = (application_id, admitted_id) + key in current || push!(obsolete, key) + end end + # Admit every existing payload/namespace before clearing the first row. for (application_id, object_id) in obsolete - location = cohort_location(store, application_id, object_id; owner) - _with_execution_cohort_location(identity, schema, location, owner, application_id, object_id) + _with_execution_retirement_id(schema, object_id) do admitted_id + location = cohort_location(store, application_id, admitted_id; owner) + _with_execution_cohort_location(identity, schema, location, owner, application_id, admitted_id) + end end for (application_id, object_id) in obsolete - remove_cohort_target!(store, application_id, object_id; owner, schema) + _with_execution_retirement_id(schema, object_id) do admitted_id + remove_cohort_target!(store, application_id, admitted_id; owner, schema) + end end return nothing end -_retire_call_cohort_targets!(::Nothing, binding, batches; schema=OpenExecutionCohortSchema()) = nothing +_retire_call_cohort_targets!(::Nothing, binding, batches; + schema=OpenExecutionCohortSchema(), batch_schema=nothing) = nothing _execution_call_owner(binding) = ( binding.application_id, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 7d30b041a..91e9f2571 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -865,7 +865,8 @@ function _record_call_execution_batch_cache!( cohort_schema=OpenExecutionCohortSchema(), ) if targets.tracks_full_membership - _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches; schema=cohort_schema) + _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches; + schema=cohort_schema, batch_schema=targets.batch_schema) end targets.last_single_snapshot = nothing cached.batches = if targets.tracks_full_membership @@ -3584,7 +3585,7 @@ function _compiled_call_execution_batches( for application_id in binding.callee_application_ids _compiled_application_by_id(compiled,application_id) do application application_schema = _call_batch_schema_for_application(batch_schema,application) - current_ids = ObjectId[object_id for object_id in binding.callee_object_ids + current_ids = [object_id for object_id in binding.callee_object_ids if _call_binding_target_matches(binding,application,object_id)] refreshed = refresh_cohort_membership!(cohorts,application.id,current_ids, nothing;owner,schema=admission) do object_id, previous_target @@ -4058,7 +4059,7 @@ function _extend_execution_target_call_batches_by_prefix!( batches = _execution_call_batches_for_application(schema, application_schema, execution_batches, application_id) isempty(batches) && return false - current_ids = ObjectId[object_id for object_id in binding.callee_object_ids + current_ids = [object_id for object_id in binding.callee_object_ids if _call_binding_target_matches(binding, application, object_id)] # Preserve the existing ordered-prefix algorithm. Only the # count leaves each admitted concrete batch operation. @@ -4333,13 +4334,15 @@ function _refresh_model_execution_group!( ) end -function _changed_execution_target_ids_by_application(changed_execution_target_ids) - changed_by_application = Dict{Symbol,Vector{ObjectId}}() +function _changed_execution_target_ids_by_application(changed_execution_target_ids, + ::Type{I}, +) where {I<:ObjectId} + changed_by_application = Dict{Symbol,Vector{I}}() for (application_id, object_id) in changed_execution_target_ids object_ids = get!(changed_by_application, application_id) do - ObjectId[] + I[] end - push!(object_ids, object_id) + push!(object_ids, object_id::I) end for object_ids in values(changed_by_application) _sort_object_ids!(object_ids) @@ -4379,9 +4382,9 @@ end # Prefer the current authored position, then search the existing owners by id. # Only scalar counts leave the concrete callback; there is one lookup loop for # both representations. Incompatible closed application types never enter f. -function _with_previous_execution_group(f, slots, application::CompiledModelApplication, +function _with_previous_execution_group(f::F, slots, application::CompiledModelApplication, visited::BitVector, -) +) where {F} preferred_slot = application.slot for candidate in 0:length(slots) slot = iszero(candidate) ? preferred_slot : candidate @@ -4465,6 +4468,7 @@ function _refresh_model_execution_plan( changed_by_application = isnothing(changed_application_ids) ? nothing : _changed_execution_target_ids_by_application( changed_execution_target_ids, + keytype(compiled.model.registry.objects), ) previous_slots = previous.groups_by_application_slot _preflight_execution_group_layout!(previous,compiled,previous_slots) @@ -5512,17 +5516,7 @@ function _call_target_object_ids(model::CompositeModel, objects) objects : (objects,) ids = ObjectId[_call_target_object_id(model, object) for object in requested] unique!(ids) - return ids -end - -function _partial_model_application( - application::CompiledModelApplication, - target_ids::Vector{ObjectId}, -) - return CompiledModelApplication( - application.plan, - target_ids, - ) + return _application_target_ids(model, ids) end struct _ApplicationsByObjectOverlay{B,O} @@ -6193,7 +6187,7 @@ function _current_topology_call_targets( selected_binding = CompiledModelCallBinding( resolved_binding.plan, resolved_binding.consumer_id, - requested_ids, + _application_target_ids(model, requested_ids), callee_application_ids, ) if !isnothing(context.temporal_streams) && diff --git a/test/runtests.jl b/test/runtests.jl index c85e12c0f..d2cee20dd 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -60,6 +60,7 @@ else @testset "Prepared execution schemas" begin include("test-model-closed-cohort-schemas.jl") + include("test-model-call-cohort-retirement.jl") include("test-model-closed-group-refresh.jl") include("test-model-closed-group-layout-preflight.jl") include("test-model-prepared-call-schemas.jl") diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl new file mode 100644 index 000000000..943d86c72 --- /dev/null +++ b/test/test-model-call-cohort-retirement.jl @@ -0,0 +1,346 @@ +module CallCohortRetirementChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "retirement_caller" verbose=false +PSE.@process "retirement_leaf" verbose=false +struct Caller <: AbstractRetirement_CallerModel + capture::Base.RefValue{Any} +end +struct Leaf <: AbstractRetirement_LeafModel end +PSE.inputs_(::Union{Caller,Leaf}) = NamedTuple() +PSE.outputs_(::Caller) = (caller_visits=0,) +PSE.outputs_(::Leaf) = (leaf_visits=0,) +function PSE.run!(model::Caller, status, environment, constants, context) + model.capture[] = context + status.caller_visits += 1 + run_call!(context, :left; publish=false) + run_call!(context, :right; publish=false) + return nothing +end +PSE.run!(::Leaf, status, environment, constants, context) = (status.leaf_visits += 1; nothing) + +# Real authored bindings: the caller has a Symbol identity, its callees Int IDs. +function fixture(; transform=identity, outputs=:none) + capture = Ref{Any}(nothing) + model = CompositeModel( + Object(:caller; scale=:Scene, status=Status(caller_visits=0)), + Object(1; scale=:Leaf, parent=:caller, status=Status(leaf_visits=0)), + Object(2; scale=:Leaf, parent=:caller, status=Status(leaf_visits=0)); + applications=( + ModelSpec(Caller(capture); name=:caller, on=One(id=:caller, scale=:Scene), + calls=(left=Many(scale=:Leaf, application=:leaf), + right=Many(scale=:Leaf, application=:leaf))), + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), + )) + model = transform(model) + simulation = run!(model; steps=0, outputs) + target = only(only(only(simulation.execution_plan.groups).batches).targets) + left = call_targets(target.context, :left) + right = call_targets(target.context, :right) + return (; model, simulation, target, left, right, capture) +end + +# Unit payloads exercise the storage protocol without inventing a Status, +# Required value, default, scientific object or model callback for a type witness. +mutable struct Payload{I,V} + object_id::I + value::V +end +payload(id, value) = Payload(ObjectId(id), Ref(value)) +schema_for(values...) = PSE._closed_execution_cohort_schema(Tuple{map(typeof, values)...}) +storage() = PSE.RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},Any}()) +batch(rows) = (application=(id=:leaf,), targets=rows) +function prefix(rows, count) + return PSE.ExecutionCohortRows{eltype(rows)}(rows.store, rows.cohort, rows.indices[1:count]) +end + +@testset "caller identity remains independent from the callee schema" begin + data = fixture() + application = data.simulation.compiled.applications_by_id[:caller] + for calls in (data.left, data.right) + binding = calls.binding + @test fieldtype(typeof(binding), :consumer_id) === ObjectId{Symbol} + @test binding.consumer_id === ObjectId(:caller) + @test eltype(binding.callee_object_ids) === ObjectId + @test all(id -> id isa ObjectId{Int}, binding.callee_object_ids) + @test PSE._current_call_binding_for_application(data.simulation.compiled, + application, binding) === binding + @test PSE._prepared_call_mode(typeof(binding)) === :manual + @test PSE._prepared_call_name(typeof(binding)) in (:left, :right) + end + @test PSE._execution_call_owner(data.left.binding) != PSE._execution_call_owner(data.right.binding) + @test model_status(data.model, :caller).caller_visits == 0 + @test model_status(data.model, 1).leaf_visits == 0 +end + +@testset "closed retirement removes only its call namespace and preserves references" begin + data = fixture() + runtime = storage() + left_owner, right_owner = map(PSE._execution_call_owner, (data.left.binding, data.right.binding)) + first, second = payload(1, 1.0), payload(2, 2.0) + other_first = Payload(first.object_id, first.value) + other_second = Payload(second.object_id, second.value) + left = PSE.cohort_rows!(runtime.cohorts, :leaf, [first, second]; owner=left_owner) + right = PSE.cohort_rows!(runtime.cohorts, :leaf, [other_first, other_second]; owner=right_owner) + # An unrelated ordinary namespace has a different identity domain. Owner + # filtering must precede closed callee-ID admission. + unrelated = payload(:unrelated, 7.0) + ordinary = PSE.cohort_rows!(runtime.cohorts, :leaf, [unrelated]; owner=:ordinary) + schema = schema_for(first) + @test eltype(PSE._call_retirement_obsolete(schema)) === Tuple{Symbol,ObjectId{Int}} + before_right = copy(right.indices) + right_location = PSE.cohort_location(runtime.cohorts, :leaf, second.object_id; owner=right_owner) + PSE._retire_call_cohort_targets!(runtime, data.left.binding, (batch(prefix(left, 1)),); schema) + @test left[1] === first + @test_throws ArgumentError left[2] + @test right.indices == before_right + @test right[1] === other_first && right[2] === other_second + @test PSE.cohort_location(runtime.cohorts, :leaf, second.object_id; owner=right_owner) === right_location + @test right[2].value === second.value + @test first.value[] == 1.0 && second.value[] == 2.0 + @test ordinary[1] === unrelated +end + +@testset "mixed admitted callee identities retire through the same algorithm" begin + data = fixture() + runtime = storage() + owner = PSE._execution_call_owner(data.left.binding) + integer, symbolic = payload(1, 1.0), payload(:leaf, 2.0f0) + integer_rows = PSE.cohort_rows!(runtime.cohorts, :leaf, [integer]; owner) + symbol_rows = PSE.cohort_rows!(runtime.cohorts, :leaf, [symbolic]; owner) + schema = schema_for(integer, symbolic) + I = Union{ObjectId{Int},ObjectId{Symbol}} + @test eltype(PSE._call_retirement_obsolete(schema)) === Tuple{Symbol,I} + PSE._retire_call_cohort_targets!(runtime, data.left.binding, (); schema) + @test isempty(runtime.cohorts.locations) + @test_throws ArgumentError integer_rows[1] + @test_throws ArgumentError symbol_rows[1] + @test integer.value[] === 1.0 && symbolic.value[] === 2.0f0 +end + +@testset "all identities and old payload families are admitted before the first clear" begin + data = fixture() + owner = PSE._execution_call_owner(data.left.binding) + for invalid in (:identity, :payload) + runtime = storage() + first = payload(1, 1.0) + second = invalid === :identity ? payload(:outside, 2.0) : payload(2, 2.0f0) + first_rows = PSE.cohort_rows!(runtime.cohorts, :leaf, [first]; owner) + second_rows = PSE.cohort_rows!(runtime.cohorts, :leaf, [second]; owner) + locations = copy(runtime.cohorts.locations) + schema = schema_for(first) + @test_throws ArgumentError PSE._retire_call_cohort_targets!(runtime, data.left.binding, (); schema) + @test runtime.cohorts.locations == locations + @test first_rows[1] === first && second_rows[1] === second + @test first.value[] === 1.0 + @test second.value[] === (invalid === :identity ? 2.0 : 2.0f0) + end +end + +struct OwnerAlias{T} + value::T +end +Base.isequal(left::OwnerAlias, right::Tuple) = isequal(left.value, right) +Base.isequal(left::Tuple, right::OwnerAlias) = isequal(left, right.value) +Base.hash(owner::OwnerAlias, seed::UInt) = hash(owner.value, seed) + +@testset "ordinary arbitrary owners keep their existing equality semantics" begin + data = fixture() + runtime = storage() + owner = PSE._execution_call_owner(data.left.binding) + alias = OwnerAlias(owner) + value = payload(1, 3.0) + rows = PSE.cohort_rows!(runtime.cohorts, :leaf, [value]; owner=alias) + location = PSE.cohort_location(runtime.cohorts, :leaf, value.object_id; owner=alias) + @test PSE._execution_cohort_owner_matches(PSE.OpenExecutionCohortSchema(), alias, owner) + @test !PSE._execution_cohort_owner_matches(schema_for(value), alias, owner) + @test PSE._check_execution_cohort_location(location, owner, :leaf, value.object_id) === nothing + @test_throws ArgumentError PSE._with_execution_cohort_location(identity, schema_for(value), + location, owner, :leaf, value.object_id) + @test rows[1] === value + PSE._retire_call_cohort_targets!(runtime, data.left.binding, ()) + @test isempty(runtime.cohorts.locations) + @test_throws ArgumentError rows[1] + @test value.value[] === 3.0 +end + +# The future Symbol Leaf descriptor uses the type of an actual complete Leaf +# status already owned by this scene. It constructs no future Status or object. +function closed_registry_with_future_leaf(model) + previous = model.registry + closed = PSE._closed_object_family_store(previous.objects) + S = typeof(model_status(model, 1)) + future = PSE.ObjectFamily{ObjectId{Symbol},S}( + Union{Nothing,PSE.ObjectFamilyRow{ObjectId{Symbol},S}}[]) + families = (closed.catalog.families..., future) + store = PSE.ObjectFamilyStore(PSE.ClosedObjectFamilyCatalog(families), + closed.locations, closed.status_owners, copy(closed.layout_cache)) + registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + return PSE.CompositeModel( + registry, model.applications, model.environment, model.instances, + model.source_adapter, model.status_conversion, model.status_conversion_records, + model.status_source_owners, model.status_source_identities, + model.scenario_plan_cache, model.binding_cache, model.environment_binding_cache, + model.bindings_dirty, model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, model.revision, + model.environment_revision, + ) +end +current_target(simulation) = only(only(only(simulation.execution_plan.groups).batches).targets) +view_ids(values) = [target.object_id for target in values] +live_state(model) = Dict(object.id => deepcopy(NamedTuple(object.status)) for object in model_objects(model)) +stream_values(simulation) = Dict(key => collect(stream) for (key, stream) in outputs(simulation)) + +# Bottom-up descriptors come from the real zero-step batches, not fake statuses, +# model invocation or a default used as a scientific witness. +function prepared_tree(data) + left_batches = PSE._materialize_call_execution_batches!(data.left) + right_batches = PSE._materialize_call_execution_batches!(data.right) + LeafB = typeof(only(left_batches)) + @test typeof(only(right_batches)) === LeafB + leaf_schema = PSE.PreparedExecutionBatchSchema{Vector{LeafB}}() + root_batch = only(only(data.simulation.execution_plan.groups).batches) + RootB = PSE._execution_batch_type_with_call_schemas(typeof(root_batch), + (left=leaf_schema, right=leaf_schema)) + simulation = PSE._prepare_execution_batch_schemas(data.simulation, + (caller=PSE.PreparedExecutionBatchSchema{Vector{RootB}}(), leaf=leaf_schema)) + target = current_target(simulation) + return merge(data, (simulation=simulation, target=target, + left=call_targets(target.context, :left), right=call_targets(target.context, :right))) +end + +function publish_current_left!(data) + step!(data.simulation) + context = data.capture[] + @test context isa PSE.RunContext + run_call!(context, :left; publish=true) + return context +end + +@testset "closed memberships use the global future identity schema" begin + data = fixture(; transform=closed_registry_with_future_leaf) + I = Union{ObjectId{Symbol},ObjectId{Int}} + @test keytype(data.model.registry.objects) === I + applications = data.simulation.compiled.applications_by_id + for name in (:caller, :leaf) + @test eltype(applications[name].target_ids) === I + end + @test all(id -> id isa ObjectId{Int}, applications[:leaf].target_ids) + for calls in (data.left, data.right) + @test fieldtype(typeof(calls.binding), :consumer_id) === ObjectId{Symbol} + @test eltype(calls.binding.callee_object_ids) === I + @test PSE._current_call_binding_for_application(data.simulation.compiled, + applications[:caller], calls.binding) === calls.binding + end + partial = PSE._partial_model_application(applications[:leaf], ObjectId{Int}[ObjectId(1)]) + @test eltype(partial.target_ids) === I + @test partial.target_ids == [ObjectId(1)] + @test partial.target_ids !== applications[:leaf].target_ids + snapshot = PSE._prepare_scenario_plan(data.model) + @test all(ids -> eltype(ids) === I, snapshot.target_ids) + copied = PSE._scenario_applications(snapshot) + for app in copied + @test eltype(app.target_ids) === I + @test app.target_ids == applications[app.id].target_ids + @test app.target_ids !== applications[app.id].target_ids + end + selected = call_targets(data.target.context, :left; objects=(1,)) + @test eltype(selected.binding.callee_object_ids) === I + @test typeof(selected.binding) === typeof(data.left.binding) + @test view_ids(selected) == [ObjectId(1)] +end + +@testset "ordinary and prepared public calls retain state histories and membership through birth and removal" begin + ordinary = fixture(; transform=closed_registry_with_future_leaf, outputs=:all) + prepared = prepared_tree(fixture(; transform=closed_registry_with_future_leaf, outputs=:all)) + fixtures = (ordinary, prepared) + references = [PSE.refvalue(model_status(data.model, 2), :leaf_visits) for data in fixtures] + held = [data.left for data in fixtures] + for data in fixtures + publish_current_left!(data) + @test model_status(data.model, 1).leaf_visits == 3 + @test model_status(data.model, 2).leaf_visits == 3 + register_object!(data.model, Object(3; scale=:Leaf, parent=:caller, + status=Status(leaf_visits=0))) + context = publish_current_left!(data) + @test model_status(data.model, 1).leaf_visits == 6 + @test model_status(data.model, 2).leaf_visits == 6 + @test model_status(data.model, 3).leaf_visits == 3 + selected = call_targets(context, :left; objects=(3,)) + @test eltype(selected.binding.callee_object_ids) === keytype(data.model.registry.objects) + @test view_ids(selected) == [ObjectId(3)] + end + @test live_state(ordinary.model) == live_state(prepared.model) + @test stream_values(ordinary.simulation) == stream_values(prepared.simulation) + for (data, full_view) in zip(fixtures, held) + @test view_ids(full_view) == [ObjectId(1), ObjectId(2), ObjectId(3)] + remove_object!(data.model, 1) + context = publish_current_left!(data) + @test view_ids(full_view) == [ObjectId(2), ObjectId(3)] + @test eltype(full_view.binding.callee_object_ids) === keytype(data.model.registry.objects) + @test model_status(data.model, 2).leaf_visits == 9 + @test model_status(data.model, 3).leaf_visits == 6 + @test model_status(data.model, :caller).caller_visits == 3 + @test view_ids(call_targets(context, :left; objects=(2,))) == [ObjectId(2)] + @test collect(outputs(data.simulation)[(:leaf, ObjectId(1), :leaf_visits)]) == [(1.0,3), (2.0,6)] + end + for (data, reference) in zip(fixtures, references) + @test PSE.refvalue(model_status(data.model, 2), :leaf_visits) === reference + end + @test live_state(ordinary.model) == live_state(prepared.model) + @test stream_values(ordinary.simulation) == stream_values(prepared.simulation) +end + +@testset "ordinary open identity domains still accept a later Symbol Leaf" begin + data = fixture() + continue!(data.simulation; steps=2) + register_object!(data.model, Object(:later_leaf; scale=:Leaf, parent=:caller, + status=Status(leaf_visits=0))) + step!(data.simulation) + @test keytype(data.model.registry.objects) === ObjectId + @test model_status(data.model, :later_leaf).leaf_visits == 2 + @test ObjectId(:later_leaf) in view_ids(call_targets(data.capture[], :left)) +end + +@testset "an initially empty Many keeps its explicit future Symbol Leaf identity family" begin + function empty_closed(model) + closed = closed_registry_with_future_leaf(model) + remove_object!(closed, 1) + remove_object!(closed, 2) + return closed + end + data = fixture(; transform=empty_closed) + I = Union{ObjectId{Symbol},ObjectId{Int}} + leaf = data.simulation.compiled.applications_by_id[:leaf] + @test isempty(leaf.target_ids) + @test eltype(leaf.target_ids) === I + @test eltype(data.left.binding.callee_object_ids) === I + @test isempty(data.left) + register_object!(data.model, Object(:future_leaf; scale=:Leaf, parent=:caller, + status=Status(leaf_visits=0))) + step!(data.simulation) + @test model_status(data.model, :future_leaf).leaf_visits == 2 + @test view_ids(data.left) == [ObjectId(:future_leaf)] + @test eltype(data.left.binding.callee_object_ids) === I + # Identity metadata under ordinary open execution: no full prepared Target + # family for a future Symbol is claimed by this case. + @test data.left.batch_schema isa PSE.OpenExecutionBatchSchema +end + +@testset "changed targets preserve the admitted identity family and sorting" begin + changed = Set{Tuple{Symbol,ObjectId}}(((:leaf, ObjectId(13)), + (:leaf, ObjectId(1)), (:leaf, ObjectId(:future)), (:caller, ObjectId(:caller)))) + original = copy(changed) + for I in (ObjectId, Union{ObjectId{Int},ObjectId{Symbol}}) + grouped = PSE._changed_execution_target_ids_by_application(changed, I) + @test eltype(grouped[:leaf]) === I + @test grouped[:leaf] == [ObjectId(1), ObjectId(13), ObjectId(:future)] + @test grouped[:caller] == [ObjectId(:caller)] + @test changed == original + end +end + +end # module CallCohortRetirementChecks From 4f58d8a05ddad964d06f238d07dd790e6dbd5590 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 05:12:21 +0100 Subject: [PATCH 022/324] Retain registry identity types in environment indexes --- src/composite_model/environment_bindings.jl | 46 +++-- src/composite_model/runtime_outputs.jl | 5 +- test/runtests.jl | 1 + ...test-model-environment-index-identities.jl | 183 ++++++++++++++++++ 4 files changed, 217 insertions(+), 18 deletions(-) create mode 100644 test/test-model-environment-index-identities.jl diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 2b2da9372..9371a43ba 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -376,11 +376,12 @@ function _compiled_environment_bindings( bindings, by_target, sample_cache=Dict{Tuple{Symbol,Int},Any}(), - positions_by_target=Dict{Tuple{Symbol,ObjectId},Int}( - (binding.application_id, binding.object_id) => index - for (index, binding) in pairs(bindings) + positions_by_target=_index_environment_binding_positions( + bindings, keytype(model.registry.objects), + ), + targets_by_object=_index_environment_targets_by_object( + bindings, keytype(model.registry.objects), ), - targets_by_object=_index_environment_targets_by_object(bindings), ) return CompiledEnvironmentBindings( model, @@ -397,25 +398,42 @@ function _compiled_environment_bindings( ) end -function _index_environment_targets_by_object(bindings) - targets_by_object = Dict{ObjectId,Vector{Tuple{Symbol,ObjectId}}}() +# The binding vector may contain several concrete handle/plan families. These +# indexes need only the fixed metadata fields, never a sampled environment. +@inline function _environment_binding_target_key(binding::CompiledEnvironmentBinding, + ::Type{I}, +) where {I<:ObjectId} + plan = getfield(binding, :plan)::CompiledEnvironmentApplicationPlan + return (getfield(plan, :application_id), getfield(binding, :object_id)::I) +end + +function _index_environment_binding_positions(bindings, ::Type{I}) where {I<:ObjectId} + return Dict{Tuple{Symbol,I},Int}( + _environment_binding_target_key(binding, I) => index + for (index, binding) in pairs(bindings) + ) +end + +function _index_environment_targets_by_object(bindings, ::Type{I}) where {I<:ObjectId} + targets_by_object = Dict{I,Vector{Tuple{Symbol,I}}}() for binding in bindings + target = _environment_binding_target_key(binding, I) push!( - get!(targets_by_object, binding.object_id) do - Tuple{Symbol,ObjectId}[] + get!(targets_by_object, target[2]) do + Tuple{Symbol,I}[] end, - (binding.application_id, binding.object_id), + target, ) end return targets_by_object end -function _index_environment_bindings(bindings) +function _index_environment_bindings(bindings, ::Type{I}) where {I<:ObjectId} # An initially empty application can acquire targets with another schema # during growth. Keep this lifecycle index value-widened; concrete handles # and sampling plans remain in the typed execution targets. - by_target = Dict{Tuple{Symbol,ObjectId},CompiledEnvironmentBinding}( - (binding.application_id, binding.object_id) => binding + by_target = Dict{Tuple{Symbol,I},CompiledEnvironmentBinding}( + _environment_binding_target_key(binding, I) => binding for binding in bindings ) length(by_target) == length(bindings) || error( @@ -434,7 +452,7 @@ function compile_environment_bindings(model::CompositeModel, compiled::CompiledC application_plans_by_id, ) _validate_model_environment_inputs!(bindings, compiled.applications_by_id) - by_target = _index_environment_bindings(bindings) + by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, compiled, @@ -567,7 +585,7 @@ function _reconcile_environment_binding_metadata( cached.targets_by_object, ) _validate_model_environment_inputs!(bindings, compiled.applications_by_id) - by_target = _index_environment_bindings(bindings) + by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, compiled, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 91e9f2571..d1b62834f 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5741,10 +5741,7 @@ function _targeted_call_environment_bindings( cached.application_plans_by_id, ) _validate_model_environment_inputs!(partial, applications_by_id) - by_target = Dict( - (binding.application_id, binding.object_id) => binding - for binding in partial - ) + by_target = _index_environment_bindings(partial, keytype(model.registry.objects)) return _compiled_environment_bindings( model, compiled, diff --git a/test/runtests.jl b/test/runtests.jl index d2cee20dd..825335248 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -294,6 +294,7 @@ else include("test-model-environment-sampling.jl") include("test-model-execution-batch-times.jl") include("test-model-environment-binding-identity.jl") + include("test-model-environment-index-identities.jl") include("test-model-global-environment-sample-schema.jl") end diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl new file mode 100644 index 000000000..f2ab4296f --- /dev/null +++ b/test/test-model-environment-index-identities.jl @@ -0,0 +1,183 @@ +module EnvironmentIndexIdentityChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +mutable struct Backend <: EA.AbstractEnvironmentBackend + values::Dict{Symbol,Float32} + binds::Int +end +mutable struct Handle + cell::Symbol + generation::Int +end +EA.base_step_seconds(::Backend) = 3600.0 +EA.get_nsteps(::Backend) = 6 +EA.environment_variables(::Backend) = Set((:T,)) +function EA.bind_environment(backend::Backend, object::Object, context, config) + backend.binds += 1 + return Handle(geometry(object).cell, backend.binds) +end +EA.sample(backend::Backend, handle::Handle, ::Symbol, time) = + backend.values[handle.cell] + Float32(handle.generation) + +PSE.@process "environment_identity_index" verbose=false +struct Probe <: AbstractEnvironment_Identity_IndexModel end +PSE.inputs_(::Probe) = NamedTuple() +PSE.outputs_(::Probe) = (seen=0.0f0, visits=0) +PSE.environment_inputs_(::Probe) = (T=0.0f0,) +function PSE.run!(::Probe, status, environment, constants, context) + status.seen = environment.T + status.visits += 1 + return nothing +end + +function close_registry(model::CompositeModel) + previous = model.registry + objects = PSE._closed_object_family_store(previous.objects) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + return PSE.CompositeModel( + registry, model.applications, model.environment, model.instances, + model.source_adapter, model.status_conversion, model.status_conversion_records, + model.status_source_owners, model.status_source_identities, + model.scenario_plan_cache, model.binding_cache, model.environment_binding_cache, + model.bindings_dirty, model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, model.revision, + model.environment_revision, + ) +end + +function fixture(closed::Bool) + backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0) + model = CompositeModel( + Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), + Object(1; scale=:Leaf, parent=:root, geometry=(cell=:a,), + status=Status(seen=0.0f0, visits=0)), + Object(:leaf; scale=:Leaf, parent=:root, geometry=(cell=:b,), + status=Status(seen=0.0f0, visits=0)); + applications=(ModelSpec(Probe(); name=:probe, on=Many(scale=:Leaf), + environment=Environment(provider=:identity_probe)),), environment=backend) + closed && (model = close_registry(model)) + simulation = run!(model; steps=1, outputs=:all) + return (; model, simulation, backend) +end + +function check_indexes(model, owner) + I = keytype(model.registry.objects) + K = Tuple{Symbol,I} + @test keytype(owner.by_target) === K + @test keytype(owner.positions_by_target) === K + @test keytype(owner.targets_by_object) === I + @test valtype(owner.targets_by_object) === Vector{K} + for (position, binding) in pairs(owner.bindings) + target = PSE._environment_binding_target_key(binding, I) + @test owner.by_target[target] === binding + @test owner.positions_by_target[target] == position + @test target in owner.targets_by_object[target[2]] + end +end + +@testset "environment indexes retain admitted identity pools" begin + for closed in (false, true) + data = fixture(closed) + I = keytype(data.model.registry.objects) + @test I === (closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId) + check_indexes(data.model, data.simulation.environment_bindings) + bindings = data.simulation.environment_bindings.bindings + empty_bindings = empty(bindings) + @test isempty(PSE._index_environment_bindings(empty_bindings, I)) + @test keytype(PSE._index_environment_bindings(empty_bindings, I)) === Tuple{Symbol,I} + @test keytype(PSE._index_environment_binding_positions(empty_bindings, I)) === Tuple{Symbol,I} + @test keytype(PSE._index_environment_targets_by_object(empty_bindings, I)) === I + @test_throws "duplicate" PSE._index_environment_bindings( + [bindings; first(bindings)], I) + @test_throws TypeError PSE._environment_binding_target_key( + first(bindings), ObjectId{String}) + end +end + +@testset "public full environment invalidation rebuilds fresh handles and sources" begin + for closed in (false, true) + data = fixture(closed) + model, simulation, backend = data.model, data.simulation, data.backend + previous = simulation.environment_bindings + old_integer = previous.by_target[(:probe, ObjectId(1))] + old_symbol = previous.by_target[(:probe, ObjectId(:leaf))] + seen_ref = PSE.refvalue(model_status(model, 1), :seen) + @test backend.binds == 2 + @test model_status(model, 1).seen === 11.0f0 + @test model_status(model, :leaf).seen === 22.0f0 + + backend.values[:a] = 30.0f0 + backend.values[:b] = 40.0f0 + mark_environment_binding_dirty!(model) + @test isnothing(model.environment_binding_cache) + @test model.lifecycle_delta.full_environment + @test simulation.environment_bindings === previous + continue!(simulation; steps=1) + current = simulation.environment_bindings + @test current !== previous + @test current === model.environment_binding_cache + @test backend.binds == 4 + integer = current.by_target[(:probe, ObjectId(1))] + symbol = current.by_target[(:probe, ObjectId(:leaf))] + @test integer.handle !== old_integer.handle + @test symbol.handle !== old_symbol.handle + @test integer.handle.generation == 3 + @test symbol.handle.generation == 4 + @test model_status(model, 1).seen === 33.0f0 + @test model_status(model, :leaf).seen === 44.0f0 + @test model_status(model, 1).visits == model_status(model, :leaf).visits == 2 + @test PSE.refvalue(model_status(model, 1), :seen) === seen_ref + check_indexes(model, current) + + # Sampling must still read fresh mutable source values with the same owner. + backend.values[:a] = 31.0f0 + backend.values[:b] = 41.0f0 + continue!(simulation; steps=1) + @test simulation.environment_bindings === current + @test backend.binds == 4 + @test model_status(model, 1).seen === 34.0f0 + @test model_status(model, :leaf).seen === 45.0f0 + @test outputs(simulation)[(:probe, ObjectId(1), :seen)] == + [(1.0, 11.0f0), (2.0, 33.0f0), (3.0, 34.0f0)] + @test outputs(simulation)[(:probe, ObjectId(:leaf), :seen)] == + [(1.0, 22.0f0), (2.0, 44.0f0), (3.0, 45.0f0)] + end +end + +@testset "partial growth and retirement update the same environment indexes" begin + for closed in (false, true) + data = fixture(closed) + model, simulation = data.model, data.simulation + previous = simulation.environment_bindings + register_object!(model, Object(2; scale=:Leaf, parent=:root, geometry=(cell=:a,), + status=Status(seen=0.0f0, visits=0))) + continue!(simulation; steps=1) + current = simulation.environment_bindings + @test current.by_target === previous.by_target + @test current.positions_by_target === previous.positions_by_target + @test current.targets_by_object === previous.targets_by_object + @test length(current.bindings) == 3 + @test model_status(model, 2).seen === 13.0f0 + @test model_status(model, 2).visits == 1 + newborn_ref = PSE.refvalue(model_status(model, 2), :seen) + check_indexes(model, current) + + remove_object!(model, 1) + continue!(simulation; steps=1) + @test !haskey(simulation.environment_bindings.by_target, (:probe, ObjectId(1))) + @test !haskey(simulation.environment_bindings.targets_by_object, ObjectId(1)) + @test length(simulation.environment_bindings.bindings) == 2 + @test PSE.refvalue(model_status(model, 2), :seen) === newborn_ref + @test model_status(model, 2).visits == 2 + @test outputs(simulation)[(:probe, ObjectId(1), :seen)] == + [(1.0, 11.0f0), (2.0, 11.0f0)] + check_indexes(model, simulation.environment_bindings) + end +end + +end From d32c3f0b492ef0a3a0b87e4fd5a40fb38afda31c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 06:18:54 +0100 Subject: [PATCH 023/324] Preserve cohort identities and admit typed cached status views --- src/composite_model/compilation.jl | 73 +++--- .../execution_batch_schemas.jl | 40 ++- .../execution_cohort_refresh.jl | 38 +-- src/composite_model/execution_cohorts.jl | 107 +++++--- src/composite_model/execution_storage.jl | 20 +- src/composite_model/runtime_outputs.jl | 28 +- src/visualization/model_graph_view.jl | 4 +- test/runtests.jl | 4 + test/test-model-binding-index-identities.jl | 242 ++++++++++++++++++ test/test-model-call-cohort-retirement.jl | 2 +- test/test-model-closed-cohort-schemas.jl | 2 +- test/test-model-cohort-store-identities.jl | 187 ++++++++++++++ test/test-model-persistent-empty-groups.jl | 4 +- test/test-model-prepared-growth-schemas.jl | 4 +- .../test-model-status-view-cache-admission.jl | 230 +++++++++++++++++ ...test-model-target-status-view-admission.jl | 174 +++++++++++++ 16 files changed, 1028 insertions(+), 131 deletions(-) create mode 100644 test/test-model-binding-index-identities.jl create mode 100644 test/test-model-cohort-store-identities.jl create mode 100644 test/test-model-status-view-cache-admission.jl create mode 100644 test/test-model-target-status-view-admission.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index cfc0a096a..d304f354e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2208,16 +2208,33 @@ function _extend_observed_manual_call_binding_callee_target_index!( return index end -function _index_model_bindings(bindings, application_field::Symbol, object_field::Symbol) - grouped = Dict{Tuple{Symbol,ObjectId},Vector{Any}}() +@inline function _model_binding_target_key( + binding::CompiledModelInputBinding, ::Type{I}, +) where {I<:ObjectId} + plan = getfield(binding, :plan)::CompiledModelInputPlan + return (getfield(plan, :application_id), getfield(binding, :consumer_id)::I) +end + +@inline function _model_binding_target_key( + binding::CompiledModelCallBinding, ::Type{I}, +) where {I<:ObjectId} + plan = getfield(binding, :plan)::CompiledModelCallPlan + return (getfield(plan, :application_id), getfield(binding, :consumer_id)::I) +end + +function _index_model_bindings(bindings, ::Type{I}) where {I<:ObjectId} + K = Tuple{Symbol,I} + grouped = Dict{K,Vector{Any}}() for binding in bindings - key = ( - getproperty(binding, application_field), - getproperty(binding, object_field), - ) - push!(get!(grouped, key, Any[]), binding) + key = _model_binding_target_key(binding, I) + values = get!(grouped, key) do + Any[] + end + push!(values, binding) end - return Dict(key => Tuple(values) for (key, values) in grouped) + # Lifecycle changes may replace a binding tuple with a new carrier schema. + # Only values are open; every consumer identity belongs to this registry. + return Dict{K,Any}(key => Tuple(values) for (key, values) in grouped) end """ @@ -2424,19 +2441,11 @@ function _compile_scene( # with a concrete carrier type. Keep the per-target index type-stable # across that replacement so an updated compiled scene can be stored in # an existing `Simulation`. - input_bindings_by_target = Dict{Any,Any}( - _index_model_bindings( - input_bindings, - :application_id, - :consumer_id, - ), + input_bindings_by_target = _index_model_bindings( + input_bindings, keytype(model.registry.objects), ) - call_bindings_by_target = Dict{Any,Any}( - _index_model_bindings( - call_bindings, - :application_id, - :consumer_id, - ), + call_bindings_by_target = _index_model_bindings( + call_bindings, keytype(model.registry.objects), ) call_owners = scenario_plan.call_owners application_children = scenario_plan.application_children @@ -3774,12 +3783,8 @@ function _prepare_structural_compiled_delta( previous_temporal_sources[key] = copy(binding.source_ids) end end - input_bindings_by_target = Dict{Any,Any}( - _index_model_bindings( - input_bindings, - :application_id, - :consumer_id, - ), + input_bindings_by_target = _index_model_bindings( + input_bindings, keytype(model.registry.objects), ) call_bindings = CompiledModelCallBinding[] @@ -3801,12 +3806,8 @@ function _prepare_structural_compiled_delta( (binding.application_id, binding.consumer_id), ) end - call_bindings_by_target = Dict{Any,Any}( - _index_model_bindings( - call_bindings, - :application_id, - :consumer_id, - ), + call_bindings_by_target = _index_model_bindings( + call_bindings, keytype(model.registry.objects), ) many_input_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -3992,9 +3993,7 @@ function _refresh_scene_call_bindings!( plans_by_application=compiled.scenario_plan.call_plans_by_application, ) replacement_call_bindings_by_target = _index_model_bindings( - replacement_call_bindings, - :application_id, - :consumer_id, + replacement_call_bindings, keytype(model.registry.objects), ) call_bindings = compiled.call_bindings for key in rebuilt_existing_call_targets @@ -4520,9 +4519,7 @@ function _extend_compiled_scene( isempty(new_call_bindings) || merge!( call_bindings_by_target, _index_model_bindings( - new_call_bindings, - :application_id, - :consumer_id, + new_call_bindings, keytype(model.registry.objects), ), ) call_owners = compiled.scenario_plan.call_owners diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 22e69f5c3..1883fb0e6 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -130,8 +130,22 @@ end return closed ? :(PreparedContextCallSchema{$C}()) : :(OpenContextCallSchema()) end -@inline _with_execution_target_type(f, ::OpenExecutionCohortSchema, application, fields, owners) = f(nothing, application, fields, owners, OpenContextCallSchema()) -@generated function _with_execution_target_type(f, ::ClosedExecutionCohortSchema{T}, application, fields, owners) where {T} +# Admit the real status view before reading its parameterized fields. The +# ordinary function barrier specializes its actual V; prepared execution uses +# the same existing finite target schema before assembling the same fields. +@inline function _with_execution_target_type(f::F, ::OpenExecutionCohortSchema, + application, status_view::V, fields, owners, +) where {F,V<:CompiledModelStatusView} + actual_fields = (object_id=fields.object_id, model=fields.model, + status_view=status_view, bound_inputs=status_view.bound_inputs, + output_targets=fields.output_targets, call_bindings=fields.call_bindings, + environment_binding=fields.environment_binding) + return f(nothing, application, actual_fields, owners, OpenContextCallSchema()) +end + +@generated function _with_execution_target_type(f, ::ClosedExecutionCohortSchema{T}, + application, status_view::CompiledModelStatusView, fields, owners, +) where {T} branches = Expr[] names = (:object_id, :model, :status_view, :bound_inputs, :output_targets, :call_bindings, :environment_binding) @@ -143,21 +157,31 @@ end closed_calls = any(fieldtype(CT,:batch_schema) <: PreparedExecutionBatchSchema for CT in fieldtypes(Calls)) closed_calls && _validate_prepared_context_calls(Calls) CallSchema = closed_calls ? PreparedContextCallSchema{Calls} : OpenContextCallSchema + V = fieldtype(Target, :status_view) checks = Expr[:(application isa $(fieldtype(Context, :application)))] + values = Expr[] for name in names - push!(checks, :(getproperty(fields, $(QuoteNode(name))) isa $(fieldtype(Target, name)))) + value = if name === :status_view + :status_view + elseif name === :bound_inputs + # The earlier status_view check short-circuits before this read. + :((status_view::$V).bound_inputs) + else + :(getproperty(fields, $(QuoteNode(name)))) + end + push!(checks, :($value isa $(fieldtype(Target, name)))) + push!(values, :($value::$(fieldtype(Target, name)))) end for name in (:compiled, :temporal_streams, :output_retention, :constants, :environment) push!(checks, :(getproperty(owners, $(QuoteNode(name))) isa $(fieldtype(Context, name)))) end condition = foldl((a,b) -> :($a && $b), checks) - values = Expr(:tuple, [:(getproperty(fields, $(QuoteNode(name)))::$(fieldtype(Target,name))) for name in names]...) owner_names = (:compiled, :temporal_streams, :output_retention, :constants, :environment) owner_values = Expr(:tuple, [:(getproperty(owners, $(QuoteNode(name)))::$(fieldtype(Context,name))) for name in owner_names]...) A = fieldtype(Context, :application) push!(branches, quote if $condition - actual_fields = NamedTuple{$(QuoteNode(names))}($values) + actual_fields = NamedTuple{$(QuoteNode(names))}($(Expr(:tuple,values...))) actual_owners = NamedTuple{$(QuoteNode(owner_names))}($owner_values) return f($Target, application::$A, actual_fields, actual_owners, $CallSchema()) @@ -505,7 +529,7 @@ function _prepare_execution_batch_schemas(simulation::Simulation, schemas::Named !cache.in_use && isnothing(cache.evaluation) && iszero(cache.execution_stamp[]) || throw(ArgumentError("Execution schemas cannot replace a used or leased timeline.")) end - storage = RuntimeStorage(simulation.temporal_streams.streams) + storage = RuntimeStorage(simulation.temporal_streams.streams, simulation.model.registry.objects) plan = compile_model_execution_plan(simulation.compiled,simulation.environment_bindings, storage,simulation.output_retention,simulation.constants; batch_schemas=schemas) closed_groups = Tuple(plan.groups) @@ -581,7 +605,9 @@ function _execution_batch_type_with_call_schemas(::Type{B}, schemas::NamedTuple) parameters[9] = prepared_context prepared_target = Core.apply_type(CompiledExecutionTarget,parameters...) I = fieldtype(prepared_target,:object_id) - Rows = ExecutionCohortRows{prepared_target,ExecutionCohort{prepared_target,I}} + Store = fieldtype(fieldtype(B, :targets), :store) + Owner = _execution_store_owner_type(Store) + Rows = ExecutionCohortRows{prepared_target,ExecutionCohort{prepared_target,I,Owner},Store} return CompiledExecutionBatch{fieldtype(B,:application),Rows, fieldtype(B,:environment_provider),fieldtype(B,:output_publication)} end diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index dbd79093f..e02134884 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -1,7 +1,7 @@ """Ordered schedule membership, separate from persistent execution payloads.""" -struct ExecutionCohortMembership{S<:ExecutionCohortSchema,I<:ObjectId,L<:ExecutionCohortLocation,R<:ExecutionCohortRows} - store::ExecutionCohortStore - owner::Any +struct ExecutionCohortMembership{S<:ExecutionCohortSchema,I<:ObjectId,L<:ExecutionCohortLocation,R<:ExecutionCohortRows,D<:ExecutionCohortStore,O} + store::D + owner::O application_id::Symbol schema::S object_ids::Vector{I} @@ -36,7 +36,7 @@ end function _execution_membership_location_has_cohort(membership, position, cohort) object_id = membership.object_ids[position] - return _with_execution_cohort_location(membership.schema, membership.locations[position], + return _with_execution_cohort_location(membership.schema, membership.store, membership.locations[position], membership.owner, membership.application_id, object_id) do location location.cohort === cohort end @@ -146,7 +146,8 @@ function _check_execution_cohort_target(target, object_id) end function _new_execution_cohort_membership(store, owner, application_id, count, schema=OpenExecutionCohortSchema()) - types = _execution_cohort_types(schema) + owner = _execution_store_owner(store, owner) + types = _execution_cohort_types(schema, store) ids = Vector{types.identity}() locations = Vector{types.location}() capacity = count + max(16, count ÷ 4) @@ -161,14 +162,14 @@ end # vectors become finite unions; all cohort payloads, references and run views # retain identity. No models, defaults, samplers or callbacks are invoked. function _close_execution_cohort_membership(previous::ExecutionCohortMembership, schema::ClosedExecutionCohortSchema) - types = _execution_cohort_types(schema) + types = _execution_cohort_types(schema, previous.store) for (object_id, location) in zip(previous.object_ids, previous.locations) object_id isa types.identity || throw(ArgumentError("An object identity is outside the prepared cohort schema.")) - _with_execution_cohort_location(identity, schema, location, previous.owner, previous.application_id, object_id) + _with_execution_cohort_location(identity, schema, previous.store, location, previous.owner, previous.application_id, object_id) end for rows in previous.runs - _with_execution_cohort_rows(schema, rows) do admitted - _check_execution_cohort_rows_owner(admitted, previous.store, previous.owner, previous.application_id) + _with_execution_cohort_rows(schema, previous.store, rows) do admitted + _check_execution_cohort_rows_owner(admitted, previous.store, previous.owner, previous.application_id, schema) end end typeof(previous.schema) === typeof(schema) && return previous @@ -187,8 +188,8 @@ function _close_execution_cohort_membership(previous::ExecutionCohortMembership, return membership end -function _check_execution_cohort_rows_owner(rows, store, owner, application_id) - rows.store === store && isequal(rows.cohort.owner, owner) && +function _check_execution_cohort_rows_owner(rows, store, owner, application_id, schema) + rows.store === store && _execution_cohort_owner_matches(schema, rows.cohort.owner, owner) && rows.cohort.application_id === application_id || throw(ArgumentError( "The execution run belongs to another store, owner or application.", )) @@ -196,8 +197,8 @@ function _check_execution_cohort_rows_owner(rows, store, owner, application_id) end @inline function _with_execution_membership_run(f, membership, index) - return _with_execution_cohort_rows(membership.schema, membership.runs[index]) do rows - _check_execution_cohort_rows_owner(rows, membership.store, membership.owner, membership.application_id) + return _with_execution_cohort_rows(membership.schema, membership.store, membership.runs[index]) do rows + _check_execution_cohort_rows_owner(rows, membership.store, membership.owner, membership.application_id, membership.schema) f(rows) end end @@ -234,6 +235,7 @@ function refresh_cohort_membership!( owner=nothing, schema=isnothing(previous) ? OpenExecutionCohortSchema() : previous.schema, ) + owner = _execution_store_owner(store, owner) if !isnothing(previous) previous.store === store && previous.application_id === application_id && isequal(previous.owner, owner) || throw(ArgumentError( @@ -243,7 +245,7 @@ function refresh_cohort_membership!( "Close the application membership before entering its prepared refresh boundary.", )) end - types = _execution_cohort_types(schema) + types = _execution_cohort_types(schema, store) staged_targets = Vector{Tuple{types.identity,types.target}}() removed_ids = Vector{types.identity}() checked_ids = isnothing(previous) || isnothing(changed_ids) ? current_ids : changed_ids @@ -252,7 +254,7 @@ function refresh_cohort_membership!( location = cohort_location(store, application_id, object_id; owner) is_current = isnothing(previous) || isnothing(changed_ids) || first(_sorted_object_id_position(current_ids, object_id)) - _with_execution_cohort_location(schema, location, owner, application_id, object_id) do admitted + _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted if !is_current push!(removed_ids, object_id) return nothing @@ -284,7 +286,7 @@ function refresh_cohort_membership!( # and every run before the first clear/splice, including a fully empty result. for object_id in removed_ids location = cohort_location(store, application_id, object_id; owner) - _with_execution_cohort_location(identity, schema, location, owner, application_id, object_id) + _with_execution_cohort_location(identity, schema, store, location, owner, application_id, object_id) end membership = isnothing(previous) ? _new_execution_cohort_membership(store, owner, application_id, length(current_ids), schema) : @@ -305,7 +307,7 @@ function refresh_cohort_membership!( changed = _with_execution_cohort_target(schema, target) do accepted cohort = _execution_cohort(store, owner, application_id, typeof(accepted)) old_location = cohort_location(store, application_id, object_id; owner) - return _with_execution_cohort_location(schema, old_location, owner, application_id, object_id) do admitted + return _with_execution_cohort_location(schema, store, old_location, owner, application_id, object_id) do admitted slot = _store_execution_cohort_target!(store, cohort, accepted, admitted) isnothing(previous) && return false location = ExecutionCohortLocation(cohort, slot) @@ -333,7 +335,7 @@ function refresh_cohort_membership!( if isnothing(previous) for object_id in current_ids location = cohort_location(store, application_id, object_id; owner) - _with_execution_cohort_location(schema, location, owner, application_id, object_id) do admitted + _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted _insert_execution_membership_row!( membership, length(membership.object_ids) + 1, object_id, admitted, ) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 6c09932d5..ee49b438c 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -1,14 +1,14 @@ abstract type AbstractExecutionCohort end -mutable struct ExecutionCohort{T,I<:ObjectId} <: AbstractExecutionCohort - owner::Any +mutable struct ExecutionCohort{T,I<:ObjectId,O} <: AbstractExecutionCohort + owner::O application_id::Symbol rows::Vector{Union{Nothing,T}} indices::Dict{I,Int} - ExecutionCohort{T,I}(owner, application_id::Symbol, rows::Vector{Union{Nothing,T}}, - indices::Dict{I,Int}) where {T,I<:ObjectId} = - new{T,I}(owner, application_id, rows, indices) + ExecutionCohort{T,I,O}(owner::O, application_id::Symbol, rows::Vector{Union{Nothing,T}}, + indices::Dict{I,Int}) where {T,I<:ObjectId,O} = + new{T,I,O}(owner, application_id, rows, indices) end struct ExecutionCohortLocation{C<:AbstractExecutionCohort} @@ -16,26 +16,40 @@ struct ExecutionCohortLocation{C<:AbstractExecutionCohort} row::Int end -"""Persistent typed execution payloads, indexed independently of schedule order.""" -mutable struct ExecutionCohortStore - cohorts::Dict{Tuple{Any,Symbol,DataType},AbstractExecutionCohort} - locations::Dict{Tuple{Any,Symbol,ObjectId},ExecutionCohortLocation} +"""Persistent payload storage with identity/owner types independent of target types. + +A closed registry admits the finite identity and canonical namespace types. +The ordinary store keeps arbitrary owners and identity types; per-application +schemas still own every concrete target/row witness. +""" +mutable struct ExecutionCohortStore{I<:ObjectId,O} + cohorts::Dict{Tuple{O,Symbol,DataType},AbstractExecutionCohort} + locations::Dict{Tuple{O,Symbol,I},ExecutionCohortLocation} end -ExecutionCohortStore() = ExecutionCohortStore( - Dict{Tuple{Any,Symbol,DataType},AbstractExecutionCohort}(), - Dict{Tuple{Any,Symbol,ObjectId},ExecutionCohortLocation}(), +ExecutionCohortStore{I,O}() where {I<:ObjectId,O} = ExecutionCohortStore{I,O}( + Dict{Tuple{O,Symbol,DataType},AbstractExecutionCohort}(), + Dict{Tuple{O,Symbol,I},ExecutionCohortLocation}(), ) +ExecutionCohortStore() = ExecutionCohortStore{ObjectId,Any}() +ExecutionCohortStore(::ObjectFamilyStore{I,<:OpenObjectFamilyCatalog}) where {I} = + ExecutionCohortStore() +ExecutionCohortStore(::ObjectFamilyStore{I,<:ClosedObjectFamilyCatalog}) where {I} = + ExecutionCohortStore{I,Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}}}() + +_execution_store_owner_type(::Type{ExecutionCohortStore{I,O}}) where {I,O} = O +_execution_store_owner(::ExecutionCohortStore{I,O}, owner) where {I,O} = owner::O +_execution_store_object_id(::ExecutionCohortStore{I}, object_id) where {I} = ObjectId(object_id)::I """An ordered membership view over one application's concrete payload family.""" -struct ExecutionCohortRows{T,C<:ExecutionCohort{T}} <: AbstractVector{T} - store::ExecutionCohortStore +struct ExecutionCohortRows{T,C<:ExecutionCohort{T},S<:ExecutionCohortStore} <: AbstractVector{T} + store::S cohort::C indices::Vector{Int} end -ExecutionCohortRows{T}(store::ExecutionCohortStore, cohort::C, indices::Vector{Int}) where {T,C<:ExecutionCohort{T}} = - ExecutionCohortRows{T,C}(store, cohort, indices) +ExecutionCohortRows{T}(store::S, cohort::C, indices::Vector{Int}) where {T,C<:ExecutionCohort{T},S<:ExecutionCohortStore} = + ExecutionCohortRows{T,C,S}(store, cohort, indices) # The finite witness belongs to one application/owner boundary, never to the # runtime store. In particular Target -> RunContext -> RuntimeStorage does not @@ -106,19 +120,20 @@ function _check_execution_cohort_location(location, owner, application_id, objec return nothing end -@inline _with_execution_cohort_location(f, schema::ExecutionCohortSchema, ::Nothing, owner, application_id, object_id) = f(nothing) -@inline function _with_execution_cohort_location(f, ::OpenExecutionCohortSchema, location::ExecutionCohortLocation, owner, application_id, object_id) +@inline _with_execution_cohort_location(f, schema::ExecutionCohortSchema, store::ExecutionCohortStore, ::Nothing, owner, application_id, object_id) = f(nothing) +@inline function _with_execution_cohort_location(f, ::OpenExecutionCohortSchema, store::ExecutionCohortStore, location::ExecutionCohortLocation, owner, application_id, object_id) _check_execution_cohort_location(location, owner, application_id, object_id) return f(location) end # Select the actual cohort before invoking the operation. An assertion after a # dynamic read/clear would leave the abstract operation reachable by JuliaC. -@generated function _with_execution_cohort_location(f, schema::ClosedExecutionCohortSchema{T}, location::ExecutionCohortLocation, owner, application_id, object_id) where {T} +@generated function _with_execution_cohort_location(f, schema::ClosedExecutionCohortSchema{T}, store::S, location::ExecutionCohortLocation, owner, application_id, object_id) where {T,S<:ExecutionCohortStore} branches = Expr[] + O = _execution_store_owner_type(S) for Target in fieldtypes(T) I = fieldtype(Target, :object_id) - L = ExecutionCohortLocation{ExecutionCohort{Target,I}} + L = ExecutionCohortLocation{ExecutionCohort{Target,I,O}} push!(branches, quote if location isa $L _check_execution_cohort_location(location, owner, application_id, object_id, schema) @@ -141,22 +156,24 @@ end end end -_execution_cohort_types(::OpenExecutionCohortSchema) = +_execution_cohort_types(::OpenExecutionCohortSchema, ::ExecutionCohortStore) = (identity=ObjectId, target=Any, location=ExecutionCohortLocation, rows=ExecutionCohortRows) -@generated function _execution_cohort_types(::ClosedExecutionCohortSchema{T}) where {T} +@generated function _execution_cohort_types(::ClosedExecutionCohortSchema{T}, ::S) where {T,S<:ExecutionCohortStore} targets = collect(fieldtypes(T)) + O = _execution_store_owner_type(S) ids = unique([fieldtype(Target, :object_id) for Target in targets]) - locations = [ExecutionCohortLocation{ExecutionCohort{Target,fieldtype(Target,:object_id)}} for Target in targets] - rows = [ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id)}} for Target in targets] + locations = [ExecutionCohortLocation{ExecutionCohort{Target,fieldtype(Target,:object_id),O}} for Target in targets] + rows = [ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id),O},S} for Target in targets] I, U, L, R = Union{ids...}, Union{targets...}, Union{locations...}, Union{rows...} return :((identity=$I, target=$U, location=$L, rows=$R)) end -@inline _with_execution_cohort_rows(f, ::OpenExecutionCohortSchema, rows::ExecutionCohortRows) = f(rows) -@generated function _with_execution_cohort_rows(f, ::ClosedExecutionCohortSchema{T}, rows::ExecutionCohortRows) where {T} +@inline _with_execution_cohort_rows(f, ::OpenExecutionCohortSchema, store::ExecutionCohortStore, rows::ExecutionCohortRows) = f(rows) +@generated function _with_execution_cohort_rows(f, ::ClosedExecutionCohortSchema{T}, store::S, rows::ExecutionCohortRows) where {T,S<:ExecutionCohortStore} branches = Expr[] + O = _execution_store_owner_type(S) for Target in fieldtypes(T) - R = ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id)}} + R = ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id),O},S} push!(branches, :(rows isa $R && return f(rows))) end return quote @@ -181,7 +198,7 @@ Base.@propagate_inbounds function Base.getindex(rows::ExecutionCohortRows{T}, in return target::T end -function _execution_cohort(store::ExecutionCohortStore, owner, application_id::Symbol, ::Type{T}) where {T} +function _execution_cohort(store::ExecutionCohortStore{StoreI,O}, owner, application_id::Symbol, ::Type{T}) where {T,StoreI,O} isconcretetype(T) && T !== Nothing || throw(ArgumentError( "An execution cohort requires a concrete target payload type.", )) @@ -189,10 +206,12 @@ function _execution_cohort(store::ExecutionCohortStore, owner, application_id::S I <: ObjectId && isconcretetype(I) || throw(ArgumentError( "An execution cohort requires a concrete ObjectId field in its target payload.", )) + I <: StoreI || throw(ArgumentError("The execution target identity is outside the store schema.")) + owner = _execution_store_owner(store, owner) cohort = get!(store.cohorts, (owner, application_id, T)) do - ExecutionCohort{T,I}(owner, application_id, Union{Nothing,T}[], Dict{I,Int}()) + ExecutionCohort{T,I,O}(owner, application_id, Union{Nothing,T}[], Dict{I,Int}()) end - return cohort::ExecutionCohort{T,I} + return cohort::ExecutionCohort{T,I,O} end function _clear_execution_cohort_row!(cohort::ExecutionCohort, row::Int) @@ -201,10 +220,11 @@ function _clear_execution_cohort_row!(cohort::ExecutionCohort, row::Int) end function _store_execution_cohort_target!(store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T) where {T} - object_id = ObjectId(target.object_id) - previous = cohort_location(store, cohort.application_id, object_id; owner=cohort.owner) - return _with_execution_cohort_location(OpenExecutionCohortSchema(), previous, - cohort.owner, cohort.application_id, object_id) do location + object_id = _execution_store_object_id(store, target.object_id) + owner = _execution_store_owner(store, cohort.owner) + previous = cohort_location(store, cohort.application_id, object_id; owner) + return _with_execution_cohort_location(OpenExecutionCohortSchema(), store, previous, + owner, cohort.application_id, object_id) do location _store_execution_cohort_target!(store, cohort, target, location) end end @@ -212,9 +232,10 @@ end function _store_execution_cohort_target!( store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T, previous, ) where {T} - object_id = ObjectId(target.object_id) + object_id = _execution_store_object_id(store, target.object_id) + owner = _execution_store_owner(store, cohort.owner) if !isnothing(previous) - _check_execution_cohort_location(previous, cohort.owner, cohort.application_id, object_id) + _check_execution_cohort_location(previous, owner, cohort.application_id, object_id) previous.cohort === cohort || _clear_execution_cohort_row!(previous.cohort, previous.row) end slot = get(cohort.indices, object_id, 0) @@ -225,7 +246,7 @@ function _store_execution_cohort_target!( else cohort.rows[slot] = target end - store.locations[(cohort.owner, cohort.application_id, object_id)] = ExecutionCohortLocation(cohort, slot) + store.locations[(owner, cohort.application_id, object_id)] = ExecutionCohortLocation(cohort, slot) return slot end @@ -331,16 +352,20 @@ function reset_cohort_rows!(rows::ExecutionCohortRows{T}, targets::AbstractVecto return rows end -cohort_location(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing) = - get(store.locations, (owner, application_id, ObjectId(object_id)), nothing) +function cohort_location(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing) + id = _execution_store_object_id(store, object_id) + admitted_owner = _execution_store_owner(store, owner) + return get(store.locations, (admitted_owner, application_id, id), nothing) +end """Remove an execution payload without renumbering any cohort's row slots.""" function remove_cohort_target!(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing, schema=OpenExecutionCohortSchema()) - object_id = ObjectId(object_id) + object_id = _execution_store_object_id(store, object_id) + owner = _execution_store_owner(store, owner) key = (owner, application_id, object_id) location = get(store.locations, key, nothing) isnothing(location) && return false - return _with_execution_cohort_location(schema, location, owner, application_id, object_id) do admitted + return _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted _clear_execution_cohort_row!(admitted.cohort, admitted.row) delete!(store.locations, key) return true diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl index d9610a761..cfa1671fb 100644 --- a/src/composite_model/execution_storage.jl +++ b/src/composite_model/execution_storage.jl @@ -4,13 +4,19 @@ Stream values retain the existing dictionary interface. Execution cohorts share that lifetime, rather than the model's reusable structural plan, so a fresh run cannot replace another simulation's targets or call-context leases. """ -struct RuntimeStorage{K,V,D<:AbstractDict{K,V}} <: AbstractDict{K,V} +struct RuntimeStorage{K,V,D<:AbstractDict{K,V},S<:ExecutionCohortStore} <: AbstractDict{K,V} streams::D - cohorts::ExecutionCohortStore + cohorts::S + + RuntimeStorage{K,V,D,S}(streams::D, cohorts::S) where {K,V,D<:AbstractDict{K,V},S<:ExecutionCohortStore} = + new{K,V,D,S}(streams, cohorts) end -RuntimeStorage(streams::AbstractDict{K,V}) where {K,V} = - RuntimeStorage{K,V,typeof(streams)}(streams, ExecutionCohortStore()) +RuntimeStorage(streams::AbstractDict{K,V}, cohorts::S) where {K,V,S<:ExecutionCohortStore} = + RuntimeStorage{K,V,typeof(streams),S}(streams, cohorts) +RuntimeStorage(streams::AbstractDict) = RuntimeStorage(streams, ExecutionCohortStore()) +RuntimeStorage(streams::AbstractDict, registry::ObjectFamilyStore) = + RuntimeStorage(streams, ExecutionCohortStore(registry)) Base.length(storage::RuntimeStorage) = length(storage.streams) Base.iterate(storage::RuntimeStorage, state...) = iterate(storage.streams, state...) @@ -23,8 +29,8 @@ Base.get!(default::Union{Function,Type}, storage::RuntimeStorage, key) = get!(default, storage.streams, key) Base.delete!(storage::RuntimeStorage, key) = (delete!(storage.streams, key); storage) Base.empty!(storage::RuntimeStorage) = (empty!(storage.streams); storage) -Base.empty(storage::RuntimeStorage) = RuntimeStorage(empty(storage.streams)) -Base.copy(storage::RuntimeStorage) = RuntimeStorage(copy(storage.streams)) +Base.empty(storage::RuntimeStorage) = RuntimeStorage(empty(storage.streams), typeof(storage.cohorts)()) +Base.copy(storage::RuntimeStorage) = RuntimeStorage(copy(storage.streams), typeof(storage.cohorts)()) Base.keys(storage::RuntimeStorage) = keys(storage.streams) Base.values(storage::RuntimeStorage) = values(storage.streams) Base.pairs(storage::RuntimeStorage) = pairs(storage.streams) @@ -104,7 +110,7 @@ function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches; for (application_id, object_id) in obsolete _with_execution_retirement_id(schema, object_id) do admitted_id location = cohort_location(store, application_id, admitted_id; owner) - _with_execution_cohort_location(identity, schema, location, owner, application_id, admitted_id) + _with_execution_cohort_location(identity, schema, store, location, owner, application_id, admitted_id) end end for (application_id, object_id) in obsolete diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index d1b62834f..2abc51c79 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1684,7 +1684,7 @@ end "No compiled status view for application `$(application.id)` on object ", "`$(object_id.value)`.", ) - return compiled.status_views_by_target[key] + return compiled.status_views_by_target[key]::CompiledModelStatusView end function _set_status_if_present!(status::Status, variable::Symbol, value) @@ -3359,7 +3359,7 @@ function _compiled_model_execution_target( ) if temporal_streams isa RuntimeStorage location = cohort_location(temporal_streams.cohorts, application.id, object_id; owner) - return _with_execution_cohort_location(cohort_schema, location, owner, application.id, object_id) do admitted + return _with_execution_cohort_location(cohort_schema, temporal_streams.cohorts, location, owner, application.id, object_id) do admitted previous = isnothing(admitted) ? nothing : _execution_cohort_target(admitted) _compiled_model_execution_target_from_previous(previous, compiled, env_bindings, application, object_id, temporal_streams, output_retention, constants; @@ -3393,13 +3393,12 @@ function _new_model_execution_target( distributed_targets = _runtime_model_output_targets(compiled, application, object_id) call_bindings = get(compiled.call_bindings_by_target, (application.id, object_id), ()) environment_binding = _environment_binding_for(env_bindings, application.id, object_id) - fields = (object_id=object_id, model=model, status_view=status_view, - bound_inputs=status_view.bound_inputs, output_targets=distributed_targets, + fields = (object_id=object_id, model=model, output_targets=distributed_targets, call_bindings=call_bindings, environment_binding=environment_binding) owners = (compiled=compiled, temporal_streams=temporal_streams, output_retention=output_retention, constants=constants, environment=_NO_ENVIRONMENT_OVERRIDE) - return _with_execution_target_type(target_schema, application, fields, owners) do Target, actual_application, actual, owner, call_schema + return _with_execution_target_type(target_schema, application, status_view, fields, owners) do Target, actual_application, actual, owner, call_schema input_bindings = isnothing(Target) ? _runtime_model_temporal_inputs(actual.status_view.temporal_inputs, owner.temporal_streams) : _prepared_runtime_temporal_inputs(fieldtype(Target,:input_bindings), @@ -3484,7 +3483,7 @@ function _execution_batches_match_membership( batches = previous_group.batches length(batches) == length(membership.runs) || return false for index in eachindex(membership.runs) - matches = _with_execution_cohort_rows(membership.schema,membership.runs[index]) do rows + matches = _with_execution_cohort_rows(membership.schema,membership.store,membership.runs[index]) do rows _with_execution_batch(batch_schema,batches[index]) do batch batch.targets === rows || return false provider = _compiled_model_execution_environment_provider(env_bindings, @@ -3528,7 +3527,7 @@ function _model_execution_batches( batches = _execution_batch_buffer(batch_schema) batches_constructed = 0 for index in eachindex(membership.runs) - constructed = _with_execution_cohort_rows(membership.schema,membership.runs[index]) do rows + constructed = _with_execution_cohort_rows(membership.schema,membership.store,membership.runs[index]) do rows provider = _compiled_model_execution_environment_provider(env_bindings, application,first(rows)) reused = _compatible_execution_batch(batch_schema, @@ -3913,6 +3912,10 @@ function _model_execution_target_change_reason( isnothing(status_view) && return :missing_status_view target.model === _application_model(application, object_id) || return :model + # Preserve the existing reference checks after admitting the target's view schema. + V = typeof(target.status_view) + status_view isa V || return :status_view + status_view = status_view::V target.status_view.status === status_view.status || return :status_view target.status_view.canonical_status === status_view.canonical_status || return :canonical_status @@ -5949,9 +5952,7 @@ function _prepare_targeted_newborn_targets( end targeted_input_bindings = _index_model_bindings( - input_bindings, - :application_id, - :consumer_id, + input_bindings, keytype(model.registry.objects), ) environment_bindings = _targeted_call_environment_bindings( @@ -6007,18 +6008,17 @@ function _append_targeted_newborn_targets!( status_view = _compile_model_status_view(runtime_model(context),partial_application, object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, targeted_runtime.application_positions,compiled.distributed_outputs; - execution_stamp=stamp) + execution_stamp=stamp)::CompiledModelStatusView output_targets = _runtime_model_output_targets(compiled,application,object_id) environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) call_bindings = () # targeted admission has rejected nested callees fields = (object_id=object_id,model=_application_model(application,object_id), - status_view=status_view,bound_inputs=status_view.bound_inputs, output_targets=output_targets,call_bindings=call_bindings, environment_binding=environment_binding) owners = (compiled=compiled,temporal_streams=context.temporal_streams, output_retention=context.output_retention,constants=context.constants, environment=context.environment) - _with_execution_target_type(admission,application,fields,owners) do Target,actual_application,actual,owner,call_schema + _with_execution_target_type(admission,application,status_view,fields,owners) do Target,actual_application,actual,owner,call_schema outputs = isnothing(Target) ? _runtime_model_output_streams(actual.status_view.status,actual_application, actual.object_id,owner.temporal_streams,owner.output_retention,true) : @@ -7878,7 +7878,7 @@ function _prepare_simulation!( :initial_output_retention_compile, started_at, ) - temporal_streams = RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},Any}()) + temporal_streams = RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},Any}(), model.registry.objects) _initialize_model_output_streams!( temporal_streams, compiled, diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 0ef3457ea..df9801942 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -159,8 +159,8 @@ function _model_graph_compiled( ) isempty(diagnostics) || return nothing applications_by_id = _applications_by_id(applications) - input_by_target = _index_model_bindings(input_bindings, :application_id, :consumer_id) - call_by_target = _index_model_bindings(call_bindings, :application_id, :consumer_id) + input_by_target = _index_model_bindings(input_bindings, keytype(model.registry.objects)) + call_by_target = _index_model_bindings(call_bindings, keytype(model.registry.objects)) timeline = _model_timeline(model) scenario_plan = _compiled_scenario_plan( model, diff --git a/test/runtests.jl b/test/runtests.jl index 825335248..3c017961d 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -60,12 +60,15 @@ else @testset "Prepared execution schemas" begin include("test-model-closed-cohort-schemas.jl") + include("test-model-cohort-store-identities.jl") + include("test-model-status-view-cache-admission.jl") include("test-model-call-cohort-retirement.jl") include("test-model-closed-group-refresh.jl") include("test-model-closed-group-layout-preflight.jl") include("test-model-prepared-call-schemas.jl") include("test-model-prepared-call-vector-api.jl") include("test-model-prepared-growth-schemas.jl") + include("test-model-target-status-view-admission.jl") include("test-model-prepared-missing-future-schema.jl") include("test-model-finite-call-extension-intents.jl") end @@ -109,6 +112,7 @@ else include("test-model-authored-spec-matching.jl") include("test-compilation-metadata.jl") include("test-model-input-recipes.jl") + include("test-model-binding-index-identities.jl") include("test-model-output-retention-owners.jl") include("test-input-default-values.jl") include("test-application-membership-slots.jl") diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl new file mode 100644 index 000000000..7d1ec02d7 --- /dev/null +++ b/test/test-model-binding-index-identities.jl @@ -0,0 +1,242 @@ +module ModelBindingIndexIdentityChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "binding_index_leaf" verbose=false +PSE.@process "binding_index_capture" verbose=false +PSE.@process "binding_index_reader" verbose=false + +struct Leaf <: AbstractBinding_Index_LeafModel end +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Leaf) = (x=0f0,) +PSE.run!(::Leaf, status, environment, constants, context) = + (status.x += 1f0; nothing) + +struct Capture <: AbstractBinding_Index_CaptureModel + context::Base.RefValue{Any} +end +PSE.inputs_(::Capture) = NamedTuple() +PSE.outputs_(::Capture) = (visits=0,) +function PSE.run!(model::Capture, status, environment, constants, context) + model.context[] = context + status.visits += 1 + return nothing +end + +struct Reader <: AbstractBinding_Index_ReaderModel end +struct ManyReader <: AbstractBinding_Index_ReaderModel end +PSE.inputs_(::Reader) = (single=Required(Float32), values=Default(Float64[])) +PSE.inputs_(::ManyReader) = (values=Default(Float64[]),) +PSE.outputs_(::Union{Reader,ManyReader}) = (total=0.0,) +function PSE.run!(::Reader, status, environment, constants, context) + status.total = Float64(status.single) + sum(bound_input(context, :values); init=0.0) + return nothing +end +function PSE.run!(::ManyReader, status, environment, constants, context) + status.total = sum(bound_input(context, :values); init=0.0) + return nothing +end + +# Close only the actual complete schemas already present in this call fixture. +# This introduces no scientific object, default evaluation, or type probe. +function close_registry(model::CompositeModel) + previous = model.registry + registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), + previous.by_scale, previous.by_kind, previous.by_species, + previous.ancestor_ids_by_object) + return PSE.CompositeModel(registry, model.applications, model.environment, + model.instances, model.source_adapter, model.status_conversion, + model.status_conversion_records, model.status_source_owners, + model.status_source_identities, model.scenario_plan_cache, + model.binding_cache, model.environment_binding_cache, model.bindings_dirty, + model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, + model.revision, model.environment_revision) +end + +function call_fixture(closed) + capture = Ref{Any}(nothing) + model = CompositeModel( + Object(:root; scale=:Plant, status=Status(visits=0)), + Object(:other; scale=:Plant, status=Status(visits=0)), + Object(1; scale=:Leaf, parent=:root, status=Status(x=3f0)), + Object(:leaf; scale=:Leaf, parent=:root, status=Status(x=5f0)), + Object(:outside; scale=:Leaf, parent=:other, status=Status(x=100f0)); + applications=( + ModelSpec(Capture(capture); name=:capture, on=One(id=:root), calls=( + one=One(id=1, within=Subtree(), application=:leaf), + many=Many(scale=:Leaf, within=Subtree(), application=:leaf))), + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), + )) + closed && (model = close_registry(model)) + simulation = run!(model; steps=0, outputs=:all) + target = only(only(only(simulation.execution_plan.groups).batches).targets) + return (; model, simulation, capture, context=target.context) +end + +function check_index(model, bindings, index) + I = keytype(model.registry.objects) + @test keytype(index) === Tuple{Symbol,I} + @test valtype(index) === Any + rebuilt = PSE._index_model_bindings(bindings, I) + @test keytype(rebuilt) === Tuple{Symbol,I} + @test valtype(rebuilt) === Any + @test Set(keys(rebuilt)) == Set(keys(index)) + for (key, values) in rebuilt + expected = Tuple(binding for binding in bindings + if (binding.application_id, binding.consumer_id) == key) + @test values === expected + @test index[key] === expected + @test all(PSE._model_binding_target_key(binding, I) === key for binding in values) + end + empty_index = PSE._index_model_bindings(empty(bindings), I) + @test isempty(empty_index) + @test keytype(empty_index) === Tuple{Symbol,I} + @test valtype(empty_index) === Any + return nothing +end + +function check_indexes(model, simulation) + compiled = simulation.compiled + check_index(model, compiled.input_bindings, compiled.input_bindings_by_target) + check_index(model, compiled.call_bindings, compiled.call_bindings_by_target) +end + +@testset "binding indexes keep registry identities for cold and observed calls" begin + for closed in (false, true) + data = call_fixture(closed) + model, simulation = data.model, data.simulation + I = keytype(model.registry.objects) + @test I === (closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId) + check_indexes(model, simulation) + bindings = simulation.compiled.call_bindings + @test Tuple(binding.call for binding in bindings) == (:one, :many) + @test simulation.compiled.call_bindings_by_target[(:capture, ObjectId(:root))] === + Tuple(bindings) + repeated = [bindings; first(bindings)] + @test PSE._index_model_bindings(repeated, I)[(:capture, ObjectId(:root))] === + Tuple(repeated) + @test_throws TypeError PSE._model_binding_target_key(first(bindings), ObjectId{String}) + one = call_targets(data.context, :one) + many = call_targets(data.context, :many) + @test many.execution_batches isa PSE.LazyCallExecutionBatches + if many.execution_batches isa PSE.LazyCallExecutionBatches + @test isnothing(many.execution_batches.batches) + end + @test !many.binding.membership_observed[] + @test only(one).object_id === ObjectId(1) + first_ref = PSE.refvalue(model_status(model, 1), :x) + step!(simulation) + run_call!(data.capture[], :one; publish=true) + run_call!(data.capture[], :many; publish=true) + @test model_status(model, 1).x === 5f0 + @test model_status(model, :leaf).x === 6f0 + @test model_status(model, :outside).x === 100f0 + @test call_targets(data.capture[], :many).binding.membership_observed[] + check_indexes(model, simulation) + + register_object!(model, Object(2; scale=:Leaf, parent=:root, status=Status(x=7f0))) + step!(simulation) + run_call!(data.capture[], :many; publish=true) + @test [target.object_id for target in call_targets(data.capture[], :many)] == + [ObjectId(1), ObjectId(2), ObjectId(:leaf)] + @test model_status(model, 2).x === 8f0 + @test model_status(model, :leaf).x === 7f0 + check_indexes(model, simulation) + + reparent_object!(model, 2, :other) + step!(simulation) + run_call!(data.capture[], :many; publish=true) + @test [target.object_id for target in call_targets(data.capture[], :many)] == + [ObjectId(1), ObjectId(:leaf)] + @test model_status(model, 2).x === 8f0 + @test model_status(model, :leaf).x === 8f0 + check_indexes(model, simulation) + + remove_object!(model, :leaf) + step!(simulation) + run_call!(data.capture[], :many; publish=true) + @test only(call_targets(data.capture[], :many)).object_id === ObjectId(1) + @test model_status(model, 1).x === 8f0 + @test model_status(model, :root).visits == 4 + @test PSE.refvalue(model_status(model, 1), :x) === first_ref + @test only(call_targets(data.capture[], :one)).status.x === 8f0 + @test outputs(simulation)[(:leaf, ObjectId(:leaf), :x)] == + [(1.0, 6f0), (2.0, 7f0), (3.0, 8f0)] + check_indexes(model, simulation) + end +end + +@testset "input binding tuple schemas may change without widening registry keys" begin + first_status = Status(x=3f0) + model = CompositeModel(Object(:root; scale=:Plant), Object(:other; scale=:Plant), + Object(1; scale=:Leaf, parent=:root, status=first_status), + Object(:leaf; scale=:Leaf, parent=:root, status=Status(x=5f0)); + applications=(ModelSpec(Reader(); name=:reader, on=One(id=:root), inputs=( + single=One(id=1, within=Subtree(), var=:x, from_status=true), + values=Many(scale=:Leaf, within=Subtree(), var=:x, from_status=true))),)) + simulation = run!(model; steps=1, outputs=:all) + check_indexes(model, simulation) + key = (:reader, ObjectId(:root)) + before = simulation.compiled.input_bindings_by_target[key] + @test Tuple(binding.input for binding in before) == (:single, :values) + single = first(before) + first_ref = PSE.refvalue(first_status, :x) + @test single.carrier === first_ref + @test model_status(model, :root).total === 11.0 + many = last(before).carrier + @test all(reference === PSE.refvalue(model_status(model, id), :x) + for (id, reference) in zip(last(before).source_ids, parent(many))) + @test_throws TypeError PSE._model_binding_target_key(single, ObjectId{String}) + + new_status = Status(x=9.0) + register_object!(model, Object(2; scale=:Leaf, parent=:root, status=new_status)) + step!(simulation) + after = simulation.compiled.input_bindings_by_target[key] + @test typeof(after) !== typeof(before) + @test last(after).carrier isa PSE.ObjectRefVector + @test first(after).carrier === first_ref + @test model_status(model, :root).total === 20.0 + @test PSE.refvalue(new_status, :x)[] === 9.0 + check_indexes(model, simulation) + + reparent_object!(model, 2, :other) + step!(simulation) + @test model_status(model, :root).total === 11.0 + @test first(simulation.compiled.input_bindings_by_target[key]).carrier === first_ref + remove_object!(model, :leaf) + step!(simulation) + @test model_status(model, :root).total === 6.0 + @test PSE.refvalue(model_status(model, 1), :x) === first_ref + @test outputs(simulation)[(:reader, ObjectId(:root), :total)] == + [(1.0, 11.0), (2.0, 20.0), (3.0, 11.0), (4.0, 6.0)] + check_indexes(model, simulation) +end + +@testset "initially empty Many changes its real carrier schema after birth" begin + model = CompositeModel(Object(:root; scale=:Plant); + applications=(ModelSpec(ManyReader(); name=:reader, on=One(id=:root), inputs=( + values=Many(scale=:Leaf, within=Subtree(), var=:x, from_status=true),)),)) + simulation = run!(model; steps=1, outputs=:all) + key = (:reader, ObjectId(:root)) + previous = simulation.compiled.input_bindings_by_target[key] + @test isempty(only(previous).source_ids) + @test isempty(only(previous).carrier) + @test model_status(model, :root).total === 0.0 + check_indexes(model, simulation) + status = Status(x=7.0) + reference = PSE.refvalue(status, :x) + register_object!(model, Object(1; scale=:Leaf, parent=:root, status)) + step!(simulation) + current = simulation.compiled.input_bindings_by_target[key] + @test typeof(current) !== typeof(previous) + @test only(current).source_ids == [ObjectId(1)] + @test only(parent(only(current).carrier)) === reference + @test model_status(model, :root).total === 7.0 + @test outputs(simulation)[(:reader, ObjectId(:root), :total)] == + [(1.0, 0.0), (2.0, 7.0)] + check_indexes(model, simulation) +end + +end diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl index 943d86c72..1a6ba452b 100644 --- a/test/test-model-call-cohort-retirement.jl +++ b/test/test-model-call-cohort-retirement.jl @@ -158,7 +158,7 @@ Base.hash(owner::OwnerAlias, seed::UInt) = hash(owner.value, seed) @test !PSE._execution_cohort_owner_matches(schema_for(value), alias, owner) @test PSE._check_execution_cohort_location(location, owner, :leaf, value.object_id) === nothing @test_throws ArgumentError PSE._with_execution_cohort_location(identity, schema_for(value), - location, owner, :leaf, value.object_id) + runtime.cohorts, location, owner, :leaf, value.object_id) @test rows[1] === value PSE._retire_call_cohort_targets!(runtime, data.left.binding, ()) @test isempty(runtime.cohorts.locations) diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl index 8db6c793c..1082b82b1 100644 --- a/test/test-model-closed-cohort-schemas.jl +++ b/test/test-model-closed-cohort-schemas.jl @@ -73,7 +73,7 @@ end @test collect(map(membership -> only(flatten(membership)).context[], memberships)) == [0, 1, 2] called = Ref(false) foreign = PSE.cohort_location(store, :growth, root.object_id; owner=owners[2]) - @test_throws ArgumentError PSE._with_execution_cohort_location(schema, foreign, + @test_throws ArgumentError PSE._with_execution_cohort_location(schema, store, foreign, owners[3], :growth, root.object_id) do admitted called[] = true end diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl new file mode 100644 index 000000000..cace99554 --- /dev/null +++ b/test/test-model-cohort-store-identities.jl @@ -0,0 +1,187 @@ +module CohortStoreIdentityChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine + +PSE.@process "cohort_store_owner" verbose=false +PSE.@process "cohort_store_leaf" verbose=false +struct Controller{C} <: AbstractCohort_Store_OwnerModel + capture::C +end +struct Leaf <: AbstractCohort_Store_LeafModel end +PSE.inputs_(::Controller) = NamedTuple() +PSE.outputs_(::Controller) = (ticks=0,) +PSE.inputs_(::Leaf) = NamedTuple() +PSE.outputs_(::Leaf) = (value=0.0f0,) +function PSE.run!(model::Controller, status, environment, constants, context) + model.capture[] = context + run_call!(context, :first; publish=true) + run_call!(context, :alias; publish=true) + status.ticks += 1 + return nothing +end +function PSE.run!(::Leaf, status, environment, constants, context) + status.value += 1.0f0 + return nothing +end + +function fixture(closed) + capture = Ref{Any}() + model = CompositeModel(Object(:root; scale=:Scene, status=Status(ticks=0)), + Object(1; scale=:Leaf, parent=:root, status=Status(value=0.0f0)); + applications=( + ModelSpec(Controller(capture); name=:controller, on=One(id=:root), calls=( + first=Many(within=Subtree(), scale=:Leaf, application=:leaf), + alias=Many(within=Subtree(), scale=:Leaf, application=:leaf))), + ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)))) + if closed + previous = model.registry + store = PSE._closed_object_family_store(previous.objects) + # Admit this ID/status family by the type of the real supplied Leaf. + # No future object, value, callback or status is constructed here. + S = typeof(model_status(model, 1)) + future = PSE.ObjectFamily{ObjectId{Symbol},S}( + Union{Nothing,PSE.ObjectFamilyRow{ObjectId{Symbol},S}}[]) + objects = PSE.ObjectFamilyStore( + PSE.ClosedObjectFamilyCatalog((store.catalog.families...,future)), + store.locations, store.status_owners, copy(store.layout_cache)) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + model = PSE.CompositeModel(registry, model.applications, model.environment, + model.instances, model.source_adapter, model.status_conversion, + model.status_conversion_records, model.status_source_owners, + model.status_source_identities, model.scenario_plan_cache, model.binding_cache, + model.environment_binding_cache, model.bindings_dirty, + model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, + model.revision, model.environment_revision) + end + return (;model,capture) +end + +function check_store(simulation, closed) + store = simulation.temporal_streams.cohorts + I = closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId + O = closed ? Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} : Any + @test typeof(store) === PSE.ExecutionCohortStore{I,O} + @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === typeof(store) + @test keytype(store.cohorts) === Tuple{O,Symbol,DataType} + @test keytype(store.locations) === Tuple{O,Symbol,I} + for group in simulation.execution_plan.groups + @test group.membership.store === store + @test fieldtype(typeof(group.membership), :store) === typeof(store) + @test fieldtype(typeof(group.membership), :owner) === typeof(group.membership.owner) + for batch in group.batches + @test batch.targets.store === store + @test fieldtype(typeof(batch.targets), :store) === typeof(store) + @test fieldtype(typeof(batch.targets.cohort), :owner) === O + end + end + copied, emptied = copy(simulation.temporal_streams), empty(simulation.temporal_streams) + @test typeof(copied) === typeof(emptied) === typeof(simulation.temporal_streams) + @test isempty(copied.cohorts.locations) && isempty(emptied.cohorts.locations) + @test copied.cohorts !== store && emptied.cohorts !== store + return store +end + +@testset "ordinary execution preserves concrete store and separate call owners" begin + for closed in (false,true) + data = fixture(closed) + simulation = run!(data.model; steps=1, outputs=:all) + store = check_store(simulation, closed) + first_calls, alias_calls = call_targets(data.capture[], :first), call_targets(data.capture[], :alias) + first_owner = PSE._execution_call_owner(first_calls.binding) + alias_owner = PSE._execution_call_owner(alias_calls.binding) + first_location = PSE.cohort_location(store, :leaf, ObjectId(1); owner=first_owner) + alias_location = PSE.cohort_location(store, :leaf, ObjectId(1); owner=alias_owner) + first_target = first_location.cohort.rows[first_location.row] + alias_target = alias_location.cohort.rows[alias_location.row] + first_context = first_target.context + reference = PSE.refvalue(model_status(data.model, 1), :value) + @test first_location.cohort !== alias_location.cohort + @test first_target !== alias_target + @test first_target.context !== alias_target.context + @test PSE.refvalue(only(first_calls).status, :value) === reference + @test PSE.refvalue(only(alias_calls).status, :value) === reference + @test model_status(data.model, 1).value === 2.0f0 + @test model_status(data.model, :root).ticks == 1 + + register_object!(data.model, Object(:later; scale=:Leaf, parent=:root, + status=Status(value=0.0f0))) + continue!(simulation; steps=1) + @test simulation.temporal_streams.cohorts === store + retained = PSE.cohort_location(store, :leaf, ObjectId(1); owner=first_owner) + @test retained.cohort === first_location.cohort + @test retained.row == first_location.row + @test retained.cohort.rows[retained.row] === first_target + @test first_target.context === first_context + @test PSE.refvalue(model_status(data.model, 1), :value) === reference + @test model_status(data.model, 1).value === 4.0f0 + @test model_status(data.model, :later).value === 2.0f0 + @test model_status(data.model, :root).ticks == 2 + @test outputs(simulation)[(:leaf,ObjectId(1),:value)] == [(1.0,2.0f0),(2.0,4.0f0)] + check_store(simulation, closed) + end +end + +@testset "prepared host reset keeps the same identity-only store schema" begin + for closed in (false,true) + data = fixture(closed) + simulation = run!(data.model; steps=0, outputs=:none) + original = simulation.temporal_streams.cohorts + batch = only(only(simulation.execution_plan.groups).batches) + target = only(batch.targets) + first_call = first(target.context.calls) + child_batch = only(PSE._materialize_call_execution_batches!(first_call)) + child_schema = PSE.PreparedExecutionBatchSchema{Vector{typeof(child_batch)}}() + Root = PSE._execution_batch_type_with_call_schemas(typeof(batch), + (first=child_schema,alias=child_schema)) + schemas = (controller=PSE.PreparedExecutionBatchSchema{Vector{Root}}(),leaf=child_schema) + prepared = PSE._prepare_execution_batch_schemas(simulation, schemas) + @test typeof(prepared.temporal_streams.cohorts) === typeof(original) + @test prepared.temporal_streams.cohorts !== original + @test prepared.temporal_streams.streams === simulation.temporal_streams.streams + continue!(prepared; steps=1) + @test model_status(data.model, 1).value === 2.0f0 + check_store(prepared, closed) + end +end + +struct Payload{I,S,M} + object_id::I + status::S + marker::M +end + +@testset "bounded stores retain the open family replacement operation" begin + data = fixture(true) + store = PSE.ExecutionCohortStore(data.model.registry.objects) + status = model_status(data.model, 1) + first = Payload(ObjectId(1), status, Ref(1)) + second = Payload(ObjectId(1), status, Ref(1.0f0)) + initial = PSE.refresh_cohort_membership!(store, :leaf, [ObjectId(1)], nothing) do id, previous + first + end + location = only(initial.membership.locations) + refreshed = PSE.refresh_cohort_membership!(store, :leaf, [ObjectId(1)], [ObjectId(1)]; + previous=initial.membership) do id, previous + second + end + @test refreshed.membership === initial.membership + @test isnothing(location.cohort.rows[location.row]) + @test only(only(refreshed.membership.runs)) === second + @test second.status === status + @test length(store.cohorts) == 2 + @test isnothing(PSE.cohort_location(store, :leaf, ObjectId(:foreign))) + @test_throws TypeError PSE.cohort_location(store, :leaf, ObjectId(1.0f0)) + @test_throws TypeError PSE.cohort_location(store, :leaf, ObjectId(1); owner=:foreign) + + open = PSE.ExecutionCohortStore() + original = PSE.cohort_rows!(open, :leaf, [first]; owner=1) + @test PSE.cohort_location(open, :leaf, ObjectId(1); owner=1.0) === + PSE.cohort_location(open, :leaf, ObjectId(1); owner=1) + @test original[1] === first +end + +end diff --git a/test/test-model-persistent-empty-groups.jl b/test/test-model-persistent-empty-groups.jl index b4428720b..2f7a94b53 100644 --- a/test/test-model-persistent-empty-groups.jl +++ b/test/test-model-persistent-empty-groups.jl @@ -58,7 +58,9 @@ end Binding = PSE.CompiledEnvironmentBinding{typeof(environment_plan),Nothing,PSE.EnvironmentContext{I}} Target = PSE.CompiledExecutionTarget{typeof(PSE.model_(application.spec)),View, Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} - Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I}} + Store = typeof(simulation.temporal_streams.cohorts) + Owner = PSE._execution_store_owner_type(Store) + Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I,Owner},Store} Batch = PSE.CompiledExecutionBatch{typeof(application),Rows, PSE.RawGlobalModelEnvironment{Nothing},PSE.CompiledOutputPublication{Tuple{}}} before_callbacks = declarations[] diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index 8e633e7aa..eab81c8fd 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -141,7 +141,9 @@ function future_leaf_batch_type(simulation) Binding = PSE.CompiledEnvironmentBinding{typeof(environment_plan),Nothing,PSE.EnvironmentContext{I}} Target = PSE.CompiledExecutionTarget{typeof(PSE.model_(application.spec)),View, Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} - Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I}} + Store = typeof(simulation.temporal_streams.cohorts) + Owner = PSE._execution_store_owner_type(Store) + Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I,Owner},Store} return PSE.CompiledExecutionBatch{typeof(application),Rows, PSE.RawGlobalModelEnvironment{Nothing},PSE.CompiledOutputPublication{Tuple{}}} end diff --git a/test/test-model-status-view-cache-admission.jl b/test/test-model-status-view-cache-admission.jl new file mode 100644 index 000000000..90a0c610c --- /dev/null +++ b/test/test-model-status-view-cache-admission.jl @@ -0,0 +1,230 @@ +module StatusViewCacheAdmissionChecks47 + +using PlantSimEngine, Test +const PSE = PlantSimEngine +const VIEW_KEY = (:consumer, ObjectId(:consumer)) + +PSE.@process "status_view_cache_admission_source" verbose=false +PSE.@process "status_view_cache_admission_scalar" verbose=false +PSE.@process "status_view_cache_admission_many" verbose=false +struct Source <: AbstractStatus_View_Cache_Admission_SourceModel + level::Float64 +end +struct ScalarConsumer <: AbstractStatus_View_Cache_Admission_ScalarModel end +struct ManyConsumer <: AbstractStatus_View_Cache_Admission_ManyModel end +PSE.inputs_(::Source) = NamedTuple() +PSE.outputs_(model::Source) = (signal=model.level,) +PSE.inputs_(::ScalarConsumer) = (signal=Required(Float64),) +PSE.inputs_(::ManyConsumer) = (signals=Required(AbstractVector),) +PSE.outputs_(::Union{ScalarConsumer,ManyConsumer}) = (value=0.0, visits=0) +PSE.run!(model::Source, status, environment, constants, context) = + (status.signal = model.level; nothing) +function PSE.run!(::ScalarConsumer, status, environment, constants, context) + status.value += status.signal + status.visits += 1 + return nothing +end +function PSE.run!(::ManyConsumer, status, environment, constants, context) + status.value += sum(bound_input(context, :signals); init=0.0) + status.visits += 1 + return nothing +end + +function fixture(mode=:one) + mode in (:one, :many, :temporal) || error("unknown fixture mode") + selector = mode === :many ? Many(scale=:Source, within=SceneScope(), + application=:source, var=:signal) : One(scale=:Source, within=SceneScope(), + application=:source, var=:signal) + consumer = mode === :many ? ManyConsumer() : ScalarConsumer() + inputs = mode === :many ? (signals=selector,) : + mode === :temporal ? (PreviousTimeStep(:signal) => selector,) : (signal=selector,) + status = mode === :many ? Status(signals=[2.0], value=0.0, visits=0) : + Status(signal=2.0, value=0.0, visits=0) + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:source_a; scale=:Source, parent=:scene, status=Status(signal=2.0)), + Object(:consumer; scale=:Leaf, parent=:scene, status=status); + applications=( + ModelSpec(Source(2.0); name=:source, on=Many(scale=:Source)), + ModelSpec(consumer; name=:consumer, on=One(id=:consumer), inputs=inputs), + )) + return (; model, simulation=run!(model; steps=0, outputs=:all), mode) +end + +target(data) = only(target for batch in data.simulation.execution_plan.batches + if batch.application.id === :consumer for target in batch.targets) +view_cache(data) = data.simulation.compiled.status_views_by_target +consumer_state(data) = deepcopy(NamedTuple(model_status(data.model, :consumer))) +consumer_cells(data) = Dict(name => PSE.refvalue(model_status(data.model, :consumer), name) + for name in keys(model_status(data.model, :consumer))) +consumer_history(data) = Dict(key => [(time, deepcopy(value)) for (time, value) in stream] + for (key, stream) in outputs(data.simulation) if first(key) === :consumer) + +# Only metadata shells are reconstructed, using the real cache's statuses, +# references, input bindings and execution stamp. No defaults or kernels run. +function shell(view; status=view.status, canonical_status=view.canonical_status, + temporal_inputs=view.temporal_inputs, bound_inputs=view.bound_inputs) + return PSE.CompiledModelStatusView(view.execution_stamp, status, canonical_status, + temporal_inputs, view.private_outputs, bound_inputs) +end + +function reason(data, previous=target(data)) + simulation = data.simulation + return PSE._model_execution_target_change_reason(previous, simulation.compiled, + simulation.environment_bindings, simulation.compiled.applications_by_id[:consumer], + simulation.output_retention, simulation.temporal_streams) +end + +function refresh_plan!(data) + simulation = data.simulation + refreshed = PSE._refresh_model_execution_plan(simulation.execution_plan, + simulation.compiled, simulation.environment_bindings, simulation.temporal_streams, + simulation.output_retention, simulation.constants) + simulation.execution_plan = refreshed.plan + return refreshed +end + +function assert_cells(data, before) + after = consumer_cells(data) + @test Set(keys(after)) == Set(keys(before)) + @test all(after[name] === reference for (name, reference) in before) +end + +@testset "cached view admission keeps compatible scalar, Many and temporal owners" begin + for mode in (:one, :many, :temporal) + data, control = fixture(mode), fixture(mode) + previous = target(data) + context, cache = previous.context, previous.call_context_cache + references = consumer_cells(data) + before = consumer_state(data) + views = view_cache(data) + @test valtype(typeof(views)) === Any + original = views[VIEW_KEY] + compatible = shell(original) + @test compatible isa PSE.CompiledModelStatusView + @test compatible !== original + views[VIEW_KEY] = compatible + @test reason(data) === nothing + retained = PSE._compiled_model_execution_target_from_previous(previous, + data.simulation.compiled, data.simulation.environment_bindings, + data.simulation.compiled.applications_by_id[:consumer], ObjectId(:consumer), + data.simulation.temporal_streams, data.simulation.output_retention, + data.simulation.constants) + @test retained === previous + refreshed = refresh_plan!(data) + @test refreshed.targets_constructed == 0 + @test target(data) === previous + @test previous.status_view === original + @test target(data).context === context + @test target(data).call_context_cache === cache + @test cache.execution_stamp === original.execution_stamp === compatible.execution_stamp + @test target(data).bound_inputs === compatible.bound_inputs + @test consumer_state(data) == before + assert_cells(data, references) + if mode === :temporal + @test only(previous.input_bindings).compiled === only(compatible.temporal_inputs) + elseif mode === :many + @test previous.context.bound_inputs.signals === compatible.bound_inputs.signals + end + step!(data.simulation) + step!(control.simulation) + @test consumer_state(data) == consumer_state(control) + @test consumer_history(data) == consumer_history(control) + @test target(data) === previous + @test target(data).context === context + assert_cells(data, references) + end +end + +@testset "cached view admission preserves canonical, bound and temporal identity reasons" begin + data, other = fixture(), fixture() + original = view_cache(data)[VIEW_KEY] + delete!(view_cache(data), VIEW_KEY) + @test reason(data) === :missing_status_view + view_cache(data)[VIEW_KEY] = original + # An actual foreign object's canonical status must still be rejected even + # though its numerical state and concrete type match the current object. + view_cache(data)[VIEW_KEY] = shell(original; + canonical_status=model_status(other.model, :consumer)) + @test consumer_state(data) == consumer_state(other) + @test reason(data) === :canonical_status + view_cache(data)[VIEW_KEY] = original + @test reason(data) === nothing + + for mode in (:many, :temporal) + data, control = fixture(mode), fixture(mode) + previous = target(data) + original = view_cache(data)[VIEW_KEY] + references = consumer_cells(data) + before = consumer_state(data) + replacement = if mode === :many + old = original.bound_inputs.signals + aligned_ids = copy(getfield(object_ids(old), :ids)) + bound = PSE.BoundMany(aligned_ids, parent(old)) + @test collect(bound) == collect(old) + @test parent(bound) === parent(old) + shell(original; bound_inputs=(signals=bound,)) + else + old = only(original.temporal_inputs) + input = PSE.CompiledTemporalInput(old.binding, copy(old.source_applications), + old.initial, old.reference) + @test input !== old + @test input.reference === old.reference + shell(original; temporal_inputs=(input,)) + end + view_cache(data)[VIEW_KEY] = replacement + @test reason(data) === (mode === :many ? :bound_inputs : :temporal_inputs) + @test consumer_state(data) == before + refreshed = refresh_plan!(data) + current = target(data) + @test refreshed.targets_constructed == 1 + @test current !== previous + @test current.context !== previous.context + @test current.call_context_cache !== previous.call_context_cache + @test current.status_view === replacement + @test current.call_context_cache.execution_stamp === previous.call_context_cache.execution_stamp + @test reason(data) === nothing + assert_cells(data, references) + step!(data.simulation) + step!(control.simulation) + @test consumer_state(data) == consumer_state(control) + @test consumer_history(data) == consumer_history(control) + assert_cells(data, references) + end +end + +@testset "real source replacement changes a Ref and rebuilds without changing science" begin + data, control = fixture(), fixture() + previous = target(data) + input_reference = PSE.refvalue(previous.status_view.status, :signal) + value_reference = PSE.refvalue(previous.status_view.status, :value) + visits_reference = PSE.refvalue(previous.status_view.status, :visits) + remove_object!(data.model, :source_a) + replacement = register_object!(data.model, + Object(:source_b; scale=:Source, parent=:scene, status=Status(signal=2.0))) + compiled = PSE.Advanced.refresh_bindings!(data.model) + environment = PSE.refresh_environment_bindings!(data.model, compiled) + current_view = compiled.status_views_by_target[VIEW_KEY] + @test valtype(typeof(compiled.status_views_by_target)) === Any + @test current_view isa PSE.CompiledModelStatusView + @test PSE.refvalue(current_view.status, :signal) !== input_reference + @test PSE.refvalue(current_view.status, :signal) === PSE.refvalue(replacement.status, :signal) + @test current_view.status.signal == input_reference[] == 2.0 + @test PSE._model_execution_target_change_reason(previous, compiled, environment, + compiled.applications_by_id[:consumer], data.simulation.output_retention, + data.simulation.temporal_streams) === :status_view + step!(data.simulation) + step!(control.simulation) + current = target(data) + @test current !== previous + @test current.context !== previous.context + @test current.call_context_cache !== previous.call_context_cache + @test PSE.refvalue(current.status_view.status, :signal) !== input_reference + @test PSE.refvalue(current.status_view.status, :value) === value_reference + @test PSE.refvalue(current.status_view.status, :visits) === visits_reference + @test current.call_context_cache.execution_stamp === previous.call_context_cache.execution_stamp + @test consumer_state(data) == consumer_state(control) + @test consumer_history(data) == consumer_history(control) + @test reason(data) === nothing +end + +end # module StatusViewCacheAdmissionChecks47 diff --git a/test/test-model-target-status-view-admission.jl b/test/test-model-target-status-view-admission.jl new file mode 100644 index 000000000..3df03d061 --- /dev/null +++ b/test/test-model-target-status-view-admission.jl @@ -0,0 +1,174 @@ +module TargetStatusViewAdmissionChecks49 + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "target_view_source" verbose=false +PSE.@process "target_view_consumer" verbose=false +PSE.@process "target_view_creator" verbose=false +PSE.@process "target_view_initializer" verbose=false + +struct Source <: AbstractTarget_View_SourceModel + declarations::Base.RefValue{Int} + runs::Base.RefValue{Int} +end +struct Scalar <: AbstractTarget_View_ConsumerModel + runs::Base.RefValue{Int} +end +struct Multiple <: AbstractTarget_View_ConsumerModel + runs::Base.RefValue{Int} +end +PSE.inputs_(::Source) = NamedTuple() +function PSE.outputs_(model::Source) + model.declarations[] += 1 + return (signal=0.0f0,) +end +PSE.inputs_(::Scalar) = (signal=Required(Float32),) +PSE.inputs_(::Multiple) = (signals=Required(AbstractVector),) +PSE.outputs_(::Union{Scalar,Multiple}) = (value=0.0f0, visits=0) +function PSE.run!(model::Source, status, environment, constants, context) + model.runs[] += 1 + status.signal += 1.0f0 + return nothing +end +function PSE.run!(model::Scalar, status, environment, constants, context) + model.runs[] += 1 + status.value += status.signal + status.visits += 1 + return nothing +end +function PSE.run!(model::Multiple, status, environment, constants, context) + model.runs[] += 1 + status.value += sum(bound_input(context, :signals); init=0.0f0) + status.visits += 1 + return nothing +end + +function fixture(mode) + declarations, source_runs, consumer_runs = Ref(0), Ref(0), Ref(0) + consumer_status = mode === :many ? Status(signals=Float32[], value=0.0f0, visits=0) : + Status(signal=3.0f0, value=0.0f0, visits=0) + objects = (Object(:scene; scale=:Scene), + Object(:a; scale=:Source, parent=:scene, status=Status(signal=3.0f0)), + Object(:consumer; scale=:Leaf, parent=:scene, status=consumer_status)) + mode === :many && (objects = (objects..., + Object(:b; scale=:Source, parent=:scene, status=Status(signal=5.0f0)))) + route = mode === :many ? Many(scale=:Source, within=SceneScope(), application=:source, var=:signal) : + One(id=:a, within=SceneScope(), application=:source, var=:signal) + inputs = mode === :many ? (signals=route,) : + mode === :temporal ? (PreviousTimeStep(:signal) => route,) : (signal=route,) + consumer = mode === :many ? Multiple(consumer_runs) : Scalar(consumer_runs) + model = CompositeModel(objects...; applications=( + ModelSpec(Source(declarations,source_runs); name=:source, on=Many(scale=:Source)), + ModelSpec(consumer; name=:consumer, on=One(id=:consumer), inputs=inputs))) + simulation = run!(model; steps=0, outputs=:all) + target = only(target for batch in simulation.execution_plan.batches + if batch.application.id === :consumer for target in batch.targets) + return (;model,simulation,target,declarations,source_runs,consumer_runs) +end + +history(simulation) = Dict(key => collect(stream) for (key,stream) in outputs(simulation)) +function construct(data, schema) + simulation = data.simulation + return PSE._new_model_execution_target(simulation.compiled, + simulation.environment_bindings, simulation.compiled.applications_by_id[:consumer], + ObjectId(:consumer), simulation.temporal_streams, simulation.output_retention, + simulation.constants; target_schema=schema) +end + +@testset "one target constructor admits real scalar, Many and temporal views" begin + for mode in (:one,:many,:temporal) + data = fixture(mode) + simulation = data.simulation + application = simulation.compiled.applications_by_id[:consumer] + key = (:consumer,ObjectId(:consumer)) + view = PSE._model_status_view_for_application(simulation.compiled, application, key[2]) + @test valtype(typeof(simulation.compiled.status_views_by_target)) === Any + @test view === simulation.compiled.status_views_by_target[key] + references = Dict(name => PSE.refvalue(model_status(data.model,:consumer),name) + for name in keys(model_status(data.model,:consumer))) + before_history = history(simulation) + declarations = data.declarations[] + schema = PSE._closed_execution_cohort_schema(Tuple{typeof(data.target)}) + for admission in (PSE.OpenExecutionCohortSchema(),schema) + target = construct(data,admission) + @test typeof(target) === typeof(data.target) + @test target !== data.target + @test target.status_view === view + @test target.bound_inputs === view.bound_inputs + @test target.context.bound_inputs === view.bound_inputs + @test target.call_context_cache.execution_stamp === view.execution_stamp + @test all(PSE.refvalue(target.status_view.canonical_status,name) === reference + for (name,reference) in references) + @test data.declarations[] == declarations + @test data.source_runs[] == data.consumer_runs[] == 0 + @test history(simulation) == before_history + end + + # Missing lookup retains its original diagnostic before construction. + delete!(simulation.compiled.status_views_by_target,key) + message = "No compiled status view for application `consumer` on object `consumer`." + @test_throws message PSE._model_status_view_for_application( + simulation.compiled,application,key[2]) + @test_throws message construct(data,schema) + simulation.compiled.status_views_by_target[key] = view + @test data.declarations[] == declarations + @test data.source_runs[] == data.consumer_runs[] == 0 + step!(simulation) + @test model_status(data.model,:consumer).value === + (mode === :many ? 10.0f0 : mode === :temporal ? 3.0f0 : 4.0f0) + @test model_status(data.model,:consumer).visits == 1 + @test data.consumer_runs[] == 1 + @test data.source_runs[] == (mode === :many ? 2 : 1) + @test all(PSE.refvalue(model_status(data.model,:consumer),name) === reference + for (name,reference) in references) + end +end + +struct LeafInitModel <: AbstractTarget_View_InitializerModel end +struct Creator{C} <: AbstractTarget_View_CreatorModel + initialized::C +end +PSE.inputs_(::LeafInitModel) = NamedTuple() +PSE.outputs_(::LeafInitModel) = (value=0.0f0, visits=0) +PSE.inputs_(::Creator) = NamedTuple() +PSE.outputs_(::Creator) = (born=false, seen=0.0f0) +function PSE.run!(::LeafInitModel,status,environment,constants,context) + status.value += 2.0f0 + status.visits += 1 + return nothing +end +function PSE.run!(model::Creator,status,environment,constants,context) + if !status.born + object = register_object!(runtime_model(context),Object(:new; + scale=:Leaf,parent=:root,status=Status(value=0.0f0,visits=0))) + model.initialized[] = run_initializer!(context,:initialize,object) + status.born = true + end + status.seen = model_status(runtime_model(context),:new).value + return nothing +end + +@testset "newborn initializer uses the same status-view admission factory" begin + initialized = Ref{Any}(nothing) + model = CompositeModel(Object(:root;scale=:Scene); applications=( + ModelSpec(Creator(initialized);name=:creator,on=One(id=:root),calls=( + initialize=PSE.Initializer(One(within=Subtree(),scale=:Leaf,application=:leaf)),)), + ModelSpec(LeafInitModel();name=:leaf,on=Many(scale=:Leaf)))) + simulation = run!(model;steps=1,outputs=:all) + newborn = model_status(model,:new) + value_ref = PSE.refvalue(newborn,:value) + @test initialized[] === newborn + @test newborn.value === 2.0f0 + @test newborn.visits == 1 + @test model_status(model,:root).seen === 2.0f0 + @test isempty(outputs(simulation)[(:leaf,ObjectId(:new),:value)]) + continue!(simulation;steps=1) + @test PSE.refvalue(model_status(model,:new),:value) === value_ref + @test newborn.value === 4.0f0 + @test newborn.visits == 2 + @test model_status(model,:root).seen === 4.0f0 + @test outputs(simulation)[(:leaf,ObjectId(:new),:value)] == [(2.0,4.0f0)] +end + +end From 5e47c5ab24c092e5d51d671ad237f84159ffe84e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 06:28:39 +0100 Subject: [PATCH 024/324] Update cohort type and call observation test assertions --- test/test-model-binding-index-identities.jl | 4 ++-- test/test-model-closed-cohort-schemas.jl | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 7d1ec02d7..c19f4046c 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -124,7 +124,7 @@ end if many.execution_batches isa PSE.LazyCallExecutionBatches @test isnothing(many.execution_batches.batches) end - @test !many.binding.membership_observed[] + @test !PSE._compiled_call_membership_is_observed(many.binding) @test only(one).object_id === ObjectId(1) first_ref = PSE.refvalue(model_status(model, 1), :x) step!(simulation) @@ -133,7 +133,7 @@ end @test model_status(model, 1).x === 5f0 @test model_status(model, :leaf).x === 6f0 @test model_status(model, :outside).x === 100f0 - @test call_targets(data.capture[], :many).binding.membership_observed[] + @test PSE._compiled_call_membership_is_observed(call_targets(data.capture[], :many).binding) check_indexes(model, simulation) register_object!(model, Object(2; scale=:Leaf, parent=:root, status=Status(x=7f0))) diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl index 1082b82b1..08218862b 100644 --- a/test/test-model-closed-cohort-schemas.jl +++ b/test/test-model-closed-cohort-schemas.jl @@ -203,9 +203,9 @@ PSE.run!(::Leaf, status, environment, constants, context) = (status.leaf_visits batches = capture[].calls[1].execution_batches schema = PSE._execution_cohort_schema(batches) @test schema isa PSE.ClosedExecutionCohortSchema - @test fieldtype(typeof(only(batches).targets), :store) === PSE.ExecutionCohortStore - @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === PSE.ExecutionCohortStore - @test typeof(simulation.temporal_streams.cohorts) === PSE.ExecutionCohortStore + @test fieldtype(typeof(only(batches).targets), :store) === PSE.ExecutionCohortStore{ObjectId,Any} + @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === PSE.ExecutionCohortStore{ObjectId,Any} + @test typeof(simulation.temporal_streams.cohorts) === PSE.ExecutionCohortStore{ObjectId,Any} owner = PSE._execution_call_owner(capture[].calls[1].binding) location = PSE.cohort_location(simulation.temporal_streams.cohorts,:middle, ObjectId(:plant);owner) From a8e5a2c9f7e37471642c75e4d84477704b90aefc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 06:30:09 +0100 Subject: [PATCH 025/324] Preserve typed owners when extending runtime streams --- .../execution_batch_schemas.jl | 5 +- src/composite_model/runtime_outputs.jl | 54 +++-- test/runtests.jl | 1 + test/test-model-runtime-stream-extensions.jl | 218 ++++++++++++++++++ 4 files changed, 260 insertions(+), 18 deletions(-) create mode 100644 test/test-model-runtime-stream-extensions.jl diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 1883fb0e6..83285915b 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -430,7 +430,7 @@ end end end -@generated function _prepared_runtime_outputs(::Type{O}, status, output_targets, +@generated function _prepared_runtime_outputs(::Type{O}, status_view::CompiledModelStatusView, output_targets, application, object_id, compiled, streams, retention, initialize_missing, ) where {O<:Tuple} entries = Expr[] @@ -446,6 +446,7 @@ end end end return quote + status = status_view.status outputs = $(Expr(:tuple,entries...)) if initialize_missing # Targeted newborns own a pre-barrier private view: it is not in @@ -463,7 +464,7 @@ end local_count == length(outputs) || throw(ArgumentError("Prepared newborn retained output count changed.")) else - _model_execution_outputs_match(outputs,compiled,application,object_id, + _model_execution_outputs_match(outputs,status_view,compiled,application,object_id, retention,streams) || throw(ArgumentError("Prepared retained output names or ownership changed.")) end return outputs diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 2abc51c79..0d599f2c1 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3410,7 +3410,7 @@ function _new_model_execution_target( actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) (local_outputs...,distributed_outputs...) else - _prepared_runtime_outputs(fieldtype(Target,:output_bindings),actual.status_view.status, + _prepared_runtime_outputs(fieldtype(Target,:output_bindings),actual.status_view, actual.output_targets,actual_application,actual.object_id,owner.compiled, owner.temporal_streams,owner.output_retention,false) end @@ -3644,13 +3644,23 @@ function compile_model_execution_plan( ) end +# Every staged source was checked against the destination's element type before +# any destination is changed. Keep that proof at the append boundary after +# selecting the real immutable owner from its typed tuple. +@inline function _append_validated_runtime_streams!( + streams::Vector{S}, new_streams::Vector{Any}, +) where {S} + S === Any && return append!(streams, new_streams) + return append!(streams, (stream::S for stream in new_streams)) +end + function _model_execution_inputs_match( runtime_inputs::Tuple, compiled_inputs::Tuple, temporal_streams=nothing, ) length(runtime_inputs) == length(compiled_inputs) || return false - additions = Tuple{Any,Vector{Any}}[] + additions = Tuple{Int,Vector{Any}}[] for index in eachindex(runtime_inputs) runtime_input = runtime_inputs[index] compiled_input = compiled_inputs[index] @@ -3684,19 +3694,28 @@ function _model_execution_inputs_match( stream isa eltype(source_streams) || return false push!(new_streams, stream) end - push!(additions, (source_streams, new_streams)) + push!(additions, (index, new_streams)) else runtime_input === compiled_input || return false end end - for (source_streams, new_streams) in additions - append!(source_streams, new_streams) + for addition in additions + _with_metadata_entry(runtime_inputs, first(addition)) do runtime_input + runtime_input isa RuntimeTemporalInput || + error("A staged temporal stream extension lost its runtime owner.") + admitted_streams = runtime_input.source_streams + admitted_streams isa Vector || + error("A staged temporal stream extension lost its vector storage.") + _append_validated_runtime_streams!(admitted_streams, last(addition)) + return nothing + end end return true end function _model_execution_outputs_match( runtime_outputs::Tuple, + status_view::CompiledModelStatusView, compiled::CompiledCompositeModel, application::CompiledModelApplication, object_id::ObjectId, @@ -3713,11 +3732,6 @@ function _model_execution_outputs_match( dependency_horizons = output_retention isa OutputRetentionPlan ? output_retention.dependency_horizons : nothing - status_view = get( - compiled.status_views_by_target, - (application.id, object_id), - nothing, - ) for variable in variables variable in _model_output_names(application) || continue output_index += 1 @@ -3736,11 +3750,10 @@ function _model_execution_outputs_match( isnothing(temporal_streams) && continue key = _model_stream_key(application.id, object_id, variable) output.stream === get(temporal_streams, key, nothing) || return false - isnothing(status_view) && return false output.reference === refvalue(status_view.status, variable) || return false end - additions = Tuple{Any,Vector{Any}}[] + additions = Tuple{Int,Vector{Any}}[] if compiled.distributed_outputs isa CompiledDistributedOutputs groups = get( compiled.distributed_outputs.by_execution_target, @@ -3797,14 +3810,22 @@ function _model_execution_outputs_match( stream isa eltype(runtime_streams) || return false push!(new_streams, stream) end - push!(additions, (runtime_streams, new_streams)) + push!(additions, (output_index, new_streams)) end end end end output_index == length(runtime_outputs) || return false - for (runtime_streams, new_streams) in additions - append!(runtime_streams, new_streams) + for addition in additions + _with_metadata_entry(runtime_outputs, first(addition)) do output + output isa RuntimeDistributedOutputStream || + error("A staged distributed stream extension lost its runtime owner.") + admitted_streams = output.streams + admitted_streams isa Vector || + error("A staged distributed stream extension lost its vector storage.") + _append_validated_runtime_streams!(admitted_streams, last(addition)) + return nothing + end end return true end @@ -3935,6 +3956,7 @@ function _model_execution_target_change_reason( return :temporal_inputs _model_execution_outputs_match( target.output_bindings, + status_view, compiled, application, object_id, @@ -6023,7 +6045,7 @@ function _append_targeted_newborn_targets!( _runtime_model_output_streams(actual.status_view.status,actual_application, actual.object_id,owner.temporal_streams,owner.output_retention,true) : _prepared_runtime_outputs(fieldtype(Target,:output_bindings), - actual.status_view.status,actual.output_targets,actual_application, + actual.status_view,actual.output_targets,actual_application, actual.object_id,owner.compiled,owner.temporal_streams, owner.output_retention,true) # Narrow a retained cache before use; no new owner is published diff --git a/test/runtests.jl b/test/runtests.jl index 3c017961d..216dce85e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -333,6 +333,7 @@ else @testset "Distributed output runtime" begin include("test-model-distributed-output-runtime.jl") + include("test-model-runtime-stream-extensions.jl") end @testset "Distributed output assignment API" begin diff --git a/test/test-model-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl new file mode 100644 index 000000000..8205d6fe1 --- /dev/null +++ b/test/test-model-runtime-stream-extensions.jl @@ -0,0 +1,218 @@ +module RuntimeStreamExtensionChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "stream_extension_distributor" verbose=false +PSE.@process "stream_extension_source" verbose=false +PSE.@process "stream_extension_reader" verbose=false + +struct Distributor <: AbstractStream_Extension_DistributorModel + runs::Base.RefValue{Int} +end +PSE.inputs_(::Distributor) = NamedTuple() +PSE.outputs_(::Distributor) = (a=Distributed(Default(0f0)), z=Distributed(Default(0.0))) +function PSE.run!(model::Distributor, status, environment, constants, context) + model.runs[] += 1 + targets = output_targets(context, (:a, :z)) + for (index, id) in enumerate(object_ids(targets)) + targets.columns.a[index] = Float32(context.time) + Float32(id.value) + targets.columns.z[index] = 10.0 * context.time + id.value + end + return nothing +end + +struct Source <: AbstractStream_Extension_SourceModel + runs::Base.RefValue{Int} +end +PSE.inputs_(::Source) = NamedTuple() +PSE.outputs_(::Source) = (a=0f0, z=0.0) +function PSE.run!(model::Source, status, environment, constants, context) + model.runs[] += 1 + status.a += 1f0 + status.z += 10.0 + return nothing +end + +struct Reader <: AbstractStream_Extension_ReaderModel + runs::Base.RefValue{Int} +end +PSE.inputs_(::Reader) = (lag_a=Required(Vector{Float32}), lag_z=Required(Vector{Float64})) +PSE.outputs_(::Reader) = (seen_a=0f0, seen_z=0.0) +function PSE.run!(model::Reader, status, environment, constants, context) + model.runs[] += 1 + status.seen_a = sum(status.lag_a; init=0f0) + status.seen_z = sum(status.lag_z; init=0.0) + return nothing +end + +function execution_target(simulation, application, id) + return only(target for group in simulation.execution_plan.groups + if group.application.id === application for batch in group.batches + for target in batch.targets if target.object_id === ObjectId(id)) +end + +# Copy only the owner's vector of actual stream references. The owner, source +# streams, scientific values, canonical refs and retained samples stay genuine. +function copied_sources(output::PSE.RuntimeDistributedOutputStream) + return typeof(output)(getfield(output, :binding), copy(getfield(output, :streams)), + getfield(output, :references), getfield(output, :dependency_horizon)) +end +function copied_sources(input::PSE.RuntimeTemporalInput) + return typeof(input)(getfield(input, :compiled), copy(getfield(input, :source_streams))) +end +histories(simulation) = Dict(key => collect(stream) for (key, stream) in outputs(simulation)) + +function check_append_allocations!(streams, new_streams) + old_length = length(streams) + @test PSE._append_validated_runtime_streams!(streams, new_streams) === streams + resize!(streams, old_length) + # A second warm execution keeps the real destination's capacity available. + PSE._append_validated_runtime_streams!(streams, new_streams) + resize!(streams, old_length) + bytes = @allocated begin + PSE._append_validated_runtime_streams!(streams, new_streams) + resize!(streams, old_length) + end + @test bytes == 0 + return nothing +end + +@testset "distributed stream extension commits only after full validation" begin + runs = Ref(0) + model = CompositeModel(Object(0; scale=:Scene), + Object(1; scale=:Leaf, parent=0, status=Status(a=0f0, z=0.0)); + applications=(ModelSpec(Distributor(runs); name=:writer, on=One(id=0), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree())),)),)) + simulation = run!(model; steps=1, outputs=:all) + target = execution_target(simulation, :writer, 0) + @test Tuple(PSE._runtime_output_variable(output) for output in target.output_bindings) == (:a, :z) + staged = map(copied_sources, target.output_bindings) + original_vectors = map(output -> getfield(output, :streams), staged) + first_streams = map(first, original_vectors) + @test all(length(streams) == 1 for streams in original_vectors) + + register_object!(model, Object(2; scale=:Leaf, parent=0, status=Status(a=0f0, z=0.0))) + step!(simulation) + current_target = execution_target(simulation, :writer, 0) + @test current_target === target + @test runs[] == 2 + @test model_status(model, 1).a === 3f0 + @test model_status(model, 2).z === 22.0 + before_history = histories(simulation) + # Both genuine owners have staged additions, then this extra genuine entry + # makes the final shape check fail. Neither vector may change on rejection. + extra_entry = (staged..., first(staged)) + @test !PSE._model_execution_outputs_match(extra_entry, target.status_view, simulation.compiled, + target.context.application, target.object_id, simulation.output_retention, + simulation.temporal_streams) + @test all(length(streams) == 1 for streams in original_vectors) + @test all(first(streams) === first_stream for (streams, first_stream) in + zip(original_vectors, first_streams)) + + @test PSE._model_execution_outputs_match(staged, target.status_view, simulation.compiled, + target.context.application, target.object_id, simulation.output_retention, + simulation.temporal_streams) + for (index, output) in enumerate(staged) + streams = getfield(output, :streams) + variable = PSE._runtime_output_variable(output) + @test streams === original_vectors[index] + @test first(streams) === first_streams[index] + @test length(streams) == 2 + @test streams[2] === outputs(simulation)[(:writer, ObjectId(2), variable)] + end + @test histories(simulation) == before_history + @test runs[] == 2 + @test outputs(simulation)[(:writer, ObjectId(2), :a)] == [(2.0, 4f0)] + check_append_allocations!(copy(first(original_vectors)), Any[last(first(original_vectors))]) + # Heterogeneous storage keeps the same bulk-copy representation as before. + check_append_allocations!(Any[first(first_streams)], Any[last(first(original_vectors))]) +end + +@testset "temporal stream extension retains validation atomicity and live owners" begin + source_runs, reader_runs = Ref(0), Ref(0) + model = CompositeModel(Object(0; scale=:Scene), + Object(1; scale=:Leaf, parent=0, status=Status(a=1f0, z=10.0)); + applications=( + ModelSpec(Reader(reader_runs); name=:reader, on=One(id=0), inputs=( + PreviousTimeStep(:lag_a) => Many(scale=:Leaf, within=Subtree(), + application=:source, var=:a), + PreviousTimeStep(:lag_z) => Many(scale=:Leaf, within=Subtree(), + application=:source, var=:z))), + ModelSpec(Source(source_runs); name=:source, on=Many(scale=:Leaf)), + )) + simulation = run!(model; steps=1, outputs=:all) + target = execution_target(simulation, :reader, 0) + staged = map(copied_sources, target.input_bindings) + original_vectors = map(input -> getfield(input, :source_streams), staged) + first_streams = map(first, original_vectors) + @test length(staged) == 2 + @test all(length(streams) == 1 for streams in original_vectors) + @test model_status(model, 0).seen_a === 1f0 + @test model_status(model, 0).seen_z === 10.0 + + register_object!(model, Object(2; scale=:Leaf, parent=0, status=Status(a=3f0, z=30.0))) + step!(simulation) + current_target = execution_target(simulation, :reader, 0) + @test current_target === target + compiled_inputs = current_target.status_view.temporal_inputs + @test all(getfield(input, :compiled) === compiled for (input, compiled) in zip(staged, compiled_inputs)) + @test source_runs[] == 3 + @test reader_runs[] == 2 + @test model_status(model, 0).seen_a === 5f0 + @test model_status(model, 0).seen_z === 50.0 + before_history = histories(simulation) + # The first input is valid and stages an append; the later actual but wrong + # compiled owner must reject before either destination vector is touched. + wrong_owner = (first(compiled_inputs), first(compiled_inputs)) + @test !PSE._model_execution_inputs_match(staged, wrong_owner, simulation.temporal_streams) + @test all(length(streams) == 1 for streams in original_vectors) + @test all(first(streams) === first_stream for (streams, first_stream) in + zip(original_vectors, first_streams)) + + @test PSE._model_execution_inputs_match(staged, compiled_inputs, simulation.temporal_streams) + for (index, input) in enumerate(staged) + streams = getfield(input, :source_streams) + @test streams === original_vectors[index] + @test first(streams) === first_streams[index] + @test length(streams) == 2 + @test streams[2] === getfield(current_target.input_bindings[index], :source_streams)[2] + end + @test histories(simulation) == before_history + @test source_runs[] == 3 + @test reader_runs[] == 2 + @test outputs(simulation)[(:reader, ObjectId(0), :seen_a)] == [(1.0, 1f0), (2.0, 5f0)] + check_append_allocations!(copy(first(original_vectors)), Any[last(first(original_vectors))]) + + # The caller supplies the already-admitted current view. Local retained refs + # still require that exact scientific owner; another real view is rejected. + source_target = execution_target(simulation, :source, 1) + other_target = execution_target(simulation, :source, 2) + application = source_target.context.application + @test PSE._model_execution_outputs_match(source_target.output_bindings, + source_target.status_view, simulation.compiled, application, + source_target.object_id, simulation.output_retention, simulation.temporal_streams) + @test !PSE._model_execution_outputs_match(source_target.output_bindings, + other_target.status_view, simulation.compiled, application, + source_target.object_id, simulation.output_retention, simulation.temporal_streams) + + # Missing-view handling stays at the two existing gateways. Restore the + # genuine entry even on failure; no kernel/refresh is performed while absent. + key = (:source, ObjectId(1)) + views = simulation.compiled.status_views_by_target + saved_view = pop!(views, key) + try + @test PSE._model_execution_target_change_reason(source_target, + simulation.compiled, simulation.environment_bindings, application, + simulation.output_retention, simulation.temporal_streams) === :missing_status_view + @test_throws "No compiled status view" PSE._model_status_view_for_application( + simulation.compiled, application, source_target.object_id) + finally + views[key] = saved_view + end + @test histories(simulation) == before_history + @test source_runs[] == 3 + @test reader_runs[] == 2 +end + +end From 5693533d74ecfbe8c4dc53b9d138146326bc3476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 06:42:59 +0100 Subject: [PATCH 026/324] Initialize required lag cells in the stream extension fixture --- test/test-model-runtime-stream-extensions.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test-model-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl index 8205d6fe1..7c01e5dcc 100644 --- a/test/test-model-runtime-stream-extensions.jl +++ b/test/test-model-runtime-stream-extensions.jl @@ -131,7 +131,7 @@ end @testset "temporal stream extension retains validation atomicity and live owners" begin source_runs, reader_runs = Ref(0), Ref(0) - model = CompositeModel(Object(0; scale=:Scene), + model = CompositeModel(Object(0; scale=:Scene, status=Status(lag_a=Float32[], lag_z=Float64[])), Object(1; scale=:Leaf, parent=0, status=Status(a=1f0, z=10.0)); applications=( ModelSpec(Reader(reader_runs); name=:reader, on=One(id=0), inputs=( From 96ed4c618c72c7035c568e5611c562a0dfe51661 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 06:54:13 +0100 Subject: [PATCH 027/324] Retain caller metadata through dynamic singleton call lookup --- src/composite_model/runtime_outputs.jl | 10 ++++++++-- test/test-model-call-cohort-retirement.jl | 2 ++ test/test-model-transient-single-call-views.jl | 10 ++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 0d599f2c1..2522dde79 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -508,6 +508,11 @@ end const _SingleCallTargetView{T,CS,EB,A,TS,OR,C,I} = CallTarget{T,CS,EB,A,CT,TS,OR,C,E,I} where {CT,E} +# A dynamic batch lookup may erase payload/application/descendant/environment +# types. The collection still owns these five caller metadata types. +const _CallTargetMetadata{CS,EB,TS,OR,C} = + CallTarget{T,CS,EB,A,CT,TS,OR,C,E,I} where {T,A,CT,E,I<:ObjectId} + # V fixes caller metadata while allowing descendant and environment types to change. # The concrete mutable slot crosses the dispatch boundary without unboxing its # immutable snapshot or erasing the metadata types needed by the caller. @@ -5423,8 +5428,9 @@ end # Reuse only indistinguishable immutable snapshots; all numerical state is # still live. General iteration/collection and borrowed-buffer paths stay fresh. -@inline function Base.only(targets::CallTargets) - return _only_call_target(targets, _materialize_call_execution_batches!(targets)) +@inline function Base.only(targets::CallTargets{CS,EB,B,TS,OR,C}) where {CS,EB,B,TS,OR,C} + return _only_call_target(targets, + _materialize_call_execution_batches!(targets))::_CallTargetMetadata{CS,EB,TS,OR,C} end """ diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl index 1a6ba452b..a1c20aad9 100644 --- a/test/test-model-call-cohort-retirement.jl +++ b/test/test-model-call-cohort-retirement.jl @@ -251,6 +251,8 @@ end @test eltype(selected.binding.callee_object_ids) === I @test typeof(selected.binding) === typeof(data.left.binding) @test view_ids(selected) == [ObjectId(1)] + @test only(selected).object_id === ObjectId(1) + @test only(selected).constants === selected.constants end @testset "ordinary and prepared public calls retain state histories and membership through birth and removal" begin diff --git a/test/test-model-transient-single-call-views.jl b/test/test-model-transient-single-call-views.jl index 3fe7d8b87..4c52dacd7 100644 --- a/test/test-model-transient-single-call-views.jl +++ b/test/test-model-transient-single-call-views.jl @@ -259,6 +259,12 @@ end # independently of the transient environment's dynamically selected type. @noinline captured_offset(targets) = only(targets).constants.offset +@noinline function captured_metadata(targets) + target = only(targets) + return (target.compiled, target.environment_bindings, + target.temporal_streams, target.output_retention, target.constants) +end + function transient_lookup_allocations(sink, targets, count) return @allocated escape_transient_single_views!(sink, targets, count) end @@ -286,6 +292,10 @@ end targets = call_targets(data.context_capture[], name) @test transient_lookup_allocations(sink, targets, 1000) == 0 @test (@inferred captured_offset(targets)) === zero(S) + metadata = @inferred captured_metadata(targets) + expected = (targets.compiled, targets.environment_bindings, + targets.temporal_streams, targets.output_retention, targets.constants) + @test all(pair -> first(pair) === last(pair), zip(metadata, expected)) @test sink[] isa PSE.CallTarget @test sink[].environment === trial @test sink[].status.seen === S(40) From 69c8b0a3e5fbd364953869cba570bd2c0008f4c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 07:11:42 +0100 Subject: [PATCH 028/324] Retain the concrete cohort store type in execution plans --- src/composite_model/runtime_outputs.jl | 4 +- test/test-model-cohort-store-identities.jl | 97 ++++++++++++++++++++++ 2 files changed, 99 insertions(+), 2 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 2522dde79..9348c8486 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1209,8 +1209,8 @@ mutable struct RuntimeApplicationSchedule{P} last_step::Int end -struct CompiledExecutionPlan{G,B,I,S,TP} - cohorts::ExecutionCohortStore +struct CompiledExecutionPlan{G,B,I,S,TP,C<:ExecutionCohortStore} + cohorts::C topology::TP groups::G batches::B diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index cace99554..4df9e32d2 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -60,11 +60,15 @@ function fixture(closed) return (;model,capture) end +@noinline plan_cohorts(plan) = plan.cohorts + function check_store(simulation, closed) store = simulation.temporal_streams.cohorts I = closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId O = closed ? Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} : Any @test typeof(store) === PSE.ExecutionCohortStore{I,O} + @test fieldtype(typeof(simulation.execution_plan), :cohorts) === typeof(store) + @test (@inferred plan_cohorts(simulation.execution_plan)) === store @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === typeof(store) @test keytype(store.cohorts) === Tuple{O,Symbol,DataType} @test keytype(store.locations) === Tuple{O,Symbol,I} @@ -184,4 +188,97 @@ end @test original[1] === first end +@testset "fixed and dynamic plans share their existing concrete store" begin + for closed in (false,true) + data = fixture(closed) + simulation = run!(data.model; steps=0, outputs=:all) + original = simulation.execution_plan + store = check_store(simulation, closed) + batch = only(only(original.groups).batches) + target = only(batch.targets) + reference = PSE.refvalue(model_status(data.model, 1), :value) + fixed = PSE._fixed_execution_plan(original) + @test fixed.topology isa PSE.FixedExecution + @test fixed.cohorts === original.cohorts === store + @test fieldtype(typeof(fixed), :cohorts) === typeof(store) + @test only(only(fixed.groups).batches) === batch + @test only(only(only(fixed.groups).batches).targets) === target + fixed_simulation = PSE._simulation_with_execution_plan(simulation, fixed) + @test fixed_simulation.temporal_streams === simulation.temporal_streams + step!(fixed_simulation) + @test model_status(data.model, 1).value === 2.0f0 + @test PSE.refvalue(model_status(data.model, 1), :value) === reference + check_store(fixed_simulation, closed) + + # Rebuild only container/topology metadata with the same canonical + # constructor. The timeline, schedule, payloads and refs are retained. + dynamic = PSE.CompiledExecutionPlan(fixed.cohorts,PSE.DynamicExecution(), + typeof(original.groups)(collect(fixed.groups)),typeof(original.batches)(collect(fixed.batches)), + typeof(original.groups_by_application_slot)(collect(fixed.groups_by_application_slot)), + fixed.schedule,fixed.model_revision,fixed.environment_revision) + dynamic_simulation = PSE._simulation_with_execution_plan(fixed_simulation, dynamic) + @test dynamic.cohorts === store + @test fieldtype(typeof(dynamic), :cohorts) === typeof(store) + @test dynamic.schedule === fixed.schedule + register_object!(data.model, Object(:later;scale=:Leaf,parent=:root, + status=Status(value=0.0f0))) + step!(dynamic_simulation) + @test model_status(data.model, 1).value === 4.0f0 + @test model_status(data.model, :later).value === 2.0f0 + @test PSE.refvalue(model_status(data.model, 1), :value) === reference + check_store(dynamic_simulation, closed) + remove_object!(data.model, 1) + step!(dynamic_simulation) + @test model_status(data.model, :later).value === 4.0f0 + @test model_status(data.model, :root).ticks == 3 + @test outputs(dynamic_simulation)[(:leaf,ObjectId(1),:value)] == [(1.0,2.0f0),(2.0,4.0f0)] + @test outputs(dynamic_simulation)[(:leaf,ObjectId(:later),:value)] == [(2.0,2.0f0),(3.0,4.0f0)] + check_store(dynamic_simulation, closed) + end +end + +@testset "fixed plans still reject topology edits before execution" begin + for closed in (false,true) + data = fixture(closed) + simulation = run!(data.model;steps=0,outputs=:none) + fixed = PSE._fixed_execution_plan(simulation.execution_plan) + simulation = PSE._simulation_with_execution_plan(simulation, fixed) + newborn = register_object!(data.model,Object(:later;scale=:Leaf,parent=:root, + status=Status(value=7.0f0))) + @test_throws "topology and bindings must stay fixed" step!(simulation) + @test model_status(data.model, :root).ticks == 0 + @test model_status(data.model, 1).value === 0.0f0 + @test newborn.status.value === 7.0f0 + check_store(simulation, closed) + end +end + +@testset "open refresh retires an unvisited scheduled owner through the same store" begin + for closed in (false,true) + data = fixture(closed) + simulation = run!(data.model;steps=0,outputs=:none) + previous = simulation.execution_plan + store = check_store(simulation, closed) + location = PSE.cohort_location(store,:controller,ObjectId(:root)) + target = location.cohort.rows[location.row] + reference = PSE.refvalue(model_status(data.model, 1), :value) + # A changed authored CS needs a fresh Simulation at the outer boundary. + # This host diagnostic exercises the canonical plan-refresh worker only. + deleteat!(data.model.applications, 1) + current = PSE.Advanced.refresh_bindings!(data.model;force=true) + environment = PSE.refresh_environment_bindings!(data.model,current) + refreshed = PSE._refresh_model_execution_plan(previous,current,environment, + simulation.temporal_streams,simulation.output_retention,simulation.constants) + @test refreshed.plan.cohorts === store + @test fieldtype(typeof(refreshed.plan), :cohorts) === typeof(store) + @test (@inferred plan_cohorts(refreshed.plan)) === store + @test only(refreshed.plan.groups).application.id === :leaf + @test isnothing(PSE.cohort_location(store,:controller,ObjectId(:root))) + @test isnothing(location.cohort.rows[location.row]) + @test target.status_view.status.ticks == 0 + @test model_status(data.model, 1).value === 0.0f0 + @test PSE.refvalue(model_status(data.model, 1), :value) === reference + end +end + end From 937426ead2d4c046ea4b7c14f0cd11569e230c1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 07:38:34 +0100 Subject: [PATCH 029/324] Prepare finite cohort keys while preserving ordinary tuple lookups --- src/composite_model/execution_cohorts.jl | 70 ++++++++++++++---- src/composite_model/execution_storage.jl | 5 +- test/test-model-closed-cohort-schemas.jl | 6 +- test/test-model-cohort-store-identities.jl | 86 +++++++++++++++++++++- 4 files changed, 146 insertions(+), 21 deletions(-) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index ee49b438c..469cac93d 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -16,31 +16,73 @@ struct ExecutionCohortLocation{C<:AbstractExecutionCohort} row::Int end +# A nominal key keeps each field's declared storage type at dictionary boundaries. +# Tuple{Union{...},...} is not a concrete tuple layout and can leave tuple equality +# unresolved in a native build. Owner equality and hashing retain their ordinary +# semantics, including equal values of different types in the open store. +struct ExecutionCohortKey{O,K} + owner::O + application_id::Symbol + item::K +end + +@inline Base.isequal(left::ExecutionCohortKey, right::ExecutionCohortKey) = + isequal(left.owner, right.owner) && + left.application_id === right.application_id && isequal(left.item, right.item) + +@inline Base.hash(key::ExecutionCohortKey, seed::UInt) = + hash(key.item, hash(key.application_id, hash(key.owner, seed))) + """Persistent payload storage with identity/owner types independent of target types. A closed registry admits the finite identity and canonical namespace types. The ordinary store keeps arbitrary owners and identity types; per-application schemas still own every concrete target/row witness. """ -mutable struct ExecutionCohortStore{I<:ObjectId,O} - cohorts::Dict{Tuple{O,Symbol,DataType},AbstractExecutionCohort} - locations::Dict{Tuple{O,Symbol,I},ExecutionCohortLocation} -end - -ExecutionCohortStore{I,O}() where {I<:ObjectId,O} = ExecutionCohortStore{I,O}( - Dict{Tuple{O,Symbol,DataType},AbstractExecutionCohort}(), - Dict{Tuple{O,Symbol,I},ExecutionCohortLocation}(), -) +mutable struct ExecutionCohortStore{I<:ObjectId,O,CK,LK} + cohorts::Dict{CK,AbstractExecutionCohort} + locations::Dict{LK,ExecutionCohortLocation} + + ExecutionCohortStore{I,O,CK,LK}(cohorts::Dict{CK,AbstractExecutionCohort}, + locations::Dict{LK,ExecutionCohortLocation}) where {I<:ObjectId,O,CK,LK} = + new{I,O,CK,LK}(cohorts, locations) +end + +ExecutionCohortStore{I,O,CK,LK}() where {I<:ObjectId,O,CK,LK} = + ExecutionCohortStore{I,O,CK,LK}( + Dict{CK,AbstractExecutionCohort}(), Dict{LK,ExecutionCohortLocation}()) +ExecutionCohortStore{I,O}() where {I<:ObjectId,O} = + ExecutionCohortStore{I,O,ExecutionCohortKey{O,DataType},ExecutionCohortKey{O,I}}() +ExecutionCohortStore{I,Any}() where {I<:ObjectId} = + ExecutionCohortStore{I,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,I}}() ExecutionCohortStore() = ExecutionCohortStore{ObjectId,Any}() ExecutionCohortStore(::ObjectFamilyStore{I,<:OpenObjectFamilyCatalog}) where {I} = ExecutionCohortStore() ExecutionCohortStore(::ObjectFamilyStore{I,<:ClosedObjectFamilyCatalog}) where {I} = ExecutionCohortStore{I,Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}}}() -_execution_store_owner_type(::Type{ExecutionCohortStore{I,O}}) where {I,O} = O +_execution_store_owner_type(::Type{<:ExecutionCohortStore{I,O}}) where {I,O} = O _execution_store_owner(::ExecutionCohortStore{I,O}, owner) where {I,O} = owner::O _execution_store_object_id(::ExecutionCohortStore{I}, object_id) where {I} = ObjectId(object_id)::I +# Open queries keep the concrete tuple literal used by the ordinary store. +# Closed dictionaries use their declared nominal key, before the same Dict ops. +@inline _execution_store_key(::Type{K}, owner, application_id, item) where {K<:Tuple} = + (owner, application_id, item) +@inline _execution_store_key(::Type{ExecutionCohortKey{O,K}}, owner, application_id, item) where {O,K} = + ExecutionCohortKey{O,K}(owner, application_id, item) +@inline _execution_cohort_key(::ExecutionCohortStore{I,O,CK}, owner, application_id, ::Type{T}) where {I,O,CK,T} = + _execution_store_key(CK, owner, application_id, T) +@inline _execution_location_key(::ExecutionCohortStore{I,O,CK,LK}, owner, application_id, object_id) where {I,O,CK,LK} = + _execution_store_key(LK, owner, application_id, object_id) + +@inline _execution_key_owner(key::Tuple) = getfield(key, 1) +@inline _execution_key_owner(key::ExecutionCohortKey) = key.owner +@inline _execution_key_application(key::Tuple) = getfield(key, 2) +@inline _execution_key_application(key::ExecutionCohortKey) = key.application_id +@inline _execution_key_item(key::Tuple) = getfield(key, 3) +@inline _execution_key_item(key::ExecutionCohortKey) = key.item + """An ordered membership view over one application's concrete payload family.""" struct ExecutionCohortRows{T,C<:ExecutionCohort{T},S<:ExecutionCohortStore} <: AbstractVector{T} store::S @@ -208,7 +250,7 @@ function _execution_cohort(store::ExecutionCohortStore{StoreI,O}, owner, applica )) I <: StoreI || throw(ArgumentError("The execution target identity is outside the store schema.")) owner = _execution_store_owner(store, owner) - cohort = get!(store.cohorts, (owner, application_id, T)) do + cohort = get!(store.cohorts, _execution_cohort_key(store, owner, application_id, T)) do ExecutionCohort{T,I,O}(owner, application_id, Union{Nothing,T}[], Dict{I,Int}()) end return cohort::ExecutionCohort{T,I,O} @@ -246,7 +288,7 @@ function _store_execution_cohort_target!( else cohort.rows[slot] = target end - store.locations[(owner, cohort.application_id, object_id)] = ExecutionCohortLocation(cohort, slot) + store.locations[_execution_location_key(store, owner, cohort.application_id, object_id)] = ExecutionCohortLocation(cohort, slot) return slot end @@ -355,14 +397,14 @@ end function cohort_location(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing) id = _execution_store_object_id(store, object_id) admitted_owner = _execution_store_owner(store, owner) - return get(store.locations, (admitted_owner, application_id, id), nothing) + return get(store.locations, _execution_location_key(store, admitted_owner, application_id, id), nothing) end """Remove an execution payload without renumbering any cohort's row slots.""" function remove_cohort_target!(store::ExecutionCohortStore, application_id::Symbol, object_id; owner=nothing, schema=OpenExecutionCohortSchema()) object_id = _execution_store_object_id(store, object_id) owner = _execution_store_owner(store, owner) - key = (owner, application_id, object_id) + key = _execution_location_key(store, owner, application_id, object_id) location = get(store.locations, key, nothing) isnothing(location) && return false return _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl index cfa1671fb..673d074cb 100644 --- a/src/composite_model/execution_storage.jl +++ b/src/composite_model/execution_storage.jl @@ -96,7 +96,10 @@ function _retire_call_cohort_targets!(storage::RuntimeStorage, binding, batches; owner = _execution_call_owner(binding) current = _call_retirement_current(schema, batches, batch_schema) obsolete = _call_retirement_obsolete(schema) - for (candidate_owner, application_id, object_id) in keys(store.locations) + for store_key in keys(store.locations) + candidate_owner = _execution_key_owner(store_key) + application_id = _execution_key_application(store_key) + object_id = _execution_key_item(store_key) # Preserve the original argument order for arbitrary ordinary owners. matches = schema isa OpenExecutionCohortSchema ? isequal(owner, candidate_owner) : _execution_cohort_owner_matches(schema, candidate_owner, owner) diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl index 08218862b..dc88af6aa 100644 --- a/test/test-model-closed-cohort-schemas.jl +++ b/test/test-model-closed-cohort-schemas.jl @@ -203,9 +203,9 @@ PSE.run!(::Leaf, status, environment, constants, context) = (status.leaf_visits batches = capture[].calls[1].execution_batches schema = PSE._execution_cohort_schema(batches) @test schema isa PSE.ClosedExecutionCohortSchema - @test fieldtype(typeof(only(batches).targets), :store) === PSE.ExecutionCohortStore{ObjectId,Any} - @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === PSE.ExecutionCohortStore{ObjectId,Any} - @test typeof(simulation.temporal_streams.cohorts) === PSE.ExecutionCohortStore{ObjectId,Any} + @test fieldtype(typeof(only(batches).targets), :store) === PSE.ExecutionCohortStore{ObjectId,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,ObjectId}} + @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === PSE.ExecutionCohortStore{ObjectId,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,ObjectId}} + @test typeof(simulation.temporal_streams.cohorts) === PSE.ExecutionCohortStore{ObjectId,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,ObjectId}} owner = PSE._execution_call_owner(capture[].calls[1].binding) location = PSE.cohort_location(simulation.temporal_streams.cohorts,:middle, ObjectId(:plant);owner) diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index 4df9e32d2..3a4da0859 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -66,12 +66,15 @@ function check_store(simulation, closed) store = simulation.temporal_streams.cohorts I = closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId O = closed ? Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} : Any - @test typeof(store) === PSE.ExecutionCohortStore{I,O} + CK = closed ? PSE.ExecutionCohortKey{O,DataType} : Tuple{O,Symbol,DataType} + LK = closed ? PSE.ExecutionCohortKey{O,I} : Tuple{O,Symbol,I} + @test typeof(store) === PSE.ExecutionCohortStore{I,O,CK,LK} + @test typeof(typeof(store)()) === typeof(store) @test fieldtype(typeof(simulation.execution_plan), :cohorts) === typeof(store) @test (@inferred plan_cohorts(simulation.execution_plan)) === store @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === typeof(store) - @test keytype(store.cohorts) === Tuple{O,Symbol,DataType} - @test keytype(store.locations) === Tuple{O,Symbol,I} + @test keytype(store.cohorts) === CK + @test keytype(store.locations) === LK for group in simulation.execution_plan.groups @test group.membership.store === store @test fieldtype(typeof(group.membership), :store) === typeof(store) @@ -280,5 +283,82 @@ end @test PSE.refvalue(model_status(data.model, 1), :value) === reference end end +# This ordinary owner deliberately aliases a canonical tuple without having its +# type. Dictionary equality must not add a type/parameter tag to the owner. +struct OwnerAlias{T} + value::T +end +Base.isequal(left::OwnerAlias, right::OwnerAlias) = isequal(left.value, right.value) +Base.isequal(left::OwnerAlias, right::Tuple) = isequal(left.value, right) +Base.isequal(left::Tuple, right::OwnerAlias) = isequal(left, right.value) +Base.hash(owner::OwnerAlias, seed::UInt) = hash(owner.value, seed) + +@testset "ordinary tuple keys preserve open owner equality and hashing" begin + data = fixture(false) + status = model_status(data.model, 1) + payload = Payload(ObjectId(1), status, Ref(1)) + for (stored,query) in ((1,1.0),(1.0,1), + ((:controller,ObjectId(:root),:first,:call), + OwnerAlias((:controller,ObjectId(:root),:first,:call))), + (OwnerAlias((:controller,ObjectId(:root),:first,:call)), + (:controller,ObjectId(:root),:first,:call))) + store = PSE.ExecutionCohortStore() + rows = PSE.cohort_rows!(store, :leaf, [payload]; owner=stored) + location = PSE.cohort_location(store, :leaf, ObjectId(1); owner=query) + @test location.cohort === rows.cohort + @test location.cohort.rows[location.row] === payload + @test PSE._execution_cohort(store, query, :leaf, typeof(payload)) === rows.cohort + @test length(store.cohorts) == 1 + stored_key = PSE._execution_location_key(store, stored, :leaf, ObjectId(1)) + query_key = PSE._execution_location_key(store, query, :leaf, ObjectId(1)) + @test isequal(query_key, stored_key) + @test hash(query_key) == hash(stored_key) + @test PSE.remove_cohort_target!(store, :leaf, ObjectId(1); owner=query) + @test isnothing(rows.cohort.rows[location.row]) + @test isempty(store.locations) + @test PSE.refvalue(payload.status, :value) === PSE.refvalue(status, :value) + end +end + +_key_value(dict, key) = get(dict, key, 0) + +@testset "bounded keys admit independent caller and callee identities" begin + I = Union{ObjectId{Int},ObjectId{Symbol}} + O = Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} + store = PSE.ExecutionCohortStore{I,O}() + K = PSE.ExecutionCohortKey{O,I} + @test isconcretetype(K) + @test fieldtype(K, :owner) === O + @test fieldtype(K, :item) === I + # Both cross-products are valid: caller identity is not the callee's type. + for (caller,callee) in ((ObjectId(:root),ObjectId(1)),(ObjectId(1),ObjectId(:leaf))) + first = (:controller,caller,:first,:call) + alias = (:controller,caller,:alias,:call) + scheduled = PSE._execution_location_key(store, nothing, :leaf, callee) + called = PSE._execution_location_key(store, first, :leaf, callee) + aliased = PSE._execution_location_key(store, alias, :leaf, callee) + @test typeof(scheduled) === typeof(called) === typeof(aliased) === K + @test !isequal(scheduled, called) && !isequal(called, aliased) + values = Dict{K,Int}(scheduled=>1,called=>2,aliased=>3) + @test (@inferred _key_value(values, called)) == 2 + @test values[scheduled] == 1 && values[aliased] == 3 + @test length(values) == 3 + end + # Representation differs; owner/id semantics and the ordinary query stay exact. + owner = (:controller,ObjectId(:root),:first,:call) + bounded = PSE._execution_location_key(store, owner, :leaf, ObjectId(1)) + open_store = PSE.ExecutionCohortStore() + open = @inferred PSE._execution_location_key(open_store, owner, :leaf, ObjectId(1)) + @test open === (owner,:leaf,ObjectId(1)) + @test typeof(open) === Tuple{typeof(owner),Symbol,ObjectId{Int}} + @test isequal(PSE._execution_key_owner(bounded),PSE._execution_key_owner(open)) + @test PSE._execution_key_application(bounded) === PSE._execution_key_application(open) + @test PSE._execution_key_item(bounded) === PSE._execution_key_item(open) + @test PSE._execution_store_owner_type(typeof(store)) === O + @test PSE._execution_store_owner_type(typeof(open_store)) === Any + rebuilt = typeof(store)() + @test typeof(rebuilt) === typeof(store) + @test isempty(rebuilt.cohorts) && isempty(rebuilt.locations) +end end From d77404972d275beb665ca84de0546ec264fb5172 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 08:12:04 +0100 Subject: [PATCH 030/324] Specialize cohort location admission callbacks --- src/composite_model/execution_cohorts.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 469cac93d..dfc5bf829 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -162,15 +162,15 @@ function _check_execution_cohort_location(location, owner, application_id, objec return nothing end -@inline _with_execution_cohort_location(f, schema::ExecutionCohortSchema, store::ExecutionCohortStore, ::Nothing, owner, application_id, object_id) = f(nothing) -@inline function _with_execution_cohort_location(f, ::OpenExecutionCohortSchema, store::ExecutionCohortStore, location::ExecutionCohortLocation, owner, application_id, object_id) +@inline _with_execution_cohort_location(f::F, schema::ExecutionCohortSchema, store::ExecutionCohortStore, ::Nothing, owner, application_id, object_id) where {F} = f(nothing) +@inline function _with_execution_cohort_location(f::F, ::OpenExecutionCohortSchema, store::ExecutionCohortStore, location::ExecutionCohortLocation, owner, application_id, object_id) where {F} _check_execution_cohort_location(location, owner, application_id, object_id) return f(location) end # Select the actual cohort before invoking the operation. An assertion after a # dynamic read/clear would leave the abstract operation reachable by JuliaC. -@generated function _with_execution_cohort_location(f, schema::ClosedExecutionCohortSchema{T}, store::S, location::ExecutionCohortLocation, owner, application_id, object_id) where {T,S<:ExecutionCohortStore} +@generated function _with_execution_cohort_location(f::F, schema::ClosedExecutionCohortSchema{T}, store::S, location::ExecutionCohortLocation, owner, application_id, object_id) where {F,T,S<:ExecutionCohortStore} branches = Expr[] O = _execution_store_owner_type(S) for Target in fieldtypes(T) From f12a9954cdc25d81bbb41f8645d04a2dd0166c49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 10:06:44 +0100 Subject: [PATCH 031/324] Avoid copying heterogeneous tuples during scenario graph preparation --- src/composite_model/compilation.jl | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index d304f354e..6dad8f539 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -824,8 +824,8 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs) # ModelSpec already owns normalized Call/Initializer declarations. Prepare # their logical routes after every application identifier is known, without # replaying dep or resolving any object/scope membership. - declaration_applications = Tuple(record for record in authored - if record isa AuthoredApplicationRecipe) + declaration_applications = AuthoredApplicationRecipe[record for record in authored + if record isa AuthoredApplicationRecipe] call_slot = 0 for index in eachindex(authored) recipe = authored[index] @@ -1401,8 +1401,16 @@ function _freeze_scenario_application_children(applications, children) ) end -function _prepare_authored_scenario_graph(applications, input_plans, call_plans, +_graph_record_vector(::Type{T}, records) where {T} = + records isa Vector{T} ? records : collect(T, records) + +function _prepare_authored_scenario_graph(application_records, input_records, call_records, distributed_output_plans) + # Graph traversal needs scalar records, not a copied heterogeneous tuple + # every time a generator or callback crosses an unspecialized boundary. + applications = _graph_record_vector(AuthoredApplicationRecipe, application_records) + input_plans = _graph_record_vector(CompiledModelInputPlan, input_records) + call_plans = _graph_record_vector(CompiledModelCallPlan, call_records) call_owners = _scenario_call_owners(applications, call_plans) manual_application_ids = Tuple(application.id for application in applications if !isempty(call_owners[application.id])) @@ -1432,7 +1440,8 @@ function _prepare_authored_scenario_graph(applications, input_plans, call_plans, frozen_children, order, failures) end -function _prepare_authored_scenario_program(applications) +function _prepare_authored_scenario_program(recipes) + applications = _graph_record_vector(AuthoredApplicationRecipe, recipes) output_records = _prepare_authored_output_records(applications) destinations = _authored_distributed_output_plans(applications, output_records) input_records = _prepare_authored_input_records(applications, destinations) From c7e1a65cc0bdab4771922f9a84163d953a6a5a21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 10:37:44 +0100 Subject: [PATCH 032/324] Preserve environment and newborn call types through the shared executor --- src/composite_model/call_evaluations.jl | 4 +- .../execution_batch_schemas.jl | 46 ++++++- src/composite_model/runtime_outputs.jl | 55 ++++---- ...est-model-finite-call-extension-intents.jl | 58 ++++++++ test/test-model-persistent-empty-groups.jl | 2 +- test/test-model-prepared-growth-schemas.jl | 127 ++++++++++++++++-- 6 files changed, 248 insertions(+), 44 deletions(-) diff --git a/src/composite_model/call_evaluations.jl b/src/composite_model/call_evaluations.jl index d9f08da63..ba3feae2a 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -105,7 +105,9 @@ function _evaluate_call_targets!(targets::AbstractVector{<:CallTarget}, sampled_ # Targeted newborn execution has lightweight individual views before the # lifecycle barrier installs the ordinary compiled batch. for target in targets - _run_call!(_evaluation_target(target), true, sampled_environment, environment) + _with_call_target_entry(targets, target) do actual + _run_call!(_evaluation_target(actual), true, sampled_environment, environment) + end end return nothing end diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 83285915b..e7b084862 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -172,11 +172,11 @@ end push!(checks, :($value isa $(fieldtype(Target, name)))) push!(values, :($value::$(fieldtype(Target, name)))) end - for name in (:compiled, :temporal_streams, :output_retention, :constants, :environment) + for name in (:compiled, :environment_bindings, :temporal_streams, :output_retention, :constants, :environment) push!(checks, :(getproperty(owners, $(QuoteNode(name))) isa $(fieldtype(Context, name)))) end condition = foldl((a,b) -> :($a && $b), checks) - owner_names = (:compiled, :temporal_streams, :output_retention, :constants, :environment) + owner_names = (:compiled, :environment_bindings, :temporal_streams, :output_retention, :constants, :environment) owner_values = Expr(:tuple, [:(getproperty(owners, $(QuoteNode(name)))::$(fieldtype(Context,name))) for name in owner_names]...) A = fieldtype(Context, :application) push!(branches, quote @@ -638,3 +638,45 @@ end cache isa Cache || throw(ArgumentError("A retained newborn context is outside its prepared schema.")) return cache::Cache end + +# Private newborn views are assembled dynamically but already have a finite +# canonical payload family. Preserve its existing CallTarget types, including +# the actual caller's typed environment owners, until the shared executor. +@inline _targeted_newborn_target_buffer(::OpenExecutionBatchSchema, context) = CallTarget[] +@generated function _targeted_newborn_target_buffer(::PreparedExecutionBatchSchema{BT}, + context::RC, +) where {BT,RC<:RunContext} + views = Type[] + CS = fieldtype(RC, :compiled) + EB = fieldtype(RC, :environment_bindings) + TS = fieldtype(RC, :temporal_streams) + OR = fieldtype(RC, :output_retention) + C = fieldtype(RC, :constants) + E = fieldtype(RC, :environment) # CallTargets.environment is deliberately Any. + for B in _prepared_execution_batch_types(BT) + Target = eltype(fieldtype(B, :targets)) + TargetContext = fieldtype(Target, :context) + A = fieldtype(TargetContext, :application) + Calls = fieldtype(TargetContext, :calls) + I = fieldtype(Target, :object_id) + push!(views, CallTarget{Target,CS,EB,A,Calls,TS,OR,C,E,I}) + end + unique!(views) + return :(Vector{$(Union{views...})}()) +end + +# Readback from a finite collection enters the same hard-call executor in a +# concrete branch. Open collections keep ordinary Julia dispatch. This admits +# metadata only; it never reconstructs an execution payload or scientific state. +@generated function _with_call_target_entry(f::F, targets::AbstractVector{V}, target) where {F,V} + views = Base.uniontypes(V) + if !all(T -> isconcretetype(T) && T <: CallTarget, views) + return :(f(target)) + end + branches = [:(target isa $T && return f(target::$T)) for T in views] + return quote + $(Expr(:meta, :inline)) + $(branches...) + throw(ArgumentError("A call target is outside its collection schema.")) + end +end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 9348c8486..c62d2e2a1 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -259,9 +259,9 @@ Runtime context passed as the final argument to model kernels. Use [`call_targets`](@ref), and [`run_call!`](@ref) instead of inspecting its fields. """ -mutable struct RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I<:ObjectId} +mutable struct RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I<:ObjectId,EB<:CompiledEnvironmentBindings} compiled::CS - environment_bindings::CompiledEnvironmentBindings + environment_bindings::EB application::A object_id::I calls::CT @@ -3400,7 +3400,8 @@ function _new_model_execution_target( environment_binding = _environment_binding_for(env_bindings, application.id, object_id) fields = (object_id=object_id, model=model, output_targets=distributed_targets, call_bindings=call_bindings, environment_binding=environment_binding) - owners = (compiled=compiled, temporal_streams=temporal_streams, + owners = (compiled=compiled, environment_bindings=env_bindings, + temporal_streams=temporal_streams, output_retention=output_retention, constants=constants, environment=_NO_ENVIRONMENT_OVERRIDE) return _with_execution_target_type(target_schema, application, status_view, fields, owners) do Target, actual_application, actual, owner, call_schema @@ -3422,7 +3423,7 @@ function _new_model_execution_target( context = if isnothing(owner.temporal_streams) && isempty(actual.output_targets) nothing else - _prepare_model_execution_context!(nothing, owner.compiled, env_bindings, + _prepare_model_execution_context!(nothing, owner.compiled, owner.environment_bindings, actual_application, actual.object_id, actual.bound_inputs, actual.output_targets, actual.call_bindings, owner.temporal_streams, owner.output_retention, 0.0, owner.constants, true, owner.environment; @@ -5998,7 +5999,7 @@ function _prepare_targeted_newborn_targets( return nothing end - targets = CallTarget[] + targets = _targeted_newborn_target_buffer(batch_schema, context) for partial_application in callee_applications _append_targeted_newborn_targets!( targets, context, targeted_runtime, partial_application, @@ -6043,7 +6044,8 @@ function _append_targeted_newborn_targets!( fields = (object_id=object_id,model=_application_model(application,object_id), output_targets=output_targets,call_bindings=call_bindings, environment_binding=environment_binding) - owners = (compiled=compiled,temporal_streams=context.temporal_streams, + owners = (compiled=compiled,environment_bindings=environment_bindings, + temporal_streams=context.temporal_streams, output_retention=context.output_retention,constants=context.constants, environment=context.environment) _with_execution_target_type(admission,application,status_view,fields,owners) do Target,actual_application,actual,owner,call_schema @@ -6060,16 +6062,18 @@ function _append_targeted_newborn_targets!( if isnothing(prepared_cache) prepared_cache = _newborn_call_context_cache(context,actual_application, actual.object_id,actual.bound_inputs,actual.output_targets, - actual.call_bindings,environment_bindings,stamp;call_schema) + actual.call_bindings,owner.environment_bindings,stamp;call_schema) end result = _targeted_newborn_call_target(context,actual_application, actual.object_id,actual.model,actual.status_view,outputs, - actual.output_targets,actual.call_bindings,environment_bindings, + actual.output_targets,actual.call_bindings,owner.environment_bindings, actual.environment_binding,prepared_cache) isnothing(Target) || result.execution_target isa Target || throw(ArgumentError("A newborn execution target is outside its prepared schema.")) - targeted_runtime.call_context_caches[key] = prepared_cache + # Admit the full caller view before publishing its cache. The + # payload and partial environment owner retain their identities. push!(targets,result) + targeted_runtime.call_context_caches[key] = prepared_cache return nothing end end @@ -6347,8 +6351,8 @@ end # not change the concrete child-call tuple. Recover the context type without # erasing the normal no-override execution path. @inline _call_context_type( - ::RunContext{CS,A,CT,BI,OT,TS,OR,C,OldE,I}, ::E, -) where {CS,A,CT,BI,OT,TS,OR,C,OldE,I,E} = RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I} + ::RunContext{CS,A,CT,BI,OT,TS,OR,C,OldE,I,EB}, ::E, +) where {CS,A,CT,BI,OT,TS,OR,C,OldE,I,EB,E} = RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I,EB} @inline _call_context_type(::Nothing, environment) = RunContext # Metadata already proved current needs only invocation values synchronized. @@ -6821,12 +6825,9 @@ function _run_call_targets!( environment, ) for target in targets - _run_call!( - target, - publish, - sampled_environment, - environment, - ) + _with_call_target_entry(targets, target) do actual + _run_call!(actual, publish, sampled_environment, environment) + end end return targets end @@ -6868,19 +6869,13 @@ function _selected_run_initializer!(cached_targets, context::RunContext, name::S context, name, requested_ids, _synchronized_named_call(cached_targets, context, name); initializer=true, ) - target = only(targets) - key = (target.application.id, target.object_id) - # Reserve the application/object pair before model code runs. If the - # initializer mutates and then throws, retrying it would duplicate an - # unknown partial side effect, so the lifecycle event remains poisoned. - push!(lifecycle_delta(model).initialized_targets, key) - _run_call_targets!( - targets, - false, - _UNSPECIFIED_SCENE_ENVIRONMENT, - context.environment, - ) - return model_status(model, target.object_id) + return _with_call_target_entry(targets, only(targets)) do target + key = (target.application.id, target.object_id) + # Reserve before model code; failure still poisons this lifecycle event. + push!(lifecycle_delta(model).initialized_targets, key) + _run_call!(target, false, _UNSPECIFIED_SCENE_ENVIRONMENT, context.environment) + return model_status(model, target.object_id) + end end function run_initializer!(context, name::Symbol, object) diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl index 115509f1e..3668d43a7 100644 --- a/test/test-model-finite-call-extension-intents.jl +++ b/test/test-model-finite-call-extension-intents.jl @@ -284,4 +284,62 @@ end @test only(raw) == (rows, candidate) end + +call_key(target) = (target.application.id, target.object_id.value) + +@testset "six real newborn call families retain finite metadata through execution" begin + ordinary, prepared = fixture(; prepared=false, wide=true), fixture(; wide=true) + for (data, closed) in ((ordinary, false), (prepared, true)) + simulation = data.simulation + step!(simulation) + context = root_target(simulation).context + cached = call_targets(context, :all) + current_owner = context.environment_bindings + add_leaves!(data) + requested = [ObjectId(100index + 1) for index in 1:6] + cells = [PSE.refvalue(model_status(data.model, id), :value) for id in requested] + before_state = state(data.model) + before_random = random_state(data.rng) + locations = copy(simulation.temporal_streams.cohorts.locations) + targets = call_targets(context, :all; objects=requested) + @test getproperty.(targets, :object_id) == requested + @test state(data.model) == before_state + @test random_state(data.rng) == before_random + @test simulation.temporal_streams.cohorts.locations == locations + partial_owner = first(targets).environment_bindings + @test partial_owner !== current_owner + @test typeof(partial_owner) === typeof(current_owner) === + fieldtype(typeof(cached), :environment_bindings) + @test all(target -> target.environment_bindings === partial_owner, targets) + @test context.environment_bindings === current_owner + if closed + @test length(Base.uniontypes(eltype(targets))) == 6 + @test all(isconcretetype, Base.uniontypes(eltype(targets))) + @test fieldtype(typeof(context), :environment_bindings) === typeof(current_owner) + @test all(target -> fieldtype(typeof(target.context_cache.default), + :environment_bindings) === typeof(partial_owner), targets) + for (index, target) in enumerate(targets) + @test (@inferred PSE._with_call_target_entry(call_key, targets, target)) === + (APP_NAMES[index], 100index + 1) + end + else + @test eltype(targets) === CallTarget + end + for (index, target) in enumerate(targets) + @test target.canonical_status === model_status(data.model, requested[index]) + @test PSE.refvalue(target.status, :value) === cells[index] + @test target.status.visits == 0 + end + run_call!(context, :all; objects=requested, publish=false) + @test all(id -> model_status(data.model, id).visits == 1, requested) + @test simulation.temporal_streams.cohorts.locations == locations + continue!(simulation; steps=1) + @test all(PSE.refvalue(model_status(data.model, id), :value) === cell + for (id, cell) in zip(requested, cells)) + end + @test state(prepared.model) == state(ordinary.model) + @test random_state(prepared.rng) == random_state(ordinary.rng) + @test collect_outputs(prepared.simulation) == collect_outputs(ordinary.simulation) +end + end # module FiniteCallExtensionIntentChecks diff --git a/test/test-model-persistent-empty-groups.jl b/test/test-model-persistent-empty-groups.jl index 2f7a94b53..14c0a65cc 100644 --- a/test/test-model-persistent-empty-groups.jl +++ b/test/test-model-persistent-empty-groups.jl @@ -54,7 +54,7 @@ end View = PSE.CompiledModelStatusView{Full,Full,Tuple{},Empty,Empty} Context = PSE.RunContext{typeof(compiled),typeof(application),Tuple{},Empty,Empty, typeof(simulation.temporal_streams),typeof(simulation.output_retention), - typeof(simulation.constants),PSE.NoEnvironmentOverride,I} + typeof(simulation.constants),PSE.NoEnvironmentOverride,I,typeof(simulation.environment_bindings)} Binding = PSE.CompiledEnvironmentBinding{typeof(environment_plan),Nothing,PSE.EnvironmentContext{I}} Target = PSE.CompiledExecutionTarget{typeof(PSE.model_(application.spec)),View, Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index eab81c8fd..f55eeeb81 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -15,7 +15,9 @@ struct GrowthController <: AbstractClosure_ControllerModel birth_day::Base.RefValue{Int} seed::Base.RefValue{Float64} end -struct LeafState <: AbstractClosure_LeafModel end +struct LeafState <: AbstractClosure_LeafModel + fail_after_mutation::Bool +end PSE.inputs_(::Pulse) = NamedTuple() PSE.outputs_(::Pulse) = (rate=0.0,) @@ -56,9 +58,10 @@ function PSE.run!(model::GrowthController, status, environment, constants, conte return nothing end -function PSE.run!(::LeafState, status, environment, constants, context) +function PSE.run!(model::LeafState, status, environment, constants, context) status.value += status.seed status.visits += 1 + model.fail_after_mutation && error("leaf initialization failed after mutation") return nothing end @@ -74,7 +77,7 @@ function make_hardcall() ) end -function make_growth() +function make_growth(; environment=nothing, fail_initializer=false) birth_day = Ref(2) seed = Ref(3.0) model = CompositeModel(Object(:owner; scale=:Scene, @@ -88,9 +91,9 @@ function make_growth() pulse=One(within=Self(), application=:pulse), initialize=Initializer(One(within=Subtree(), scale=:Leaf, application=:leaf)), )), - ModelSpec(LeafState(); name=:leaf, on=Many(scale=:Leaf)), + ModelSpec(LeafState(fail_initializer); name=:leaf, on=Many(scale=:Leaf)), ModelSpec(Pulse(); name=:pulse, on=One(id=:owner)), - ), + ), environment, ) return (; model, birth_day, seed) end @@ -127,7 +130,7 @@ function future_leaf_batch_type(simulation) compiled = simulation.compiled application = compiled.applications_by_id[:leaf] environment_plan = simulation.environment_bindings.application_plans_by_id[:leaf] - @assert environment_plan.backend isa PSE.GlobalConstant{Nothing} + @assert environment_plan.backend isa PSE.GlobalConstant @assert environment_plan.uses_raw_global_source @assert isempty(application.target_ids) Empty = NamedTuple{(),Tuple{}} @@ -137,7 +140,7 @@ function future_leaf_batch_type(simulation) View = PSE.CompiledModelStatusView{LeafFullStatus,LeafFullStatus,Tuple{},Empty,Empty} Context = PSE.RunContext{typeof(compiled),typeof(application),Tuple{},Empty,Empty, typeof(simulation.temporal_streams),typeof(simulation.output_retention), - typeof(simulation.constants),PSE.NoEnvironmentOverride,I} + typeof(simulation.constants),PSE.NoEnvironmentOverride,I,typeof(simulation.environment_bindings)} Binding = PSE.CompiledEnvironmentBinding{typeof(environment_plan),Nothing,PSE.EnvironmentContext{I}} Target = PSE.CompiledExecutionTarget{typeof(PSE.model_(application.spec)),View, Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} @@ -145,11 +148,12 @@ function future_leaf_batch_type(simulation) Owner = PSE._execution_store_owner_type(Store) Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I,Owner},Store} return PSE.CompiledExecutionBatch{typeof(application),Rows, - PSE.RawGlobalModelEnvironment{Nothing},PSE.CompiledOutputPublication{Tuple{}}} + PSE.RawGlobalModelEnvironment{typeof(environment_plan.prepared_source)}, + PSE.CompiledOutputPublication{Tuple{}}} end -function prepare_schema_growth() - setup = make_growth() +function prepare_schema_growth(; environment=nothing, fail_initializer=false) + setup = make_growth(; environment, fail_initializer) model = with_closed_registry(setup.model;future=(LeafSeedStatus,LeafFullStatus)) simulation = run!(model;steps=0,outputs=:none) controller = only(simulation.execution_plan.groups) @@ -215,4 +219,107 @@ end end end + +call_key(target) = (target.application.id, target.object_id.value) + +@testset "prepared newborn views retain current and private environment owners" begin + for environment in (nothing, (T=3f0,)) + state = prepare_schema_growth(; environment) + state.birth_day[] = 100 # The test registers its real target explicitly. + simulation = state.simulation + step!(simulation) # Obtain a context invoked by the actual root kernel. + controller = only(group for group in simulation.execution_plan.groups + if group.application.id === :controller) + context = only(only(controller.batches).targets).context + cached = only(calls for calls in context.calls + if PSE._compiled_call_name(calls.binding) === :initialize) + current_owner = context.environment_bindings + leaf_group = only(group for group in simulation.execution_plan.groups + if group.application.id === :leaf) + leaf = register_object!(simulation.model, Object(:leaf; scale=:Leaf, + parent=:owner, status=Status(seed=2.5))) + targets = PSE._targeted_new_object_call_targets(context, :initialize, + [ObjectId(:leaf)], cached; initializer=true) + target = only(targets) + partial_owner = target.environment_bindings + @test isconcretetype(eltype(targets)) + @test (@inferred PSE._with_call_target_entry(call_key, targets, target)) === (:leaf, :leaf) + @test partial_owner !== current_owner + @test typeof(partial_owner) === typeof(current_owner) === + fieldtype(typeof(cached), :environment_bindings) + @test fieldtype(typeof(context), :environment_bindings) === typeof(current_owner) + @test fieldtype(typeof(target.context_cache.default), :environment_bindings) === + typeof(partial_owner) + TrialContext = PSE._call_context_type(target.context_cache.default, (T=9f0,)) + @test fieldtype(TrialContext, :environment_bindings) === typeof(partial_owner) + @test context.environment_bindings === current_owner + @test only(partial_owner.bindings).object_id == ObjectId(:leaf) + canonical = model_status(simulation.model, leaf) + @test target.canonical_status === canonical + @test PSE.refvalue(target.status, :seed) === PSE.refvalue(canonical, :seed) + @test canonical.visits == 0 && canonical.value == 0.0 + if isnothing(environment) + # All other owners/fields belong to the real admitted newborn. + # Only EB comes from another genuine scenario, outside its schema. + foreign = prepare_schema_growth(; environment=(T=3f0,)) + foreign_owner = foreign.simulation.environment_bindings + @test !(foreign_owner isa typeof(partial_owner)) + fields = (object_id=target.object_id, model=target.model, + output_targets=target.output_targets, + call_bindings=target.execution_target.call_bindings, + environment_binding=target.environment_binding) + owners = (compiled=target.compiled, environment_bindings=foreign_owner, + temporal_streams=target.temporal_streams, + output_retention=target.output_retention, constants=target.constants, + environment=target.environment) + admission = PSE._call_cohort_admission(cached.batch_schema, + PSE.OpenExecutionCohortSchema()) + @test_throws ArgumentError PSE._with_execution_target_type( + (args...) -> error("foreign owner entered target factory"), admission, + target.application, target.execution_target.status_view, fields, owners) + @test canonical.visits == 0 && canonical.value == 0.0 + @test isempty(PSE.lifecycle_delta(simulation.model).initialized_targets) + end + @test isempty(leaf_group.batches) + @test PSE.cohort_location(simulation.temporal_streams.cohorts, + :leaf, ObjectId(:leaf)) === nothing + + @test run_initializer!(context, :initialize, leaf) === canonical + @test canonical.visits == 1 && canonical.value == 2.5 + @test (:leaf, ObjectId(:leaf)) in PSE.lifecycle_delta(simulation.model).initialized_targets + @test isempty(leaf_group.batches) + @test_throws "already initialized" run_initializer!(context, :initialize, leaf) + @test canonical.visits == 1 + continue!(simulation; steps=1) + payload = only(only(leaf_group.batches).targets) + @test canonical.visits == 2 && canonical.value == 5.0 + @test payload.status_view.canonical_status === canonical + @test payload.call_context_cache !== target.context_cache + @test payload.call_context_cache.execution_stamp === target.context_cache.execution_stamp + @test target.environment_bindings === partial_owner + end +end + +@testset "a failed prepared initializer reserves before its only kernel" begin + state = prepare_schema_growth(; fail_initializer=true) + state.birth_day[] = 100 + simulation = state.simulation + step!(simulation) + controller = only(group for group in simulation.execution_plan.groups + if group.application.id === :controller) + context = only(only(controller.batches).targets).context + leaf = register_object!(simulation.model, Object(:leaf; scale=:Leaf, + parent=:owner, status=Status(seed=3.0))) + @test_throws "failed after mutation" run_initializer!(context, :initialize, leaf) + canonical = model_status(simulation.model, leaf) + @test canonical.visits == 1 && canonical.value == 3.0 + delta = PSE.lifecycle_delta(simulation.model) + key = (:leaf, ObjectId(:leaf)) + @test key in delta.initialized_targets + @test !delta.targeted_topology_runtime.call_context_caches[key].in_use + @test_throws "already initialized" run_initializer!(context, :initialize, leaf) + @test canonical.visits == 1 && canonical.value == 3.0 + @test PSE.cohort_location(simulation.temporal_streams.cohorts, :leaf, ObjectId(:leaf)) === nothing +end + end From 2bd75c12fa2d258d199c783b35ca8470267b184b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 10:40:00 +0100 Subject: [PATCH 033/324] Inline finite cohort location admission before payload operations --- src/composite_model/execution_cohorts.jl | 1 + 1 file changed, 1 insertion(+) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index dfc5bf829..82281cce4 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -184,6 +184,7 @@ end end) end return quote + $(Expr(:meta, :inline)) $(branches...) throw(ArgumentError("The existing execution payload is outside its prepared application schema.")) end From b2f49fc234c449aadcc6bf3b6b11c364714a92b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 11:56:45 +0100 Subject: [PATCH 034/324] Exercise prepared environment identity after checkpoint restoration --- ...test-model-environment-binding-identity.jl | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 79dfe39c3..5831019d4 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -1,5 +1,6 @@ module EnvironmentBindingsIdentityChecks using PlantSimEngine +using Serialization using Test const PSE = PlantSimEngine const EA = PSE.EnvironmentAPI @@ -75,6 +76,72 @@ function fixture(::Type{T}) where {T} return (; model, simulation, capture, backend, batch, kept) end +function checkpoint_copy(simulation) + buffer = IOBuffer() + serialize(buffer, simulation) + seekstart(buffer) + return deserialize(buffer) +end + +@testset "checkpointed environment owners preserve application identity" begin + for copy_simulation in (deepcopy, checkpoint_copy) + data = fixture(Float32) + simulation = data.simulation + original_context = data.capture[] + original_targets = only(original_context.calls) + PSE._materialize_call_execution_batches!(original_targets) + @test PSE._call_targets_preparation_is_current(original_targets, + simulation.compiled, simulation.environment_bindings, + simulation.temporal_streams, simulation.output_retention, simulation.constants) + + restored = copy_simulation(simulation) + environment_bindings = restored.environment_bindings + owner = only(group for group in restored.execution_plan.groups + if group.application.id === :owner) + context = only(only(owner.batches).targets).context + targets = only(context.calls) + cached_batches = PSE._cached_call_execution_batches(targets) + @test !isnothing(cached_batches) + + # Inspect the restored graph before an accessor can refresh its owners. + @test PSE._environment_bindings_match_compiled(environment_bindings, restored.compiled) + @test !PSE._environment_bindings_match_compiled(environment_bindings, simulation.compiled) + @test PSE._call_targets_preparation_is_current(targets, + restored.compiled, environment_bindings, restored.temporal_streams, + restored.output_retention, restored.constants) + + # Equal application records in another vector are a different generation. + applications = restored.compiled.applications + restored.compiled.applications = copy(applications) + @test !PSE._environment_bindings_match_compiled(environment_bindings, restored.compiled) + restored.compiled.applications = applications + @test PSE._environment_bindings_match_compiled(environment_bindings, restored.compiled) + + backend = first(environment_bindings.bindings).backend + samples = backend.samples + @test PSE.Advanced.refresh_environment_bindings!(restored.model, restored.compiled) === + environment_bindings + @test PSE._cached_call_execution_batches(targets) === cached_batches + @test backend.samples == samples + @test PSE._call_targets_preparation_is_current(targets, + restored.compiled, environment_bindings, restored.temporal_streams, + restored.output_retention, restored.constants) + + # Reuse the restored Many preparation, then advance the ordinary scheduler. + backend.values[:a] = data.backend.values[:a] = 13.0f0 + backend.values[:b] = data.backend.values[:b] = 23.0f0 + run_call!(context, :leaves; publish=false) + run_call!(original_context, :leaves; publish=false) + @test model_status(restored.model, :manual).seen === 13.0f0 + @test model_status(restored.model, :manual).calls == 1 + continue!(restored; steps=1) + continue!(simulation; steps=1) + @test final_state(restored, Many()) == final_state(simulation, Many()) + @test isequal(collect_outputs(restored), collect_outputs(simulation)) + @test backend.samples == data.backend.samples + end +end + @testset "clean and dirty environment shells preserve live backend and trial sampling" begin for T in (Float32, Float64) data = fixture(T) From 938d98fe6c34f3f52469fae235327ba3d9fb55c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 12:01:53 +0100 Subject: [PATCH 035/324] Keep application owner references valid across prepared snapshots --- src/composite_model/compilation.jl | 2 +- src/composite_model/environment_bindings.jl | 6 +++--- src/composite_model/runtime_outputs.jl | 9 ++++----- test/test-model-environment-binding-identity.jl | 9 ++++++--- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6dad8f539..df08fdc18 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1809,7 +1809,7 @@ mutable struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C} const sample_cache::C const model_revision::Int const environment_revision::Int - const applications_identity::UInt + const compiled_applications::Vector{CompiledModelApplication} end # Keep a stable heap identity at dynamic execution-batch boundaries. The diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 9371a43ba..0283e163f 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -394,7 +394,7 @@ function _compiled_environment_bindings( sample_cache, model.revision, model.environment_revision, - objectid(compiled.applications), + compiled.applications, ) end @@ -754,7 +754,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, # A public Advanced refresh may have prepared another application # set. Reconcile that current owner before using its plans for a # partial event in this compiled scene. - partial_owner = cached.applications_identity == objectid(compiled.applications) ? + partial_owner = cached.compiled_applications === compiled.applications ? cached : _reconcile_environment_binding_metadata(model, compiled, cached) if isnothing(partial_owner) compile_environment_bindings(model, compiled) @@ -776,7 +776,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, return refreshed elseif cached.model_revision == compiled.revision && cached.environment_revision == model.environment_revision && - cached.applications_identity == objectid(compiled.applications) + cached.compiled_applications === compiled.applications return cached else reconciled = _reconcile_environment_binding_metadata(model, compiled, cached) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index c62d2e2a1..f25c8dd2d 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -593,7 +593,7 @@ struct CallTargetsPreparation{CS,EB,TS,OR,C} constants::C model_revision::Int environment_revision::Int - applications_identity::UInt + compiled_applications::Vector{CompiledModelApplication} membership_reference::Base.RefValue{UInt64} membership_generation::UInt64 end @@ -604,7 +604,7 @@ function _call_targets_preparation( return CallTargetsPreparation( compiled, environment_bindings, temporal_streams, output_retention, constants, compiled.revision, environment_bindings.environment_revision, - environment_bindings.applications_identity, + environment_bindings.compiled_applications, getfield(binding, :membership_generation), _compiled_call_membership_generation(binding), ) @@ -709,7 +709,7 @@ end prepared.constants === constants && prepared.model_revision == compiled.revision && prepared.environment_revision == environment_bindings.environment_revision && - prepared.applications_identity == environment_bindings.applications_identity && + prepared.compiled_applications === environment_bindings.compiled_applications && prepared.membership_reference === getfield(targets.binding, :membership_generation) && prepared.membership_generation == _compiled_call_membership_generation(targets.binding) end @@ -774,8 +774,7 @@ end ) return environment_bindings isa CompiledEnvironmentBindings && environment_bindings.model_revision == compiled.revision && - environment_bindings.applications_identity == - objectid(compiled.applications) + environment_bindings.compiled_applications === compiled.applications end function _prebarrier_environment_bindings( diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 5831019d4..38c8228c9 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -106,6 +106,9 @@ end # Inspect the restored graph before an accessor can refresh its owners. @test PSE._environment_bindings_match_compiled(environment_bindings, restored.compiled) @test !PSE._environment_bindings_match_compiled(environment_bindings, simulation.compiled) + @test environment_bindings.compiled_applications === restored.compiled.applications + @test environment_bindings.compiled_applications !== simulation.compiled.applications + @test targets.preparation.compiled_applications === restored.compiled.applications @test PSE._call_targets_preparation_is_current(targets, restored.compiled, environment_bindings, restored.temporal_streams, restored.output_retention, restored.constants) @@ -305,12 +308,12 @@ end is_current_alternate = current === alternate && current !== full @test is_current_alternate @test length(current.bindings) == 2 - @test current.applications_identity == objectid(alternate_compiled.applications) + @test current.compiled_applications === alternate_compiled.applications samples = data.backend.samples restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) is_restored = restored === PSE.compiled_environment_bindings(data.model) @test is_restored - @test restored.applications_identity == objectid(simulation.compiled.applications) + @test restored.compiled_applications === simulation.compiled.applications @test length(restored.bindings) == 4 @test all(binding -> binding.backend === data.backend, restored.bindings) @test restored.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b @@ -395,7 +398,7 @@ end @test data.backend.samples == samples uses_current = simulation.environment_bindings === PSE.compiled_environment_bindings(data.model) @test uses_current - @test simulation.environment_bindings.applications_identity == objectid(simulation.compiled.applications) + @test simulation.environment_bindings.compiled_applications === simulation.compiled.applications @test length(simulation.environment_bindings.bindings) == 4 handles_current = all(batch -> all(target -> target.environment_binding.handle === simulation.environment_bindings.by_target[ From 957d826e5b40ed8f50a9c737f13e06790e2b1758 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 13:13:11 +0100 Subject: [PATCH 036/324] Keep cohort index edits outside typed payload admission --- .../execution_cohort_refresh.jl | 71 ++++++++++--------- test/test-model-closed-cohort-schemas.jl | 50 +++++++++++++ 2 files changed, 89 insertions(+), 32 deletions(-) diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index e02134884..2e3b8ce62 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -27,13 +27,20 @@ function _execution_cohort_rows( return ExecutionCohortRows{T}(store, cohort, indices) end -function _shift_execution_run_starts!(membership, first_run, delta) - for index in first_run:lastindex(membership.run_starts) - membership.run_starts[index] += delta +function _shift_execution_run_starts!(starts::Vector{Int}, first_run, delta) + for index in first_run:lastindex(starts) + starts[index] += delta end return nothing end +function _split_execution_run_indices!(indices::Vector{Int}, local_index) + right = indices[local_index:end] + sizehint!(right, length(right) + max(16, length(right) ÷ 4)) + resize!(indices, local_index - 1) + return right +end + function _execution_membership_location_has_cohort(membership, position, cohort) object_id = membership.object_ids[position] return _with_execution_cohort_location(membership.schema, membership.store, membership.locations[position], @@ -63,35 +70,35 @@ function _insert_execution_membership_row!(membership, position, object_id, loca end else run_index = searchsortedlast(starts, position) - _with_execution_membership_run(membership, run_index) do rows - local_index = position - starts[run_index] + 1 - if rows.cohort === location.cohort - insert!(rows.indices, local_index, location.row) - _shift_execution_run_starts!(membership, run_index + 1, 1) - elseif local_index == 1 && run_index > 1 && - _execution_membership_run_has_cohort(membership, run_index - 1, location.cohort) - _with_execution_membership_run(membership, run_index - 1) do previous_rows - push!(previous_rows.indices, location.row) - end - _shift_execution_run_starts!(membership, run_index, 1) - elseif local_index == 1 - insert!(runs, run_index, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) - insert!(starts, run_index, position) - _shift_execution_run_starts!(membership, run_index + 1, 1) - else - # This is the same ordered reconciliation algorithm: split only - # membership indices; retain payloads and scientific references. - right_indices = rows.indices[local_index:end] - sizehint!(right_indices, length(right_indices) + max(16, length(right_indices) ÷ 4)) - right = _execution_cohort_rows(membership.store, rows.cohort, right_indices) - resize!(rows.indices, local_index - 1) - insert!(runs, run_index + 1, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) - insert!(starts, run_index + 1, position) - insert!(runs, run_index + 2, right) - insert!(starts, run_index + 2, position + 1) - _shift_execution_run_starts!(membership, run_index + 3, 1) + indices, same_cohort = _with_execution_membership_run(membership, run_index) do rows + (rows.indices, rows.cohort === location.cohort) + end + local_index = position - starts[run_index] + 1 + if same_cohort + insert!(indices, local_index, location.row) + _shift_execution_run_starts!(starts, run_index + 1, 1) + elseif local_index == 1 && run_index > 1 && + _execution_membership_run_has_cohort(membership, run_index - 1, location.cohort) + _with_execution_membership_run(membership, run_index - 1) do previous_rows + push!(previous_rows.indices, location.row) end - return nothing + _shift_execution_run_starts!(starts, run_index, 1) + elseif local_index == 1 + insert!(runs, run_index, _execution_cohort_rows(membership.store, location.cohort, Int[location.row])) + insert!(starts, run_index, position) + _shift_execution_run_starts!(starts, run_index + 1, 1) + else + # Split only membership indices; payloads and scientific references + # stay in their original cohorts. + right_indices = _split_execution_run_indices!(indices, local_index) + store = membership.store + insert!(runs, run_index + 1, _execution_cohort_rows(store, location.cohort, Int[location.row])) + insert!(starts, run_index + 1, position) + _with_execution_membership_run(membership, run_index) do rows + insert!(runs, run_index + 2, _execution_cohort_rows(store, rows.cohort, right_indices)) + end + insert!(starts, run_index + 2, position + 1) + _shift_execution_run_starts!(starts, run_index + 3, 1) end end insert!(membership.object_ids, position, object_id) @@ -107,7 +114,7 @@ function _delete_execution_membership_row!(membership, position) deleteat!(rows.indices, position - starts[run_index] + 1) isempty(rows.indices) end - _shift_execution_run_starts!(membership, run_index + 1, -1) + _shift_execution_run_starts!(starts, run_index + 1, -1) if run_empty deleteat!(runs, run_index) deleteat!(starts, run_index) diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl index dc88af6aa..4ea2614ce 100644 --- a/test/test-model-closed-cohort-schemas.jl +++ b/test/test-model-closed-cohort-schemas.jl @@ -101,6 +101,56 @@ end @test getproperty.(flatten(membership), :object_id) == ids((1, 3)) end +@testset "interior insertions preserve ordered run families and live payloads" begin + for closed in (false, true) + store = PSE.ExecutionCohortStore() + left, right = make_target(20, 20.0), make_target(80, 80.0) + middle = make_target(50, 50.0f0) + targets = Dict{ObjectId,Any}(target.object_id => target for target in (left, right, middle)) + schema = closed ? schema_for(left, middle) : PSE.OpenExecutionCohortSchema() + membership = refresh(store, targets, (20, 80); schema).membership + original_run = only(membership.runs) + original_indices = original_run.indices + original_left = PSE.cohort_location(store, :growth, left.object_id) + original_right = PSE.cohort_location(store, :growth, right.object_id) + left_reference = PSE.refvalue(left.status, :value) + right_reference = PSE.refvalue(right.status, :value) + + # A new B inside A splits only its ordered index view into A/B/A. + refresh(store, targets, (20, 50, 80), (50,); previous=membership, schema) + @test membership.run_starts == [1, 2, 3] + @test first(membership.runs) === original_run + @test first(membership.runs).indices === original_indices + @test flatten(membership) == [left, middle, right] + @test first(membership.runs).cohort === last(membership.runs).cohort + + # Exercise previous-family append, front insertion, tail reuse/new run, + # and same-family insertion within an existing run. + current = [20, 50, 80] + for (id, value) in ((30, 30.0), (10, 10.0f0), (90, 90.0), + (100, 100.0f0), (25, 25.0)) + target = make_target(id, value) + targets[target.object_id] = target + push!(current, id) + sort!(current) + changed = refresh(store, targets, current, (id,); previous=membership, schema) + @test changed.targets_constructed == 1 + @test changed.targets_reused == length(current) - 1 + @test getproperty.(flatten(membership), :object_id) == ids(current) + end + @test membership.run_starts == [1, 2, 5, 6, 8] + @test getproperty.(flatten(membership), :object_id) == ids((10, 20, 25, 30, 50, 80, 90, 100)) + @test membership.runs[2] === original_run + @test membership.runs[2].indices === original_indices + @test PSE.cohort_location(store, :growth, left.object_id) === original_left + @test PSE.cohort_location(store, :growth, right.object_id) === original_right + @test PSE.refvalue(left.status, :value) === left_reference + @test PSE.refvalue(right.status, :value) === right_reference + @test only(target for target in flatten(membership) if target.object_id == left.object_id) === left + @test only(target for target in flatten(membership) if target.object_id == right.object_id) === right + end +end + @testset "an empty future schema creates no target or scientific default" begin S = Status{(:value,),Tuple{Base.RefValue{Float64}}} T = Target{ObjectId{Int},S,Base.RefValue{Int}} From be172fc010c5d62693b98eec22ac67bafc6d51be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 16:16:46 +0100 Subject: [PATCH 037/324] Keep lifecycle admission finite for native execution --- src/composite_model/compilation.jl | 2 +- .../execution_batch_schemas.jl | 2 +- .../execution_cohort_refresh.jl | 14 ++++--- test/test-model-binding-index-identities.jl | 30 ++++++++++++++ .../test-model-newborn-context-initializer.jl | 6 +++ test/test-model-prepared-call-schemas.jl | 41 +++++++++++++++++++ 6 files changed, 87 insertions(+), 8 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index df08fdc18..90e226638 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8700,7 +8700,7 @@ function _resolved_compiled_call_membership( # A newborn has no compiled application/status/environment target until # the safe refresh barrier. Keep it out of a first complete view so the # observed binding's normal addition delta can append it exactly once. - pending_added_ids = Set(snapshot.id for snapshot in lifecycle_delta(model).added) + pending_added_ids = Set{keytype(model.registry.objects)}(snapshot.id for snapshot in lifecycle_delta(model).added) filter!(object_id -> object_id ∉ pending_added_ids, object_ids) end application_ids = Symbol[] diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index e7b084862..888eaf1b9 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -126,7 +126,7 @@ end @inline _context_call_schema(::Nothing) = OpenContextCallSchema() @generated function _context_call_schema(context::RunContext{CS,A,C}) where {CS,A,C} - closed = any(fieldtype(CT, :batch_schema) <: PreparedExecutionBatchSchema for CT in fieldtypes(C)) + closed = isempty(fieldtypes(C)) || any(fieldtype(CT, :batch_schema) <: PreparedExecutionBatchSchema for CT in fieldtypes(C)) return closed ? :(PreparedContextCallSchema{$C}()) : :(OpenContextCallSchema()) end diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index 2e3b8ce62..71e7bcf2b 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -119,12 +119,14 @@ function _delete_execution_membership_row!(membership, position) deleteat!(runs, run_index) deleteat!(starts, run_index) if run_index > 1 && run_index <= length(runs) - merged = _with_execution_membership_run(membership, run_index - 1) do left - _with_execution_membership_run(membership, run_index) do right - left.cohort === right.cohort || return false - append!(left.indices, right.indices) - return true - end + left_index = run_index - 1 + left_indices = _with_execution_membership_run(membership, left_index) do left + left.indices + end + merged = _with_execution_membership_run(membership, run_index) do right + membership.runs[left_index].cohort === right.cohort || return false + append!(left_indices, right.indices) + return true end if merged deleteat!(runs, run_index) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index c19f4046c..76388a6ad 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -239,4 +239,34 @@ end check_indexes(model, simulation) end +@testset "cold Many excludes pending births with mixed registry identities" begin + for closed in (false, true) + data = call_fixture(closed) + model, simulation = data.model, data.simulation + binding = only(binding for binding in simulation.compiled.call_bindings + if binding.call === :many) + references = Dict(id => PSE.refvalue(model_status(model, id), :x) + for id in (1, :leaf)) + register_object!(model, Object(2; scale=:Leaf, parent=:root, + status=Status(x=7f0))) + register_object!(model, Object(:new_leaf; scale=:Leaf, parent=:root, + status=Status(x=9f0))) + + ids, applications = PSE._resolved_compiled_call_membership( + simulation.compiled, binding) + @test ids == [ObjectId(1), ObjectId(:leaf)] + @test applications == [:leaf] + @test !PSE._compiled_call_membership_is_observed(binding) + step!(simulation) + run_call!(data.capture[], :many; publish=true) + @test [target.object_id for target in call_targets(data.capture[], :many)] == + [ObjectId(1), ObjectId(2), ObjectId(:leaf), ObjectId(:new_leaf)] + @test model_status(model, 2).x === 8f0 + @test model_status(model, :new_leaf).x === 10f0 + @test all(PSE.refvalue(model_status(model, id), :x) === ref + for (id, ref) in references) + check_indexes(model, simulation) + end +end + end diff --git a/test/test-model-newborn-context-initializer.jl b/test/test-model-newborn-context-initializer.jl index b3cfaa7eb..77138850b 100644 --- a/test/test-model-newborn-context-initializer.jl +++ b/test/test-model-newborn-context-initializer.jl @@ -57,6 +57,12 @@ end @test !first.publication_allowed @test first.environment isa PSE.NoEnvironmentOverride @test first.calls === () + schema = PSE._context_call_schema(first) + @test schema isa PSE.PreparedContextCallSchema{Tuple{}} + @test isempty(PSE._execution_append_intent_buffer(schema)) + @test isempty(PSE._execution_binding_intent_buffer(schema)) + @test eltype(PSE._execution_append_intent_buffer(schema)) === Union{} + @test eltype(PSE._execution_binding_intent_buffer(schema)) === Union{} @test isempty(get(outputs(simulation),(:leaf,ObjectId(:born),:draw),[])) continue!(simulation; steps=1) diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl index e6776e62a..cc069a6ab 100644 --- a/test/test-model-prepared-call-schemas.jl +++ b/test/test-model-prepared-call-schemas.jl @@ -317,4 +317,45 @@ end assert_prepared_tree(prepared) end +@testset "an empty call layout is finite and declaration changes start a new timeline" begin + data = fixture() + model = data.model + original = model.applications[1] + model.applications[1] = ModelSpec(PSE.model_(original); + name=:root, on=One(id=:root)) + Advanced.refresh_bindings!(model; force=true) + previous = run!(model; steps=1, outputs=:all) + target = only(target for group in previous.execution_plan.groups + for batch in group.batches for target in batch.targets + if batch.application.id === :root) + @test target.context.calls === () + schema = PSE._context_call_schema(target.context) + @test schema isa PSE.PreparedContextCallSchema{Tuple{}} + @test eltype(PSE._execution_append_intent_buffer(schema)) === Union{} + @test eltype(PSE._execution_binding_intent_buffer(schema)) === Union{} + @test PSE._context_call_schema(nothing) isa PSE.OpenContextCallSchema + cells, state, random_state = status_cells(model), scientific_state(model), rng_probe(data.rng) + previous_history = history(previous) + + model.applications[1] = original + current = Advanced.refresh_bindings!(model; force=true) + bindings = current.call_bindings_by_target[(:root, ObjectId(:root))] + @test length(bindings) == 1 + @test isnothing(PSE._admitted_current_execution_call_bindings(schema, target, bindings)) + # Changing declaration layouts uses a fresh timeline, as documented. + fresh = run!(model; steps=0, outputs=:all) + @test fresh.compiled === current + @test current_step(fresh) == 0 + @test scientific_state(model) == state + @test rng_probe(data.rng) == random_state + @test history(previous) == previous_history + assert_same_cells(model, cells) + step!(fresh) + run_call!(data.capture[], :middle; publish=true) + @test length(call_targets(data.capture[], :middle)) == 2 + @test all(model_status(model, id).visits == 2 + for id in (:middle_a, :middle_b, :leaf_a, :leaf_b)) + assert_same_cells(model, cells) +end + end # module ColdCallSchemaActivationChecks From 471a35542bd8b8cd31518dd75f0f7d56e0f62ec0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 16:28:52 +0100 Subject: [PATCH 038/324] Shard the complete test suite without splitting test dependencies --- .github/workflows/CI.yml | 7 +- test/runtests.jl | 410 +++------------------------------------ test/test_groups.jl | 298 ++++++++++++++++++++++++++++ 3 files changed, 329 insertions(+), 386 deletions(-) create mode 100644 test/test_groups.jl diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 8dc599e47..a90e19bde 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -20,9 +20,9 @@ concurrency: jobs: test: if: ${{ github.event_name != 'workflow_dispatch' || !inputs.juliac_safe }} - name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ github.event_name }} + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - shard ${{ matrix.shard }}/3 - ${{ github.event_name }} runs-on: ${{ matrix.os }} - # The expanded full suite with coverage can exceed two hours on the latest Julia. + # Keep the full suite within the limit by running independent test groups separately. timeout-minutes: 180 permissions: # needed to allow julia-actions/cache to proactively delete old caches that it has created @@ -38,6 +38,7 @@ jobs: - ubuntu-latest - macOS-latest - windows-latest + shard: [1, 2, 3] steps: - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 @@ -48,6 +49,8 @@ jobs: - uses: julia-actions/julia-runtest@v1 env: JULIA_NUM_THREADS: 4 + PSE_TEST_SHARD_COUNT: "3" + PSE_TEST_SHARD_INDEX: ${{ matrix.shard }} - uses: julia-actions/julia-processcoverage@v1 - uses: codecov/codecov-action@v7 with: diff --git a/test/runtests.jl b/test/runtests.jl index 216dce85e..bd94dd6eb 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -33,393 +33,35 @@ if length(ARGS) == 1 && endswith(only(ARGS), ".jl") include(focused_path) end else - @testset "Testing PlantSimEngine" begin - Aqua.test_all(PlantSimEngine, ambiguities=false) - Aqua.test_ambiguities([PlantSimEngine]) - - @testset "Unified model/object API" begin - include("test-unified-model-object-api.jl") - end - - @testset "Registered object identity" begin - include("test-model-object-id.jl") - include("test-object-families.jl") - end - - @testset "Concrete runtime object identities" begin - include("test-model-concrete-object-identities.jl") - end - - @testset "Persistent typed execution cohorts" begin - include("test-execution-cohorts.jl") - include("test-execution-cohort-refresh.jl") - include("test-model-canonical-cohorts.jl") - include("test-model-persistent-empty-groups.jl") - include("test-model-slot-group-refresh.jl") - end - - @testset "Prepared execution schemas" begin - include("test-model-closed-cohort-schemas.jl") - include("test-model-cohort-store-identities.jl") - include("test-model-status-view-cache-admission.jl") - include("test-model-call-cohort-retirement.jl") - include("test-model-closed-group-refresh.jl") - include("test-model-closed-group-layout-preflight.jl") - include("test-model-prepared-call-schemas.jl") - include("test-model-prepared-call-vector-api.jl") - include("test-model-prepared-growth-schemas.jl") - include("test-model-target-status-view-admission.jl") - include("test-model-prepared-missing-future-schema.jl") - include("test-model-finite-call-extension-intents.jl") - end - - @testset "Organ creation allocations" begin - include("test-organ-creation-allocation.jl") - end - - @testset "Lifecycle snapshot allocations" begin - include("test-lifecycle-snapshot-allocations.jl") - end - - @testset "Structural delta binding intersection" begin - include("test-structural-delta-intersection.jl") - end - - @testset "Organ status assembly" begin - include("test-organ-status-assembly.jl") - include("test-status-construction.jl") - end - - @testset "CompositeModel display" begin - include("test-model-display.jl") - end - - @testset "Composite Model/Object API stabilization" begin - include("test-model-api-stabilization.jl") - end - - @testset "Reusable scenario plans" begin - include("test-model-prepared-scenario.jl") - include("test-model-scenario-authoring.jl") - include("test-model-authored-port-inventory.jl") - include("test-model-authored-input-graph.jl") - include("test-model-prepared-authoring-owner.jl") - include("test-model-public-refresh-owners.jl") - include("test-model-authored-call-plans.jl") - include("test-model-spec-normalization.jl") - include("test-model-runtime-snapshot-isolation.jl") - include("test-model-refreshed-schedule.jl") - include("test-model-authored-spec-matching.jl") - include("test-compilation-metadata.jl") - include("test-model-input-recipes.jl") - include("test-model-binding-index-identities.jl") - include("test-model-output-retention-owners.jl") - include("test-input-default-values.jl") - include("test-application-membership-slots.jl") - include("test-registered-status-dispatch.jl") - include("test-owned-metadata-tables.jl") - include("test-resolved-input-materialization.jl") - include("test-input-source-matching.jl") - end - - @testset "Isolated model diagnostics" begin - include("test-model-diagnostic-isolation.jl") - include("test-model-diagnostic-authoring-recovery.jl") - end - - @testset "Public native compilation API" begin - include("test-native-compilation.jl") - end - - @testset "Typed temporal initial values" begin - include("test-model-temporal-initial-typing.jl") - end - - @testset "Concrete selector construction" begin - include("test-selector-construction-inference.jl") - end - - @testset "Selector candidate scope fast path" begin - include("test-selector-candidate-empty-scope.jl") - include("test-selector-query-scope-root.jl") - include("test-selector-query-scope-append.jl") - include("test-selector-ancestor-index.jl") - end - - @testset "Lifecycle without target additions" begin - include("test-model-lifecycle-empty-targets.jl") - end - - @testset "Public model authoring API" begin - include("test-authoring-api.jl") - end - - @testset "Process authoring tutorial" begin - include("test-process-generation.jl") - end - - @testset "Packaged PlantSimEngine agent skill" begin - include("test-agent-skill.jl") - end - - @testset "Readable CompositeModel source" begin - include("test-model-source-compilation.jl") - end - - @testset "Composite model hard calls" begin - include("test-model-hard-calls.jl") - end - - @testset "Accepted call evaluations" begin - include("test-model-call-evaluations.jl") - include("test-model-call-execution-identity.jl") - include("test-call-evaluation-parent-generation.jl") - end - - @testset "Prepared environment inputs" begin - include("test-prepared-environment-inputs.jl") - end - - @testset "Transient manual-call context reuse" begin - include("test-model-call-context-cache.jl") - include("test-model-call-context-cloning.jl") - end - - @testset "Lightweight manual-call target views" begin - include("test-model-lightweight-call-targets.jl") - end - - @testset "Collected hard-call target types" begin - include("test-model-collected-call-targets.jl") - end - - @testset "Reusable scoped hard-call targets" begin - include("test-model-reusable-call-targets.jl") - end - - @testset "Materialized manual-call dispatch" begin - include("test-model-materialized-call-dispatch.jl") - end - - @testset "Singular manual-call snapshot cache" begin - include("test-model-single-call-snapshot-cache.jl") - end - - @testset "Singular manual-call target access" begin - include("test-model-only-call-targets.jl") - end - - @testset "Transient singular manual-call views" begin - include("test-model-transient-single-call-views.jl") - end - - @testset "Individual manual-call environments" begin - include("test-model-individual-call-environments.jl") - end - - @testset "Individual environments in generated source" begin - include("test-model-individual-source-environment.jl") - end - - @testset "Newborn retained manual calls" begin - include("test-model-newborn-retention.jl") - end - - @testset "Scheduled newborn initializers" begin - include("test-model-initializers.jl") - include("test-model-newborn-execution-owner.jl") - include("test-model-newborn-context-initializer.jl") - include("test-model-newborn-context-nested.jl") - include("test-model-runtime-call-names.jl") - end - - @testset "Composite model numerical parity" begin - include("test-model-numerical-parity.jl") - end - - @testset "Composite model status initialization" begin - include("test-model-status-initialization.jl") - end - - @testset "Initial status preparation" begin - include("test-initial-status-preparation.jl") - end - - @testset "Manual producers in Many inputs" begin - include("test-manual-many-input-filter.jl") - end - - @testset "Composite model status type conversion" begin - include("test-model-status-type-conversion.jl") - end - - @testset "Composite model status type conversion runtime" begin - include("test-model-status-type-runtime.jl") - end - - @testset "Composite model status type conversion lifecycle" begin - include("test-model-status-type-lifecycle.jl") - end - - @testset "Composite model status type conversion temporal policies" begin - include("test-model-status-type-temporal.jl") - end - - @testset "Composite model status type conversion with particles" begin - include("test-model-status-type-particles.jl") - end - - @testset "Composite model status type conversion templates" begin - include("test-model-status-type-templates.jl") - end - - @testset "Composite model status type conversion performance" begin - include("test-model-status-type-performance.jl") - end - - @testset "Composite model output boundaries" begin - include("test-model-output-boundaries.jl") - include("test-model-empty-output-requests.jl") - end - - @testset "Composite model output datetimes" begin - include("test-model-output-datetime.jl") - end - - @testset "Composite model time validation" begin - include("test-model-time-validation.jl") - end - - @testset "Composite model runtime matrix" begin - include("test-model-runtime-matrix.jl") - end - - @testset "Composite model environment sampling" begin - include("test-model-environment-sampling.jl") - include("test-model-execution-batch-times.jl") - include("test-model-environment-binding-identity.jl") - include("test-model-environment-index-identities.jl") - include("test-model-global-environment-sample-schema.jl") - end - - @testset "Composite model temporal reducers" begin - include("test-model-temporal-reducers.jl") - end - - @testset "PreviousTimeStep application-local status views" begin - include("test-model-previous-timestep-views.jl") - end - - @testset "Composite model binding inference" begin - include("test-model-binding-inference.jl") - end - - @testset "Compile-local output name metadata" begin - include("test-model-input-plan-output-metadata.jl") - end - - @testset "Adaptive subtree selectors" begin - include("test-model-adaptive-selectors.jl") - end - - @testset "Identity-aware Many inputs" begin - include("test-model-bound-many.jl") - end - - @testset "Distributed output declarations" begin - include("test-model-output-destination-declarations.jl") - include("test-model-distributed-route-ownership.jl") - end - - @testset "Distributed output runtime" begin - include("test-model-distributed-output-runtime.jl") - include("test-model-runtime-stream-extensions.jl") - end + include("test_groups.jl") + shard_count = parse(Int, get(ENV, "PSE_TEST_SHARD_COUNT", "1")) + shard_index = parse(Int, get(ENV, "PSE_TEST_SHARD_INDEX", "1")) + 1 <= shard_index <= shard_count <= length(TEST_GROUPS) || + error("Test shard index/count must satisfy 1 <= index <= count <= $(length(TEST_GROUPS)).") + group_indices = shard_index:shard_count:length(TEST_GROUPS) + @info "Test partition" shard_index shard_count groups=length(group_indices) - @testset "Distributed output assignment API" begin - include("test-model-output-targets-api.jl") - end - - @testset "Composite model multirate integration" begin - include("test-model-multirate-integration.jl") - end - - @testset "Composite model configuration errors" begin - include("test-model-configuration-errors.jl") - end - - @testset "Model discovery" begin - include("test-model-discovery.jl") - end - - @testset "Model graph viewer" begin - include("test-model-graph-view.jl") - end - - @testset "Model graph editor extension" begin - include("test-model-graph-editor-extension.jl") - end - - @testset "Model contract" begin - include("test-model-contract.jl") - end - - @testset "ModelSpec Updates" begin - include("test-updates.jl") - end - - @testset "Environment traits" begin - include("test-environment-traits.jl") - end - - @testset "Environment backends" begin - include("test-environment-backends.jl") - end - - @testset "MAESPA-style model example" begin - include("test-maespa-model-example.jl") - end - - @testset "Two-plant allocation comparison" begin - include("test-two-plant-allocation.jl") - end - - @testset "Status" begin - include("test-Status.jl") - end - - @testset "TimeStepTable" begin - include("test-TimeStepTable.jl") - end - - @testset "Statistics" begin - include("test-statistics.jl") - end - - @testset "Fitting" begin - include("test-fitting.jl") - end - - @testset "Toy models" begin - include("test-toy_models.jl") - end - - @testset "Readable-source call evaluation acceptance" begin - include("test-model-source-call-evaluations.jl") - end - - @testset "Temporal inputs inside call evaluations" begin - include("test-model-call-evaluation-temporal-inputs.jl") - end + @testset "Testing PlantSimEngine" begin + if shard_index == 1 + Aqua.test_all(PlantSimEngine, ambiguities=false) + Aqua.test_ambiguities([PlantSimEngine]) + end - if VERSION >= v"1.10" - # Some formating changed in Julia 1.10, e.g. @NamedTuple instead of NamedTuple. - @testset "Doctests" begin - DocMeta.setdocmeta!(PlantSimEngine, :DocTestSetup, :(using PlantSimEngine, PlantMeteo, DataFrames); recursive=true) + for group_index in group_indices + name, files = TEST_GROUPS[group_index] + @testset "$name" begin + for file in files + include(file) + end + end + end - # Testing the doctests, i.e. the examples in the docstrings marked with jldoctest: - doctest(PlantSimEngine; manual=false) + if shard_index == 1 + @testset "Doctests" begin + DocMeta.setdocmeta!(PlantSimEngine, :DocTestSetup, + :(using PlantSimEngine, PlantMeteo, DataFrames); recursive=true) + doctest(PlantSimEngine; manual=false) + end end end - end end diff --git a/test/test_groups.jl b/test/test_groups.jl new file mode 100644 index 000000000..61b607cb4 --- /dev/null +++ b/test/test_groups.jl @@ -0,0 +1,298 @@ +# Keep dependent files together: each group runs in order in one process. +const TEST_GROUPS = ( + "Unified model/object API" => ( + "test-unified-model-object-api.jl", + ), + "Registered object identity" => ( + "test-model-object-id.jl", + "test-object-families.jl", + ), + "Concrete runtime object identities" => ( + "test-model-concrete-object-identities.jl", + ), + "Persistent typed execution cohorts" => ( + "test-execution-cohorts.jl", + "test-execution-cohort-refresh.jl", + "test-model-canonical-cohorts.jl", + "test-model-persistent-empty-groups.jl", + "test-model-slot-group-refresh.jl", + ), + "Prepared execution schemas" => ( + "test-model-closed-cohort-schemas.jl", + "test-model-cohort-store-identities.jl", + "test-model-status-view-cache-admission.jl", + "test-model-call-cohort-retirement.jl", + "test-model-closed-group-refresh.jl", + "test-model-closed-group-layout-preflight.jl", + "test-model-prepared-call-schemas.jl", + "test-model-prepared-call-vector-api.jl", + "test-model-prepared-growth-schemas.jl", + "test-model-target-status-view-admission.jl", + "test-model-prepared-missing-future-schema.jl", + "test-model-finite-call-extension-intents.jl", + ), + "Organ creation allocations" => ( + "test-organ-creation-allocation.jl", + ), + "Lifecycle snapshot allocations" => ( + "test-lifecycle-snapshot-allocations.jl", + ), + "Structural delta binding intersection" => ( + "test-structural-delta-intersection.jl", + ), + "Organ status assembly" => ( + "test-organ-status-assembly.jl", + "test-status-construction.jl", + ), + "CompositeModel display" => ( + "test-model-display.jl", + ), + "Composite Model/Object API stabilization" => ( + "test-model-api-stabilization.jl", + ), + "Reusable scenario plans" => ( + "test-model-prepared-scenario.jl", + "test-model-scenario-authoring.jl", + "test-model-authored-port-inventory.jl", + "test-model-authored-input-graph.jl", + "test-model-prepared-authoring-owner.jl", + "test-model-public-refresh-owners.jl", + "test-model-authored-call-plans.jl", + "test-model-spec-normalization.jl", + "test-model-runtime-snapshot-isolation.jl", + "test-model-refreshed-schedule.jl", + "test-model-authored-spec-matching.jl", + "test-compilation-metadata.jl", + "test-model-input-recipes.jl", + "test-model-binding-index-identities.jl", + "test-model-output-retention-owners.jl", + "test-input-default-values.jl", + "test-application-membership-slots.jl", + "test-registered-status-dispatch.jl", + "test-owned-metadata-tables.jl", + "test-resolved-input-materialization.jl", + "test-input-source-matching.jl", + ), + "Isolated model diagnostics" => ( + "test-model-diagnostic-isolation.jl", + "test-model-diagnostic-authoring-recovery.jl", + ), + "Public native compilation API" => ( + "test-native-compilation.jl", + ), + "Typed temporal initial values" => ( + "test-model-temporal-initial-typing.jl", + ), + "Concrete selector construction" => ( + "test-selector-construction-inference.jl", + ), + "Selector candidate scope fast path" => ( + "test-selector-candidate-empty-scope.jl", + "test-selector-query-scope-root.jl", + "test-selector-query-scope-append.jl", + "test-selector-ancestor-index.jl", + ), + "Lifecycle without target additions" => ( + "test-model-lifecycle-empty-targets.jl", + ), + "Public model authoring API" => ( + "test-authoring-api.jl", + ), + "Process authoring tutorial" => ( + "test-process-generation.jl", + ), + "Packaged PlantSimEngine agent skill" => ( + "test-agent-skill.jl", + ), + "Readable CompositeModel source" => ( + "test-model-source-compilation.jl", + ), + "Composite model hard calls" => ( + "test-model-hard-calls.jl", + ), + "Accepted call evaluations" => ( + "test-model-call-evaluations.jl", + "test-model-call-execution-identity.jl", + "test-call-evaluation-parent-generation.jl", + ), + "Prepared environment inputs" => ( + "test-prepared-environment-inputs.jl", + ), + "Transient manual-call context reuse" => ( + "test-model-call-context-cache.jl", + "test-model-call-context-cloning.jl", + ), + "Lightweight manual-call target views" => ( + "test-model-lightweight-call-targets.jl", + ), + "Collected hard-call target types" => ( + "test-model-collected-call-targets.jl", + ), + "Reusable scoped hard-call targets" => ( + "test-model-reusable-call-targets.jl", + ), + "Materialized manual-call dispatch" => ( + "test-model-materialized-call-dispatch.jl", + ), + "Singular manual-call snapshot cache" => ( + "test-model-single-call-snapshot-cache.jl", + ), + "Singular manual-call target access" => ( + "test-model-only-call-targets.jl", + ), + "Transient singular manual-call views" => ( + "test-model-transient-single-call-views.jl", + ), + "Individual manual-call environments" => ( + "test-model-individual-call-environments.jl", + ), + "Individual environments in generated source" => ( + "test-model-individual-source-environment.jl", + ), + "Newborn retained manual calls" => ( + "test-model-newborn-retention.jl", + ), + "Scheduled newborn initializers" => ( + "test-model-initializers.jl", + "test-model-newborn-execution-owner.jl", + "test-model-newborn-context-initializer.jl", + "test-model-newborn-context-nested.jl", + "test-model-runtime-call-names.jl", + ), + "Composite model numerical parity" => ( + "test-model-numerical-parity.jl", + ), + "Composite model status initialization" => ( + "test-model-status-initialization.jl", + ), + "Initial status preparation" => ( + "test-initial-status-preparation.jl", + ), + "Manual producers in Many inputs" => ( + "test-manual-many-input-filter.jl", + ), + "Composite model status type conversion" => ( + "test-model-status-type-conversion.jl", + ), + "Composite model status type conversion runtime" => ( + "test-model-status-type-runtime.jl", + ), + "Composite model status type conversion lifecycle" => ( + "test-model-status-type-lifecycle.jl", + ), + "Composite model status type conversion temporal policies" => ( + "test-model-status-type-temporal.jl", + ), + "Composite model status type conversion with particles" => ( + "test-model-status-type-particles.jl", + ), + "Composite model status type conversion templates" => ( + "test-model-status-type-templates.jl", + ), + "Composite model status type conversion performance" => ( + "test-model-status-type-performance.jl", + ), + "Composite model output boundaries" => ( + "test-model-output-boundaries.jl", + "test-model-empty-output-requests.jl", + ), + "Composite model output datetimes" => ( + "test-model-output-datetime.jl", + ), + "Composite model time validation" => ( + "test-model-time-validation.jl", + ), + "Composite model runtime matrix" => ( + "test-model-runtime-matrix.jl", + ), + "Composite model environment sampling" => ( + "test-model-environment-sampling.jl", + "test-model-execution-batch-times.jl", + "test-model-environment-binding-identity.jl", + "test-model-environment-index-identities.jl", + "test-model-global-environment-sample-schema.jl", + ), + "Composite model temporal reducers" => ( + "test-model-temporal-reducers.jl", + ), + "PreviousTimeStep application-local status views" => ( + "test-model-previous-timestep-views.jl", + ), + "Composite model binding inference" => ( + "test-model-binding-inference.jl", + ), + "Compile-local output name metadata" => ( + "test-model-input-plan-output-metadata.jl", + ), + "Adaptive subtree selectors" => ( + "test-model-adaptive-selectors.jl", + ), + "Identity-aware Many inputs" => ( + "test-model-bound-many.jl", + ), + "Distributed output declarations" => ( + "test-model-output-destination-declarations.jl", + "test-model-distributed-route-ownership.jl", + ), + "Distributed output runtime" => ( + "test-model-distributed-output-runtime.jl", + "test-model-runtime-stream-extensions.jl", + ), + "Distributed output assignment API" => ( + "test-model-output-targets-api.jl", + ), + "Composite model multirate integration" => ( + "test-model-multirate-integration.jl", + ), + "Composite model configuration errors" => ( + "test-model-configuration-errors.jl", + ), + "Model discovery" => ( + "test-model-discovery.jl", + ), + "Model graph viewer" => ( + "test-model-graph-view.jl", + ), + "Model graph editor extension" => ( + "test-model-graph-editor-extension.jl", + ), + "Model contract" => ( + "test-model-contract.jl", + ), + "ModelSpec Updates" => ( + "test-updates.jl", + ), + "Environment traits" => ( + "test-environment-traits.jl", + ), + "Environment backends" => ( + "test-environment-backends.jl", + ), + "MAESPA-style model example" => ( + "test-maespa-model-example.jl", + ), + "Two-plant allocation comparison" => ( + "test-two-plant-allocation.jl", + ), + "Status" => ( + "test-Status.jl", + ), + "TimeStepTable" => ( + "test-TimeStepTable.jl", + ), + "Statistics" => ( + "test-statistics.jl", + ), + "Fitting" => ( + "test-fitting.jl", + ), + "Toy models" => ( + "test-toy_models.jl", + ), + "Readable-source call evaluation acceptance" => ( + "test-model-source-call-evaluations.jl", + ), + "Temporal inputs inside call evaluations" => ( + "test-model-call-evaluation-temporal-inputs.jl", + ), +) From 000b6b542fb8cc1bfafc50dacca6a8cabe641d4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 16:30:36 +0100 Subject: [PATCH 039/324] Preserve prepared target types through lifecycle factories --- src/composite_model/compilation.jl | 10 +- .../execution_batch_schemas.jl | 4 +- src/composite_model/runtime_outputs.jl | 128 ++++++++++-------- 3 files changed, 78 insertions(+), 64 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 90e226638..f3f146586 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8671,10 +8671,12 @@ end function _matching_callee_applications(applications, object_id::ObjectId, proc, application_name_filter) matches = Symbol[] - for application in get(applications, object_id, Any[]) - isnothing(proc) || application.process == proc || continue - isnothing(application_name_filter) || application.id == application_name_filter || continue - push!(matches, application.id) + for entry in get(applications, object_id, Any[]) + application = entry::CompiledModelApplication + plan = getfield(application, :plan)::CompiledApplicationPlan + isnothing(proc) || getfield(plan, :process) == proc || continue + isnothing(application_name_filter) || getfield(plan, :id) == application_name_filter || continue + push!(matches, getfield(plan, :id)) end return matches end diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 888eaf1b9..6e233faa2 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -140,7 +140,7 @@ end status_view=status_view, bound_inputs=status_view.bound_inputs, output_targets=fields.output_targets, call_bindings=fields.call_bindings, environment_binding=fields.environment_binding) - return f(nothing, application, actual_fields, owners, OpenContextCallSchema()) + return f(Val{nothing}(), application, actual_fields, owners, OpenContextCallSchema()) end @generated function _with_execution_target_type(f, ::ClosedExecutionCohortSchema{T}, @@ -183,7 +183,7 @@ end if $condition actual_fields = NamedTuple{$(QuoteNode(names))}($(Expr(:tuple,values...))) actual_owners = NamedTuple{$(QuoteNode(owner_names))}($owner_values) - return f($Target, application::$A, actual_fields, actual_owners, + return f(Val{$Target}(), application::$A, actual_fields, actual_owners, $CallSchema()) end end) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f25c8dd2d..2c761c8e8 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3403,38 +3403,43 @@ function _new_model_execution_target( temporal_streams=temporal_streams, output_retention=output_retention, constants=constants, environment=_NO_ENVIRONMENT_OVERRIDE) - return _with_execution_target_type(target_schema, application, status_view, fields, owners) do Target, actual_application, actual, owner, call_schema - input_bindings = isnothing(Target) ? - _runtime_model_temporal_inputs(actual.status_view.temporal_inputs, owner.temporal_streams) : - _prepared_runtime_temporal_inputs(fieldtype(Target,:input_bindings), - actual.status_view.temporal_inputs,owner.temporal_streams) - output_bindings = if isnothing(Target) - local_outputs = _runtime_model_output_streams(actual.status_view.status, - actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) - distributed_outputs = _runtime_model_distributed_output_streams(owner.compiled, - actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) - (local_outputs...,distributed_outputs...) - else - _prepared_runtime_outputs(fieldtype(Target,:output_bindings),actual.status_view, - actual.output_targets,actual_application,actual.object_id,owner.compiled, - owner.temporal_streams,owner.output_retention,false) - end - context = if isnothing(owner.temporal_streams) && isempty(actual.output_targets) - nothing - else - _prepare_model_execution_context!(nothing, owner.compiled, owner.environment_bindings, - actual_application, actual.object_id, actual.bound_inputs, - actual.output_targets, actual.call_bindings, owner.temporal_streams, - owner.output_retention, 0.0, owner.constants, true, owner.environment; - call_schema) - end - target = _compiled_execution_target(actual.object_id, actual.model, - actual.status_view, input_bindings, actual.bound_inputs, - actual.output_targets, output_bindings, actual.call_bindings, - actual.environment_binding, context, - CallContextCache(context, actual.status_view.execution_stamp)) - return isnothing(Target) ? target : target::Target + return _with_execution_target_type(_new_model_execution_target, target_schema, + application, status_view, fields, owners) +end + +function _new_model_execution_target(::Val{Target}, actual_application, actual, owner, + call_schema, +) where {Target} + input_bindings = isnothing(Target) ? + _runtime_model_temporal_inputs(actual.status_view.temporal_inputs, owner.temporal_streams) : + _prepared_runtime_temporal_inputs(fieldtype(Target,:input_bindings), + actual.status_view.temporal_inputs,owner.temporal_streams) + output_bindings = if isnothing(Target) + local_outputs = _runtime_model_output_streams(actual.status_view.status, + actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) + distributed_outputs = _runtime_model_distributed_output_streams(owner.compiled, + actual_application,actual.object_id,owner.temporal_streams,owner.output_retention) + (local_outputs...,distributed_outputs...) + else + _prepared_runtime_outputs(fieldtype(Target,:output_bindings),actual.status_view, + actual.output_targets,actual_application,actual.object_id,owner.compiled, + owner.temporal_streams,owner.output_retention,false) end + context = if isnothing(owner.temporal_streams) && isempty(actual.output_targets) + nothing + else + _prepare_model_execution_context!(nothing, owner.compiled, owner.environment_bindings, + actual_application, actual.object_id, actual.bound_inputs, + actual.output_targets, actual.call_bindings, owner.temporal_streams, + owner.output_retention, 0.0, owner.constants, true, owner.environment; + call_schema) + end + target = _compiled_execution_target(actual.object_id, actual.model, + actual.status_view, input_bindings, actual.bound_inputs, + actual.output_targets, output_bindings, actual.call_bindings, + actual.environment_binding, context, + CallContextCache(context, actual.status_view.execution_stamp)) + return isnothing(Target) ? target : target::Target end function _compiled_model_execution_environment_provider( @@ -6047,33 +6052,9 @@ function _append_targeted_newborn_targets!( temporal_streams=context.temporal_streams, output_retention=context.output_retention,constants=context.constants, environment=context.environment) - _with_execution_target_type(admission,application,status_view,fields,owners) do Target,actual_application,actual,owner,call_schema - outputs = isnothing(Target) ? - _runtime_model_output_streams(actual.status_view.status,actual_application, - actual.object_id,owner.temporal_streams,owner.output_retention,true) : - _prepared_runtime_outputs(fieldtype(Target,:output_bindings), - actual.status_view,actual.output_targets,actual_application, - actual.object_id,owner.compiled,owner.temporal_streams, - owner.output_retention,true) - # Narrow a retained cache before use; no new owner is published - # until all real fields have passed the same target admission. - prepared_cache = _admit_newborn_context_cache(Target,cache) - if isnothing(prepared_cache) - prepared_cache = _newborn_call_context_cache(context,actual_application, - actual.object_id,actual.bound_inputs,actual.output_targets, - actual.call_bindings,owner.environment_bindings,stamp;call_schema) - end - result = _targeted_newborn_call_target(context,actual_application, - actual.object_id,actual.model,actual.status_view,outputs, - actual.output_targets,actual.call_bindings,owner.environment_bindings, - actual.environment_binding,prepared_cache) - isnothing(Target) || result.execution_target isa Target || - throw(ArgumentError("A newborn execution target is outside its prepared schema.")) - # Admit the full caller view before publishing its cache. The - # payload and partial environment owner retain their identities. - push!(targets,result) - targeted_runtime.call_context_caches[key] = prepared_cache - return nothing + _with_execution_target_type(admission,application,status_view,fields,owners) do target_type,actual_application,actual,owner,call_schema + _append_targeted_newborn_target!(target_type,actual_application,actual,owner, + call_schema,targets,context,cache,stamp,targeted_runtime,key) end end return nothing @@ -6081,6 +6062,37 @@ function _append_targeted_newborn_targets!( return targets end +function _append_targeted_newborn_target!(::Val{Target}, actual_application, actual, owner, + call_schema, targets, context, cache, stamp, targeted_runtime, key, +) where {Target} + outputs = isnothing(Target) ? + _runtime_model_output_streams(actual.status_view.status,actual_application, + actual.object_id,owner.temporal_streams,owner.output_retention,true) : + _prepared_runtime_outputs(fieldtype(Target,:output_bindings), + actual.status_view,actual.output_targets,actual_application, + actual.object_id,owner.compiled,owner.temporal_streams, + owner.output_retention,true) + # Narrow a retained cache before use; no new owner is published + # until all real fields have passed the same target admission. + prepared_cache = _admit_newborn_context_cache(Target,cache) + if isnothing(prepared_cache) + prepared_cache = _newborn_call_context_cache(context,actual_application, + actual.object_id,actual.bound_inputs,actual.output_targets, + actual.call_bindings,owner.environment_bindings,stamp;call_schema) + end + result = _targeted_newborn_call_target(context,actual_application, + actual.object_id,actual.model,actual.status_view,outputs, + actual.output_targets,actual.call_bindings,owner.environment_bindings, + actual.environment_binding,prepared_cache) + isnothing(Target) || result.execution_target isa Target || + throw(ArgumentError("A newborn execution target is outside its prepared schema.")) + # Admit the full caller view before publishing its cache. The + # payload and partial environment owner retain their identities. + push!(targets,result) + targeted_runtime.call_context_caches[key] = prepared_cache + return nothing +end + # Adopt a pre-barrier newborn's logical counter when the ordinary compiler # installs its view. This is cold construction over an existing cache directory, # never a kernel-time identity lookup or a second target store. From d9968ead632edada5d3fe7e07b0a101d2c63bbe1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 18:37:58 +0100 Subject: [PATCH 040/324] Preserve registry identity types and current environment owners --- src/composite_model/runtime_outputs.jl | 3 +- src/composite_model/selectors.jl | 6 +-- test/test-model-binding-index-identities.jl | 47 +++++++++++++++++++ ...test-model-environment-binding-identity.jl | 28 +++++++++++ test/test-selector-query-scope-root.jl | 26 ++++++++++ 5 files changed, 106 insertions(+), 4 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 2c761c8e8..b6f78db76 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -801,7 +801,8 @@ function _synchronize_tracked_call_targets!(targets::CallTargets{CS,EB}) where { end candidate_environment = topology_dirty ? _prebarrier_environment_bindings(model,current_compiled,targets.environment_bindings) : - refresh_environment_bindings!(model,current_compiled) + _refresh_environment_bindings!(model,current_compiled, + _current_environment_binding_owner(model,targets.environment_bindings)) if isnothing(candidate_environment) current_compiled = targets.compiled current_environment_bindings = targets.environment_bindings diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 9a60f139e..8809a6185 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -744,7 +744,7 @@ function _scope_object_ids(model::CompositeModel, scope, context) current_id = _object_id_from_context(context) if scope isa Self isnothing(current_id) && error("`Self()` selectors require a current object context.") - return ObjectId[current_id] + return [current_id] elseif scope isa Subtree isnothing(current_id) && error("`Subtree()` selectors require a current object context.") return _descendant_ids(model, current_id) @@ -1022,7 +1022,7 @@ function _available_selector_labels(model::CompositeModel, candidate_ids) scales = Symbol[] kinds = Symbol[] species = Symbol[] - ids = ObjectId[] + ids = Vector{keytype(model.registry.objects)}() for object in objects isnothing(object.scale) || push!(scales, object.scale) isnothing(object.kind) || push!(kinds, object.kind) @@ -1221,7 +1221,7 @@ function _matching_selector_ids( # The adaptive candidate source may be a local vector, an index iterator, # or registry keys. Specialize this loop at that boundary, rather than # dispatching dynamically for every object in a heterogeneous query. - ids = ObjectId[] + ids = Vector{keytype(model.registry.objects)}() for id in candidates haskey(model.registry.objects, id) || continue _selector_matches_object_id( diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 76388a6ad..3ac8a75c8 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -269,4 +269,51 @@ end end end +@testset "selector results preserve the registry identity family" begin + for closed in (false, true) + data = call_fixture(closed) + model, simulation = data.model, data.simulation + I = keytype(model.registry.objects) + references = Dict(id => PSE.refvalue(model_status(model, id), :x) + for id in (1, :leaf)) + matcher = PSE._compile_selector_matcher(model, Many()) + candidates = (ObjectId(1), ObjectId(1.25), ObjectId(:leaf)) + ids = PSE._matching_selector_ids(model, matcher, candidates, + nothing, false, nothing, false) + @test eltype(ids) === I + @test ids == [ObjectId(1), ObjectId(:leaf)] + selected = resolve_object_ids(model, Many(Subtree(); scale=:Leaf); context=:root) + @test eltype(selected) === I + @test selected == ids + self = resolve_object_ids(model, One(within=Self()); context=:root) + @test eltype(self) === I + @test only(self) === ObjectId(:root) + missing = resolve_object_ids(model, Many(id=1.25)) + @test isempty(missing) && eltype(missing) === I + @test_throws "No model object with id" resolve_object_ids(model, + One(within=Self()); context=ObjectId(1.25)) + @test all(PSE.refvalue(model_status(model, id), :x) === reference + for (id, reference) in references) + check_indexes(model, simulation) + end +end + +@testset "selector diagnostics preserve available labels and suggestions" begin + ordinary = call_fixture(false).model + closed = call_fixture(true).model + message(model, selector) = try + resolve_object_ids(model, selector) + "" + catch error + sprint(showerror, error) + end + for selector in (One(scale=:Leaf), One(scale=:Leef)) + expected = message(ordinary, selector) + @test occursin("Expected exactly one object", expected) + @test occursin("available=", expected) && occursin("suggestions=", expected) + @test message(closed, selector) == expected + end + @test occursin("suggestions=(scale = [:Leaf]", message(closed, One(scale=:Leef))) +end + end diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 38c8228c9..98f98c856 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -426,4 +426,32 @@ end simulation.environment_bindings.by_target[(:manual_probe, ObjectId(:manual))].handle @test manual_handle_current end +@testset "retained manual targets use the current public environment owner" begin + for force in (false, true) + data = fixture(Float32) + targets = call_targets(data.capture[], :leaves) + PSE._materialize_call_execution_batches!(targets) + previous = targets.environment_bindings + status = model_status(data.model, :manual) + reference = PSE.refvalue(status, :seen) + move_object!(data.model, :manual, (cell=:b,)) + current = PSE.Advanced.refresh_environment_bindings!(data.model, + data.simulation.compiled; force) + @test current !== previous + @test getfield(targets, :environment_bindings) === previous + @test !PSE.bindings_dirty(data.model) && !PSE.environment_bindings_dirty(data.model) + samples = data.backend.samples + PSE._synchronize_tracked_call_targets!(targets) + @test targets.environment_bindings === current + @test data.backend.samples == samples + target = only(targets) + @test target.environment_binding.backend === data.backend + @test target.environment_binding.handle.cell === :b + run_call!(target; publish=false) + @test status.seen === 20f0 && status.calls == 1 + @test data.backend.samples == samples + 1 + @test PSE.refvalue(status, :seen) === reference + end +end + end diff --git a/test/test-selector-query-scope-root.jl b/test/test-selector-query-scope-root.jl index 9e80ec7f0..c044a51af 100644 --- a/test/test-selector-query-scope-root.jl +++ b/test/test-selector-query-scope-root.jl @@ -136,4 +136,30 @@ end sorted_ids(:plant_a_leaf_1) end +@testset "Self retains current identity inference, references and errors" begin + for raw_ids in ((1, 2), (:one, :two), (1, :leaf)) + model = CompositeModel((Object(id; name="same", + status=Status(value=Float32(index))) + for (index, id) in enumerate(raw_ids))...) + order = object_ids(model) + references = Dict(id => PSE.refvalue(model_status(model, id), :value) + for id in order) + selector = One(within=Self()) + for id in order + scoped = PSE._scope_object_ids(model, Self(), id) + @test (@inferred only(scoped)) === id + @test resolve_object_ids(model, selector; context=id) == [id] + @test resolve_object_ids(model, selector; context=model_object(model, id)) == [id] + end + @test_throws "current object context" resolve_object_ids(model, selector) + for missing in (ObjectId(999), ObjectId(:missing), ObjectId(1.25)) + @test_throws "No model object with id" resolve_object_ids(model, selector; + context=missing) + end + @test object_ids(model) == order + @test all(PSE.refvalue(model_status(model, id), :value) === reference + for (id, reference) in references) + end +end + end From 370e79e92d413349fb0c9de5bd73d4aec9cba1a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 18:38:14 +0100 Subject: [PATCH 041/324] Run full XPalm lint on Julia 1.12 and scientific regression on latest --- .github/workflows/Integration.yml | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/.github/workflows/Integration.yml b/.github/workflows/Integration.yml index 0c94d1c87..95f863a4c 100644 --- a/.github/workflows/Integration.yml +++ b/.github/workflows/Integration.yml @@ -13,7 +13,7 @@ concurrency: cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} jobs: test: - name: ${{ matrix.package.name }} - Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ github.event_name }} + name: ${{ matrix.package.name }} - Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ github.event_name }}${{ matrix.test_args && ' - reference-regression' || '' }} runs-on: ${{ matrix.os }} timeout-minutes: 60 permissions: @@ -23,14 +23,22 @@ jobs: strategy: fail-fast: false matrix: - version: - - "1" - os: - - ubuntu-latest - package: - - { name: XPalm, user: PalmStudio, repo: XPalm.jl, branch: main, default: main } - - { name: PlantBiophysics, user: VEZY, repo: PlantBiophysics.jl, branch: master, default: master } - - { name: PlantGeom, user: VEZY, repo: PlantGeom.jl, branch: main, default: main } + include: + # Keep the complete XPalm suite, including JET, on Julia 1.12. + - version: "1.12" + os: ubuntu-latest + package: { name: XPalm, user: PalmStudio, repo: XPalm.jl, branch: main, default: main } + - version: "1" + os: ubuntu-latest + package: { name: PlantBiophysics, user: VEZY, repo: PlantBiophysics.jl, branch: master, default: master } + - version: "1" + os: ubuntu-latest + package: { name: PlantGeom, user: VEZY, repo: PlantGeom.jl, branch: main, default: main } + # XPalm's existing mode runs its full-cycle scientific oracle on latest Julia. + - version: "1" + os: ubuntu-latest + package: { name: XPalm, user: PalmStudio, repo: XPalm.jl, branch: main, default: main } + test_args: reference-regression steps: - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 @@ -94,6 +102,7 @@ jobs: - name: Run the downstream tests env: DOWNSTREAM_PACKAGE: ${{ matrix.package.name }} + DOWNSTREAM_TEST_ARGS: ${{ matrix.test_args || '' }} shell: julia --threads 4 --color=yes --project=downstream --depwarn=yes {0} run: | using Pkg @@ -126,7 +135,8 @@ jobs: end Pkg.status() - Pkg.test() + test_args = isempty(ENV["DOWNSTREAM_TEST_ARGS"]) ? String[] : [ENV["DOWNSTREAM_TEST_ARGS"]] + Pkg.test(; test_args) - name: Only succeed if the checks pass on the dependencies' main/master branches if: ${{ matrix.package.branch != matrix.package.default }} run: | From 771b0a073b41a0563f5cfe9fb4d99d75380c9353 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 19:15:55 +0100 Subject: [PATCH 042/324] Build lifecycle environment indexes with checked reads --- src/composite_model/environment_bindings.jl | 17 +++++++------- src/composite_model/runtime_outputs.jl | 2 +- ...test-model-environment-binding-identity.jl | 22 +++++++++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 0283e163f..a37938734 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -429,13 +429,14 @@ function _index_environment_targets_by_object(bindings, ::Type{I}) where {I<:Obj end function _index_environment_bindings(bindings, ::Type{I}) where {I<:ObjectId} - # An initially empty application can acquire targets with another schema - # during growth. Keep this lifecycle index value-widened; concrete handles - # and sampling plans remain in the typed execution targets. - by_target = Dict{Tuple{Symbol,I},CompiledEnvironmentBinding}( - _environment_binding_target_key(binding, I) => binding - for binding in bindings - ) + # Keep lifecycle indexing open to future binding families; reads validate the + # CompiledEnvironmentBinding domain. Execution targets retain concrete + # handles and sampling plans. + by_target = Dict{Tuple{Symbol,I},Any}() + sizehint!(by_target, length(bindings)) + for binding in bindings + by_target[_environment_binding_target_key(binding, I)] = binding + end length(by_target) == length(bindings) || error( "Environment binding compilation produced duplicate `(application_id, object_id)` targets.", ) @@ -542,7 +543,7 @@ function _reconcile_environment_binding_metadata( plan = application_plans_by_id[application.id] for object_id in application.target_ids key = (application.id, object_id) - old = get(cached.by_target, key, nothing) + old = get(cached.by_target, key, nothing)::Union{Nothing,CompiledEnvironmentBinding} isnothing(old) && return nothing object = _model_object(model, object_id) context = _object_environment_context(application, object) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index b6f78db76..65b9c68b3 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1668,7 +1668,7 @@ _compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) = _compiled_application_by_id(identity, compiled, id) function _environment_binding_for(env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId) - return get(env_bindings.by_target, (application_id, object_id), nothing) + return get(env_bindings.by_target, (application_id, object_id), nothing)::Union{Nothing,CompiledEnvironmentBinding} end function _model_object_status(model::CompositeModel, object_id::ObjectId) diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 98f98c856..2256f403f 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -454,4 +454,26 @@ end end end +@testset "cold environment indexes preserve distinct binding families" begin + left = fixture(Float32).simulation.environment_bindings + right = fixture(Float64).simulation.environment_bindings + first_binding = only(binding for binding in left.bindings + if binding.object_id == ObjectId(:scheduled_keep)) + later_binding = only(binding for binding in right.bindings + if binding.object_id == ObjectId(:manual)) + @test typeof(first_binding) !== typeof(later_binding) + bindings = PSE.CompiledEnvironmentBinding[first_binding, later_binding] + I = typeof(ObjectId(:scheduled_keep)) + index = PSE._index_environment_bindings(bindings, I) + @test length(index) == 2 + for binding in bindings + @test index[PSE._environment_binding_target_key(binding, I)] === binding + end + empty_index = PSE._index_environment_bindings(PSE.CompiledEnvironmentBinding[], I) + @test isempty(empty_index) + @test typeof(empty_index) === typeof(index) + @test_throws ErrorException PSE._index_environment_bindings( + PSE.CompiledEnvironmentBinding[first_binding, first_binding], I) +end + end From 4a6fa94dc006eed354f32cb3360ad9da0a79b3be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 20:20:03 +0100 Subject: [PATCH 043/324] Render selector diagnostics with prepared field layouts --- src/composite_model/selectors.jl | 206 +++++++++++++++++++- test/test-model-api-stabilization.jl | 6 +- test/test-model-binding-index-identities.jl | 113 ++++++++++- test/test-selector-query-scope-root.jl | 13 +- test/test-unified-model-object-api.jl | 8 +- 5 files changed, 326 insertions(+), 20 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 8809a6185..fbcf88319 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1037,6 +1037,189 @@ function _available_selector_labels(model::CompositeModel, candidate_ids) ) end +# Type display is fixed by the schema. Keeping its text constant avoids the +# generic Julia syntax printer in the compiled application's error paths. +@generated function _selector_diagnostic_type_name(::Type{T}) where {T} + return QuoteNode(string(T)) +end + +function _print_selector_diagnostic(io, value::T, ancestors) where {T} + # Ancestors are inspected only with ===; recursive values remain typed by + # this method's argument, never recovered from the identity stack. + tracked = ismutabletype(T) + if tracked + any(ancestor -> ancestor === value, ancestors) && + return print(io, "") + push!(ancestors, value) + end + try + _print_selector_diagnostic_value(io, value, ancestors) + finally + tracked && pop!(ancestors) + end + return nothing +end + +function _print_selector_diagnostic_value(io, value::AbstractString, ancestors) + print(io, '"') + escape_string(io, value, ('"',)) + print(io, '"') + return nothing +end + +function _print_selector_diagnostic_value(io, value::Symbol, ancestors) + print(io, "Symbol(") + _print_selector_diagnostic_value(io, String(value), ancestors) + print(io, ')') + return nothing +end + +_print_selector_diagnostic_value(io, ::Nothing, ancestors) = print(io, "nothing") + +# User numeric types use the record printer too; their custom show methods must +# not silently reintroduce the generic syntax printer. +_print_selector_diagnostic_value(io, value::Union{ + Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128, + Float16,Float32,Float64,BigInt,BigFloat, +}, ancestors) = + print(io, value) + +function _print_selector_diagnostic_value(io, value::Char, ancestors) + print(io, "Char(") + _print_selector_diagnostic_value(io, string(value), ancestors) + print(io, ')') + return nothing +end + +function _print_selector_diagnostic_value(io, value::ObjectId, ancestors) + print(io, "ObjectId(") + _print_selector_diagnostic(io, value.value, ancestors) + print(io, ')') + return nothing +end + +function _print_selector_diagnostic_value(io, ::Type{T}, ancestors) where {T} + print(io, _selector_diagnostic_type_name(T)) + return nothing +end + +function _print_selector_diagnostic_items(io, items::Tuple, ancestors) + isempty(items) && return nothing + _print_selector_diagnostic(io, first(items), ancestors) + if length(items) > 1 + print(io, ", ") + _print_selector_diagnostic_items(io, Base.tail(items), ancestors) + end + return nothing +end + +function _print_selector_diagnostic_items(io, items::AbstractVector, ancestors) + for (index, item) in enumerate(items) + index == 1 || print(io, ", ") + _print_selector_diagnostic(io, item, ancestors) + end + return nothing +end + +function _print_selector_diagnostic_value(io, items::Union{Tuple,AbstractVector}, ancestors) + tuple = items isa Tuple + print(io, tuple ? '(' : '[') + _print_selector_diagnostic_items(io, items, ancestors) + tuple && length(items) == 1 && print(io, ',') + print(io, tuple ? ')' : ']') + return nothing +end + +function _print_selector_diagnostic_value(io, items::AbstractArray, ancestors) + print(io, _selector_diagnostic_type_name(typeof(items)), "(size=") + _print_selector_diagnostic(io, size(items), ancestors) + print(io, ", values=[") + for (index, item) in enumerate(items) + index == 1 || print(io, ", ") + _print_selector_diagnostic(io, item, ancestors) + end + print(io, "])") + return nothing +end + +function _print_selector_diagnostic_value(io, items::AbstractDict, ancestors) + print(io, _selector_diagnostic_type_name(typeof(items)), '(') + for (index, (key, value)) in enumerate(items) + index == 1 || print(io, ", ") + _print_selector_diagnostic(io, key, ancestors) + print(io, " => ") + _print_selector_diagnostic(io, value, ancestors) + end + print(io, ')') + return nothing +end + +function _print_selector_diagnostic_value(io, items::AbstractSet, ancestors) + print(io, _selector_diagnostic_type_name(typeof(items)), '(') + for (index, item) in enumerate(items) + index == 1 || print(io, ", ") + _print_selector_diagnostic(io, item, ancestors) + end + print(io, ')') + return nothing +end + +@generated function _print_selector_diagnostic_fields(io, value::T, ancestors) where {T} + statements = Expr[] + for (index, name) in enumerate(fieldnames(T)) + index == 1 || push!(statements, :(print(io, ", "))) + push!(statements, quote + print(io, $(String(name)), '=') + if isdefined(value, $index) + _print_selector_diagnostic(io, getfield(value, $index), ancestors) + else + print(io, "") + end + end) + end + return quote + $(statements...) + return nothing + end +end + +function _print_selector_diagnostic_value(io, value::NamedTuple, ancestors) + print(io, '(') + _print_selector_diagnostic_fields(io, value, ancestors) + print(io, ')') + return nothing +end + +function _print_selector_diagnostic_record(io, label, value::T, ancestors) where {T} + print(io, label, '(') + _print_selector_diagnostic_fields(io, value, ancestors) + print(io, ')') + return nothing +end + +function _print_selector_diagnostic_value(io, selector::AbstractObjectMultiplicity, ancestors) + label = selector isa One ? "One" : selector isa OptionalOne ? "OptionalOne" : "Many" + print(io, label) + _print_selector_diagnostic_value(io, criteria(selector), ancestors) + return nothing +end + +function _print_selector_diagnostic_value(io, scope::_OBJECT_SELECTOR_POSITIONAL_TYPES, ancestors) + _print_selector_diagnostic_record(io, String(nameof(typeof(scope))), scope, ancestors) + return nothing +end + +function _print_selector_diagnostic_value(io, value::T, ancestors) where {T} + if isprimitivetype(T) + print(io, _selector_diagnostic_type_name(T), "(bytes=") + _print_selector_diagnostic(io, reinterpret(NTuple{sizeof(T),UInt8}, value), ancestors) + print(io, ')') + else + _print_selector_diagnostic_record(io, _selector_diagnostic_type_name(T), value, ancestors) + end + return nothing +end + function _selector_resolution_error( model::CompositeModel, selector, @@ -1056,13 +1239,22 @@ function _selector_resolution_error( ) expected = selector isa One ? "exactly one" : "zero or one" context_id = _object_id_from_context(context) - error( - "Expected $(expected) object for selector `$(selector)`, got $(length(matched_ids)). ", - "context=$(isnothing(context_id) ? nothing : context_id.value), ", - "matched_ids=$([id.value for id in matched_ids]), ", - "requested=(scale=$(scale), kind=$(kind), species=$(species), id=$(id)), ", - "available=$(available), suggestions=$(suggestions)." - ) + io = IOBuffer() + ancestors = Any[] + print(io, "Expected ", expected, " object for selector `") + _print_selector_diagnostic(io, selector, ancestors) + print(io, "`, got ", length(matched_ids), ". context=") + _print_selector_diagnostic(io, context_id, ancestors) + print(io, ", matched_ids=") + _print_selector_diagnostic(io, matched_ids, ancestors) + print(io, ", requested=") + _print_selector_diagnostic(io, (; scale, kind, species, id), ancestors) + print(io, ", available=") + _print_selector_diagnostic(io, available, ancestors) + print(io, ", suggestions=") + _print_selector_diagnostic(io, suggestions, ancestors) + print(io, '.') + error(String(take!(io))) end function _matches_object_criteria(object::Object; scale=nothing, kind=nothing, species=nothing, id=nothing) diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index bbd98d8c8..12a07627d 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -993,7 +993,7 @@ end end @test contains( ambiguous_scoped_error, - "available=(scales = [:Leaf],", + "available=(scales=[Symbol(\"Leaf\")],", ) missing_scoped_error = try @@ -1008,9 +1008,9 @@ end end @test contains( missing_scoped_error, - "available=(scales = [:Leaf, :Plant],", + "available=(scales=[Symbol(\"Leaf\"), Symbol(\"Plant\")],", ) - @test contains(missing_scoped_error, "suggestions=(scale = [:Leaf]") + @test contains(missing_scoped_error, "suggestions=(scale=[Symbol(\"Leaf\")]") long_scope_objects = Object[Object(:long_root; scale=:Plant)] long_scope_leaf_ids = Set{ObjectId}() diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 3ac8a75c8..6ed657b99 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -313,7 +313,118 @@ end @test occursin("available=", expected) && occursin("suggestions=", expected) @test message(closed, selector) == expected end - @test occursin("suggestions=(scale = [:Leaf]", message(closed, One(scale=:Leef))) + @test occursin("suggestions=(scale=[Symbol(\"Leaf\")]", message(closed, One(scale=:Leef))) +end + +function diagnostic_text(value) + io = IOBuffer() + PSE._print_selector_diagnostic(io, value, Any[]) + return String(take!(io)) +end + +struct DiagnosticIdentity{Tag} + ordinal::Int + label::Symbol +end + +# A diagnostic must use the declared value fields, not an arbitrary user printer. +Base.show(::IO, ::DiagnosticIdentity) = error("custom identity show must not be called") + +struct DiagnosticNumber <: Number + amount::Int + label::Symbol +end +Base.show(::IO, ::DiagnosticNumber) = error("custom numeric show must not be called") + +primitive type DiagnosticPrimitive 8 end + +mutable struct DiagnosticCycle + label::Symbol + next::Union{Nothing,DiagnosticCycle} +end + +@testset "selector diagnostic text preserves identities and complete criteria" begin + text = diagnostic_text + @test text((1, Symbol("1"), Symbol("feuille α"), Symbol("a,b\n\""))) == + "(1, Symbol(\"1\"), Symbol(\"feuille α\"), Symbol(\"a,b\\n\\\"\"))" + @test text(ObjectId(1)) == "ObjectId(1)" + @test text(ObjectId(Symbol("1"))) == "ObjectId(Symbol(\"1\"))" + @test text(ObjectId(DiagnosticIdentity{:a}(1, :leaf))) != + text(ObjectId(DiagnosticIdentity{:b}(1, :leaf))) + custom = text(ObjectId(DiagnosticIdentity{:a}(1, Symbol("feuille α")))) + @test occursin("DiagnosticIdentity{:a}", custom) + @test occursin("ordinal=1, label=Symbol(\"feuille α\")", custom) + @test occursin("amount=3, label=Symbol(\"leaf\")", text(DiagnosticNumber(3, :leaf))) + primitive_text = text(reinterpret(DiagnosticPrimitive, UInt8(1))) + @test occursin("DiagnosticPrimitive(bytes=", primitive_text) + @test primitive_text != text(reinterpret(DiagnosticPrimitive, UInt8(2))) + @test occursin("size=(2, 1), values=[Symbol(\"a\"), Symbol(\"b\")]", + text(reshape([:a, :b], 2, 1))) + @test occursin("Symbol(\"a\") => 2", text(Dict(:a => 2))) + @test occursin("Symbol(\"a\")", text(Set((:a,)))) + + factor = Ref(2) + label = Symbol("captured α") + reducer = values -> (factor[] + length(String(label))) * sum(values) + selector = One(Scope(ObjectId(Symbol("plante α"))); + scale=(:Leaf, :Flower), kind=:active, species=:palm, + id=(1, Symbol("1")), relation=:children, + process=:growth, application=:leaf, var=:x, + policy=Aggregate(reducer), window=PSE.Dates.Hour(2), + from_status=true, after=(:first, :second)) + rendered = text(selector) + for field in (:selectors, :scale, :kind, :species, :id, :relation, + :process, :application, :var, :policy, :window, + :from_status, :after) + @test occursin(String(field) * "=", rendered) + end + @test occursin("Scope(root=ObjectId(Symbol(\"plante α\")))", rendered) + @test occursin("Aggregate", rendered) + @test occursin("Hour", rendered) && occursin("value=2", rendered) + @test occursin("reducer=", rendered) + @test occursin("Symbol(\"captured α\")", rendered) + @test occursin("x=2", rendered) + @test occursin("from_status=true", rendered) + @test occursin("after=(Symbol(\"first\"), Symbol(\"second\"))", rendered) + + node = DiagnosticCycle(Symbol("cycle α"), nothing) + node.next = node + cycle = text(node) + @test occursin("label=Symbol(\"cycle α\")", cycle) + @test occursin("next=", cycle) + array = Any[] + push!(array, array) + @test text(array) == "[]" +end + +@testset "cardinality messages preserve mixed IDs and Unicode in Open and Closed models" begin + messages = String[] + for closed in (false, true) + model = CompositeModel( + Object(Symbol("plante α"); scale=:Plant), + Object(1; scale=:Leaf, parent=Symbol("plante α")), + Object(Symbol("1"); scale=:Leaf, parent=Symbol("plante α")), + Object(Symbol("feuille α"); scale=:Leaf, parent=Symbol("plante α"))) + closed && (model = close_registry(model)) + message = try + resolve_object_ids(model, One(Subtree(); scale=:Leaf); + context=Symbol("plante α")) + "no error" + catch error + sprint(showerror, error) + end + @test occursin("Expected exactly one object", message) + @test occursin("One(selectors=(Subtree(),), scale=Symbol(\"Leaf\"))", message) + @test occursin("context=ObjectId(Symbol(\"plante α\"))", message) + @test occursin("ObjectId(1)", message) + @test occursin("ObjectId(Symbol(\"1\"))", message) + @test occursin("ObjectId(Symbol(\"feuille α\"))", message) + for field in ("matched_ids=", "requested=", "available=", "suggestions=") + @test occursin(field, message) + end + push!(messages, message) + end + @test messages[1] == messages[2] end end diff --git a/test/test-selector-query-scope-root.jl b/test/test-selector-query-scope-root.jl index c044a51af..4352dc7d8 100644 --- a/test/test-selector-query-scope-root.jl +++ b/test/test-selector-query-scope-root.jl @@ -91,13 +91,16 @@ end @testset "raw authored scopes remain in cardinality and context errors" begin model = scope_scene() - for selector in (One(SelfPlant(); scale=:Leaf), - One(Subtree(); scale=:Leaf), - One(Ancestor(scale=:Plant); scale=:Leaf), - One(Scope(ObjectId(:plant_a)); scale=:Leaf)) + for (selector, scope_text) in ( + (One(SelfPlant(); scale=:Leaf), "SelfPlant()"), + (One(Subtree(); scale=:Leaf), "Subtree()"), + (One(Ancestor(scale=:Plant); scale=:Leaf), "Ancestor(scale=Symbol(\"Plant\"))"), + (One(Scope(ObjectId(:plant_a)); scale=:Leaf), "Scope(root=ObjectId(Symbol(\"plant_a\")))"), + ) error = query_error(model, selector; context=:axis_a) @test occursin("Expected exactly one object", error) - @test occursin(string(selector), error) + @test occursin("One(selectors=(" * scope_text, error) + @test occursin("scale=Symbol(\"Leaf\")", error) @test !occursin("CompiledNamedScope", error) end @test_throws "current object context" resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf)) diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index 8689a302b..a56ebb69f 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -1394,16 +1394,16 @@ end catch error sprint(showerror, error) end - @test contains(typo_selector_error, "requested=(scale=Leef") - @test contains(typo_selector_error, "available=(scales = [:Axis, :Leaf, :Plant, :Scene, :Soil]") - @test contains(typo_selector_error, "suggestions=(scale = [:Leaf]") + @test contains(typo_selector_error, "requested=(scale=Symbol(\"Leef\")") + @test contains(typo_selector_error, "available=(scales=[Symbol(\"Axis\"), Symbol(\"Leaf\"), Symbol(\"Plant\"), Symbol(\"Scene\"), Symbol(\"Soil\")]") + @test contains(typo_selector_error, "suggestions=(scale=[Symbol(\"Leaf\")]") ambiguous_selector_error = try resolve_object_ids(selector_scene, One(scale=:Leaf)) nothing catch error sprint(showerror, error) end - @test contains(ambiguous_selector_error, "matched_ids=[:leaf_1, :leaf_2, :leaf_3]") + @test contains(ambiguous_selector_error, "matched_ids=[ObjectId(Symbol(\"leaf_1\")), ObjectId(Symbol(\"leaf_2\")), ObjectId(Symbol(\"leaf_3\"))]") @test_throws "Unsupported object selector keyword" One(sacle=:Leaf) @test_throws "object-query" resolve_object_ids( selector_scene, From 37b79b3fc7e27817a7c703443ca657bab534f7dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 20:20:38 +0100 Subject: [PATCH 044/324] Avoid unused environment checks and untyped error rows --- src/composite_model/compilation.jl | 1 + src/composite_model/environment_bindings.jl | 48 +++++------- ...test-model-environment-binding-identity.jl | 76 +++++++++++++++++++ 3 files changed, 96 insertions(+), 29 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f3f146586..e4e6b1d32 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8660,6 +8660,7 @@ end end @inline _with_metadata_entry(f, entries::AbstractVector, key::Integer) = f(entries[key]) +@inline _with_metadata_entry(f, entries::AbstractDict, key::Symbol) = f(entries[key]) function _foreach_object_application(f, compiled::CompiledCompositeModel, object_id::ObjectId) slots = _application_membership_slots(compiled, object_id) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index a37938734..e66cd1a99 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -297,46 +297,36 @@ function _compile_environment_bindings( end function _validate_model_environment_inputs!(bindings, applications_by_id) - missing_rows = NamedTuple[] + missing_details = String[] for binding in bindings + plan = getfield(binding, :plan)::CompiledEnvironmentApplicationPlan + application_id = getfield(plan, :application_id) + no_inputs = _with_metadata_entry(applications_by_id, application_id) do application + isempty(_model_environment_input_names(application)) + end + no_inputs && continue available = environment_variables(binding.backend) isnothing(available) && continue application = applications_by_id[binding.application_id] for (target, source) in binding.sampling_rules source in available && continue - push!( - missing_rows, - ( - application_id=binding.application_id, - object_id=binding.object_id.value, - process=application.process, - target=target, - source=source, - available=Tuple(sort!(collect(available); by=string)), - ), - ) - end - end - isempty(missing_rows) && return nothing - details = join( - [ - string( - row.application_id, + push!(missing_details, string( + binding.application_id, "/", - row.object_id, + binding.object_id.value, " (", - row.process, + application.process, ") needs `", - row.target, + target, "` from source `", - row.source, + source, "`; available=", - row.available, - ) - for row in missing_rows - ], - "; ", - ) + Tuple(sort!(collect(available); by=string)), + )) + end + end + isempty(missing_details) && return nothing + details = join(missing_details, "; ") error("Composite model environment is missing required source inputs: ", details) end diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 2256f403f..e2cba854f 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -476,4 +476,80 @@ end PSE.CompiledEnvironmentBinding[first_binding, first_binding], I) end +mutable struct PortlessValidationBackend <: EA.AbstractEnvironmentBackend + inventory_reads::Int +end +EA.base_step_seconds(::PortlessValidationBackend) = 3600.0 +EA.get_nsteps(::PortlessValidationBackend) = 8 +function EA.environment_variables(backend::PortlessValidationBackend) + backend.inventory_reads += 1 + return Set((:unused,)) +end + +@testset "portless applications do not query backend inventories" begin + backend = PortlessValidationBackend(0) + model = CompositeModel(Object(:scene; scale=:Scene); + applications=(ModelSpec(Owner(Ref{Any}()); name=:owner, on=One(id=:scene)),), + environment=backend) + simulation = run!(model; steps=0, outputs=:none) + @test backend.inventory_reads == 0 + bindings = simulation.environment_bindings.bindings + tables = (simulation.compiled.applications_by_id, + Dict(application.id => application for application in simulation.compiled.applications)) + for table in tables + @test PSE._validate_model_environment_inputs!(bindings, table) === nothing + @test backend.inventory_reads == 0 + end +end + +@testset "environment validation preserves all missing local and spatial sources" begin + backend = Backend(Dict(:a=>10f0, :b=>20f0), 0) + for local_backend in (false, true) + config = local_backend ? + Environment(backend=(other=3f0,), sources=(T=:missing,)) : + Environment(provider=:shell_probe, sources=(T=:missing,)) + model = CompositeModel( + Object(:one; scale=:Leaf, geometry=(cell=:a,)), + Object(:two; scale=:Leaf, geometry=(cell=:b,)); + applications=(ModelSpec(Leaf(0f0); name=:leaf, on=Many(scale=:Leaf), + environment=config),), environment=backend) + compiled = PSE.Advanced.refresh_bindings!(model) + _, plans = PSE._compile_environment_application_plans(model, compiled.applications) + bindings = PSE._compile_environment_bindings_for_applications( + model, compiled.applications, plans) + tables = (compiled.applications_by_id, + Dict(application.id => application for application in compiled.applications)) + messages = String[] + expected = if local_backend + "Composite model environment is missing required source inputs: leaf/one " * + "(environment_shell_leaf) needs `T` from source `missing`; " * + "available=(:other,); leaf/two (environment_shell_leaf) needs `T` from source" * + " `missing`; available=(:other,)" + else + "Composite model environment is missing required source inputs: leaf/one " * + "(environment_shell_leaf) needs `T` from source `missing`; available=(:T,); " * + "leaf/two (environment_shell_leaf) needs `T` from source `missing`; " * + "available=(:T,)" + end + for table in tables + failure = try + PSE._validate_model_environment_inputs!(bindings, table) + nothing + catch exception + exception + end + @test failure isa ErrorException + message = sprint(showerror, failure) + @test message == expected + @test occursin("leaf/one", message) && occursin("leaf/two", message) + @test occursin("needs `T` from source `missing`", message) + @test occursin("available=", message) + @test occursin(local_backend ? "other" : "T", message) + push!(messages, message) + end + @test messages[1] == messages[2] + @test backend.samples == 0 + end +end + end From 6f1bb63e5ce2ad3d008d6fd4ee01cb488f5091e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 21:32:19 +0100 Subject: [PATCH 045/324] Allow time for the complete XPalm integration suite --- .github/workflows/Integration.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/Integration.yml b/.github/workflows/Integration.yml index 95f863a4c..b62916ddb 100644 --- a/.github/workflows/Integration.yml +++ b/.github/workflows/Integration.yml @@ -15,7 +15,7 @@ jobs: test: name: ${{ matrix.package.name }} - Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ github.event_name }}${{ matrix.test_args && ' - reference-regression' || '' }} runs-on: ${{ matrix.os }} - timeout-minutes: 60 + timeout-minutes: ${{ matrix.timeout_minutes || 60 }} permissions: # needed to allow julia-actions/cache to proactively delete old caches that it has created actions: write @@ -27,6 +27,8 @@ jobs: # Keep the complete XPalm suite, including JET, on Julia 1.12. - version: "1.12" os: ubuntu-latest + # The complete XPalm suite includes cold compilation and VPalm tests. + timeout_minutes: 90 package: { name: XPalm, user: PalmStudio, repo: XPalm.jl, branch: main, default: main } - version: "1" os: ubuntu-latest From 6e509db8fe49e164f78ccf7b5165658da9fcf8fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 22:12:25 +0100 Subject: [PATCH 046/324] Fail XPalm CI on internal analyzer errors --- .github/scripts/require_complete_jet.jl | 55 +++++++++++++ .github/scripts/test_require_complete_jet.jl | 81 ++++++++++++++++++++ .github/workflows/Integration.yml | 10 ++- 3 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/require_complete_jet.jl create mode 100644 .github/scripts/test_require_complete_jet.jl diff --git a/.github/scripts/require_complete_jet.jl b/.github/scripts/require_complete_jet.jl new file mode 100644 index 000000000..7aaf119bb --- /dev/null +++ b/.github/scripts/require_complete_jet.jl @@ -0,0 +1,55 @@ +# Loaded in the full XPalm test subprocess before JET creates analysis tasks. +module JETAnalysisGuard + +using Logging + +struct AnalyzerErrorLogger{L<:AbstractLogger} <: AbstractLogger + inner::L + errors::Threads.Atomic{Int} +end + +is_analyzer_error(level, source) = + level >= Logging.Error && source isa Module && first(Base.fullname(source)) === :JET + +Logging.min_enabled_level(logger::AnalyzerErrorLogger) = + min(Logging.Error, Logging.min_enabled_level(logger.inner)) + +function Logging.shouldlog(logger::AnalyzerErrorLogger, level, source, group, id) + return is_analyzer_error(level, source) || + (level >= Logging.min_enabled_level(logger.inner) && + Logging.shouldlog(logger.inner, level, source, group, id)) +end + +Logging.catch_exceptions(logger::AnalyzerErrorLogger) = + Logging.catch_exceptions(logger.inner) + +function Logging.handle_message( + logger::AnalyzerErrorLogger, level, message, source, group, id, file, line; kwargs..., +) + if is_analyzer_error(level, source) + Threads.atomic_add!(logger.errors, 1) + end + if level >= Logging.min_enabled_level(logger.inner) && + Logging.shouldlog(logger.inner, level, source, group, id) + Logging.handle_message(logger.inner, level, message, source, group, id, file, line; kwargs...) + end + return nothing +end + +function install!() + logger = AnalyzerErrorLogger(global_logger(), Threads.Atomic{Int}(0)) + global_logger(logger) + atexit() do exit_code + count = logger.errors[] + if count > 0 + println(stderr, "JET analysis incomplete: ", count, " internal analyzer error(s).") + # Julia catches exceptions from exit hooks; failing requires exit(). + exit(iszero(exit_code) ? 1 : exit_code) + end + end + return nothing +end + +end + +JETAnalysisGuard.install!() diff --git a/.github/scripts/test_require_complete_jet.jl b/.github/scripts/test_require_complete_jet.jl new file mode 100644 index 000000000..525e7c056 --- /dev/null +++ b/.github/scripts/test_require_complete_jet.jl @@ -0,0 +1,81 @@ +using Test + +const GUARD = joinpath(@__DIR__, "require_complete_jet.jl") + +function guarded_case(packages, source) + output, errors = IOBuffer(), IOBuffer() + command = `$(Base.julia_cmd()) --startup-file=no --threads=2 --load=$GUARD -e $source` + load_path = join((packages, "@stdlib"), Sys.iswindows() ? ';' : ':') + process = run(pipeline(ignorestatus(addenv(command, "JULIA_LOAD_PATH" => load_path)); + stdout=output, stderr=errors)) + return (code=process.exitcode, output=String(take!(output)), errors=String(take!(errors))) +end + +@testset "incomplete JET analysis fails its test subprocess" begin + mktempdir() do packages + source_dir = mkpath(joinpath(packages, "JET", "src")) + write(joinpath(source_dir, "JET.jl"), """ + module JET + using Logging + function analyze(; broken=false) + if broken + try + error("deliberate analyzer failure") + catch exception + @error "Analyzer worker aborted" exception + end + else + @info "Analysis completed" + end + return current_task() + end + module Workers + using Logging + fail() = @error "Another internal analyzer diagnostic" + end + end + """) + + clean = guarded_case(packages, "using JET; JET.analyze()") + @test clean.code == 0 + @test occursin("Analysis completed", clean.errors) + @test !occursin("analysis incomplete", clean.errors) + + swallowed = guarded_case(packages, "using JET; JET.analyze(; broken=true)") + @test swallowed.code == 1 + @test occursin("Analyzer worker aborted", swallowed.errors) + @test occursin("JET analysis incomplete: 1 internal analyzer error(s).", swallowed.errors) + + worker = guarded_case(packages, """ + using JET + parent = current_task() + task = Threads.@spawn JET.analyze(; broken=true) + @assert fetch(task) !== parent + """) + @test worker.code == 1 + @test occursin("JET analysis incomplete: 1 internal analyzer error(s).", worker.errors) + + concurrent = guarded_case(packages, """ + using JET + @sync for _ in 1:32 + Threads.@spawn JET.Workers.fail() + end + """) + @test concurrent.code == 1 + @test occursin("JET analysis incomplete: 32 internal analyzer error(s).", concurrent.errors) + + unrelated = guarded_case(packages, """ + using Test, Logging, JET + @test_logs (:error, "expected unrelated error") @error "expected unrelated error" + @error "unrelated module error remains visible" + JET.analyze() + """) + @test unrelated.code == 0 + @test occursin("unrelated module error remains visible", unrelated.errors) + @test !occursin("analysis incomplete", unrelated.errors) + + prior_failure = guarded_case(packages, "using JET; JET.analyze(; broken=true); exit(7)") + @test prior_failure.code == 7 + @test occursin("JET analysis incomplete: 1 internal analyzer error(s).", prior_failure.errors) + end +end diff --git a/.github/workflows/Integration.yml b/.github/workflows/Integration.yml index b62916ddb..44296f382 100644 --- a/.github/workflows/Integration.yml +++ b/.github/workflows/Integration.yml @@ -101,6 +101,10 @@ jobs: "PlantSimEngine resolved to $(pse.source), expected $(realpath(pwd()))", ) @info "Verified local PlantSimEngine test source" path=pse.source + - name: Test the JET analysis failure guard + if: ${{ matrix.package.name == 'XPalm' && !matrix.test_args }} + shell: julia --color=yes {0} + run: include(joinpath(pwd(), ".github", "scripts", "test_require_complete_jet.jl")) - name: Run the downstream tests env: DOWNSTREAM_PACKAGE: ${{ matrix.package.name }} @@ -138,7 +142,11 @@ jobs: Pkg.status() test_args = isempty(ENV["DOWNSTREAM_TEST_ARGS"]) ? String[] : [ENV["DOWNSTREAM_TEST_ARGS"]] - Pkg.test(; test_args) + julia_args = String[] + if ENV["DOWNSTREAM_PACKAGE"] == "XPalm" && isempty(test_args) + push!(julia_args, "--load=" * joinpath(pwd(), ".github", "scripts", "require_complete_jet.jl")) + end + Pkg.test(; test_args, julia_args) - name: Only succeed if the checks pass on the dependencies' main/master branches if: ${{ matrix.package.branch != matrix.package.default }} run: | From a5baec035299c03695fe8ddaaf888c56664c11b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 22:18:54 +0100 Subject: [PATCH 047/324] Preserve registry identity types during application preparation Keep the registry identity type in both canonical application buffers and bound application plans to their actual domain. Preserve generation-owner identity without converting the executable array, and capture the fixed prefix boundary outside the growth callback. Validated with 2286 assertions across nine maintained files and Aqua, plus matched preparation allocation and scientific-state controls. Actual safe compilation advances beyond the identity lookup failure; environment-context inference remains unresolved. --- src/composite_model/compilation.jl | 17 ++++-- src/composite_model/runtime_outputs.jl | 6 +- test/test-compilation-metadata.jl | 8 +++ test/test-model-binding-index-identities.jl | 60 +++++++++++++++++++ test/test-model-call-cohort-retirement.jl | 2 +- ...est-model-finite-call-extension-intents.jl | 38 ++++++++++++ test/test-model-prepared-scenario.jl | 12 ++-- test/test-model-runtime-snapshot-isolation.jl | 4 +- 8 files changed, 130 insertions(+), 17 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index e4e6b1d32..81510c97c 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -20,7 +20,7 @@ end """ Object-dependent runtime state for one compiled application. """ -mutable struct CompiledModelApplication{P,I<:ObjectId} +mutable struct CompiledModelApplication{P<:CompiledApplicationPlan,I<:ObjectId} const plan::P target_ids::Vector{I} end @@ -927,9 +927,11 @@ function _prepared_application_targets(model, applications; copy_targets=false) return T[copy_targets ? copy(app.target_ids) : app.target_ids for app in applications] end -Base.@nospecializeinfer function _scenario_applications(prepared::PreparedScenario) +Base.@nospecializeinfer function _scenario_applications( + prepared::PreparedScenario, ::Type{I}, +) where {I<:ObjectId} @nospecialize prepared - return CompiledModelApplication[ + return CompiledModelApplication{<:CompiledApplicationPlan,I}[ CompiledModelApplication(plan, sizehint!(copy(ids), length(ids) + 1)) for (plan, ids) in zip(prepared.plan.applications, prepared.target_ids) ] @@ -1809,7 +1811,8 @@ mutable struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C} const sample_cache::C const model_revision::Int const environment_revision::Int - const compiled_applications::Vector{CompiledModelApplication} + # Generation identity token only; executable membership stays in compiled.applications. + const compiled_applications::Any end # Keep a stable heap identity at dynamic execution-batch boundaries. The @@ -2396,7 +2399,8 @@ function _compile_scene( end function _compile_scene(model::CompositeModel, prepared::PreparedScenario; kwargs...) - return _compile_scene(model, prepared.plan, _scenario_applications(prepared); kwargs...) + applications = _scenario_applications(prepared, keytype(model.registry.objects)) + return _compile_scene(model, prepared.plan, applications; kwargs...) end function _compile_scene( @@ -5030,7 +5034,8 @@ end function _resolve_application_recipes( model::CompositeModel, recipes::Tuple, timeline; on_environment_error=nothing, ) - applications = CompiledModelApplication[] + I = keytype(model.registry.objects) + applications = CompiledModelApplication{<:CompiledApplicationPlan,I}[] for recipe in recipes target_matcher = _resolve_selector_matcher(model, recipe.target_matcher) selector = applies_to(recipe.spec) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 65b9c68b3..f651f2c7b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -593,7 +593,8 @@ struct CallTargetsPreparation{CS,EB,TS,OR,C} constants::C model_revision::Int environment_revision::Int - compiled_applications::Vector{CompiledModelApplication} + # The actual vector is an identity token, never a source of executable data. + compiled_applications::Any membership_reference::Base.RefValue{UInt64} membership_generation::UInt64 end @@ -4109,8 +4110,9 @@ function _extend_execution_target_call_batches_by_prefix!( end existing_count == length(current_ids) && return true admission = _call_cohort_admission(application_schema, OpenExecutionCohortSchema()) + first_new_index = existing_count + 1 return _with_execution_batch(application_schema, last(batches)) do destination_batch - for index in (existing_count + 1):lastindex(current_ids) + for index in first_new_index:lastindex(current_ids) object_id = current_ids[index] execution_target = _compiled_model_execution_target( compiled, env_bindings, application, object_id, diff --git a/test/test-compilation-metadata.jl b/test/test-compilation-metadata.jl index f9b015e60..15b25e356 100644 --- a/test/test-compilation-metadata.jl +++ b/test/test-compilation-metadata.jl @@ -3,6 +3,11 @@ module CompilationMetadataChecks using PlantSimEngine, Test const PSE = PlantSimEngine +function application_identity_from_membership(applications::Vector{PSE.CompiledModelApplication}) + application = first(applications) + return (application.id, application.process) +end + PSE.@process "compiled_port_metadata" verbose=false struct PortProbe{C} <: AbstractCompiled_Port_MetadataModel declarations::C @@ -21,6 +26,9 @@ PSE.run!(::PortProbe, status, environment, constants, context) = nothing simulation = run!(model; steps=0, outputs=:none) application = only(simulation.compiled.applications) prepared_count = declarations[] + erased = PSE.CompiledModelApplication[simulation.compiled.applications...] + @test (@inferred application_identity_from_membership(erased)) == + (:probe, :compiled_port_metadata) @test PSE._model_output_names(application) === (:value, :scratch) @test PSE._model_canonical_output_names(application) === (:value,) for _ in 1:20 diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 6ed657b99..2b2b2a92c 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -427,4 +427,64 @@ end @test messages[1] == messages[2] end +@testset "environment compilation preserves registry IDs and broad partial membership" begin + for closed in (false, true) + data = call_fixture(closed) + model, simulation = data.model, data.simulation + I = keytype(model.registry.objects) + @test fieldtype(eltype(simulation.compiled.applications), :target_ids) === Vector{I} + prepared = PSE._prepare_scenario_plan(model) + copied = PSE._scenario_applications(prepared, I) + @test eltype(copied) === eltype(simulation.compiled.applications) + authored = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + @test eltype(authored) === eltype(copied) + for application in simulation.compiled.applications + ids = application.target_ids + @test PSE._application_target_ids(model, ids) === ids + end + leaf = simulation.compiled.applications_by_id[:leaf] + references = (PSE.refvalue(model_status(model, :leaf), :x), + PSE.refvalue(model_status(model, 1), :x)) + before = (NamedTuple(model_status(model, :leaf)), NamedTuple(model_status(model, 1))) + wide = ObjectId[ObjectId(:leaf), ObjectId(1)] + for source in (wide, view(wide, 2:-1:1)) + adapted = PSE._application_target_ids(model, source) + @test eltype(adapted) === I + @test adapted == collect(source) + @test map(typeof, adapted) == map(typeof, source) + partial = PSE.CompiledModelApplication(leaf.plan, ObjectId[source...]) + bindings = PSE._compile_environment_bindings_for_applications(model, + PSE.CompiledModelApplication[partial], + simulation.environment_bindings.application_plans_by_id) + @test [binding.object_id for binding in bindings] == collect(source) + @test length(bindings) == 2 # The canonical application also owns :outside. + @test all(binding.plan === simulation.environment_bindings.application_plans_by_id[:leaf] + for binding in bindings) + end + empty_ids = PSE._application_target_ids(model, ObjectId[]) + @test eltype(empty_ids) === I && isempty(empty_ids) + @test PSE.refvalue(model_status(model, :leaf), :x) === references[1] + @test PSE.refvalue(model_status(model, 1), :x) === references[2] + @test (NamedTuple(model_status(model, :leaf)), NamedTuple(model_status(model, 1))) == before + end +end + +@testset "empty canonical application buffers retain registry identity families" begin + for closed in (false, true) + model = CompositeModel( + Object(:root; scale=:Plant, status=Status(visits=0)), + Object(1; scale=:Leaf, parent=:root, status=Status(x=3f0)); + applications=()) + closed && (model = close_registry(model)) + I = keytype(model.registry.objects) + authored = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + prepared = PSE._prepare_scenario_plan(model) + copied = PSE._scenario_applications(prepared, I) + @test isempty(authored) && isempty(copied) + @test eltype(authored) === eltype(copied) + @test fieldtype(eltype(authored), :target_ids) === Vector{I} + @test model_status(model, 1).x === 3f0 + end +end + end diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl index a1c20aad9..cd6dff2ef 100644 --- a/test/test-model-call-cohort-retirement.jl +++ b/test/test-model-call-cohort-retirement.jl @@ -241,7 +241,7 @@ end @test partial.target_ids !== applications[:leaf].target_ids snapshot = PSE._prepare_scenario_plan(data.model) @test all(ids -> eltype(ids) === I, snapshot.target_ids) - copied = PSE._scenario_applications(snapshot) + copied = PSE._scenario_applications(snapshot, eltype(eltype(snapshot.target_ids))) for app in copied @test eltype(app.target_ids) === I @test app.target_ids == applications[app.id].target_ids diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl index 3668d43a7..9cc2bf38b 100644 --- a/test/test-model-finite-call-extension-intents.jl +++ b/test/test-model-finite-call-extension-intents.jl @@ -202,6 +202,44 @@ random_state(rng) = rand(copy(rng), UInt64, 8) end end +@testset "prefix extension appends after a nonempty updated boundary" begin + for prepared in (false, true) + data = fixture(; prepared, wide=true) + simulation = data.simulation + target = root_target(simulation) + add_leaves!(data) + @test extend!(:prefix, target, refreshed_owners(data), simulation) === true + rows = [only(call_targets(target.context, name).execution_batches).targets + for name in MANUAL_NAMES] + prefix = [collect(row) for row in rows] + cells = [[PSE.refvalue(child.status_view.status, :value) for child in row] + for row in rows] + @test all(length(row) == 2 for row in rows) + for (index, kind) in enumerate((:a, :b, :c, :d, :e, :f)), offset in 2:4 + register_object!(data.model, Object(100index + offset; kind, + scale=:Leaf, parent=1, status=Status(visits=0, value=0.0))) + end + owners = refreshed_owners(data) + before_state = state(data.model) + before_random = random_state(data.rng) + @test extend!(:prefix, target, owners, simulation) === true + @test state(data.model) == before_state + @test random_state(data.rng) == before_random + @test all(isempty, values(outputs(simulation))) + for (index, name) in enumerate(MANUAL_NAMES) + current = only(call_targets(target.context, name).execution_batches).targets + @test current === rows[index] + @test length(current) == 5 + @test all(current[position] === child for (position, child) in enumerate(prefix[index])) + @test all(PSE.refvalue(current[position].status_view.status, :value) === cell + for (position, cell) in enumerate(cells[index])) + kind_index = name === :alias_a ? 1 : findfirst(==(name), (:a, :b, :c, :d, :e, :f)) + @test getproperty.(collect(current), :object_id) == + [ObjectId(100kind_index + offset) for offset in 0:4] + end + end +end + @testset "a later inadmissible binding rejects before any earlier append" begin for algorithm in (:prefix, :pure_addition), mismatch in (:type, :owner) data = fixture() diff --git a/test/test-model-prepared-scenario.jl b/test/test-model-prepared-scenario.jl index 621518047..7ed531eca 100644 --- a/test/test-model-prepared-scenario.jl +++ b/test/test-model-prepared-scenario.jl @@ -73,9 +73,9 @@ end @test model_object(model, :sensor).status === initial_status # A lowering may assemble target vectors, but those vectors belong to that execution. - left_apps = PlantSimEngine._scenario_applications(prepared) + left_apps = PlantSimEngine._scenario_applications(prepared, eltype(eltype(prepared.target_ids))) empty!(only(app for app in left_apps if app.id == :reader_a).target_ids) - right_apps = PlantSimEngine._scenario_applications(prepared) + right_apps = PlantSimEngine._scenario_applications(prepared, eltype(eltype(prepared.target_ids))) @test only(app for app in right_apps if app.id == :reader_a).target_ids == [ObjectId(:sensor)] copied_model = deepcopy(model) @@ -104,18 +104,18 @@ end register_object!(model, Object(:extra; scale=:Sensor, parent=:plant_b, status=Status(lagged=-1.0))) added = PlantSimEngine._prepare_scenario_plan(model) @test added !== first - @test only(app for app in PlantSimEngine._scenario_applications(added) if app.id == :reader_b).target_ids == + @test only(app for app in PlantSimEngine._scenario_applications(added, eltype(eltype(added.target_ids))) if app.id == :reader_b).target_ids == [ObjectId(:extra)] reparent_object!(model, :sensor, :plant_b) moved = PlantSimEngine._prepare_scenario_plan(model) @test moved !== added - @test isempty(only(app for app in PlantSimEngine._scenario_applications(moved) if app.id == :reader_a).target_ids) + @test isempty(only(app for app in PlantSimEngine._scenario_applications(moved, eltype(eltype(moved.target_ids))) if app.id == :reader_a).target_ids) remove_object!(model, :extra) removed = PlantSimEngine._prepare_scenario_plan(model) @test removed !== moved - @test only(app for app in PlantSimEngine._scenario_applications(removed) if app.id == :reader_b).target_ids == + @test only(app for app in PlantSimEngine._scenario_applications(removed, eltype(eltype(removed.target_ids))) if app.id == :reader_b).target_ids == [ObjectId(:sensor)] cached_sim = run!(model; steps=4, outputs=:all) @@ -128,7 +128,7 @@ end # A live simulation still handles additions through its incremental refresh. register_object!(model, Object(:new_sensor; scale=:Sensor, parent=:plant_a, status=Status(lagged=-1.0))) pending = PlantSimEngine._prepare_scenario_plan(model) - @test only(app for app in PlantSimEngine._scenario_applications(pending) if app.id == :reader_a).target_ids == + @test only(app for app in PlantSimEngine._scenario_applications(pending, eltype(eltype(pending.target_ids))) if app.id == :reader_a).target_ids == [ObjectId(:new_sensor)] continue!(cached_sim; steps=1) @test cached_sim.compiled.scenario_plan === removed.plan diff --git a/test/test-model-runtime-snapshot-isolation.jl b/test/test-model-runtime-snapshot-isolation.jl index c1594f6e4..4e30d63a8 100644 --- a/test/test-model-runtime-snapshot-isolation.jl +++ b/test/test-model-runtime-snapshot-isolation.jl @@ -50,7 +50,7 @@ end register_object!(model, Object(:born; scale=:Leaf, parent=:root)) born_snapshot = PSE._prepare_scenario_plan(model; force=true) @test identity(born_snapshot.plan !== plan) - @test ObjectId(:born) in only(PSE._scenario_applications(born_snapshot)).target_ids + @test ObjectId(:born) in only(PSE._scenario_applications(born_snapshot, eltype(eltype(born_snapshot.target_ids)))).target_ids @test identity(model.binding_cache === compiled) @test PSE.bindings_dirty(model) step!(simulation) @@ -72,7 +72,7 @@ end remove_object!(model, :born) removed_snapshot = PSE._prepare_scenario_plan(model; force=true) - @test only(PSE._scenario_applications(removed_snapshot)).target_ids == [ObjectId(:leaf)] + @test only(PSE._scenario_applications(removed_snapshot, eltype(eltype(removed_snapshot.target_ids)))).target_ids == [ObjectId(:leaf)] step!(simulation) @test identity(simulation.compiled.scenario_plan === plan) @test model_status(model, :leaf).visits == 5 From 3fda4fd31d023ab4263b3553218c53054419ad18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 22:50:57 +0100 Subject: [PATCH 048/324] Keep resolved object identities in environment contexts Pass the identity already resolved by each application-target loop into the single context constructor. Preserve the exact identity type for backend dispatch and update both environment compilation and reconciliation. Validated by 1363 assertions across four complete files and Aqua. The actual safe call build passes this previous blocker and now exposes erased backend/config metadata in the environment-plan map. --- src/composite_model/environment_bindings.jl | 10 ++++++---- test/test-model-binding-index-identities.jl | 7 +++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index e66cd1a99..e90c65bf2 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -11,9 +11,11 @@ function _environment_backend_from_config(model::CompositeModel, config) return environment_backend(model.environment) end -function _object_environment_context(application::CompiledModelApplication, object::Object) +function _object_environment_context( + application::CompiledModelApplication, object::Object, object_id::ObjectId, +) scale = isnothing(object.scale) ? :Default : object.scale - return EnvironmentContext(application.id, object.id, scale, application.process) + return EnvironmentContext(application.id, object_id, scale, application.process) end """ @@ -259,7 +261,7 @@ function _compile_environment_bindings_for_applications( plan = plans_by_id[application.id] for object_id in application.target_ids object = _model_object(model, object_id) - context = _object_environment_context(application, object) + context = _object_environment_context(application, object, object_id) binding_object, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) handle = bind_environment( @@ -536,7 +538,7 @@ function _reconcile_environment_binding_metadata( old = get(cached.by_target, key, nothing)::Union{Nothing,CompiledEnvironmentBinding} isnothing(old) && return nothing object = _model_object(model, object_id) - context = _object_environment_context(application, object) + context = _object_environment_context(application, object, object_id) _, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) _same_environment_backend(old.backend, plan.backend) || return nothing diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 2b2b2a92c..1b0494604 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -460,6 +460,13 @@ end @test length(bindings) == 2 # The canonical application also owns :outside. @test all(binding.plan === simulation.environment_bindings.application_plans_by_id[:leaf] for binding in bindings) + for binding in bindings + canonical = model_object(model, binding.object_id) + @test binding.context.object_id === canonical.id + @test typeof(binding.context) === PSE.EnvironmentContext{typeof(canonical.id)} + @test (binding.context.application, binding.context.scale, binding.context.process) === + (:leaf, :Leaf, PSE.process(Leaf())) + end end empty_ids = PSE._application_target_ids(model, ObjectId[]) @test eltype(empty_ids) === I && isempty(empty_ids) From ca7fa89774620ea7bfb2e7e3894e01d8a2a2efb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 23:01:44 +0100 Subject: [PATCH 049/324] Retain binding plan domains through metadata containers Bound input and call bindings to their actual plan types, including the call factory. Read declaration metadata through genuinely erased binding vectors without losing Symbol, Int and Bool fields or replacing live plans and reference carriers. Validated with 1609 assertions across five complete files and Aqua. The stock growth build preserves its five host parity cases but still fails at the existing prefix callback; this does not qualify native execution. --- src/composite_model/compilation.jl | 6 +-- test/test-model-binding-index-identities.jl | 52 +++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 81510c97c..36c198e11 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1550,7 +1550,7 @@ function _compiled_scenario_plan( ) end -struct CompiledModelInputBinding{PL,P,C,I<:ObjectId,SI<:AbstractVector{<:ObjectId}} +struct CompiledModelInputBinding{PL<:CompiledModelInputPlan,P,C,I<:ObjectId,SI<:AbstractVector{<:ObjectId}} plan::PL consumer_id::I source_ids::SI @@ -1626,7 +1626,7 @@ mutable struct CompiledModelStatusView{S,C,T,P,BI} const bound_inputs::BI end -struct CompiledModelCallBinding{P,I<:ObjectId,J<:ObjectId} +struct CompiledModelCallBinding{P<:CompiledModelCallPlan,I<:ObjectId,J<:ObjectId} plan::P consumer_id::I callee_object_ids::Vector{J} @@ -1648,7 +1648,7 @@ function CompiledModelCallBinding( consumer_id::I, callee_object_ids::Vector{J}, callee_application_ids::Vector{Symbol}, -) where {P,I<:ObjectId,J<:ObjectId} +) where {P<:CompiledModelCallPlan,I<:ObjectId,J<:ObjectId} return CompiledModelCallBinding{P,I,J}( plan, consumer_id, diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 1b0494604..f659d9042 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -494,4 +494,56 @@ end end end +# These readers deliberately accept containers with erased concrete binding +# parameters. Primitive declaration metadata must keep its semantic types. +function input_binding_metadata(bindings::Vector{PSE.CompiledModelInputBinding}) + binding = first(bindings) + return (binding.application_id, binding.input, binding.source_var, + binding.multiplicity, binding.slot, binding.application_slot, + binding.breaks_same_step_cycle) +end + +function call_binding_metadata(bindings::Vector{PSE.CompiledModelCallBinding}) + binding = first(bindings) + return (binding.application_id, binding.call, binding.multiplicity, + binding.slot, binding.application_slot) +end + +@testset "binding metadata stays inferred through abstract binding containers" begin + for closed in (false, true) + calls = call_fixture(closed).simulation.compiled.call_bindings + erased_calls = PSE.CompiledModelCallBinding[calls...] + @test eltype(erased_calls) === PSE.CompiledModelCallBinding + expected_call = first(calls) + @test (@inferred call_binding_metadata(erased_calls)) == + (expected_call.application_id, expected_call.call, + expected_call.multiplicity, expected_call.slot, + expected_call.application_slot) + @test first(erased_calls).plan === expected_call.plan + @test first(erased_calls).callee_object_ids === expected_call.callee_object_ids + + model = CompositeModel( + Object(:root; scale=:Plant, + status=Status(single=0f0, values=Float64[], total=0.0)), + Object(1; scale=:Leaf, parent=:root, status=Status(x=3f0)); + applications=(ModelSpec(Reader(); name=:reader, on=One(id=:root), + inputs=(single=One(id=1, within=Subtree(), var=:x, + from_status=true),)),)) + closed && (model = close_registry(model)) + simulation = run!(model; steps=0, outputs=:none) + bindings = simulation.compiled.input_bindings + erased_inputs = PSE.CompiledModelInputBinding[bindings...] + @test length(erased_inputs) == 1 + @test eltype(erased_inputs) === PSE.CompiledModelInputBinding + expected_input = only(bindings) + @test (@inferred input_binding_metadata(erased_inputs)) == + (expected_input.application_id, expected_input.input, + expected_input.source_var, expected_input.multiplicity, + expected_input.slot, expected_input.application_slot, + expected_input.breaks_same_step_cycle) + @test only(erased_inputs).plan === expected_input.plan + @test only(erased_inputs).carrier === PSE.refvalue(model_status(model, 1), :x) + end +end + end From 029b0969e8bc8c2c36bd835fe69d4cf7565e66c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 23:02:43 +0100 Subject: [PATCH 050/324] Load the analyzer guard during Pkg cache probes Use the logging API already provided by Base instead of importing a package before Pkg has initialized LOAD_PATH. Preserve the same logger methods and add the actual empty-LOAD_PATH cache-flags subprocess as a regression. All 18 assertions across seven real child-process cases pass on Julia 1.12.7; the original six analyzer-error cases remain unchanged. --- .github/scripts/require_complete_jet.jl | 4 +++- .github/scripts/test_require_complete_jet.jl | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/scripts/require_complete_jet.jl b/.github/scripts/require_complete_jet.jl index 7aaf119bb..c27850cc6 100644 --- a/.github/scripts/require_complete_jet.jl +++ b/.github/scripts/require_complete_jet.jl @@ -1,7 +1,9 @@ # Loaded in the full XPalm test subprocess before JET creates analysis tasks. module JETAnalysisGuard -using Logging +# Pkg probes cache flags with an empty LOAD_PATH before loading packages. +using Base.CoreLogging: AbstractLogger, global_logger +const Logging = Base.CoreLogging struct AnalyzerErrorLogger{L<:AbstractLogger} <: AbstractLogger inner::L diff --git a/.github/scripts/test_require_complete_jet.jl b/.github/scripts/test_require_complete_jet.jl index 525e7c056..5a4ef5dc5 100644 --- a/.github/scripts/test_require_complete_jet.jl +++ b/.github/scripts/test_require_complete_jet.jl @@ -11,6 +11,17 @@ function guarded_case(packages, source) return (code=process.exitcode, output=String(take!(output)), errors=String(take!(errors))) end +@testset "Pkg cache-flag probe with an empty LOAD_PATH" begin + output, errors = IOBuffer(), IOBuffer() + command = `$(Base.julia_cmd()) --code-coverage=none --color=yes --check-bounds=yes --warn-overwrite=yes --depwarn=yes --inline=yes --startup-file=no --track-allocation=none --load=$GUARD --eval 'show(ccall(:jl_cache_flags, UInt8, ()))'` + process = run(pipeline(ignorestatus(addenv(command, "JULIA_LOAD_PATH" => "")); + stdout=output, stderr=errors)) + cache_flags = (code=process.exitcode, output=String(take!(output)), errors=String(take!(errors))) + @test cache_flags.code == 0 + @test cache_flags.output == sprint(show, parse(UInt8, cache_flags.output)) + @test isempty(cache_flags.errors) +end + @testset "incomplete JET analysis fails its test subprocess" begin mktempdir() do packages source_dir = mkpath(joinpath(packages, "JET", "src")) From 0be31f562f240e18b173c7a3952719d4ffb9fdac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 23:22:37 +0100 Subject: [PATCH 051/324] Isolate saved declaration errors from inference aliases Use one cold nonspecializing throw helper for saved port and contract failures. Preserve the original exception object, stored backtrace, cached metadata and callback counts. Under the same strict Julia 1.12.7/JET control, the exact a5 baseline fails and the one-file helper candidate passes without internal errors. Four maintained files and Aqua pass 641 assertions; the final integrated regression file passes 288 assertions, including 102 identity and trace checks. --- src/composite_model/authored_ports.jl | 10 ++++- test/test-model-authored-port-inventory.jl | 46 ++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl index dbb8c05bf..5e530ae88 100644 --- a/src/composite_model/authored_ports.jl +++ b/src/composite_model/authored_ports.jl @@ -14,10 +14,16 @@ function Base.deepcopy_internal(failure::ScenarioPreparationFailure, stack::IdDi end end +# Diagnostic failures retain their original payload; only the cold throw +# operand crosses the inference boundary. +Base.@noinline Base.@nospecializeinfer function _throw_preparation_error(@nospecialize(exception)) + throw(exception) +end + struct AuthoredPortNames{NAMES} end AuthoredPortNames(names::Tuple{Vararg{Symbol}}) = AuthoredPortNames{names}() _authored_port_names(::AuthoredPortNames{NAMES}) where {NAMES} = NAMES -_authored_port_names(failure::ScenarioPreparationFailure) = throw(failure.error) +_authored_port_names(failure::ScenarioPreparationFailure) = _throw_preparation_error(failure.error) struct AuthoredOutputPorts{ALL,LOCAL,DISTRIBUTED,CANONICAL} end function AuthoredOutputPorts(all_names, local_names, distributed_names, canonical_names) @@ -55,7 +61,7 @@ Base.propertynames(ports::AuthoredPortInventory) = (fieldnames(typeof(ports))..., :input_names, :environment_input_names, :environment_output_names) _authored_metadata_value(value) = value -_authored_metadata_value(failure::ScenarioPreparationFailure) = throw(failure.error) +_authored_metadata_value(failure::ScenarioPreparationFailure) = _throw_preparation_error(failure.error) function _capture_authored_metadata(operation, phase::Symbol, application_id::Union{Nothing,Symbol}) try diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index f18b1823c..589d8642b 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -460,4 +460,50 @@ PSE.run!(::NativeMetadataProbe, status, environment, constants, context) = (stat end end +module CapturedPreparationErrorIdentityChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine + +mutable struct TaggedHookError <: Exception + marker::Symbol +end +Base.showerror(io::IO, error::TaggedHookError) = print(io, "saved hook error: ", error.marker) + +@testset "saved declaration errors keep identity and original traces" begin + for error in (ErrorException("saved declaration"), + MethodError(identity, (1, 2)), TaggedHookError(:original)) + calls = Ref(0) + failure = PSE._capture_authored_metadata(:input_ports, :identity) do + calls[] += 1 + throw(error) + end + original_backtrace = failure.backtrace + original_frames = copy(original_backtrace) + message = sprint(showerror, error) + @test calls[] == 1 + @test !isempty(original_backtrace) + for reader in (PSE._authored_port_names, PSE._authored_metadata_value), _ in 1:2 + caught = try + reader(failure) + nothing + catch exception + exception + end + @test caught === error + @test sprint(showerror, caught) == message + @test failure.error === error + @test failure.backtrace === original_backtrace + @test failure.backtrace == original_frames + @test (failure.phase, failure.application_id) == (:input_ports, :identity) + @test calls[] == 1 + end + copied = deepcopy(failure) + @test copied.error === error + @test copied.backtrace !== original_backtrace + @test copied.backtrace == original_frames + @test calls[] == 1 + end +end +end + end From a3a8f9f83d79828fc9df426d9b1e708178e1d5d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 7 Nov 2026 23:54:31 +0100 Subject: [PATCH 052/324] Keep the analyzer runtime out of dependency precompilation Use a small load bootstrap that installs the unchanged analyzer logger only outside output generation. Dependency precompilers continue normally without creating a new Main module. Validated under Julia 1.12.7 with 23 assertions across eight real child processes and a complete offline Pkg.test that precompiles a local stub before running five test assertions. --- .github/scripts/jet_analysis_guard_runtime.jl | 57 ++++++++++++++++++ .github/scripts/require_complete_jet.jl | 60 ++----------------- .github/scripts/test_require_complete_jet.jl | 27 +++++++++ 3 files changed, 88 insertions(+), 56 deletions(-) create mode 100644 .github/scripts/jet_analysis_guard_runtime.jl diff --git a/.github/scripts/jet_analysis_guard_runtime.jl b/.github/scripts/jet_analysis_guard_runtime.jl new file mode 100644 index 000000000..c27850cc6 --- /dev/null +++ b/.github/scripts/jet_analysis_guard_runtime.jl @@ -0,0 +1,57 @@ +# Loaded in the full XPalm test subprocess before JET creates analysis tasks. +module JETAnalysisGuard + +# Pkg probes cache flags with an empty LOAD_PATH before loading packages. +using Base.CoreLogging: AbstractLogger, global_logger +const Logging = Base.CoreLogging + +struct AnalyzerErrorLogger{L<:AbstractLogger} <: AbstractLogger + inner::L + errors::Threads.Atomic{Int} +end + +is_analyzer_error(level, source) = + level >= Logging.Error && source isa Module && first(Base.fullname(source)) === :JET + +Logging.min_enabled_level(logger::AnalyzerErrorLogger) = + min(Logging.Error, Logging.min_enabled_level(logger.inner)) + +function Logging.shouldlog(logger::AnalyzerErrorLogger, level, source, group, id) + return is_analyzer_error(level, source) || + (level >= Logging.min_enabled_level(logger.inner) && + Logging.shouldlog(logger.inner, level, source, group, id)) +end + +Logging.catch_exceptions(logger::AnalyzerErrorLogger) = + Logging.catch_exceptions(logger.inner) + +function Logging.handle_message( + logger::AnalyzerErrorLogger, level, message, source, group, id, file, line; kwargs..., +) + if is_analyzer_error(level, source) + Threads.atomic_add!(logger.errors, 1) + end + if level >= Logging.min_enabled_level(logger.inner) && + Logging.shouldlog(logger.inner, level, source, group, id) + Logging.handle_message(logger.inner, level, message, source, group, id, file, line; kwargs...) + end + return nothing +end + +function install!() + logger = AnalyzerErrorLogger(global_logger(), Threads.Atomic{Int}(0)) + global_logger(logger) + atexit() do exit_code + count = logger.errors[] + if count > 0 + println(stderr, "JET analysis incomplete: ", count, " internal analyzer error(s).") + # Julia catches exceptions from exit hooks; failing requires exit(). + exit(iszero(exit_code) ? 1 : exit_code) + end + end + return nothing +end + +end + +JETAnalysisGuard.install!() diff --git a/.github/scripts/require_complete_jet.jl b/.github/scripts/require_complete_jet.jl index c27850cc6..829742c63 100644 --- a/.github/scripts/require_complete_jet.jl +++ b/.github/scripts/require_complete_jet.jl @@ -1,57 +1,5 @@ -# Loaded in the full XPalm test subprocess before JET creates analysis tasks. -module JETAnalysisGuard - -# Pkg probes cache flags with an empty LOAD_PATH before loading packages. -using Base.CoreLogging: AbstractLogger, global_logger -const Logging = Base.CoreLogging - -struct AnalyzerErrorLogger{L<:AbstractLogger} <: AbstractLogger - inner::L - errors::Threads.Atomic{Int} +# Pkg forwards --load to cache probes, dependency precompilers, and test runners. +# Defining a runtime module in Main is invalid while an incremental image is built. +if !Base.generating_output() + include(joinpath(@__DIR__, "jet_analysis_guard_runtime.jl")) end - -is_analyzer_error(level, source) = - level >= Logging.Error && source isa Module && first(Base.fullname(source)) === :JET - -Logging.min_enabled_level(logger::AnalyzerErrorLogger) = - min(Logging.Error, Logging.min_enabled_level(logger.inner)) - -function Logging.shouldlog(logger::AnalyzerErrorLogger, level, source, group, id) - return is_analyzer_error(level, source) || - (level >= Logging.min_enabled_level(logger.inner) && - Logging.shouldlog(logger.inner, level, source, group, id)) -end - -Logging.catch_exceptions(logger::AnalyzerErrorLogger) = - Logging.catch_exceptions(logger.inner) - -function Logging.handle_message( - logger::AnalyzerErrorLogger, level, message, source, group, id, file, line; kwargs..., -) - if is_analyzer_error(level, source) - Threads.atomic_add!(logger.errors, 1) - end - if level >= Logging.min_enabled_level(logger.inner) && - Logging.shouldlog(logger.inner, level, source, group, id) - Logging.handle_message(logger.inner, level, message, source, group, id, file, line; kwargs...) - end - return nothing -end - -function install!() - logger = AnalyzerErrorLogger(global_logger(), Threads.Atomic{Int}(0)) - global_logger(logger) - atexit() do exit_code - count = logger.errors[] - if count > 0 - println(stderr, "JET analysis incomplete: ", count, " internal analyzer error(s).") - # Julia catches exceptions from exit hooks; failing requires exit(). - exit(iszero(exit_code) ? 1 : exit_code) - end - end - return nothing -end - -end - -JETAnalysisGuard.install!() diff --git a/.github/scripts/test_require_complete_jet.jl b/.github/scripts/test_require_complete_jet.jl index 5a4ef5dc5..35af6bee3 100644 --- a/.github/scripts/test_require_complete_jet.jl +++ b/.github/scripts/test_require_complete_jet.jl @@ -22,6 +22,33 @@ end @test isempty(cache_flags.errors) end +@testset "incremental precompilation leaves Main untouched" begin + mktempdir() do directory + input = joinpath(directory, "GuardPrecompileProbe.jl") + cache = joinpath(directory, "probe.ji") + object = joinpath(directory, "probe.o") + write(input, "module GuardPrecompileProbe; value() = 42; end") + source = """ + @assert Base.generating_output(true) + @assert !isdefined(Main, :JETAnalysisGuard) + Base.include_package_for_output(Base.PkgId("GuardPrecompileProbe"), ARGS[1], + copy(DEPOT_PATH), copy(Base.DL_LOAD_PATH), copy(LOAD_PATH), + Base._concrete_dependencies, nothing) + """ + output, errors = IOBuffer(), IOBuffer() + command = `$(Base.julia_cmd()) --startup-file=no --output-incremental=yes --output-ji=$cache --output-o=$object --load=$GUARD --eval $source $input` + process = run(pipeline(ignorestatus(command); stdout=output, stderr=errors)) + incremental = (code=process.exitcode, output=String(take!(output)), errors=String(take!(errors))) + @test incremental.code == 0 + @test isempty(incremental.errors) + @test isfile(cache) && filesize(cache) > 0 + @test isfile(object) && filesize(object) > 0 + if isfile(cache) + @test !iszero(open(Base.isvalid_cache_header, cache)) + end + end +end + @testset "incomplete JET analysis fails its test subprocess" begin mktempdir() do packages source_dir = mkpath(joinpath(packages, "JET", "src")) From 3164bd52c1f0e696478cf28ae5268c4a937077fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 00:50:57 +0100 Subject: [PATCH 053/324] Preserve finite environment plan families through lifecycle refresh Prepare normalized environment plan witnesses before the first binding pass and keep the same policy through partial refreshes, full invalidation, and checkpoints. Ordinary preparation remains open and uses the same constructors and providers. Validate concrete registry identities without capturing an existential binding. Validated the exact source with 2,002 assertions across six whole test files plus Aqua, including mixed identities, zero-target plans, provider counters, partial/full invalidation, and deepcopy/serialization. Complete native XPalm qualification remains pending. --- src/composite_model/compilation.jl | 4 +- src/composite_model/environment_bindings.jl | 226 +++++++--- src/composite_model/registry_topology.jl | 7 +- src/composite_model/runtime_outputs.jl | 15 +- src/visualization/model_graph_view.jl | 1 + test/test-model-binding-index-identities.jl | 24 ++ ...test-model-environment-binding-identity.jl | 393 +++++++++++++----- 7 files changed, 503 insertions(+), 167 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 36c198e11..05d0cc3a2 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1800,10 +1800,12 @@ Base.propertynames(binding::CompiledEnvironmentBinding) = ( # Share one heap identity across typed simulation fields and context caches. # Providers and cache contents keep their existing live sampling semantics. -mutable struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C} +mutable struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C,S} const model::SC const application_plans::AP const application_plans_by_id::API + # nothing is the stable open policy; closed metadata holds only Val{PlanType}. + const application_plan_schema::S const bindings::B const by_target::I const positions_by_target::PI diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index e90c65bf2..09b56325a 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -185,6 +185,7 @@ function _compile_environment_application_plans( applications; previous_plans_by_id=nothing, prepare_runtime::Bool=true, + plan_schema=nothing, ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() @@ -242,6 +243,7 @@ function _compile_environment_application_plans( backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, ), ) + _with_environment_plan(identity, plan_schema, plan) push!(plans, plan) haskey(plans_by_id, application.id) && error( "Environment application-plan compilation produced duplicate application id `$(application.id)`.", @@ -251,36 +253,89 @@ function _compile_environment_application_plans( return plans, plans_by_id end +# Open owners retain the same type when their live configuration changes. +_environment_plan_schema(::Nothing) = nothing +_environment_plan_schema(owner::CompiledEnvironmentBindings) = owner.application_plan_schema + +# The default preparation inherits its owner. Collection explicitly stays open; +# a fixed native schema is supplied before the first compilation of its plans. +_preparation_environment_plan_schema(::Nothing, cached) = _environment_plan_schema(cached) +_preparation_environment_plan_schema(::Val{:collect}, cached) = nothing +_preparation_environment_plan_schema(schema::CompiledMetadataTable, cached) = schema + +@inline _with_environment_plan(f, ::Nothing, plan) = f(plan) +@generated function _with_environment_plan(f::F, schema::CompiledMetadataTable{T}, + plan::CompiledEnvironmentApplicationPlan, +) where {F,T} + branches = Expr[] + for Witness in fieldtypes(T) + Witness <: Val || error("Environment-plan metadata must contain type witnesses only.") + P = only(Witness.parameters) + P isa DataType && isconcretetype(P) && P <: CompiledEnvironmentApplicationPlan || + error("Environment-plan metadata needs actual concrete normalized plan types.") + push!(branches, :(plan isa $P && return f(plan::$P))) + end + return quote + $(branches...) + throw(ArgumentError(string("The normalized environment plan for application `", + getfield(plan, :application_id), + "` is outside its prepared family schema. Prepare a new compilation schema for this configuration."))) + end +end + +# Host-only reconstruction from TYPES already observed in collection worlds. +# Their union must cover the initial and future normalized plan families. +function _environment_plan_schema_from_types(observed_types) + plan_types = unique(observed_types) + all(P -> P isa DataType && isconcretetype(P) && P <: CompiledEnvironmentApplicationPlan, + plan_types) || throw(ArgumentError("Supply actual observed normalized plan types.")) + witnesses = Tuple(Val(P) for P in plan_types) + names = ntuple(index -> Symbol(:environment_plan_, index), length(witnesses)) + return CompiledMetadataTable(NamedTuple{names}(witnesses)) +end + +function _retype_environment_plan_owner(compiled, owner, schema) + for plan in owner.application_plans + _with_environment_plan(identity, schema, plan) + end + return _compiled_environment_bindings(owner.model, compiled, + owner.application_plans, owner.application_plans_by_id, + owner.bindings, owner.by_target, owner.sample_cache, + owner.positions_by_target, owner.targets_by_object; plan_schema=schema) +end + function _compile_environment_bindings_for_applications( model::CompositeModel, applications, - plans_by_id, + plans_by_id; + plan_schema=nothing, ) bindings = CompiledEnvironmentBinding[] for application in applications - plan = plans_by_id[application.id] - for object_id in application.target_ids - object = _model_object(model, object_id) - context = _object_environment_context(application, object, object_id) - binding_object, geometry_source_object_id, geometry_source = - _environment_binding_object(model, object) - handle = bind_environment( - plan.backend, - binding_object, - context, - _environment_config_payload(plan.config), - ) - push!( - bindings, - CompiledEnvironmentBinding( - plan, - object_id, - handle, + _with_environment_plan(plan_schema, plans_by_id[application.id]) do plan + for object_id in application.target_ids + object = _model_object(model, object_id) + context = _object_environment_context(application, object, object_id) + binding_object, geometry_source_object_id, geometry_source = + _environment_binding_object(model, object) + handle = bind_environment( + plan.backend, + binding_object, context, - geometry_source_object_id, - geometry_source, - ), - ) + _environment_config_payload(plan.config), + ) + push!( + bindings, + CompiledEnvironmentBinding( + plan, + object_id, + handle, + context, + geometry_source_object_id, + geometry_source, + ), + ) + end end end return bindings @@ -289,42 +344,49 @@ end function _compile_environment_bindings( model::CompositeModel, compiled::CompiledCompositeModel, - plans_by_id, + plans_by_id; + plan_schema=nothing, ) return _compile_environment_bindings_for_applications( model, compiled.applications, - plans_by_id, + plans_by_id; + plan_schema, ) end -function _validate_model_environment_inputs!(bindings, applications_by_id) +function _validate_model_environment_inputs!(bindings, applications_by_id, + ::Type{I}; plan_schema=nothing, +) where {I<:ObjectId} missing_details = String[] for binding in bindings plan = getfield(binding, :plan)::CompiledEnvironmentApplicationPlan - application_id = getfield(plan, :application_id) - no_inputs = _with_metadata_entry(applications_by_id, application_id) do application - isempty(_model_environment_input_names(application)) - end - no_inputs && continue - available = environment_variables(binding.backend) - isnothing(available) && continue - application = applications_by_id[binding.application_id] - for (target, source) in binding.sampling_rules - source in available && continue - push!(missing_details, string( - binding.application_id, - "/", - binding.object_id.value, - " (", - application.process, - ") needs `", - target, - "` from source `", - source, - "`; available=", - Tuple(sort!(collect(available); by=string)), - )) + object_id = getfield(binding, :object_id)::I + _with_environment_plan(plan_schema, plan) do plan + application_id = getfield(plan, :application_id) + no_inputs = _with_metadata_entry(applications_by_id, application_id) do application + isempty(_model_environment_input_names(application)) + end + no_inputs && return nothing + available = environment_variables(plan.backend) + isnothing(available) && return nothing + application = applications_by_id[application_id] + for (target, source) in plan.sampling_rules + source in available && continue + push!(missing_details, string( + application_id, + "/", + object_id.value, + " (", + application.process, + ") needs `", + target, + "` from source `", + source, + "`; available=", + Tuple(sort!(collect(available); by=string)), + )) + end end end isempty(missing_details) && return nothing @@ -373,12 +435,14 @@ function _compiled_environment_bindings( ), targets_by_object=_index_environment_targets_by_object( bindings, keytype(model.registry.objects), - ), + ); + plan_schema=nothing, ) return CompiledEnvironmentBindings( model, application_plans, application_plans_by_id, + plan_schema, bindings, by_target, positions_by_target, @@ -436,15 +500,24 @@ function _index_environment_bindings(bindings, ::Type{I}) where {I<:ObjectId} end function compile_environment_bindings(model::CompositeModel, compiled::CompiledCompositeModel=refresh_bindings!(model)) + cached = getfield(model, :environment_binding_cache)::Union{Nothing,CompiledEnvironmentBindings} + return _compile_environment_binding_owner(model, compiled, _environment_plan_schema(cached)) +end + +function _compile_environment_binding_owner(model::CompositeModel, + compiled::CompiledCompositeModel, plan_schema, +) _update_model_environment_indices!(model, compiled) application_plans, application_plans_by_id = - _compile_environment_application_plans(model, compiled.applications) + _compile_environment_application_plans(model, compiled.applications; plan_schema) bindings = _compile_environment_bindings( model, compiled, - application_plans_by_id, + application_plans_by_id; + plan_schema, ) - _validate_model_environment_inputs!(bindings, compiled.applications_by_id) + _validate_model_environment_inputs!(bindings, compiled.applications_by_id, + keytype(model.registry.objects); plan_schema) by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, @@ -452,7 +525,8 @@ function compile_environment_bindings(model::CompositeModel, compiled::CompiledC application_plans, application_plans_by_id, bindings, - by_target, + by_target; + plan_schema, ) end @@ -495,6 +569,7 @@ function _reconciled_environment_application_plans( model, compiled.applications; previous_plans_by_id=cached.application_plans_by_id, + plan_schema=cached.application_plan_schema, ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() @@ -575,9 +650,12 @@ function _reconcile_environment_binding_metadata( cached.by_target, cached.sample_cache, cached.positions_by_target, - cached.targets_by_object, + cached.targets_by_object; + plan_schema=cached.application_plan_schema, ) - _validate_model_environment_inputs!(bindings, compiled.applications_by_id) + _validate_model_environment_inputs!(bindings, compiled.applications_by_id, + keytype(model.registry.objects); + plan_schema=cached.application_plan_schema) by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, @@ -586,7 +664,8 @@ function _reconcile_environment_binding_metadata( application_plans_by_id, bindings, by_target, - cached.sample_cache, + cached.sample_cache; + plan_schema=cached.application_plan_schema, ) end @@ -627,7 +706,8 @@ function _refresh_environment_bindings_for_objects( for binding in _compile_environment_bindings_for_applications( model, (partial_application,), - cached.application_plans_by_id, + cached.application_plans_by_id; + plan_schema=cached.application_plan_schema, ) replacements[( binding.application_id, @@ -640,6 +720,8 @@ function _refresh_environment_bindings_for_objects( _validate_model_environment_inputs!( values(replacements), compiled.applications_by_id, + keytype(model.registry.objects); + plan_schema=cached.application_plan_schema, ) for target in stale_targets @@ -686,7 +768,8 @@ function _refresh_environment_bindings_for_objects( cached.by_target, cached.sample_cache, cached.positions_by_target, - cached.targets_by_object, + cached.targets_by_object; + plan_schema=cached.application_plan_schema, ) end @@ -726,7 +809,7 @@ function refresh_environment_bindings!(model::CompositeModel, compiled=refresh_b return _refresh_environment_bindings!(model, compiled, cached; force) end -# Canonical model caches keep the same container schema: plan/binding Vectors, +# Open canonical model caches keep the same container schema: plan/binding Vectors, # Symbol/target/object Dicts, the sample Dict, and SC == typeof(model). Backends, # handles, remapping, and alternate compiled applications remain values inside # those containers. Targeted partial shells are never installed in this cache. @@ -740,17 +823,30 @@ end function _refresh_environment_bindings!(model::CompositeModel, compiled, cached::Union{Nothing,CompiledEnvironmentBindings}; force::Bool=false, + plan_schema=_environment_plan_schema(cached), ) - if force || model.environment_bindings_dirty || isnothing(cached) + policy_changed = !isnothing(cached) && cached.application_plan_schema !== plan_schema + if policy_changed && !force && !model.environment_bindings_dirty && + cached.model_revision == compiled.revision && + cached.environment_revision == model.environment_revision && + cached.compiled_applications === compiled.applications + # Only the policy changes: validate current normalized values and retain + # every existing handle/container, without replaying provider code. + refreshed = _retype_environment_plan_owner(compiled, cached, plan_schema) + model.environment_binding_cache = refreshed + _record_runtime_owner_replacement!(model, cached, refreshed) + return refreshed + end + if force || model.environment_bindings_dirty || isnothing(cached) || policy_changed delta = model.lifecycle_delta - refreshed = if !force && !isnothing(cached) && !delta.full_environment + refreshed = if !force && !policy_changed && !isnothing(cached) && !delta.full_environment # A public Advanced refresh may have prepared another application # set. Reconcile that current owner before using its plans for a # partial event in this compiled scene. partial_owner = cached.compiled_applications === compiled.applications ? cached : _reconcile_environment_binding_metadata(model, compiled, cached) if isnothing(partial_owner) - compile_environment_bindings(model, compiled) + _compile_environment_binding_owner(model, compiled, plan_schema) else _refresh_environment_bindings_for_objects( model, @@ -760,7 +856,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, ) end else - compile_environment_bindings(model, compiled) + _compile_environment_binding_owner(model, compiled, plan_schema) end model.environment_binding_cache = refreshed _record_runtime_owner_replacement!(model, cached, refreshed) @@ -774,7 +870,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, else reconciled = _reconcile_environment_binding_metadata(model, compiled, cached) refreshed = isnothing(reconciled) ? - compile_environment_bindings(model, compiled) : reconciled + _compile_environment_binding_owner(model, compiled, plan_schema) : reconciled model.environment_binding_cache = refreshed _record_runtime_owner_replacement!(model, cached, refreshed) return refreshed diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 8abb0aa9f..9d7c3062a 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -889,7 +889,12 @@ function _mark_environment_bindings_dirty!( delta.mutation_generation += UInt64(1) ids = _lifecycle_object_ids(object_ids) if isnothing(ids) || isnothing(model.environment_binding_cache) - model.environment_binding_cache = nothing + cached = model.environment_binding_cache + # Retain a closed owner's fixed policy while dirty; full_environment + # still forces every handle to be rebuilt before the next execution. + closed = cached isa CompiledEnvironmentBindings && + getfield(cached, :application_plan_schema) isa CompiledMetadataTable + model.environment_binding_cache = closed ? cached : nothing delta.full_environment = true elseif !delta.full_environment union!(delta.environment_dirty_ids, ids) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f651f2c7b..6c7a031e3 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5777,9 +5777,12 @@ function _targeted_call_environment_bindings( partial = _compile_environment_bindings_for_applications( model, applications, - cached.application_plans_by_id, + cached.application_plans_by_id; + plan_schema=cached.application_plan_schema, ) - _validate_model_environment_inputs!(partial, applications_by_id) + _validate_model_environment_inputs!(partial, applications_by_id, + keytype(model.registry.objects); + plan_schema=cached.application_plan_schema) by_target = _index_environment_bindings(partial, keytype(model.registry.objects)) return _compiled_environment_bindings( model, @@ -5788,7 +5791,8 @@ function _targeted_call_environment_bindings( cached.application_plans_by_id, partial, by_target, - cached.sample_cache, + cached.sample_cache; + plan_schema=cached.application_plan_schema, ) end @@ -7822,6 +7826,7 @@ function _prepare_simulation!( constants, outputs, performance::Bool=false, + environment_plan_schema=nothing, ) performance_counters = performance ? RuntimePerformanceCounters() : nothing initial_composite_started_at = @@ -7891,7 +7896,9 @@ function _prepare_simulation!( length(compiled.call_bindings), ) started_at = _runtime_performance_start(performance_counters) - env_bindings = refresh_environment_bindings!(model, compiled) + cached_environment = getfield(model, :environment_binding_cache)::Union{Nothing,CompiledEnvironmentBindings} + plan_schema = _preparation_environment_plan_schema(environment_plan_schema, cached_environment) + env_bindings = _refresh_environment_bindings!(model, compiled, cached_environment; plan_schema) _runtime_performance_finish!( performance_counters, :initial_environment_compile, diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index df9801942..2577d36fe 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -342,6 +342,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) _validate_model_environment_inputs!( environment_bindings, Dict(application.id => application for application in applications), + keytype(model.registry.objects), ) end diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index f659d9042..cec60e787 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -546,4 +546,28 @@ end end end +@testset "environment validation captures the registry identity family" begin + for closed in (false, true) + data = call_fixture(closed) + model = data.model + simulation = data.simulation + owner = simulation.environment_bindings + bindings = owner.bindings + I = keytype(model.registry.objects) + schema = PSE._environment_plan_schema_from_types(typeof(plan) for plan in owner.application_plans) + references = (PSE.refvalue(model_status(model, 1), :x), + PSE.refvalue(model_status(model, :leaf), :x)) + states = (NamedTuple(model_status(model, 1)), NamedTuple(model_status(model, :leaf))) + ids = [binding.object_id for binding in bindings] + for table in (simulation.compiled.applications_by_id, + Dict(application.id => application for application in simulation.compiled.applications)) + @test PSE._validate_model_environment_inputs!(bindings, table, I; plan_schema=schema) === nothing + @test [binding.object_id for binding in bindings] == ids + @test PSE.refvalue(model_status(model, 1), :x) === references[1] + @test PSE.refvalue(model_status(model, :leaf), :x) === references[2] + @test (NamedTuple(model_status(model, 1)), NamedTuple(model_status(model, :leaf))) == states + end + end +end + end diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index e2cba854f..f7c4afe22 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -53,7 +53,7 @@ function PSE.run!(::Leaf, status, environment, constants, context) return nothing end -function fixture(::Type{T}) where {T} +function fixture(::Type{T}; steps=1, environment_plan_schema=nothing) where {T} capture = Ref{Any}() backend = Backend(Dict(:a => T(10), :b => T(20)), 0) model = CompositeModel( @@ -69,13 +69,25 @@ function fixture(::Type{T}) where {T} ModelSpec(Leaf(zero(T)); name=:manual_probe, on=Many(kind=:manual), environment=Environment(provider=:shell_probe)), ), environment=backend) - simulation = run!(model; steps=1, outputs=:all) + simulation = if isnothing(environment_plan_schema) + run!(model; steps, outputs=:all) + else + prepared = PSE._prepare_simulation!(model; steps, outputs=:all, + constants=PSE.Constants(), environment_plan_schema) + PSE._continue_scene!(prepared, steps) + end batch = only(batch for batch in simulation.execution_plan.batches if batch.application.id == :scheduled_probe) kept = only(target for target in batch.targets if target.object_id == ObjectId(:scheduled_keep)) return (; model, simulation, capture, backend, batch, kept) end +function fixture_plan_schema(::Type{T}) where {T} + initial = fixture(T; steps=0) + return PSE._environment_plan_schema_from_types( + typeof(plan) for plan in initial.simulation.environment_bindings.application_plans) +end + function checkpoint_copy(simulation) buffer = IOBuffer() serialize(buffer, simulation) @@ -84,8 +96,8 @@ function checkpoint_copy(simulation) end @testset "checkpointed environment owners preserve application identity" begin - for copy_simulation in (deepcopy, checkpoint_copy) - data = fixture(Float32) + for schema in (nothing, fixture_plan_schema(Float32)), copy_simulation in (deepcopy, checkpoint_copy) + data = fixture(Float32; environment_plan_schema=schema) simulation = data.simulation original_context = data.capture[] original_targets = only(original_context.calls) @@ -100,6 +112,10 @@ end if group.application.id === :owner) context = only(only(owner.batches).targets).context targets = only(context.calls) + @test typeof(environment_bindings.application_plan_schema) === + typeof(simulation.environment_bindings.application_plan_schema) + @test context.environment_bindings.application_plan_schema === + environment_bindings.application_plan_schema cached_batches = PSE._cached_call_execution_batches(targets) @test !isnothing(cached_batches) @@ -268,56 +284,61 @@ end end @testset "the typed boundary selects the current model cache after public refresh" begin - data = fixture(Float32) - simulation = data.simulation - prepared = simulation.environment_bindings - @test PSE._current_environment_binding_owner(data.model, prepared) === prepared + for schema in (nothing, fixture_plan_schema(Float32)) + data = fixture(Float32; environment_plan_schema=schema) + simulation = data.simulation + prepared = simulation.environment_bindings + @test PSE._current_environment_binding_owner(data.model, prepared) === prepared - move_object!(data.model, :scheduled_move, (cell=:b,)) - partial = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) - current = PSE._current_environment_binding_owner(data.model, prepared) - is_current_partial = current === partial && current !== prepared - @test is_current_partial - @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b - @test all(binding -> binding.backend === data.backend, current.bindings) - samples = data.backend.samples - clean = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) - same_clean = clean === partial - @test same_clean - @test data.backend.samples == samples + move_object!(data.model, :scheduled_move, (cell=:b,)) + partial = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + current = PSE._current_environment_binding_owner(data.model, prepared) + is_current_partial = current === partial && current !== prepared + @test is_current_partial + @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b + @test all(binding -> binding.backend === data.backend, current.bindings) + samples = data.backend.samples + clean = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) + same_clean = clean === partial + @test same_clean + @test data.backend.samples == samples - mark_environment_binding_dirty!(data.model) - @test isnothing(PSE._current_environment_binding_owner(data.model, prepared)) - full = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) - current = PSE._current_environment_binding_owner(data.model, prepared) - is_current_full = current === full && current !== partial - @test is_current_full - same_schema = typeof(full) === typeof(prepared) - @test same_schema - @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b - - # Advanced compilation may replace model metadata before this Simulation - # resumes. The current cache remains authoritative even for another set of - # applications; the common refresh algorithm reconciles it when requested. - alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( - ModelSpec(Leaf(0.0f0); name=:scheduled_probe, on=Many(kind=:scheduled), - environment=Environment(provider=:shell_probe)), - )) - alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) - current = PSE._current_environment_binding_owner(data.model, prepared) - is_current_alternate = current === alternate && current !== full - @test is_current_alternate - @test length(current.bindings) == 2 - @test current.compiled_applications === alternate_compiled.applications - samples = data.backend.samples - restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) - is_restored = restored === PSE.compiled_environment_bindings(data.model) - @test is_restored - @test restored.compiled_applications === simulation.compiled.applications - @test length(restored.bindings) == 4 - @test all(binding -> binding.backend === data.backend, restored.bindings) - @test restored.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b - @test data.backend.samples == samples + mark_environment_binding_dirty!(data.model) + @test isnothing(schema) ? + isnothing(PSE._current_environment_binding_owner(data.model, prepared)) : + PSE._current_environment_binding_owner(data.model, prepared) === partial + full = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + current = PSE._current_environment_binding_owner(data.model, prepared) + is_current_full = current === full && current !== partial + @test is_current_full + same_schema = typeof(full) === typeof(prepared) + @test same_schema + @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b + + # Advanced compilation may replace model metadata before this Simulation + # resumes. The current cache remains authoritative even for another set of + # applications; the common refresh algorithm reconciles it when requested. + alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( + ModelSpec(Leaf(0.0f0); name=:scheduled_probe, on=Many(kind=:scheduled), + environment=Environment(provider=:shell_probe)), + )) + alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) + current = PSE._current_environment_binding_owner(data.model, prepared) + is_current_alternate = current === alternate && current !== full + @test is_current_alternate + @test length(current.bindings) == 2 + @test current.compiled_applications === alternate_compiled.applications + @test current.application_plan_schema === schema + samples = data.backend.samples + restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) + is_restored = restored === PSE.compiled_environment_bindings(data.model) + @test is_restored + @test restored.compiled_applications === simulation.compiled.applications + @test length(restored.bindings) == 4 + @test all(binding -> binding.backend === data.backend, restored.bindings) + @test restored.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b + @test data.backend.samples == samples + end end @testset "a public refresh cannot hide stale runtime geometry bindings" begin @@ -383,48 +404,51 @@ end end @testset "a pending move reconciles an authoritative Advanced subset cache" begin - data = fixture(Float32) - simulation = data.simulation - alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( - ModelSpec(Leaf(0.0f0); name=:manual_probe, on=Many(kind=:manual), - environment=Environment(provider=:shell_probe)), - )) - alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) - @test length(alternate.bindings) == 1 - @test !haskey(alternate.application_plans_by_id, :scheduled_probe) - move_object!(data.model, :scheduled_move, (cell=:b,)) - samples = data.backend.samples - PSE._refresh_simulation_runtime!(simulation) - @test data.backend.samples == samples - uses_current = simulation.environment_bindings === PSE.compiled_environment_bindings(data.model) - @test uses_current - @test simulation.environment_bindings.compiled_applications === simulation.compiled.applications - @test length(simulation.environment_bindings.bindings) == 4 - handles_current = all(batch -> all(target -> - target.environment_binding.handle === simulation.environment_bindings.by_target[ - (batch.application.id, target.object_id)].handle, batch.targets), - simulation.execution_plan.batches) - @test handles_current - scheduled = only(batch for batch in simulation.execution_plan.batches - if batch.application.id === :scheduled_probe) - target = only(target for target in scheduled.targets - if target.object_id === ObjectId(:scheduled_move)) - @test target.environment_binding.handle.cell === :b - @test target.environment_binding.backend === data.backend - @test model_status(data.model, :scheduled_move).calls == 1 - continue!(simulation) - @test model_status(data.model, :scheduled_move).seen === 20.0f0 - @test model_status(data.model, :scheduled_move).calls == 2 - @test model_status(data.model, :manual).calls == 0 - @test outputs(simulation)[(:scheduled_probe, ObjectId(:scheduled_move), :seen)] == - [(1.0, 10.0f0), (2.0, 20.0f0)] - selected = only(call_targets(data.capture[], :leaves)) - run_call!(selected; publish=false) - @test selected.status.seen === 10.0f0 - @test selected.environment_binding.backend === data.backend - manual_handle_current = selected.environment_binding.handle === - simulation.environment_bindings.by_target[(:manual_probe, ObjectId(:manual))].handle - @test manual_handle_current + for schema in (nothing, fixture_plan_schema(Float32)) + data = fixture(Float32; environment_plan_schema=schema) + simulation = data.simulation + alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( + ModelSpec(Leaf(0.0f0); name=:manual_probe, on=Many(kind=:manual), + environment=Environment(provider=:shell_probe)), + )) + alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) + @test alternate.application_plan_schema === schema + @test length(alternate.bindings) == 1 + @test !haskey(alternate.application_plans_by_id, :scheduled_probe) + move_object!(data.model, :scheduled_move, (cell=:b,)) + samples = data.backend.samples + PSE._refresh_simulation_runtime!(simulation) + @test data.backend.samples == samples + uses_current = simulation.environment_bindings === PSE.compiled_environment_bindings(data.model) + @test uses_current + @test simulation.environment_bindings.compiled_applications === simulation.compiled.applications + @test length(simulation.environment_bindings.bindings) == 4 + handles_current = all(batch -> all(target -> + target.environment_binding.handle === simulation.environment_bindings.by_target[ + (batch.application.id, target.object_id)].handle, batch.targets), + simulation.execution_plan.batches) + @test handles_current + scheduled = only(batch for batch in simulation.execution_plan.batches + if batch.application.id === :scheduled_probe) + target = only(target for target in scheduled.targets + if target.object_id === ObjectId(:scheduled_move)) + @test target.environment_binding.handle.cell === :b + @test target.environment_binding.backend === data.backend + @test model_status(data.model, :scheduled_move).calls == 1 + continue!(simulation) + @test model_status(data.model, :scheduled_move).seen === 20.0f0 + @test model_status(data.model, :scheduled_move).calls == 2 + @test model_status(data.model, :manual).calls == 0 + @test outputs(simulation)[(:scheduled_probe, ObjectId(:scheduled_move), :seen)] == + [(1.0, 10.0f0), (2.0, 20.0f0)] + selected = only(call_targets(data.capture[], :leaves)) + run_call!(selected; publish=false) + @test selected.status.seen === 10.0f0 + @test selected.environment_binding.backend === data.backend + manual_handle_current = selected.environment_binding.handle === + simulation.environment_bindings.by_target[(:manual_probe, ObjectId(:manual))].handle + @test manual_handle_current + end end @testset "retained manual targets use the current public environment owner" begin for force in (false, true) @@ -497,7 +521,7 @@ end tables = (simulation.compiled.applications_by_id, Dict(application.id => application for application in simulation.compiled.applications)) for table in tables - @test PSE._validate_model_environment_inputs!(bindings, table) === nothing + @test PSE._validate_model_environment_inputs!(bindings, table, keytype(model.registry.objects)) === nothing @test backend.inventory_reads == 0 end end @@ -533,7 +557,7 @@ end end for table in tables failure = try - PSE._validate_model_environment_inputs!(bindings, table) + PSE._validate_model_environment_inputs!(bindings, table, keytype(model.registry.objects)) nothing catch exception exception @@ -552,4 +576,181 @@ end end end +# These counters distinguish preparation policy changes from provider work. +mutable struct PlanPolicyBackend{T} <: EA.AbstractEnvironmentBackend + values::NamedTuple{(:T, :U),Tuple{T,T}} + binds::Int + samples::Int +end +mutable struct PlanPolicySource{B} + backend::B + normalizations::Int +end +function EA.environment_backend(source::PlanPolicySource) + source.normalizations += 1 + return source.backend +end +EA.base_step_seconds(::PlanPolicyBackend) = 3600.0 +EA.get_nsteps(::PlanPolicyBackend) = 8 +EA.environment_variables(::PlanPolicyBackend) = Set((:T, :U)) +function EA.bind_environment(backend::PlanPolicyBackend, object::Object, context, config) + backend.binds += 1 + return Handle(isnothing(geometry(object)) ? :a : geometry(object).cell) +end +function EA.sample(backend::PlanPolicyBackend, handle, variable::Symbol, time) + backend.samples += 1 + return getproperty(backend.values, variable) +end +struct PlanPolicyProbe{V,T} <: AbstractEnvironment_Shell_LeafModel + initial::T +end +PSE.inputs_(::PlanPolicyProbe) = NamedTuple() +PSE.outputs_(model::PlanPolicyProbe) = (seen=model.initial, calls=0) +PSE.environment_inputs_(model::PlanPolicyProbe{V}) where {V} = + NamedTuple{(V,)}((model.initial,)) +function PSE.run!(::PlanPolicyProbe{V}, status, environment, constants, context) where {V} + status.seen = getproperty(environment, V) + status.calls += 1 + return nothing +end + +policy_spec(variable; active=true) = ModelSpec(PlanPolicyProbe{variable,Float32}(0f0); + name=:policy_probe, on=Many(kind=active ? :active : :absent)) +function policy_model(variable=:T; active=true) + backend = PlanPolicyBackend((T=10f0, U=20f0), 0, 0) + source = PlanPolicySource(backend, 0) + model = CompositeModel(Object(:leaf; scale=:Leaf, kind=:active, geometry=(cell=:a,)), + Object(1; scale=:Leaf, kind=:active, geometry=(cell=:a,)); + applications=(policy_spec(variable; active),), environment=source) + return (; model, source, backend) +end +function prepare_policy(data; schema=nothing) + return PSE._prepare_simulation!(data.model; steps=0, outputs=:all, + constants=PSE.Constants(), environment_plan_schema=schema) +end +policy_counts(data) = (data.source.normalizations, data.backend.binds, data.backend.samples) +policy_types(simulation) = [typeof(plan) for plan in simulation.environment_bindings.application_plans] + +@testset "fixed environment policies admit plans before any initial bind" begin + initial = policy_model(:T) + first_simulation = prepare_policy(initial; schema=Val(:collect)) + first_types = policy_types(first_simulation) + initial_schema = PSE._environment_plan_schema_from_types(first_types) + @test first_simulation.environment_bindings.application_plan_schema === nothing + for active in (false, true) + missing = policy_model(:U; active) + @test_throws "policy_probe` is outside its prepared family schema" prepare_policy(missing; schema=initial_schema) + @test missing.backend.binds == 0 + @test missing.backend.samples == 0 + end + ordinary = policy_model(:T) + control = prepare_policy(ordinary) + fixed = policy_model(:T) + compiled = prepare_policy(fixed; schema=initial_schema) + @test policy_counts(fixed) == policy_counts(ordinary) + @test fixed.backend.binds == 2 + @test compiled.environment_bindings.application_plan_schema === initial_schema + @test map(binding -> binding.object_id, compiled.environment_bindings.bindings) == + map(binding -> binding.object_id, control.environment_bindings.bindings) + @test Set(binding.object_id for binding in compiled.environment_bindings.bindings) == + Set((ObjectId(:leaf), ObjectId(1))) + @test all(binding -> binding.backend === fixed.backend, compiled.environment_bindings.bindings) + step!(compiled) + step!(control) + @test final_state(compiled, Many()) == final_state(control, Many()) + @test isequal(collect_outputs(compiled), collect_outputs(control)) + @test policy_counts(fixed) == policy_counts(ordinary) +end + +@testset "zero-target plans and observed future families obey the fixed union" begin + a = policy_model(:T; active=false) + simulation = prepare_policy(a; schema=Val(:collect)) + first_types = policy_types(simulation) + first_schema = PSE._environment_plan_schema_from_types(first_types) + alternate = PSE.Advanced.compile_composite_model(a.model, (policy_spec(:U; active=false),)) + future = PSE.Advanced.refresh_environment_bindings!(a.model, alternate; force=true) + @test isempty(future.bindings) + @test future.application_plan_schema === nothing + future_types = [typeof(plan) for plan in future.application_plans] + @test first_types != future_types + b = policy_model(:T; active=false) + fixed = prepare_policy(b; schema=first_schema) + alternate_b = PSE.Advanced.compile_composite_model(b.model, (policy_spec(:U; active=false),)) + @test_throws "policy_probe` is outside its prepared family schema" PSE.Advanced.refresh_environment_bindings!(b.model, alternate_b) + @test b.backend.binds == 0 + union_schema = PSE._environment_plan_schema_from_types(vcat(first_types, future_types)) + c = policy_model(:T; active=false) + admitted = prepare_policy(c; schema=union_schema) + E = typeof(admitted.environment_bindings) + alternate_c = PSE.Advanced.compile_composite_model(c.model, (policy_spec(:U; active=false),)) + current = PSE.Advanced.refresh_environment_bindings!(c.model, alternate_c; force=true) + @test typeof(current) === E + @test current.application_plan_schema === union_schema + @test only(typeof.(current.application_plans)) in future_types + @test only(policy_types(admitted)) in first_types + @test c.backend.binds == c.backend.samples == 0 +end + +@testset "collection can reopen clean and dirty fixed environment owners" begin + observed = prepare_policy(policy_model()) + schema = PSE._environment_plan_schema_from_types(policy_types(observed)) + for dirty in (false, true) + data = policy_model() + simulation = prepare_policy(data; schema) + owner = simulation.environment_bindings + if dirty + mark_environment_binding_dirty!(data.model) + @test data.model.environment_binding_cache === owner + @test PSE.lifecycle_delta(data.model).full_environment + end + before = policy_counts(data) + current = PSE._refresh_environment_bindings!(data.model, simulation.compiled, owner; + plan_schema=nothing) + delta = policy_counts(data) .- before + @test current.application_plan_schema === nothing + @test current.application_plans === owner.application_plans || dirty + @test current.bindings === owner.bindings || dirty + @test data.backend.binds == before[2] + (dirty ? 2 : 0) + if !dirty + @test delta == (0, 0, 0) + @test current.by_target === owner.by_target + @test current.sample_cache === owner.sample_cache + end + # A new host collection ignores an older fixed policy, including a stale + # alternate whose newly normalized family was not in that old schema. + data = policy_model() + previous = prepare_policy(data; schema) + dirty && mark_environment_binding_dirty!(data.model) + collected = prepare_policy(data; schema=Val(:collect)) + @test collected.environment_bindings.application_plan_schema === nothing + alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) + refreshed = PSE.Advanced.refresh_environment_bindings!(data.model, alternate) + @test refreshed.application_plan_schema === nothing + @test only(refreshed.application_plans).compiled_sampling_rules != + only(previous.environment_bindings.application_plans).compiled_sampling_rules + end +end + +@testset "dirty fixed policies survive checkpoints and rebuild handles" begin + schema = fixture_plan_schema(Float32) + for copy_simulation in (deepcopy, checkpoint_copy) + data = fixture(Float32; environment_plan_schema=schema) + move_object!(data.model, :scheduled_move, (cell=:b,)) + mark_environment_binding_dirty!(data.model) + restored = copy_simulation(data.simulation) + retained = restored.environment_bindings + @test restored.model.environment_binding_cache === retained + S = typeof(retained.application_plan_schema) + current = PSE.Advanced.refresh_environment_bindings!(restored.model, restored.compiled) + @test current !== retained + @test typeof(current.application_plan_schema) === S + @test current.application_plan_schema === retained.application_plan_schema + moved = current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))] + @test moved.handle.cell === :b + @test moved.handle !== retained.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle + step!(restored) + @test model_status(restored.model, :scheduled_move).seen === 20f0 + end +end + end From 7dfb696107cdf8885c0e2619e412aab4156e1641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 00:58:31 +0100 Subject: [PATCH 054/324] Capture concrete metadata when constructing environment bindings Pass application identity, process and target IDs into the finite environment-plan callback instead of capturing an application with an existential plan type. Both environment context callers use the same scalar constructor; binding order and providers are unchanged. The exact source passes 1,646 assertions across five whole test files plus Aqua. Complete native qualification remains pending. --- src/composite_model/environment_bindings.jl | 17 ++++++++++------- test/test-model-binding-index-identities.jl | 2 ++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 09b56325a..3f17e9691 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -11,11 +11,11 @@ function _environment_backend_from_config(model::CompositeModel, config) return environment_backend(model.environment) end -function _object_environment_context( - application::CompiledModelApplication, object::Object, object_id::ObjectId, +function _object_environment_context(application_id::Symbol, application_process::Symbol, + object::Object, object_id::ObjectId, ) scale = isnothing(object.scale) ? :Default : object.scale - return EnvironmentContext(application.id, object_id, scale, application.process) + return EnvironmentContext(application_id, object_id, scale, application_process) end """ @@ -312,10 +312,13 @@ function _compile_environment_bindings_for_applications( ) bindings = CompiledEnvironmentBinding[] for application in applications - _with_environment_plan(plan_schema, plans_by_id[application.id]) do plan - for object_id in application.target_ids + application_id = application.id + application_process = application.process + target_ids = application.target_ids + _with_environment_plan(plan_schema, plans_by_id[application_id]) do plan + for object_id in target_ids object = _model_object(model, object_id) - context = _object_environment_context(application, object, object_id) + context = _object_environment_context(application_id, application_process, object, object_id) binding_object, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) handle = bind_environment( @@ -613,7 +616,7 @@ function _reconcile_environment_binding_metadata( old = get(cached.by_target, key, nothing)::Union{Nothing,CompiledEnvironmentBinding} isnothing(old) && return nothing object = _model_object(model, object_id) - context = _object_environment_context(application, object, object_id) + context = _object_environment_context(application.id, application.process, object, object_id) _, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) _same_environment_backend(old.backend, plan.backend) || return nothing diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index cec60e787..a68be1616 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -453,9 +453,11 @@ end @test adapted == collect(source) @test map(typeof, adapted) == map(typeof, source) partial = PSE.CompiledModelApplication(leaf.plan, ObjectId[source...]) + target_ids = partial.target_ids bindings = PSE._compile_environment_bindings_for_applications(model, PSE.CompiledModelApplication[partial], simulation.environment_bindings.application_plans_by_id) + @test partial.target_ids === target_ids @test [binding.object_id for binding in bindings] == collect(source) @test length(bindings) == 2 # The canonical application also owns :outside. @test all(binding.plan === simulation.environment_bindings.application_plans_by_id[:leaf] From 27b1830d23535f7b901a8ce5803258dd227b7e2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 01:17:35 +0100 Subject: [PATCH 055/324] Pass registry identities to graph editor environment validation Update the editor extension call to the same three-argument validator used by the compiler and graph view. Scene and application environment edits can commit again. The complete maintained extension test file passes all 167 assertions; five runtime/source guards also pass. Browser E2E confirmation remains pending. --- ext/PlantSimEngineGraphEditorExt.jl | 1 + 1 file changed, 1 insertion(+) diff --git a/ext/PlantSimEngineGraphEditorExt.jl b/ext/PlantSimEngineGraphEditorExt.jl index 27fa18ce6..2aacbf9e6 100644 --- a/ext/PlantSimEngineGraphEditorExt.jl +++ b/ext/PlantSimEngineGraphEditorExt.jl @@ -184,6 +184,7 @@ function apply_edit!(session::GraphEditorSession, edit::PlantSimEngine.GraphEdit PlantSimEngine._validate_model_environment_inputs!( bindings, Dict(application.id => application for application in report.applications), + keytype(candidate.registry.objects), ) end push!(session.history, session.model) From b6832fdd341486354b3122a899325878e5289df8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 01:25:06 +0100 Subject: [PATCH 056/324] Preserve registry identity types through inherited geometry lookup Check parent and geometry-source identities against the registry domain before lookup. Reuse the same index identity helper for application membership and environment routing, with a general name and no compatibility alias. The exact candidate passes 1,303 terminal assertions across five complete test files plus Aqua, including mixed identities, ancestor geometry, reparenting, movement, and status-reference preservation. Stock native qualification remains pending. --- src/composite_model/compilation.jl | 6 +-- src/composite_model/environment_bindings.jl | 8 ++- src/composite_model/runtime_outputs.jl | 2 +- test/test-application-membership-slots.jl | 4 +- test/test-model-binding-index-identities.jl | 58 +++++++++++++++++++++ 5 files changed, 70 insertions(+), 8 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 05d0cc3a2..bee8ce037 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8627,16 +8627,16 @@ function Base.iterate(slots::ApplicationMembershipSlots, state...) return _application_membership_slot(slots.applications, member), next end -@inline function _application_index_object_id(::AbstractDict{I}, object_id::ObjectId) where {I<:ObjectId} +@inline function _index_object_id(::AbstractDict{I}, object_id::ObjectId) where {I<:ObjectId} object_id isa I || throw(ArgumentError( - "The object identity is outside the compiled application index schema.", + "The object identity is outside the prepared index schema.", )) return object_id::I end function _application_membership_slots(compiled::CompiledCompositeModel, object_id::ObjectId) index = compiled.applications_by_object - id = _application_index_object_id(index, object_id) + id = _index_object_id(index, object_id) return ApplicationMembershipSlots(compiled.applications_by_id, get(index, id, ())) end diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 3f17e9691..e3bace27a 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -31,9 +31,13 @@ handle directly. bind_environment(backend, object::Object, context, config=nothing) = nothing function _environment_binding_object(model::CompositeModel, object::Object) - !isnothing(geometry(object)) && return object, object.id, :self + if !isnothing(geometry(object)) + object_id = _index_object_id(model.registry.objects, object.id) + return object, object_id, :self + end ancestor_id = object.parent while !isnothing(ancestor_id) + ancestor_id = _index_object_id(model.registry.objects, ancestor_id) ancestor = _model_object(model, ancestor_id) if !isnothing(geometry(ancestor)) proxy = Object( @@ -48,7 +52,7 @@ function _environment_binding_object(model::CompositeModel, object::Object) status=object.status, applications=object.applications, ) - return proxy, ancestor.id, :ancestor + return proxy, ancestor_id, :ancestor end ancestor_id = ancestor.parent end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 6c7a031e3..cd31de808 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7285,7 +7285,7 @@ function _refresh_simulation_runtime!(simulation::Simulation) # The lifecycle set can contain heterogeneous IDs. Capture the # canonical index's identity schema inside this query instead # of an existential ObjectId in the application callback. - let object_id = _application_index_object_id( + let object_id = _index_object_id( simulation.compiled.applications_by_object, dirty_object_id, ) diff --git a/test/test-application-membership-slots.jl b/test/test-application-membership-slots.jl index 6bf54445e..04237d9bd 100644 --- a/test/test-application-membership-slots.jl +++ b/test/test-application-membership-slots.jl @@ -65,8 +65,8 @@ end closed = PSE._closed_object_family_store(model.registry.objects) index = PSE._applications_by_object(compiled.applications, closed) @test keytype(index) === ObjectId{Symbol} - @test PSE._application_index_object_id(index, ObjectId(:leaf)) === ObjectId(:leaf) - @test_throws ArgumentError PSE._application_index_object_id(index, ObjectId(7)) + @test PSE._index_object_id(index, ObjectId(:leaf)) === ObjectId(:leaf) + @test_throws ArgumentError PSE._index_object_id(index, ObjectId(7)) @test index[ObjectId(:leaf)] == compiled.applications_by_object[ObjectId(:leaf)] @test all(left === right for (left, right) in zip(index[ObjectId(:leaf)], compiled.applications)) @test PSE.model_status(model, :leaf) === status diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index a68be1616..292d61425 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -572,4 +572,62 @@ end end end +struct GeometryOwnerBackend <: PSE.EnvironmentAPI.AbstractEnvironmentBackend end +mutable struct GeometryOwnerHandle{G} + geometry::G +end +PSE.EnvironmentAPI.base_step_seconds(::GeometryOwnerBackend) = 3600.0 +PSE.EnvironmentAPI.get_nsteps(::GeometryOwnerBackend) = 8 +PSE.EnvironmentAPI.bind_environment(::GeometryOwnerBackend, object::Object, context, config) = + GeometryOwnerHandle(geometry(object)) + +@testset "environment geometry provenance retains the registry identity family" begin + for closed in (false, true) + model = CompositeModel( + Object(:root; scale=:Plant, geometry=(cell=:a,), status=Status()), + Object(1; scale=:Branch, parent=:root, status=Status()), + Object(:leaf; scale=:Leaf, parent=1, status=Status(x=3f0)), + Object(:other; scale=:Plant, geometry=(cell=:b,), status=Status()), + Object(:no_geometry; scale=:Plant, status=Status()), + Object(:blank_branch; scale=:Branch, parent=:no_geometry, status=Status()); + applications=(ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)),), + environment=GeometryOwnerBackend()) + closed && (model = close_registry(model)) + simulation = run!(model; steps=0, outputs=:none) + leaf = model_object(model, :leaf) + reference = PSE.refvalue(leaf.status, :x) + for (id, source_id, role) in ((:root, ObjectId(:root), :self), + (1, ObjectId(:root), :ancestor), (:leaf, ObjectId(:root), :ancestor), + (:no_geometry, nothing, :global), (:blank_branch, nothing, :global)) + object = model_object(model, id) + bound, source, actual_role = PSE._environment_binding_object(model, object) + @test actual_role === role + @test source === source_id + @test bound.status === object.status + @test bound.id === object.id + if !isnothing(source) + @test typeof(source) === typeof(model_object(model, source).id) + @test geometry(bound) == (cell=:a,) + end + end + binding = simulation.environment_bindings.by_target[(:leaf, ObjectId(:leaf))] + @test binding.geometry_source_object_id === ObjectId(:root) + @test binding.handle.geometry == (cell=:a,) + reparent_object!(model, :leaf, :other) + refreshed = PSE.Advanced.refresh_environment_bindings!(model) + moved = refreshed.by_target[(:leaf, ObjectId(:leaf))] + @test moved.geometry_source_object_id === ObjectId(:other) + @test moved.handle.geometry == (cell=:b,) + @test moved.handle !== binding.handle + move_object!(model, :other, (cell=:c,)) + current = PSE.Advanced.refresh_environment_bindings!(model) + moved_again = current.by_target[(:leaf, ObjectId(:leaf))] + @test moved_again.geometry_source_object_id === ObjectId(:other) + @test moved_again.handle.geometry == (cell=:c,) + @test moved_again.handle !== moved.handle + @test PSE.refvalue(leaf.status, :x) === reference + @test leaf.status.x === 3f0 + end +end + end From 2848190e8777781e6b02e8bdae8a8f0baca2bd0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 04:34:50 +0100 Subject: [PATCH 057/324] Preserve application types during environment preparation --- ext/PlantSimEngineGraphEditorExt.jl | 4 +- src/composite_model/compilation.jl | 3 +- src/composite_model/environment_bindings.jl | 107 +++++++++--------- src/visualization/model_graph_view.jl | 7 +- test/test-model-authored-port-inventory.jl | 6 +- ...test-model-environment-binding-identity.jl | 3 +- ...-model-global-environment-sample-schema.jl | 3 +- 7 files changed, 74 insertions(+), 59 deletions(-) diff --git a/ext/PlantSimEngineGraphEditorExt.jl b/ext/PlantSimEngineGraphEditorExt.jl index 2aacbf9e6..dabc16372 100644 --- a/ext/PlantSimEngineGraphEditorExt.jl +++ b/ext/PlantSimEngineGraphEditorExt.jl @@ -173,7 +173,9 @@ function apply_edit!(session::GraphEditorSession, edit::PlantSimEngine.GraphEdit _, environment_plans_by_id = PlantSimEngine._compile_environment_application_plans( candidate, - report.applications; + report.applications, + isnothing(report.compiled) ? PlantSimEngine._applications_by_id(report.applications) : + report.compiled.applications_by_id; prepare_runtime=false, ) bindings = PlantSimEngine._compile_environment_bindings_for_applications( diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index bee8ce037..fe67cc1c1 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4837,7 +4837,8 @@ function explain_initialization(model::CompositeModel) _, environment_plans_by_id = _compile_environment_application_plans( model, - compiled.applications; + compiled.applications, + compiled.applications_by_id; prepare_runtime=false, ) environment_bindings = Dict( diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index e3bace27a..d1f2bda36 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -186,7 +186,8 @@ end function _compile_environment_application_plans( model::CompositeModel, - applications; + applications, + applications_by_id; previous_plans_by_id=nothing, prepare_runtime::Bool=true, plan_schema=nothing, @@ -203,56 +204,58 @@ function _compile_environment_application_plans( prepared_by_source[source] = plan.prepared_source end end - for application in applications - config = environment_config(application.spec) - backend = _environment_backend_from_config(model, config) - bindings, environment_sources = _environment_sampling_configuration(application.spec) - required_inputs = _model_environment_input_names(application) - sampling_rules = Tuple(_environment_sampling_rules(bindings, environment_sources, required_inputs)) - compiled_sampling_rules = Tuple( - CompiledEnvironmentSamplingRule(target, source) - for (target, source) in sampling_rules - ) - source_inputs = _environment_source_variable_names(sampling_rules) - produced_outputs = _model_environment_output_names(application) - sampler = nothing - prepared_source = nothing - if prepare_runtime && backend isa GlobalConstant - source = environment_source(backend) - sampler = get!(samplers_by_source, source) do - _prepare_environment_sampler(source) - end - prepared_source = get!(prepared_by_source, source) do - _prepare_global_environment(source) + for candidate in applications + _with_metadata_entry(applications_by_id, candidate.id) do application + config = environment_config(application.spec) + backend = _environment_backend_from_config(model, config) + bindings, environment_sources = _environment_sampling_configuration(application.spec) + required_inputs = _model_environment_input_names(application) + sampling_rules = Tuple(_environment_sampling_rules(bindings, environment_sources, required_inputs)) + compiled_sampling_rules = Tuple( + CompiledEnvironmentSamplingRule(target, source) + for (target, source) in sampling_rules + ) + source_inputs = _environment_source_variable_names(sampling_rules) + produced_outputs = _model_environment_output_names(application) + sampler = nothing + prepared_source = nothing + if prepare_runtime && backend isa GlobalConstant + source = environment_source(backend) + sampler = get!(samplers_by_source, source) do + _prepare_environment_sampler(source) + end + prepared_source = get!(prepared_by_source, source) do + _prepare_global_environment(source) + end end + has_bindings = !isempty(keys(bindings)) + has_source_overrides = !isempty(keys(environment_sources)) + uses_raw_global_source = backend isa GlobalConstant && + isnothing(sampler) && + !has_bindings && !has_source_overrides + plan = CompiledEnvironmentApplicationPlan( + application.id, + backend, + config, + required_inputs, + source_inputs, + produced_outputs, + sampling_rules, + compiled_sampling_rules, + sampler, + prepared_source, + uses_raw_global_source, + _global_environment_sample_schema( + backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, + ), + ) + _with_environment_plan(identity, plan_schema, plan) + push!(plans, plan) + haskey(plans_by_id, application.id) && error( + "Environment application-plan compilation produced duplicate application id `$(application.id)`.", + ) + plans_by_id[application.id] = plan end - has_bindings = !isempty(keys(bindings)) - has_source_overrides = !isempty(keys(environment_sources)) - uses_raw_global_source = backend isa GlobalConstant && - isnothing(sampler) && - !has_bindings && !has_source_overrides - plan = CompiledEnvironmentApplicationPlan( - application.id, - backend, - config, - required_inputs, - source_inputs, - produced_outputs, - sampling_rules, - compiled_sampling_rules, - sampler, - prepared_source, - uses_raw_global_source, - _global_environment_sample_schema( - backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, - ), - ) - _with_environment_plan(identity, plan_schema, plan) - push!(plans, plan) - haskey(plans_by_id, application.id) && error( - "Environment application-plan compilation produced duplicate application id `$(application.id)`.", - ) - plans_by_id[application.id] = plan end return plans, plans_by_id end @@ -516,7 +519,8 @@ function _compile_environment_binding_owner(model::CompositeModel, ) _update_model_environment_indices!(model, compiled) application_plans, application_plans_by_id = - _compile_environment_application_plans(model, compiled.applications; plan_schema) + _compile_environment_application_plans(model, compiled.applications, + compiled.applications_by_id; plan_schema) bindings = _compile_environment_bindings( model, compiled, @@ -574,7 +578,8 @@ function _reconciled_environment_application_plans( ) candidates, candidates_by_id = _compile_environment_application_plans( model, - compiled.applications; + compiled.applications, + compiled.applications_by_id; previous_plans_by_id=cached.application_plans_by_id, plan_schema=cached.application_plan_schema, ) diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 2577d36fe..82bdd55f2 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -331,7 +331,8 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) _model_graph_phase!(diagnostics, :environment_bindings, nothing) do _, environment_plans_by_id = _compile_environment_application_plans( model, - applications; + applications, + _applications_by_id(applications); prepare_runtime=false, ) environment_bindings = _compile_environment_bindings_for_applications( @@ -1371,7 +1372,9 @@ function _model_graph_environment_edges(report, level, environment_catalog) environment_bindings = try _, environment_plans_by_id = _compile_environment_application_plans( report.model, - report.applications; + report.applications, + isnothing(report.compiled) ? _applications_by_id(report.applications) : + report.compiled.applications_by_id; prepare_runtime=false, ) _compile_environment_bindings_for_applications( diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index 589d8642b..2c78f0a71 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -97,7 +97,8 @@ end applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) PSE._resolve_model_input_plans(model, PSE._scenario_preparation(model), applications, destinations) - PSE._compile_environment_application_plans(model, applications; prepare_runtime=false) + PSE._compile_environment_application_plans(model, applications, + PSE._applications_by_id(applications); prepare_runtime=false) @test a.counter[] == before_a @test b.counter[] == before_b if all(recipe -> hasproperty(recipe, :ports), recipes) @@ -278,7 +279,8 @@ end destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) @test_throws message PSE._resolve_model_input_plans(model, PSE._scenario_preparation(model), applications, destinations) @test counter[] == 1 # even empty contracts validate all declared port names - @test_throws message PSE._compile_environment_application_plans(model, applications; prepare_runtime=false) + @test_throws message PSE._compile_environment_application_plans(model, applications, + PSE._applications_by_id(applications); prepare_runtime=false) @test counter[] == 1 @test_throws message run!(model; steps=0) @test counter[] == 1 diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index f7c4afe22..9341322a5 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -538,7 +538,8 @@ end applications=(ModelSpec(Leaf(0f0); name=:leaf, on=Many(scale=:Leaf), environment=config),), environment=backend) compiled = PSE.Advanced.refresh_bindings!(model) - _, plans = PSE._compile_environment_application_plans(model, compiled.applications) + _, plans = PSE._compile_environment_application_plans(model, + compiled.applications, compiled.applications_by_id) bindings = PSE._compile_environment_bindings_for_applications( model, compiled.applications, plans) tables = (compiled.applications_by_id, diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 232aeaadd..21e40eecc 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -137,7 +137,8 @@ cache_hit_allocations(data, count) = @allocated cached_temperature(data, count) @test Set(keys(shared.simulation.environment_bindings.sample_cache)) == Set(((:probe, 1), (:other, 1))) plans, _ = PSE._compile_environment_application_plans(shared.model, - shared.simulation.compiled.applications; prepare_runtime=false) + shared.simulation.compiled.applications, + shared.simulation.compiled.applications_by_id; prepare_runtime=false) @test all(plan -> plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any}, plans) @test counted.reads == Dict(1 => 2) end From 50055594a8b36a6a2238a9367769456d8c39e3ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 04:34:50 +0100 Subject: [PATCH 058/324] Preserve the shape of environment sampling rules --- src/time/runtime/environment_backends.jl | 6 ++--- ...-model-global-environment-sample-schema.jl | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index 5186e7497..e2043cb25 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -363,8 +363,7 @@ function _environment_sampling_configuration(model_spec::ModelSpec) end function _environment_sampling_rules(bindings, environment_sources, input_names) - rules = Pair{Symbol,Symbol}[] - for target in input_names + return map(input_names) do target source = target if haskey(bindings, target) rule = bindings[target] @@ -373,9 +372,8 @@ function _environment_sampling_rules(bindings, environment_sources, input_names) if haskey(environment_sources, target) source = Symbol(environment_sources[target]) end - push!(rules, target => source) + return convert(Pair{Symbol,Symbol}, target => source) end - return rules end function _environment_source_overrides(model_spec::ModelSpec) diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 21e40eecc..7c747e3fd 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -334,4 +334,31 @@ end @test final_state(simulation) == (seen=7.75f0, visits=1) end +struct SamplingRuleSource + name::Symbol + visits::Vector{Symbol} +end +Base.Symbol(source::SamplingRuleSource) = (push!(source.visits, source.name); source.name) + +@testset "environment rules retain tuple arity and remapping order" begin + for names in ((:T, :RH, :CO2), [:T, :RH, :CO2]) + visits = Symbol[] + bindings = (T=(source=SamplingRuleSource(:bound_T, visits),), + RH=(source=SamplingRuleSource(:bound_RH, visits),)) + sources = (T=SamplingRuleSource(:override_T, visits), + CO2=SamplingRuleSource(:override_CO2, visits)) + rules = PSE._environment_sampling_rules(bindings, sources, names) + @test collect(rules) == [:T => :override_T, :RH => :bound_RH, :CO2 => :override_CO2] + @test visits == [:bound_T, :override_T, :bound_RH, :override_CO2] + @test eltype(rules) === Pair{Symbol,Symbol} + @test names isa Tuple ? rules isa Tuple : rules isa Vector + end + @test (@inferred PSE._environment_sampling_rules((;), (;), ())) === () + @test (@inferred PSE._environment_sampling_rules((;), (;), Symbol[])) == Pair{Symbol,Symbol}[] + visits = Symbol[] + unused = (unused=(source=SamplingRuleSource(:not_read, visits),),) + @test PSE._environment_sampling_rules(unused, (;), ()) === () + @test isempty(visits) +end + end # module GlobalEnvironmentSampleSchemaChecks From 95d5d7c3f29170bcd1052feb18a8a09bc564511a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 04:34:50 +0100 Subject: [PATCH 059/324] Share typed environment preparation by source --- src/composite_model/environment_bindings.jl | 82 ++++++------ ...-model-global-environment-sample-schema.jl | 124 ++++++++++++++++++ 2 files changed, 169 insertions(+), 37 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index d1f2bda36..e504b95d4 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -178,10 +178,12 @@ end # retain Any until their result schema is known; preparation never samples a # custom source merely to discover its return type. function _global_environment_sample_schema(backend, source, sampler, uses_raw::Bool, prepare_runtime::Bool) - R = prepare_runtime && isnothing(sampler) && uses_raw && - backend isa GlobalConstant && - DataFormat(environment_source(backend)) isa SingletonAlike ? typeof(source) : Any - return GlobalEnvironmentSampleSchema{R}() + if prepare_runtime && isnothing(sampler) && uses_raw && + backend isa GlobalConstant && + DataFormat(environment_source(backend)) isa SingletonAlike + return GlobalEnvironmentSampleSchema{typeof(source)}() + end + return GlobalEnvironmentSampleSchema{Any}() end function _compile_environment_application_plans( @@ -194,14 +196,12 @@ function _compile_environment_application_plans( ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() - samplers_by_source = IdDict{Any,Any}() - prepared_by_source = IdDict{Any,Any}() + plans_by_source = IdDict{Any,CompiledEnvironmentApplicationPlan}() if !isnothing(previous_plans_by_id) for plan in values(previous_plans_by_id) plan.backend isa GlobalConstant || continue source = environment_source(plan.backend) - samplers_by_source[source] = plan.sampler - prepared_by_source[source] = plan.prepared_source + plans_by_source[source] = plan end end for candidate in applications @@ -217,38 +217,46 @@ function _compile_environment_application_plans( ) source_inputs = _environment_source_variable_names(sampling_rules) produced_outputs = _model_environment_output_names(application) - sampler = nothing - prepared_source = nothing - if prepare_runtime && backend isa GlobalConstant + function build_plan(sampler, prepared_source) + has_bindings = !isempty(keys(bindings)) + has_source_overrides = !isempty(keys(environment_sources)) + uses_raw_global_source = backend isa GlobalConstant && + isnothing(sampler) && + !has_bindings && !has_source_overrides + return CompiledEnvironmentApplicationPlan( + application.id, + backend, + config, + required_inputs, + source_inputs, + produced_outputs, + sampling_rules, + compiled_sampling_rules, + sampler, + prepared_source, + uses_raw_global_source, + _global_environment_sample_schema( + backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, + ), + ) + end + plan = if prepare_runtime && backend isa GlobalConstant source = environment_source(backend) - sampler = get!(samplers_by_source, source) do - _prepare_environment_sampler(source) - end - prepared_source = get!(prepared_by_source, source) do - _prepare_global_environment(source) + cached_plan = get(plans_by_source, source, nothing) + if isnothing(cached_plan) + sampler = _prepare_environment_sampler(source) + prepared_source = _prepare_global_environment(source) + prepared_plan = build_plan(sampler, prepared_source) + plans_by_source[source] = prepared_plan + prepared_plan + else + _with_environment_plan(plan_schema, cached_plan) do admitted_plan + build_plan(admitted_plan.sampler, admitted_plan.prepared_source) + end end + else + build_plan(nothing, nothing) end - has_bindings = !isempty(keys(bindings)) - has_source_overrides = !isempty(keys(environment_sources)) - uses_raw_global_source = backend isa GlobalConstant && - isnothing(sampler) && - !has_bindings && !has_source_overrides - plan = CompiledEnvironmentApplicationPlan( - application.id, - backend, - config, - required_inputs, - source_inputs, - produced_outputs, - sampling_rules, - compiled_sampling_rules, - sampler, - prepared_source, - uses_raw_global_source, - _global_environment_sample_schema( - backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, - ), - ) _with_environment_plan(identity, plan_schema, plan) push!(plans, plan) haskey(plans_by_id, application.id) && error( diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 7c747e3fd..8178f7879 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -361,4 +361,128 @@ Base.Symbol(source::SamplingRuleSource) = (push!(source.visits, source.name); so @test isempty(visits) end +mutable struct MemoPreparationSource{T} + T::T + U::T + duration::Hour + sampler_preparations::Int + source_preparations::Int +end +PSE.DataFormat(::Type{<:MemoPreparationSource}) = PSE.SingletonAlike() +PSE._prepare_environment_sampler(source::MemoPreparationSource) = + (source.sampler_preparations += 1; nothing) +PSE._prepare_global_environment(source::MemoPreparationSource) = + (source.source_preparations += 1; source) + +function memo_source_model(source) + return CompositeModel(Object(:a; scale=:Leaf), Object(:b; scale=:Leaf); + applications=( + ModelSpec(Probe(0f0); name=:raw, on=One(id=:a)), + ModelSpec(Probe(0f0); name=:mapped, on=One(id=:b), + environment=Environment(sources=(T=:U,)))), environment=source) +end +memo_preparations(source) = (source.sampler_preparations, source.source_preparations) + +@testset "source-plan memo shares preparation and preserves current application metadata" begin + observed_source = MemoPreparationSource(10f0, 20f0, Hour(1), 0, 0) + observed = run!(memo_source_model(observed_source); steps=0, outputs=:none) + schema = PSE._environment_plan_schema_from_types(typeof.(observed.environment_bindings.application_plans)) + for fixed in (false, true) + source = MemoPreparationSource(10f0, 20f0, Hour(1), 0, 0) + model = memo_source_model(source) + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_plan_schema=fixed ? schema : nothing) + compiled, owner = simulation.compiled, simulation.environment_bindings + @test memo_preparations(source) == (1, 1) + raw, mapped = owner.application_plans_by_id[:raw], owner.application_plans_by_id[:mapped] + @test raw.application_id === :raw && mapped.application_id === :mapped + @test raw.prepared_source === mapped.prepared_source === source + @test raw.sampler === mapped.sampler === nothing + @test raw.sampling_rules == (:T => :T,) + @test mapped.sampling_rules == (:T => :U,) + @test raw.uses_raw_global_source && !mapped.uses_raw_global_source + @test raw.sample_schema isa PSE.GlobalEnvironmentSampleSchema{typeof(source)} + @test mapped.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any} + current, by_id = PSE._compile_environment_application_plans(model, + compiled.applications, compiled.applications_by_id; + previous_plans_by_id=owner.application_plans_by_id, + plan_schema=owner.application_plan_schema) + @test memo_preparations(source) == (1, 1) + @test map(plan -> plan.application_id, current) == [:raw, :mapped] + for original in (raw, mapped) + reused = by_id[original.application_id] + @test reused.sampler === original.sampler + @test reused.prepared_source === original.prepared_source + @test reused.config === original.config + @test reused.compiled_sampling_rules === original.compiled_sampling_rules + @test reused.sample_schema === original.sample_schema + end + disabled, _ = PSE._compile_environment_application_plans(model, + compiled.applications, compiled.applications_by_id; + previous_plans_by_id=owner.application_plans_by_id, prepare_runtime=false) + @test memo_preparations(source) == (1, 1) + @test all(plan -> isnothing(plan.sampler) && isnothing(plan.prepared_source) && + plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any}, disabled) + for (id, object_id, expected) in ((:raw, :a, 11f0), (:mapped, :b, 21f0)) + source.T, source.U = 11f0, 21f0 + application = compiled.applications_by_id[id] + binding = owner.by_target[(id, ObjectId(object_id))] + @test PSE._model_environment_for_binding(owner, application, binding, 1, source).T === expected + source.T, source.U = 12f0, 22f0 + @test PSE._model_environment_for_binding(owner, application, binding, 1, source).T === expected + 1f0 + end + @test memo_preparations(source) == (1, 1) + if fixed + @test all(plan -> PSE._with_environment_plan(identity, schema, plan) === plan, current) + mapped_schema = PSE._environment_plan_schema_from_types([typeof(mapped)]) + @test_throws "raw` is outside its prepared family schema" PSE._refresh_environment_bindings!( + model, compiled, owner; plan_schema=mapped_schema) + @test model.environment_binding_cache === owner + alternate = PSE.Advanced.compile_composite_model(model, (model.applications[2],)) + replacement = PSE._refresh_environment_bindings!(model, alternate, owner; + plan_schema=mapped_schema) + @test replacement.application_plan_schema === mapped_schema + @test only(replacement.application_plans).application_id === :mapped + @test memo_preparations(source) == (2, 2) + again, _ = PSE._compile_environment_application_plans(model, + alternate.applications, alternate.applications_by_id; + previous_plans_by_id=replacement.application_plans_by_id, + plan_schema=replacement.application_plan_schema) + @test only(again).prepared_source === source + @test memo_preparations(source) == (2, 2) + end + end +end + +@testset "previous source plans retain the last sampler and prepared-source pair" begin + weather = PSE.PlantMeteo.Weather([ + PSE.PlantMeteo.Atmosphere(date=DateTime(2025, 1, 1), T=10.0, + Wind=1.0, Rh=0.5, duration=Hour(1)), + PSE.PlantMeteo.Atmosphere(date=DateTime(2025, 1, 1, 1), T=20.0, + Wind=1.0, Rh=0.5, duration=Hour(1))]) + for source in (DataFrame(T=Float32[10, 20], duration=fill(Hour(1), 2)), weather) + data = prepared(source; shared=true) + compiled, owner = data.simulation.compiled, data.simulation.environment_bindings + fresh, fresh_by_id = PSE._compile_environment_application_plans(data.model, + compiled.applications, compiled.applications_by_id) + initial = owner.application_plans_by_id[:probe] + newer = fresh_by_id[:other] + if source isa DataFrame + @test initial.prepared_source.rows !== newer.prepared_source.rows + else + @test initial.sampler !== newer.sampler + end + previous = Dict(:initial => initial, :newer => newer) + expected = last(collect(values(previous))) + for schema in (nothing, PSE._environment_plan_schema_from_types(typeof.(fresh))) + reused, _ = PSE._compile_environment_application_plans(data.model, + compiled.applications, compiled.applications_by_id; + previous_plans_by_id=previous, plan_schema=schema) + @test map(plan -> plan.application_id, reused) == [:probe, :other] + @test all(plan -> plan.sampler === expected.sampler, reused) + @test all(plan -> plan.prepared_source === expected.prepared_source, reused) + end + end +end + end # module GlobalEnvironmentSampleSchemaChecks From b1a0229ad426a7edb8216a403d494e4dae67ae5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 04:35:59 +0100 Subject: [PATCH 060/324] Materialize heterogeneous environment index metadata explicitly --- src/composite_model/environment_bindings.jl | 7 +- ...test-model-environment-index-identities.jl | 73 ++++++++++++++++++- 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index e504b95d4..58c27f6a0 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -84,7 +84,12 @@ function _model_environment_entities(model::CompositeModel, object_ids=nothing) if haskey(model.registry.objects, object_id) ) end - return [_model_environment_entity(object) for object in objects] + # Backend index metadata may mix identity and geometry value types. + entities = NamedTuple[] + for object in objects + push!(entities, _model_environment_entity(object)) + end + return entities end function _model_environment_backends(model::CompositeModel, compiled::CompiledCompositeModel) diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index f2ab4296f..137af5e6c 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -8,6 +8,7 @@ const EA = PSE.EnvironmentAPI mutable struct Backend <: EA.AbstractEnvironmentBackend values::Dict{Symbol,Float32} binds::Int + index_updates::Vector{Any} end mutable struct Handle cell::Symbol @@ -22,6 +23,10 @@ function EA.bind_environment(backend::Backend, object::Object, context, config) end EA.sample(backend::Backend, handle::Handle, ::Symbol, time) = backend.values[handle.cell] + Float32(handle.generation) +function EA.update_index!(backend::Backend, entities, removed_object_ids) + push!(backend.index_updates, (; entities, removed_object_ids)) + return nothing +end PSE.@process "environment_identity_index" verbose=false struct Probe <: AbstractEnvironment_Identity_IndexModel end @@ -51,7 +56,7 @@ function close_registry(model::CompositeModel) end function fixture(closed::Bool) - backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0) + backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, Any[]) model = CompositeModel( Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), Object(1; scale=:Leaf, parent=:root, geometry=(cell=:a,), @@ -65,6 +70,72 @@ function fixture(closed::Bool) return (; model, simulation, backend) end +@testset "environment index metadata preserves mixed values, order and live aliases" begin + for closed in (false, true) + data = fixture(closed) + model, backend = data.model, data.backend + initial = first(backend.index_updates) + # The backend boundary deliberately accepts heterogeneous NamedTuple rows, + # including an empty batch; it does not infer a concrete row eltype. + @test eltype(initial.entities) === NamedTuple + @test [entity.id for entity in initial.entities] == + [object.id.value for object in model_objects(model)] + @test isempty(initial.removed_object_ids) + + position_a = Float32[1, 2, 3] + bounds_a = Dict(:radius => 0.5f0) + geometry_a = (cell=:a, position=position_a, bounds=bounds_a) + geometry_b = (cell=:b, position=(x=4.0, y=5.0, z=6.0), bounds=(width=2.0,)) + update_geometry!(model, 1, geometry_a; invalidate_environment=false) + update_geometry!(model, :leaf, geometry_b; invalidate_environment=false) + changed = ObjectId[ObjectId(:leaf), ObjectId(1), ObjectId(:leaf)] + before = length(backend.index_updates) + PSE._update_model_environment_indices!(model, [backend], changed) + @test length(backend.index_updates) == before + 1 + batch = last(backend.index_updates) + @test eltype(batch.entities) === NamedTuple + @test [entity.id for entity in batch.entities] == [:leaf, 1, :leaf] + @test isempty(batch.removed_object_ids) + @test batch.entities[1].object === batch.entities[3].object === model_object(model, :leaf) + integer = batch.entities[2] + @test integer.object === model_object(model, 1) + @test integer.geometry === geometry_a + @test batch.entities[1].geometry === geometry_b + @test typeof(integer.geometry) !== typeof(batch.entities[1].geometry) + @test integer.position === position_a + @test integer.bounds === bounds_a + + position_a[1] = 7f0 + bounds_a[:radius] = 2f0 + model_status(model, 1).seen = 70f0 + @test integer.geometry.position[1] === 7f0 + @test integer.bounds[:radius] === 2f0 + @test geometry(integer.object).position === position_a + @test integer.object.status.seen === 70f0 + + replacement = (cell=:a, position=Float32[8, 9, 10], bounds=Dict(:radius => 3f0)) + update_geometry!(model, 1, replacement; invalidate_environment=false) + @test geometry(integer.object) === replacement + @test integer.geometry === geometry_a + PSE._update_model_environment_indices!(model, [backend], ObjectId[ObjectId(1)]) + @test only(last(backend.index_updates).entities).geometry === replacement + + remove_object!(model, :leaf) + PSE._update_model_environment_indices!(model, [backend], changed) + surviving = last(backend.index_updates) + @test [entity.id for entity in surviving.entities] == [1] + @test surviving.removed_object_ids == ObjectId[ObjectId(:leaf), ObjectId(:leaf)] + remove_object!(model, 1) + PSE._update_model_environment_indices!(model, [backend], changed) + removed = last(backend.index_updates) + @test isempty(removed.entities) + @test eltype(removed.entities) === NamedTuple + @test removed.removed_object_ids == changed + @test typeof.(removed.removed_object_ids) == + [ObjectId{Symbol}, ObjectId{Int}, ObjectId{Symbol}] + end +end + function check_indexes(model, owner) I = keytype(model.registry.objects) K = Tuple{Symbol,I} From bc9a8b0b0ebc2b0910ee05c521a89d47c655fd32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 08:22:42 +0100 Subject: [PATCH 061/324] Preserve environment types during lifecycle preparation --- src/composite_model/compilation.jl | 2 +- src/composite_model/environment_bindings.jl | 182 +++++++---- ...test-model-environment-index-identities.jl | 304 +++++++++++++++++- 3 files changed, 420 insertions(+), 68 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index fe67cc1c1..bd87934fa 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8670,7 +8670,7 @@ end @inline _with_metadata_entry(f, entries::AbstractVector, key::Integer) = f(entries[key]) @inline _with_metadata_entry(f, entries::AbstractDict, key::Symbol) = f(entries[key]) -function _foreach_object_application(f, compiled::CompiledCompositeModel, object_id::ObjectId) +function _foreach_object_application(f::F, compiled::CompiledCompositeModel, object_id::ObjectId) where {F} slots = _application_membership_slots(compiled, object_id) for slot in slots _with_metadata_entry(f, slots.applications, slot) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 58c27f6a0..5b08a5d87 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -92,27 +92,41 @@ function _model_environment_entities(model::CompositeModel, object_ids=nothing) return entities end -function _model_environment_backends(model::CompositeModel, compiled::CompiledCompositeModel) - backends = Any[] +function _model_environment_backends(model::CompositeModel, + applications::CompiledMetadataTable{T}, +) where {T} + slots = Int[] seen = Set{UInt}() - for application in compiled.applications - backend = _environment_backend_from_config(model, environment_config(application.spec)) - isnothing(backend) && continue - id = objectid(backend) - id in seen && continue - push!(seen, id) - push!(backends, backend) + # Preserve actual discovery values, independently of the later plan pass. + # The entry count is already encoded in the fixed application metadata. + backends = ntuple(Val(fieldcount(T))) do slot + _with_metadata_entry(applications, slot) do application + backend = _environment_backend_from_config(model, environment_config(application.spec)) + if !isnothing(backend) + id = objectid(backend) + if !(id in seen) + push!(seen, id) + push!(slots, slot) + end + end + return backend + end end - return backends + return CompiledMetadataTable(NamedTuple{fieldnames(T)}(backends)), slots end function _update_model_environment_indices!( + with_backend, model::CompositeModel, - backends, - dirty_object_ids=nothing, + entries, + dirty_object_ids, ) - filter!(backend -> !(backend isa GlobalConstant), backends) - isempty(backends) && return nothing + filter!(entries) do entry + with_backend(entry) do backend + !(backend isa GlobalConstant) + end + end + isempty(entries) && return nothing entities = _model_environment_entities(model, dirty_object_ids) removed_object_ids = isnothing(dirty_object_ids) ? ObjectId[] : @@ -120,22 +134,29 @@ function _update_model_environment_indices!( object_id for object_id in dirty_object_ids if !haskey(model.registry.objects, object_id) ] - for backend in backends - update_index!(backend, entities, removed_object_ids) + for entry in entries + with_backend(entry) do backend + update_index!(backend, entities, removed_object_ids) + end end return nothing end +function _update_model_environment_indices!(model::CompositeModel, backends, dirty_object_ids=nothing) + return _update_model_environment_indices!(model, backends, dirty_object_ids) do consume, backend + consume(backend) + end +end + function _update_model_environment_indices!( model::CompositeModel, compiled::CompiledCompositeModel, dirty_object_ids=nothing, ) - return _update_model_environment_indices!( - model, - _model_environment_backends(model, compiled), - dirty_object_ids, - ) + backends, slots = _model_environment_backends(model, compiled.applications_by_id) + return _update_model_environment_indices!(model, slots, dirty_object_ids) do consume, slot + _with_metadata_entry(consume, backends, slot) + end end function _update_model_environment_indices_for_objects!( @@ -145,7 +166,8 @@ function _update_model_environment_indices_for_objects!( dirty_object_ids, ) application_ids = Set{Symbol}() - for object_id in dirty_object_ids + for dirty_id in dirty_object_ids + object_id = _index_object_id(cached.targets_by_object, dirty_id) _foreach_object_application(compiled, object_id) do application push!(application_ids, application.id) end @@ -153,22 +175,26 @@ function _update_model_environment_indices_for_objects!( push!(application_ids, target[1]) end end - backends = Any[] + plans = CompiledEnvironmentApplicationPlan[] seen = Set{UInt}() for application_id in application_ids plan = cached.application_plans_by_id[application_id] - backend = plan.backend - isnothing(backend) && continue - id = objectid(backend) - id in seen && continue - push!(seen, id) - push!(backends, backend) - end - return _update_model_environment_indices!( - model, - backends, - dirty_object_ids, - ) + _with_environment_plan(cached.application_plan_schema, plan) do admitted_plan + backend = admitted_plan.backend + isnothing(backend) && return nothing + id = objectid(backend) + id in seen && return nothing + push!(seen, id) + push!(plans, admitted_plan) + end + end + # Plans are immutable snapshots. Index callbacks may replace the owner's + # dictionary entries, so consume these selected plans without rereading it. + return _update_model_environment_indices!(model, plans, dirty_object_ids) do consume, plan + _with_environment_plan(cached.application_plan_schema, plan) do admitted_plan + consume(admitted_plan.backend) + end + end end function _environment_variable_names(vars) @@ -569,6 +595,13 @@ function _same_environment_context(a, b) a.process == b.process end +function _same_environment_plan_configuration( + a::CompiledEnvironmentApplicationPlan, b::CompiledEnvironmentApplicationPlan, +) + return _same_environment_backend(a.backend, b.backend) && + isequal(a.config, b.config) +end + function _same_environment_application_plan(a, b) return _same_environment_backend(a.backend, b.backend) && isequal(a.config, b.config) && @@ -598,16 +631,23 @@ function _reconciled_environment_application_plans( ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() + plan_schema = cached.application_plan_schema for candidate in candidates - old = get(cached.application_plans_by_id, candidate.application_id, nothing) - if !isnothing(old) - _same_environment_backend(old.backend, candidate.backend) || - return nothing - isequal(old.config, candidate.config) || return nothing + application_id = candidate.application_id + old = get(cached.application_plans_by_id, application_id, nothing) + plan = if isnothing(old) + _with_environment_plan(identity, plan_schema, candidates_by_id[application_id]) + else + _with_environment_plan(plan_schema, old) do admitted_old + _with_environment_plan(plan_schema, candidates_by_id[application_id]) do admitted_candidate + _same_environment_plan_configuration(admitted_old, admitted_candidate) || + return nothing + return _same_environment_application_plan(admitted_old, admitted_candidate) ? + admitted_old : _with_environment_plan(identity, plan_schema, candidates_by_id[application_id]) + end + end end - plan = !isnothing(old) && - _same_environment_application_plan(old, candidate) ? - old : candidates_by_id[candidate.application_id] + isnothing(plan) && return nothing push!(plans, plan) plans_by_id[plan.application_id] = plan end @@ -631,18 +671,25 @@ function _reconcile_environment_binding_metadata( bindings = CompiledEnvironmentBinding[] changed = false + plan_schema = cached.application_plan_schema for application in compiled.applications - plan = application_plans_by_id[application.id] + application_id = application.id + plan = application_plans_by_id[application_id] for object_id in application.target_ids - key = (application.id, object_id) + key = (application_id, object_id) old = get(cached.by_target, key, nothing)::Union{Nothing,CompiledEnvironmentBinding} isnothing(old) && return nothing object = _model_object(model, object_id) context = _object_environment_context(application.id, application.process, object, object_id) _, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) - _same_environment_backend(old.backend, plan.backend) || return nothing - isequal(old.config, plan.config) || return nothing + old_plan = getfield(old, :plan)::CompiledEnvironmentApplicationPlan + same_configuration = _with_environment_plan(plan_schema, old_plan) do admitted_old + _with_environment_plan(plan_schema, application_plans_by_id[application_id]) do admitted_current + _same_environment_plan_configuration(admitted_old, admitted_current) + end + end + same_configuration || return nothing old.geometry_source_object_id == geometry_source_object_id || return nothing old.geometry_source == geometry_source || return nothing @@ -700,7 +747,14 @@ function _refresh_environment_bindings_for_objects( cached::CompiledEnvironmentBindings, dirty_object_ids, ) - dirty_ids = ObjectId[dirty_object_ids...] + I = keytype(cached.targets_by_object) + dirty_ids = I[] + if Base.IteratorSize(typeof(dirty_object_ids)) isa Union{Base.HasLength,Base.HasShape} + sizehint!(dirty_ids, length(dirty_object_ids)) + end + for dirty_id in dirty_object_ids + push!(dirty_ids, _index_object_id(cached.targets_by_object, dirty_id)) + end _sort_object_ids!(dirty_ids) _update_model_environment_indices_for_objects!( model, @@ -708,11 +762,14 @@ function _refresh_environment_bindings_for_objects( cached, dirty_ids, ) - stale_targets = Set{Tuple{Symbol,ObjectId}}() - replacements = Dict{Tuple{Symbol,ObjectId},CompiledEnvironmentBinding}() - for object_id in dirty_ids + K = keytype(cached.by_target) + stale_targets = Set{K}() + replacements = Dict{K,Any}() + empty_targets = K[] + for dirty_id in dirty_ids + object_id = _index_object_id(cached.targets_by_object, dirty_id) current_applications = _application_membership_slots(compiled, object_id) - previous_targets = get(cached.targets_by_object, object_id, ()) + previous_targets = get(cached.targets_by_object, object_id, empty_targets) isempty(current_applications) && isempty(previous_targets) && continue current_application_ids = Set{Symbol}() for slot in current_applications @@ -727,23 +784,20 @@ function _refresh_environment_bindings_for_objects( haskey(model.registry.objects, object_id) || continue for slot in current_applications _with_metadata_entry(current_applications.applications, slot) do application - partial_application = _partial_model_application(application, ObjectId[object_id]) + partial_application = _partial_model_application(application, I[object_id]) for binding in _compile_environment_bindings_for_applications( model, (partial_application,), cached.application_plans_by_id; plan_schema=cached.application_plan_schema, ) - replacements[( - binding.application_id, - binding.object_id, - )] = binding + replacements[_environment_binding_target_key(binding, I)] = binding end end end end _validate_model_environment_inputs!( - values(replacements), + (binding::CompiledEnvironmentBinding for binding in values(replacements)), compiled.applications_by_id, keytype(model.registry.objects); plan_schema=cached.application_plan_schema, @@ -755,10 +809,7 @@ function _refresh_environment_bindings_for_objects( if position != last_position moved_binding = cached.bindings[last_position] cached.bindings[position] = moved_binding - cached.positions_by_target[( - moved_binding.application_id, - moved_binding.object_id, - )] = position + cached.positions_by_target[_environment_binding_target_key(moved_binding, I)] = position end pop!(cached.bindings) delete!(cached.by_target, target) @@ -767,15 +818,16 @@ function _refresh_environment_bindings_for_objects( isnothing(target_index) || deleteat!(object_targets, target_index) isempty(object_targets) && delete!(cached.targets_by_object, target[2]) end - for (target, binding) in replacements + for (target, value) in replacements + binding = value::CompiledEnvironmentBinding position = get(cached.positions_by_target, target, nothing) if isnothing(position) push!(cached.bindings, binding) cached.positions_by_target[target] = lastindex(cached.bindings) push!( - get!(cached.targets_by_object, binding.object_id) do - Tuple{Symbol,ObjectId}[] + get!(cached.targets_by_object, target[2]) do + K[] end, target, ) diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index 137af5e6c..2072d0975 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -9,6 +9,7 @@ mutable struct Backend <: EA.AbstractEnvironmentBackend values::Dict{Symbol,Float32} binds::Int index_updates::Vector{Any} + on_index::Any end mutable struct Handle cell::Symbol @@ -24,10 +25,21 @@ end EA.sample(backend::Backend, handle::Handle, ::Symbol, time) = backend.values[handle.cell] + Float32(handle.generation) function EA.update_index!(backend::Backend, entities, removed_object_ids) - push!(backend.index_updates, (; entities, removed_object_ids)) + push!(backend.index_updates, (; phase=:index, backend_id=objectid(backend), entities, removed_object_ids)) + isnothing(backend.on_index) || backend.on_index() return nothing end +struct IndexDiscoverySource{B} + backend::B + name::Symbol +end +function EA.environment_backend(source::IndexDiscoverySource) + push!(source.backend.index_updates, + (phase=:discover, name=source.name, backend_id=objectid(source.backend))) + return source.backend +end + PSE.@process "environment_identity_index" verbose=false struct Probe <: AbstractEnvironment_Identity_IndexModel end PSE.inputs_(::Probe) = NamedTuple() @@ -56,7 +68,7 @@ function close_registry(model::CompositeModel) end function fixture(closed::Bool) - backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, Any[]) + backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, Any[], nothing) model = CompositeModel( Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), Object(1; scale=:Leaf, parent=:root, geometry=(cell=:a,), @@ -70,6 +82,207 @@ function fixture(closed::Bool) return (; model, simulation, backend) end +function index_discovery_fixture(closed::Bool; extra_applications::Int=0) + events = Any[] + backend_a = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, events, nothing) + backend_b = Backend(copy(backend_a.values), 0, events, nothing) + extra_objects = ntuple(extra_applications) do index + Object(Symbol(:extra_, index); scale=:Leaf, parent=:root, geometry=(cell=:a,), + status=Status(seen=0.0f0, visits=0)) + end + extra_specs = ntuple(extra_applications) do index + name = Symbol(:extra_, index) + ModelSpec(Probe(); name, on=One(id=name), + environment=Environment(backend=IndexDiscoverySource(backend_a, name))) + end + model = CompositeModel( + Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), + Object(1; scale=:Leaf, parent=:root, geometry=(cell=:a,), status=Status(seen=0.0f0, visits=0)), + Object(:leaf; scale=:Leaf, parent=:root, geometry=(cell=:b,), status=Status(seen=0.0f0, visits=0)), + Object(:other; scale=:Leaf, parent=:root, geometry=(cell=:a,), status=Status(seen=0.0f0, visits=0)), + Object(:global; scale=:Leaf, parent=:root, geometry=(cell=:b,), status=Status(seen=0.0f0, visits=0)), + extra_objects...; + applications=( + ModelSpec(Probe(); name=:first, on=One(id=1), + environment=Environment(backend=IndexDiscoverySource(backend_a, :first))), + ModelSpec(Probe(); name=:shared, on=One(id=:leaf), + environment=Environment(backend=IndexDiscoverySource(backend_a, :shared), provider=:shared)), + ModelSpec(Probe(); name=:other, on=One(id=:other), + environment=Environment(backend=IndexDiscoverySource(backend_b, :other))), + ModelSpec(Probe(); name=:global, on=One(id=:global), + environment=Environment(backend=EA.GlobalConstant((T=30.0f0,)))), + extra_specs..., + ), + environment=backend_a) + closed && (model = close_registry(model)) + return (; model, backend_a, backend_b, events) +end + +index_trace(events) = [ + (event.phase, event.phase === :discover ? event.name : event.backend_id) + for event in events +] + +struct ApplicationIDCollector + ids::Vector{Symbol} +end +(collector::ApplicationIDCollector)(application) = push!(collector.ids, application.id) + +@testset "environment backend admission preserves discovery and index callback order" begin + observed = index_discovery_fixture(false) + control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, + constants=PSE.Constants()) + plan_types = unique(typeof.(control.environment_bindings.application_plans)) + # Two distinct plan families share the same backend type. One index callback + # must not be repeated for each matching family witness. + @test count(P -> fieldtype(P, :backend) === Backend, plan_types) == 2 + schema = PSE._environment_plan_schema_from_types(plan_types) + for fixed in (false, true) + data = index_discovery_fixture(fixed) + model, events = data.model, data.events + active_schema = fixed ? schema : nothing + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_plan_schema=active_schema) + compiled = simulation.compiled + application_ids = Symbol[] + collector = ApplicationIDCollector(application_ids) + @test !(collector isa Function) + @test isnothing(PSE._foreach_object_application(collector, compiled, ObjectId(1))) + @test application_ids == [:first] + discoveries = [(:discover, :first), (:discover, :shared), (:discover, :other)] + indexed = [(:index, objectid(data.backend_a)), (:index, objectid(data.backend_b))] + # Initial preparation has its existing discovery pass, then index calls, + # then the separate existing application-plan normalization pass. + @test index_trace(events) == vcat(discoveries, indexed, discoveries) + @test simulation.environment_bindings.application_plan_schema === active_schema + + empty!(events) + PSE._update_model_environment_indices!(model, compiled) + @test index_trace(events) == vcat(discoveries, indexed) + updates = filter(event -> event.phase === :index, events) + @test updates[1].entities === updates[2].entities + @test updates[1].removed_object_ids === updates[2].removed_object_ids + @test data.backend_a !== data.backend_b + @test data.backend_a.values == data.backend_b.values + + empty!(events) + owner = model.environment_binding_cache + changed = ObjectId[ObjectId(:leaf), ObjectId(1)] + PSE._update_model_environment_indices_for_objects!(model, compiled, owner, changed) + @test index_trace(events) == [(:index, objectid(data.backend_a))] + @test [entity.id for entity in only(events).entities] == [:leaf, 1] + + empty!(events) + mark_environment_binding_dirty!(model) + owner = PSE.Advanced.refresh_environment_bindings!(model, compiled) + @test owner.application_plan_schema === active_schema + @test index_trace(events) == vcat(discoveries, indexed, discoveries) + + # A different current geometry owner must preserve its schema and the + # newly discovered backend order, rather than the witness-table order. + alternate = PSE.Advanced.compile_composite_model(model, + (model.applications[3], model.applications[2], model.applications[1], model.applications[4])) + empty!(events) + PSE.Advanced.refresh_environment_bindings!(model, alternate; force=true) + alternate_discoveries = [(:discover, :other), (:discover, :shared), (:discover, :first)] + @test index_trace(events) == vcat(alternate_discoveries, reverse(indexed), alternate_discoveries) + empty!(events) + update_geometry!(model, 1, (cell=:b,)) + restored = PSE.Advanced.refresh_environment_bindings!(model, compiled) + @test restored.application_plan_schema === active_schema + @test index_trace(events) == vcat(discoveries, [(:index, objectid(data.backend_a))]) + @test only(last(events).entities).geometry == (cell=:b,) + + empty!(events) + forbidden_iteration = (error("Global sources must not collect index entities") for _ in 1:1) + @test isnothing(PSE._update_model_environment_indices!(model, + Any[EA.GlobalConstant((T=1.0f0,))], forbidden_iteration)) + @test isempty(events) + end +end + +@testset "environment discovery retains actual values beyond 32 applications" begin + observed = index_discovery_fixture(false) + control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, + constants=PSE.Constants()) + schema = PSE._environment_plan_schema_from_types( + unique(typeof.(control.environment_bindings.application_plans))) + for fixed in (false, true) + data = index_discovery_fixture(fixed; extra_applications=36) + simulation = PSE._prepare_simulation!(data.model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_plan_schema=fixed ? schema : nothing) + compiled = simulation.compiled + names = [:first, :shared, :other, [Symbol(:extra_, index) for index in 1:36]...] + discoveries = [(:discover, name) for name in names] + indexed = [(:index, objectid(data.backend_a)), (:index, objectid(data.backend_b))] + @test length(compiled.applications) == 40 + @test index_trace(data.events) == vcat(discoveries, indexed, discoveries) + + empty!(data.events) + backends, slots = PSE._model_environment_backends(data.model, compiled.applications_by_id) + @test backends isa PSE.CompiledMetadataTable + @test length(backends) == 40 + @test slots == [1, 3, 4] + @test backends[:first] === backends[:shared] === data.backend_a + @test backends[:other] === data.backend_b + @test all(index -> backends[Symbol(:extra_, index)] === data.backend_a, 1:36) + @test index_trace(data.events) == discoveries + + empty!(data.events) + PSE._update_model_environment_indices!(data.model, compiled) + @test index_trace(data.events) == vcat(discoveries, indexed) + end +end + +@testset "partial index updates snapshot selected plans and retain previous application IDs" begin + observed = index_discovery_fixture(false) + control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, + constants=PSE.Constants()) + schema = PSE._environment_plan_schema_from_types( + unique(typeof.(control.environment_bindings.application_plans))) + for fixed in (false, true) + data = index_discovery_fixture(fixed) + model, events = data.model, data.events + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_plan_schema=fixed ? schema : nothing) + compiled, owner = simulation.compiled, simulation.environment_bindings + + # A previous target remains relevant even when the supplied compiled + # application set no longer contains that application ID. + subset = PSE.Advanced.compile_composite_model(model, (model.applications[1],)) + empty!(events) + PSE._update_model_environment_indices_for_objects!(model, subset, owner, [ObjectId(:other)]) + @test index_trace(events) == [(:index, objectid(data.backend_b))] + + # Preserve the Set's actual order. The first callback replaces a later + # dictionary entry; its already-selected immutable plan must still run. + application_ids = Set{Symbol}() + push!(application_ids, :first) + push!(application_ids, :other) + first_id, second_id = collect(application_ids) + first_plan = owner.application_plans_by_id[first_id] + second_plan = owner.application_plans_by_id[second_id] + @test !ismutabletype(typeof(first_plan)) + @test first_plan.backend !== second_plan.backend + first_plan.backend.on_index = () -> (owner.application_plans_by_id[second_id] = first_plan) + empty!(events) + PSE._update_model_environment_indices_for_objects!(model, compiled, owner, + [ObjectId(1), ObjectId(:other)]) + @test index_trace(events) == [(:index, objectid(first_plan.backend)), + (:index, objectid(second_plan.backend))] + @test owner.application_plans_by_id[second_id] === first_plan + + first_plan.backend.on_index = nothing + owner.application_plans_by_id[second_id] = second_plan + remove_object!(model, :other) + empty!(events) + PSE._update_model_environment_indices_for_objects!(model, subset, owner, [ObjectId(:other)]) + @test index_trace(events) == [(:index, objectid(data.backend_b))] + @test isempty(only(events).entities) + @test only(events).removed_object_ids == [ObjectId(:other)] + end +end + @testset "environment index metadata preserves mixed values, order and live aliases" begin for closed in (false, true) data = fixture(closed) @@ -252,3 +465,90 @@ end end end + +module SwitchingBackendRepro +using PlantSimEngine, Dates, Test +import ..EnvironmentIndexIdentityChecks: close_registry +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +mutable struct Backend{Tag} <: EA.AbstractEnvironmentBackend + events::Vector{Any} +end +mutable struct Source{A,B} + a::A + b::B + calls::Int +end +tag(::Backend{Tag}) where {Tag} = Tag +function EA.environment_backend(source::Source) + source.calls += 1 + backend = isodd(source.calls) ? source.a : source.b + push!(backend.events, (; phase=:discover, call=source.calls, + tag=tag(backend), backend_id=objectid(backend))) + return backend +end +EA.base_step_seconds(::Backend) = 3600.0 +EA.get_nsteps(::Backend) = 1 +EA.environment_variables(::Backend) = Set((:T,)) +EA.bind_environment(::Backend, ::Object, context, config) = nothing +EA.sample(::Backend, ::Nothing, ::Symbol, time) = 5.0f0 +function EA.update_index!(backend::Backend, entities, removed_object_ids) + push!(backend.events, (; phase=:index, tag=tag(backend), + backend_id=objectid(backend), entity_ids=[entity.id for entity in entities], + removed_count=length(removed_object_ids))) + return nothing +end + +PSE.@process "switching_backend_probe" verbose=false +struct Probe <: AbstractSwitching_Backend_ProbeModel end +PSE.inputs_(::Probe) = NamedTuple() +PSE.outputs_(::Probe) = (seen=0.0f0,) +PSE.environment_inputs_(::Probe) = (T=0.0f0,) +function PSE.run!(::Probe, status, environment, constants, context) + status.seen = environment.T + return nothing +end + +function fixture(closed::Bool) + events = Any[] + a = Backend{:A}(events) + b = Backend{:B}(events) + source = Source(a, b, 0) + model = CompositeModel( + Object(:root; scale=:Scene, status=Status(seen=0.0f0)); + applications=(ModelSpec(Probe(); name=:probe, on=One(id=:root), + every=Dates.Hour(1), environment=Environment(backend=source)),), + environment=b) + closed && (model = close_registry(model)) + return (; model, source, a, b, events) +end + +@testset "discovered backend is independent of the later normalized plan family" begin + opened = fixture(false) + open_simulation = PSE._prepare_simulation!(opened.model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_plan_schema=Val(:collect)) + @test opened.source.calls == 2 + @test [(event.phase, event.tag) for event in opened.events] == + [(:discover, :A), (:index, :A), (:discover, :B)] + @test only(filter(event -> event.phase === :index, opened.events)).backend_id == objectid(opened.a) + @test only(open_simulation.environment_bindings.application_plans).backend === opened.b + plan_types = unique(typeof.(open_simulation.environment_bindings.application_plans)) + @test length(plan_types) == 1 + @test fieldtype(only(plan_types), :backend) === typeof(opened.b) + schema = PSE._environment_plan_schema_from_types(plan_types) + + closed = fixture(true) + simulation = PSE._prepare_simulation!(closed.model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_plan_schema=schema) + @test closed.source.calls == 2 + @test [(event.phase, event.tag) for event in closed.events] == + [(:discover, :A), (:index, :A), (:discover, :B)] + updates = filter(event -> event.phase === :index, closed.events) + @test only(updates).backend_id == objectid(closed.a) + @test only(updates).entity_ids == [:root] + @test only(updates).removed_count == 0 + @test only(simulation.environment_bindings.application_plans).backend === closed.b + @test simulation.environment_bindings.application_plan_schema === schema +end +end From a345e98cdbfa35a391d1d44d4c0ab38242809eaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 08:22:42 +0100 Subject: [PATCH 062/324] Report elapsed time for each test group --- test/runtests.jl | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test/runtests.jl b/test/runtests.jl index bd94dd6eb..211569a33 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -49,10 +49,16 @@ else for group_index in group_indices name, files = TEST_GROUPS[group_index] - @testset "$name" begin - for file in files - include(file) + @info "Test group start" group_index name files + group_started_at = time_ns() + try + @testset "$name" begin + for file in files + include(file) + end end + finally + @info "Test group end" group_index name elapsed_seconds=(time_ns() - group_started_at) / 1.0e9 end end From d667a4ea7873527641d2fc1ce1f54d42cbf3a067 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 10:37:41 +0100 Subject: [PATCH 063/324] Validate environment context IDs during refresh Preserve mixed identity families and removed-object metadata while admitting compiler-owned contexts at the comparison boundary. The two maintained environment files and targeted Aqua checks pass 782 assertions. JuliaC safe advances to the next binding-construction blocker; complete native XPalm remains unqualified. --- src/composite_model/environment_bindings.jl | 14 +++--- src/time/runtime/environment_backends.jl | 4 ++ ...test-model-environment-index-identities.jl | 44 +++++++++++++++++++ 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 5b08a5d87..d673dc245 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -588,11 +588,13 @@ function _same_environment_backend(a, b) return false end -function _same_environment_context(a, b) - return a.application == b.application && - a.object_id == b.object_id && - a.scale == b.scale && - a.process == b.process +function _same_environment_context(a, b, ::Type{I}) where {I<:ObjectId} + previous = a::EnvironmentContext + current = b::EnvironmentContext + return previous.application == current.application && + (previous.object_id::I) == (current.object_id::I) && + previous.scale == current.scale && + previous.process == current.process end function _same_environment_plan_configuration( @@ -693,7 +695,7 @@ function _reconcile_environment_binding_metadata( old.geometry_source_object_id == geometry_source_object_id || return nothing old.geometry_source == geometry_source || return nothing - _same_environment_context(old.context, context) || return nothing + _same_environment_context(old.context, context, keytype(cached.targets_by_object)) || return nothing if old.plan === plan push!(bindings, old) diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index e2043cb25..b622ecbfe 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -18,6 +18,10 @@ Immutable model-target metadata passed to [`bind_environment`](@ref). Backends return an opaque handle from that method and use the handle for all subsequent sampling and commits. Runtime status and geometry are intentionally absent: object-to-environment routing belongs to the compiled handle. + +For `CompositeModel` bindings, the compiler constructs this context with an +`ObjectId` value from its prepared identity family. Providers customize the +returned handle, while this metadata remains owned by the compiler. """ struct EnvironmentContext{O} application::Symbol diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index 2072d0975..0471452d9 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -364,6 +364,50 @@ function check_indexes(model, owner) end end +@testset "canonical environment contexts admit identity values independently of their parameter" begin + for closed in (false, true) + data = fixture(closed) + model, owner = data.model, data.simulation.environment_bindings + I = keytype(owner.targets_by_object) + integer = owner.by_target[(:probe, ObjectId(1))].context + symbolic = owner.by_target[(:probe, ObjectId(:leaf))].context + for context in (integer, symbolic) + fields = (context.application, context.object_id, context.scale, context.process) + @test PSE._same_environment_context(context, EA.EnvironmentContext(fields...), I) + for O in (Any, I) + widened = EA.EnvironmentContext{O}(fields...) + @test PSE._same_environment_context(context, widened, I) + @test PSE._same_environment_context(widened, context, I) + end + end + # An owner may mix identity types; a different context parameter is not + # an admission failure, and different identity values still compare false. + @test PSE._same_environment_context(integer, symbolic, I) === false + @test PSE._same_environment_context(symbolic, integer, I) === false + for changed in ( + EA.EnvironmentContext(:other, integer.object_id, integer.scale, integer.process), + EA.EnvironmentContext(integer.application, integer.object_id, :Other, integer.process), + EA.EnvironmentContext(integer.application, integer.object_id, integer.scale, :other), + ) + @test PSE._same_environment_context(integer, changed, I) === false + end + + # Keep the original short-circuit: different applications do not read + # or admit the identity value, even when it is outside the owner domain. + different_application = EA.EnvironmentContext(:other, missing, integer.scale, integer.process) + @test PSE._same_environment_context(different_application, integer, I) === false + same_application = EA.EnvironmentContext(integer.application, missing, integer.scale, integer.process) + @test_throws TypeError PSE._same_environment_context(same_application, integer, I) + + remove_object!(model, 1) + @test !haskey(model.registry.objects, integer.object_id) + retained = EA.EnvironmentContext{Any}(integer.application, integer.object_id, + integer.scale, integer.process) + @test PSE._same_environment_context(integer, retained, I) + @test PSE._same_environment_context(integer, symbolic, I) === false + end +end + @testset "environment indexes retain admitted identity pools" begin for closed in (false, true) data = fixture(closed) From fee076d4bd17a072573b29f57e6289529793d126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 14:14:04 +0100 Subject: [PATCH 064/324] Preserve concrete environment families in canonical preparation --- src/composite_model/compilation.jl | 19 +- src/composite_model/environment_bindings.jl | 342 +++++++++++++----- src/composite_model/registry_topology.jl | 8 +- src/composite_model/runtime_outputs.jl | 24 +- test/test-model-binding-index-identities.jl | 6 +- ...test-model-environment-binding-identity.jl | 325 ++++++++++++++--- ...test-model-environment-index-identities.jl | 56 +-- ...-model-global-environment-sample-schema.jl | 28 +- 8 files changed, 613 insertions(+), 195 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index bd87934fa..23686c4ef 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1760,6 +1760,21 @@ struct CompiledEnvironmentBinding{P,H,C} geometry_source::Symbol end +"""Type-only environment policy: open, collecting, or explicitly frozen.""" +struct EnvironmentBindingSchema{P,EB} + plans::P + bindings::EB + function EnvironmentBindingSchema(plans::P, bindings::EB) where {P,EB} + valid = (plans isa Nothing && bindings isa Nothing) || + (plans isa Vector{DataType} && bindings isa Vector{DataType}) || + (plans isa NamedTuple && bindings isa NamedTuple) + valid || throw(ArgumentError("An environment schema needs two matching open, collecting, or frozen type collections.")) + return new{P,EB}(plans, bindings) + end +end + +EnvironmentBindingSchema() = EnvironmentBindingSchema(nothing, nothing) + @inline function Base.getproperty( binding::CompiledEnvironmentBinding, name::Symbol, @@ -1804,8 +1819,8 @@ mutable struct CompiledEnvironmentBindings{SC,AP,API,B,I,PI,OI,C,S} const model::SC const application_plans::AP const application_plans_by_id::API - # nothing is the stable open policy; closed metadata holds only Val{PlanType}. - const application_plan_schema::S + # Only plan/binding TYPES enter this policy, never targets or live contexts. + const environment_schema::S const bindings::B const by_target::I const positions_by_target::PI diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index d673dc245..d00fc4ccd 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -179,7 +179,7 @@ function _update_model_environment_indices_for_objects!( seen = Set{UInt}() for application_id in application_ids plan = cached.application_plans_by_id[application_id] - _with_environment_plan(cached.application_plan_schema, plan) do admitted_plan + _with_environment_plan(cached.environment_schema, plan) do admitted_plan backend = admitted_plan.backend isnothing(backend) && return nothing id = objectid(backend) @@ -191,7 +191,7 @@ function _update_model_environment_indices_for_objects!( # Plans are immutable snapshots. Index callbacks may replace the owner's # dictionary entries, so consume these selected plans without rereading it. return _update_model_environment_indices!(model, plans, dirty_object_ids) do consume, plan - _with_environment_plan(cached.application_plan_schema, plan) do admitted_plan + _with_environment_plan(cached.environment_schema, plan) do admitted_plan consume(admitted_plan.backend) end end @@ -223,7 +223,7 @@ function _compile_environment_application_plans( applications_by_id; previous_plans_by_id=nothing, prepare_runtime::Bool=true, - plan_schema=nothing, + environment_schema=EnvironmentBindingSchema(), ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() @@ -281,14 +281,14 @@ function _compile_environment_application_plans( plans_by_source[source] = prepared_plan prepared_plan else - _with_environment_plan(plan_schema, cached_plan) do admitted_plan + _with_environment_plan(environment_schema, cached_plan) do admitted_plan build_plan(admitted_plan.sampler, admitted_plan.prepared_source) end end else build_plan(nothing, nothing) end - _with_environment_plan(identity, plan_schema, plan) + _with_environment_plan(identity, environment_schema, plan) push!(plans, plan) haskey(plans_by_id, application.id) && error( "Environment application-plan compilation produced duplicate application id `$(application.id)`.", @@ -299,22 +299,79 @@ function _compile_environment_application_plans( return plans, plans_by_id end -# Open owners retain the same type when their live configuration changes. -_environment_plan_schema(::Nothing) = nothing -_environment_plan_schema(owner::CompiledEnvironmentBindings) = owner.application_plan_schema +_environment_schema(::Nothing) = EnvironmentBindingSchema() +_environment_schema(owner::CompiledEnvironmentBindings) = owner.environment_schema +_collecting_environment_binding_schema() = EnvironmentBindingSchema(DataType[], DataType[]) -# The default preparation inherits its owner. Collection explicitly stays open; -# a fixed native schema is supplied before the first compilation of its plans. -_preparation_environment_plan_schema(::Nothing, cached) = _environment_plan_schema(cached) -_preparation_environment_plan_schema(::Val{:collect}, cached) = nothing -_preparation_environment_plan_schema(schema::CompiledMetadataTable, cached) = schema +_is_open_environment_schema(::EnvironmentBindingSchema{Nothing,Nothing}) = true +_is_open_environment_schema(::EnvironmentBindingSchema) = false +_is_collecting_environment_schema(::EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}) = true +_is_collecting_environment_schema(::EnvironmentBindingSchema) = false -@inline _with_environment_plan(f, ::Nothing, plan) = f(plan) -@generated function _with_environment_plan(f::F, schema::CompiledMetadataTable{T}, +function _remember_environment_type!(types::Vector{DataType}, T::DataType) + T in types || push!(types, T) + return nothing +end + +function _merge_environment_binding_schema!( + destination::EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}, + source::EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}, +) + foreach(T -> _remember_environment_type!(destination.plans, T), source.plans) + foreach(T -> _remember_environment_type!(destination.bindings, T), source.bindings) + return destination +end + +# Promoting an execution owner/type from collection would reintroduce the +# owner -> schema -> target/context -> owner cycle in a fresh prepared world. +function _environment_schema_contains_execution_type(T, seen=IdDict{Any,Nothing}()) + haskey(seen, T) && return false + seen[T] = nothing + if T isa Union + return any(part -> _environment_schema_contains_execution_type(part, seen), Base.uniontypes(T)) + elseif T isa UnionAll + return _environment_schema_contains_execution_type(Base.unwrap_unionall(T), seen) + elseif T isa Tuple + return any(part -> _environment_schema_contains_execution_type(part, seen), T) + elseif !(T isa DataType) + return false + end + for name in (:CompiledEnvironmentBindings, :CompiledExecutionTarget, :RunContext, :CallTargets, :Simulation) + isdefined(@__MODULE__, name) || continue + T <: getfield(@__MODULE__, name) && return true + end + return any(part -> _environment_schema_contains_execution_type(part, seen), T.parameters) +end + +function _freeze_environment_binding_schema( + collected::EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}, +) + all(P -> isconcretetype(P) && P <: CompiledEnvironmentApplicationPlan, collected.plans) || + throw(ArgumentError("Environment-plan evidence needs real concrete normalized plan types.")) + all(B -> isconcretetype(B) && B <: CompiledEnvironmentBinding, collected.bindings) || + throw(ArgumentError("Environment-binding evidence needs real concrete binding types.")) + any(_environment_schema_contains_execution_type, vcat(collected.plans, collected.bindings)) && + throw(ArgumentError("Environment evidence embeds execution-owner/target/context types; a fresh closed owner is not proven for that handle family.")) + names(prefix, types) = ntuple(index -> Symbol(prefix, index), length(types)) + plans = NamedTuple{names(:environment_plan_, collected.plans)}(Tuple(Val(P) for P in collected.plans)) + bindings = NamedTuple{names(:environment_binding_, collected.bindings)}(Tuple(Val(B) for B in collected.bindings)) + return EnvironmentBindingSchema(plans, bindings) +end + +_with_environment_plan(f, ::EnvironmentBindingSchema{Nothing,Nothing}, plan) = f(plan) +function _with_environment_plan(f, + schema::EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}, plan::CompiledEnvironmentApplicationPlan, -) where {F,T} +) + _remember_environment_type!(schema.plans, typeof(plan)) + return f(plan) +end + +@generated function _with_environment_plan(f::F, schema::EnvironmentBindingSchema{PT,BT}, + plan::CompiledEnvironmentApplicationPlan, +) where {F,PT<:NamedTuple,BT<:NamedTuple} branches = Expr[] - for Witness in fieldtypes(T) + for Witness in fieldtypes(PT) Witness <: Val || error("Environment-plan metadata must contain type witnesses only.") P = only(Witness.parameters) P isa DataType && isconcretetype(P) && P <: CompiledEnvironmentApplicationPlan || @@ -329,39 +386,99 @@ _preparation_environment_plan_schema(schema::CompiledMetadataTable, cached) = sc end end -# Host-only reconstruction from TYPES already observed in collection worlds. -# Their union must cover the initial and future normalized plan families. -function _environment_plan_schema_from_types(observed_types) - plan_types = unique(observed_types) - all(P -> P isa DataType && isconcretetype(P) && P <: CompiledEnvironmentApplicationPlan, - plan_types) || throw(ArgumentError("Supply actual observed normalized plan types.")) - witnesses = Tuple(Val(P) for P in plan_types) - names = ntuple(index -> Symbol(:environment_plan_, index), length(witnesses)) - return CompiledMetadataTable(NamedTuple{names}(witnesses)) +_with_environment_binding(f, ::EnvironmentBindingSchema{Nothing,Nothing}, binding::CompiledEnvironmentBinding) = f(binding) +function _with_environment_binding(f, + schema::EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}, + binding::CompiledEnvironmentBinding, +) + _with_environment_plan(identity, schema, getfield(binding, :plan)::CompiledEnvironmentApplicationPlan) + _remember_environment_type!(schema.bindings, typeof(binding)) + return f(binding) end -function _retype_environment_plan_owner(compiled, owner, schema) - for plan in owner.application_plans - _with_environment_plan(identity, schema, plan) +@generated function _with_environment_binding(f::F, schema::EnvironmentBindingSchema{P,EB}, + binding::CompiledEnvironmentBinding, +) where {F,P<:NamedTuple,EB<:NamedTuple} + branches = Expr[] + for Witness in fieldtypes(EB) + Witness <: Val || error("Environment-binding metadata needs type witnesses only.") + B = only(Witness.parameters) + B isa DataType && isconcretetype(B) && B <: CompiledEnvironmentBinding || + error("Environment-binding metadata needs actual concrete binding types.") + push!(branches, :(binding isa $B && return f(binding::$B))) end + return quote + $(branches...) + throw(ArgumentError("The environment binding is outside its prepared family schema. Prepare complete present/call/future binding evidence.")) + end +end + +function _construct_environment_binding(schema, plan, object_id, handle, context, + geometry_source_object_id, geometry_source, +) + binding = CompiledEnvironmentBinding(plan, object_id, handle, context, + geometry_source_object_id, geometry_source) + return _with_environment_binding(identity, schema, binding) +end + +function _new_environment_binding( + schema::Union{EnvironmentBindingSchema{Nothing,Nothing},EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}}, + plan, object_id, handle, context, geometry_source_object_id, geometry_source, +) + return _construct_environment_binding(schema, plan, object_id, handle, context, + geometry_source_object_id, geometry_source) +end + +@generated function _new_environment_binding(schema::EnvironmentBindingSchema{P,EB}, + plan::CompiledEnvironmentApplicationPlan, object_id::ObjectId, handle, context, + geometry_source_object_id::Union{Nothing,ObjectId}, geometry_source::Symbol, +) where {P<:NamedTuple,EB<:NamedTuple} + branches = Expr[] + for Witness in fieldtypes(EB) + B = only(Witness.parameters) + BP, H, C = (fieldtype(B, name) for name in (:plan, :handle, :context)) + # These describe the ordinary outer constructor's actual result. A + # widened old H remains admissible, but does not predict a new H value. + all(isconcretetype, (BP, H, C)) || continue + push!(branches, quote + if plan isa $BP && handle isa $H && context isa $C + return _construct_environment_binding(schema, plan::$BP, object_id, + handle::$H, context::$C, geometry_source_object_id, geometry_source) + end + end) + end + return quote + $(branches...) + throw(ArgumentError("The real environment binding fields have no witnessed constructor family. An undeclared future handle family cannot be inferred.")) + end +end + +_check_environment_schema_owner(::EnvironmentBindingSchema{Nothing,Nothing}, plans, bindings) = nothing +function _check_environment_schema_owner(schema::EnvironmentBindingSchema, plans, bindings) + foreach(plan -> _with_environment_plan(identity, schema, plan), plans) + foreach(binding -> _with_environment_binding(identity, schema, binding), bindings) + return nothing +end + +function _retype_environment_binding_owner(compiled, owner, schema) return _compiled_environment_bindings(owner.model, compiled, owner.application_plans, owner.application_plans_by_id, owner.bindings, owner.by_target, owner.sample_cache, - owner.positions_by_target, owner.targets_by_object; plan_schema=schema) + owner.positions_by_target, owner.targets_by_object; environment_schema=schema) end function _compile_environment_bindings_for_applications( model::CompositeModel, applications, plans_by_id; - plan_schema=nothing, + environment_schema=EnvironmentBindingSchema(), ) bindings = CompiledEnvironmentBinding[] for application in applications application_id = application.id application_process = application.process target_ids = application.target_ids - _with_environment_plan(plan_schema, plans_by_id[application_id]) do plan + _with_environment_plan(environment_schema, plans_by_id[application_id]) do plan for object_id in target_ids object = _model_object(model, object_id) context = _object_environment_context(application_id, application_process, object, object_id) @@ -375,7 +492,8 @@ function _compile_environment_bindings_for_applications( ) push!( bindings, - CompiledEnvironmentBinding( + _new_environment_binding( + environment_schema, plan, object_id, handle, @@ -394,24 +512,24 @@ function _compile_environment_bindings( model::CompositeModel, compiled::CompiledCompositeModel, plans_by_id; - plan_schema=nothing, + environment_schema=EnvironmentBindingSchema(), ) return _compile_environment_bindings_for_applications( model, compiled.applications, plans_by_id; - plan_schema, + environment_schema, ) end function _validate_model_environment_inputs!(bindings, applications_by_id, - ::Type{I}; plan_schema=nothing, + ::Type{I}; environment_schema=EnvironmentBindingSchema(), ) where {I<:ObjectId} missing_details = String[] for binding in bindings plan = getfield(binding, :plan)::CompiledEnvironmentApplicationPlan object_id = getfield(binding, :object_id)::I - _with_environment_plan(plan_schema, plan) do plan + _with_environment_plan(environment_schema, plan) do plan application_id = getfield(plan, :application_id) no_inputs = _with_metadata_entry(applications_by_id, application_id) do application isempty(_model_environment_input_names(application)) @@ -485,13 +603,14 @@ function _compiled_environment_bindings( targets_by_object=_index_environment_targets_by_object( bindings, keytype(model.registry.objects), ); - plan_schema=nothing, + environment_schema=EnvironmentBindingSchema(), ) + _check_environment_schema_owner(environment_schema, application_plans, bindings) return CompiledEnvironmentBindings( model, application_plans, application_plans_by_id, - plan_schema, + environment_schema, bindings, by_target, positions_by_target, @@ -550,24 +669,24 @@ end function compile_environment_bindings(model::CompositeModel, compiled::CompiledCompositeModel=refresh_bindings!(model)) cached = getfield(model, :environment_binding_cache)::Union{Nothing,CompiledEnvironmentBindings} - return _compile_environment_binding_owner(model, compiled, _environment_plan_schema(cached)) + return _compile_environment_binding_owner(model, compiled, _environment_schema(cached)) end function _compile_environment_binding_owner(model::CompositeModel, - compiled::CompiledCompositeModel, plan_schema, + compiled::CompiledCompositeModel, environment_schema, ) _update_model_environment_indices!(model, compiled) application_plans, application_plans_by_id = _compile_environment_application_plans(model, compiled.applications, - compiled.applications_by_id; plan_schema) + compiled.applications_by_id; environment_schema) bindings = _compile_environment_bindings( model, compiled, application_plans_by_id; - plan_schema, + environment_schema, ) _validate_model_environment_inputs!(bindings, compiled.applications_by_id, - keytype(model.registry.objects); plan_schema) + keytype(model.registry.objects); environment_schema) by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, @@ -576,7 +695,7 @@ function _compile_environment_binding_owner(model::CompositeModel, application_plans_by_id, bindings, by_target; - plan_schema, + environment_schema, ) end @@ -629,25 +748,23 @@ function _reconciled_environment_application_plans( compiled.applications, compiled.applications_by_id; previous_plans_by_id=cached.application_plans_by_id, - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() - plan_schema = cached.application_plan_schema + environment_schema = cached.environment_schema for candidate in candidates application_id = candidate.application_id old = get(cached.application_plans_by_id, application_id, nothing) plan = if isnothing(old) - _with_environment_plan(identity, plan_schema, candidates_by_id[application_id]) + _with_environment_plan(identity, environment_schema, candidates_by_id[application_id]) else - _with_environment_plan(plan_schema, old) do admitted_old - _with_environment_plan(plan_schema, candidates_by_id[application_id]) do admitted_candidate - _same_environment_plan_configuration(admitted_old, admitted_candidate) || - return nothing - return _same_environment_application_plan(admitted_old, admitted_candidate) ? - admitted_old : _with_environment_plan(identity, plan_schema, candidates_by_id[application_id]) - end - end + admitted_old = _with_environment_plan(identity, environment_schema, old) + admitted_candidate = _with_environment_plan(identity, environment_schema, candidates_by_id[application_id]) + _same_environment_plan_configuration(admitted_old, admitted_candidate) || + return nothing + _same_environment_application_plan(admitted_old, admitted_candidate) ? + admitted_old : _with_environment_plan(identity, environment_schema, candidates_by_id[application_id]) end isnothing(plan) && return nothing push!(plans, plan) @@ -656,6 +773,59 @@ function _reconciled_environment_application_plans( return plans, plans_by_id end +function _reconcile_environment_binding_values(schema, old, old_plan, plan, + object_id, context, geometry_source_object_id, geometry_source, ::Type{I}, +) where {I<:ObjectId} + _same_environment_plan_configuration(old_plan, plan) || return nothing + old.geometry_source_object_id == geometry_source_object_id || return nothing + old.geometry_source == geometry_source || return nothing + _same_environment_context(old.context, context, I) || return nothing + old.plan === plan && return old + return _new_environment_binding(schema, plan, object_id, old.handle, context, + geometry_source_object_id, geometry_source) +end + +function _reconcile_environment_binding( + schema::Union{EnvironmentBindingSchema{Nothing,Nothing},EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}}, + old::CompiledEnvironmentBinding, plan::CompiledEnvironmentApplicationPlan, + object_id, context, geometry_source_object_id, geometry_source, I::Type{<:ObjectId}, +) + _with_environment_binding(identity, schema, old) + old_plan = getfield(old, :plan)::CompiledEnvironmentApplicationPlan + _with_environment_plan(identity, schema, old_plan) + return _reconcile_environment_binding_values(schema, old, old_plan, plan, + object_id, context, geometry_source_object_id, geometry_source, I) +end + +# Admit the real old EB and both actual plans before entering the worker. No +# closure or argument tuple is constructed from an existential old binding. +@generated function _reconcile_environment_binding(schema::EnvironmentBindingSchema{PT,BT}, + old::CompiledEnvironmentBinding, plan::CompiledEnvironmentApplicationPlan, + object_id, context, geometry_source_object_id, geometry_source, I::Type{<:ObjectId}, +) where {PT<:NamedTuple,BT<:NamedTuple} + plan_types = [only(W.parameters) for W in fieldtypes(PT)] + branches = Expr[] + for Witness in fieldtypes(BT) + B = only(Witness.parameters) + old_plan = fieldtype(B, :plan) + old_types = isconcretetype(old_plan) && old_plan <: CompiledEnvironmentApplicationPlan ? + (old_plan,) : plan_types + for OP in old_types, NP in plan_types + push!(branches, quote + if old isa $B && getfield(old::$B, :plan) isa $OP && plan isa $NP + return _reconcile_environment_binding_values(schema, old::$B, + getfield(old::$B, :plan)::$OP, plan::$NP, object_id, context, + geometry_source_object_id, geometry_source, I) + end + end) + end + end + return quote + $(branches...) + throw(ArgumentError("Environment reconciliation lacks a witnessed old binding/current plan family.")) + end +end + function _reconcile_environment_binding_metadata( model::CompositeModel, compiled::CompiledCompositeModel, @@ -673,7 +843,7 @@ function _reconcile_environment_binding_metadata( bindings = CompiledEnvironmentBinding[] changed = false - plan_schema = cached.application_plan_schema + environment_schema = cached.environment_schema for application in compiled.applications application_id = application.id plan = application_plans_by_id[application_id] @@ -685,34 +855,12 @@ function _reconcile_environment_binding_metadata( context = _object_environment_context(application.id, application.process, object, object_id) _, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) - old_plan = getfield(old, :plan)::CompiledEnvironmentApplicationPlan - same_configuration = _with_environment_plan(plan_schema, old_plan) do admitted_old - _with_environment_plan(plan_schema, application_plans_by_id[application_id]) do admitted_current - _same_environment_plan_configuration(admitted_old, admitted_current) - end - end - same_configuration || return nothing - old.geometry_source_object_id == geometry_source_object_id || - return nothing - old.geometry_source == geometry_source || return nothing - _same_environment_context(old.context, context, keytype(cached.targets_by_object)) || return nothing - - if old.plan === plan - push!(bindings, old) - else - changed = true - push!( - bindings, - CompiledEnvironmentBinding( - plan, - object_id, - old.handle, - context, - geometry_source_object_id, - geometry_source, - ), - ) - end + binding = _reconcile_environment_binding(environment_schema, old, plan, + object_id, context, geometry_source_object_id, geometry_source, + keytype(cached.targets_by_object)) + isnothing(binding) && return nothing + changed |= binding !== old + push!(bindings, binding) end end changed || return _compiled_environment_bindings( @@ -725,11 +873,11 @@ function _reconcile_environment_binding_metadata( cached.sample_cache, cached.positions_by_target, cached.targets_by_object; - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) _validate_model_environment_inputs!(bindings, compiled.applications_by_id, keytype(model.registry.objects); - plan_schema=cached.application_plan_schema) + environment_schema=cached.environment_schema) by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, @@ -739,7 +887,7 @@ function _reconcile_environment_binding_metadata( bindings, by_target, cached.sample_cache; - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) end @@ -791,7 +939,7 @@ function _refresh_environment_bindings_for_objects( model, (partial_application,), cached.application_plans_by_id; - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) replacements[_environment_binding_target_key(binding, I)] = binding end @@ -802,7 +950,7 @@ function _refresh_environment_bindings_for_objects( (binding::CompiledEnvironmentBinding for binding in values(replacements)), compiled.applications_by_id, keytype(model.registry.objects); - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) for target in stale_targets @@ -848,7 +996,7 @@ function _refresh_environment_bindings_for_objects( cached.sample_cache, cached.positions_by_target, cached.targets_by_object; - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) end @@ -902,16 +1050,16 @@ end function _refresh_environment_bindings!(model::CompositeModel, compiled, cached::Union{Nothing,CompiledEnvironmentBindings}; force::Bool=false, - plan_schema=_environment_plan_schema(cached), + environment_schema=_environment_schema(cached), ) - policy_changed = !isnothing(cached) && cached.application_plan_schema !== plan_schema + policy_changed = !isnothing(cached) && cached.environment_schema !== environment_schema if policy_changed && !force && !model.environment_bindings_dirty && cached.model_revision == compiled.revision && cached.environment_revision == model.environment_revision && cached.compiled_applications === compiled.applications # Only the policy changes: validate current normalized values and retain # every existing handle/container, without replaying provider code. - refreshed = _retype_environment_plan_owner(compiled, cached, plan_schema) + refreshed = _retype_environment_binding_owner(compiled, cached, environment_schema) model.environment_binding_cache = refreshed _record_runtime_owner_replacement!(model, cached, refreshed) return refreshed @@ -925,7 +1073,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, partial_owner = cached.compiled_applications === compiled.applications ? cached : _reconcile_environment_binding_metadata(model, compiled, cached) if isnothing(partial_owner) - _compile_environment_binding_owner(model, compiled, plan_schema) + _compile_environment_binding_owner(model, compiled, environment_schema) else _refresh_environment_bindings_for_objects( model, @@ -935,7 +1083,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, ) end else - _compile_environment_binding_owner(model, compiled, plan_schema) + _compile_environment_binding_owner(model, compiled, environment_schema) end model.environment_binding_cache = refreshed _record_runtime_owner_replacement!(model, cached, refreshed) @@ -949,7 +1097,7 @@ function _refresh_environment_bindings!(model::CompositeModel, compiled, else reconciled = _reconcile_environment_binding_metadata(model, compiled, cached) refreshed = isnothing(reconciled) ? - _compile_environment_binding_owner(model, compiled, plan_schema) : reconciled + _compile_environment_binding_owner(model, compiled, environment_schema) : reconciled model.environment_binding_cache = refreshed _record_runtime_owner_replacement!(model, cached, refreshed) return refreshed diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 9d7c3062a..fa3905f51 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -890,11 +890,11 @@ function _mark_environment_bindings_dirty!( ids = _lifecycle_object_ids(object_ids) if isnothing(ids) || isnothing(model.environment_binding_cache) cached = model.environment_binding_cache - # Retain a closed owner's fixed policy while dirty; full_environment + # Keep explicit collection/frozen evidence while dirty; full_environment # still forces every handle to be rebuilt before the next execution. - closed = cached isa CompiledEnvironmentBindings && - getfield(cached, :application_plan_schema) isa CompiledMetadataTable - model.environment_binding_cache = closed ? cached : nothing + preserve_schema = cached isa CompiledEnvironmentBindings && + !_is_open_environment_schema(getfield(cached, :environment_schema)) + model.environment_binding_cache = preserve_schema ? cached : nothing delta.full_environment = true elseif !delta.full_environment union!(delta.environment_dirty_ids, ids) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index cd31de808..218065326 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -803,7 +803,8 @@ function _synchronize_tracked_call_targets!(targets::CallTargets{CS,EB}) where { candidate_environment = topology_dirty ? _prebarrier_environment_bindings(model,current_compiled,targets.environment_bindings) : _refresh_environment_bindings!(model,current_compiled, - _current_environment_binding_owner(model,targets.environment_bindings)) + _current_environment_binding_owner(model,targets.environment_bindings); + environment_schema=targets.environment_bindings.environment_schema) if isnothing(candidate_environment) current_compiled = targets.compiled current_environment_bindings = targets.environment_bindings @@ -1669,7 +1670,9 @@ _compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) = _compiled_application_by_id(identity, compiled, id) function _environment_binding_for(env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId) - return get(env_bindings.by_target, (application_id, object_id), nothing)::Union{Nothing,CompiledEnvironmentBinding} + binding = get(env_bindings.by_target, (application_id, object_id), nothing)::Union{Nothing,CompiledEnvironmentBinding} + isnothing(binding) && return nothing + return _with_environment_binding(identity, env_bindings.environment_schema, binding) end function _model_object_status(model::CompositeModel, object_id::ObjectId) @@ -5778,11 +5781,11 @@ function _targeted_call_environment_bindings( model, applications, cached.application_plans_by_id; - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) _validate_model_environment_inputs!(partial, applications_by_id, keytype(model.registry.objects); - plan_schema=cached.application_plan_schema) + environment_schema=cached.environment_schema) by_target = _index_environment_bindings(partial, keytype(model.registry.objects)) return _compiled_environment_bindings( model, @@ -5792,7 +5795,7 @@ function _targeted_call_environment_bindings( partial, by_target, cached.sample_cache; - plan_schema=cached.application_plan_schema, + environment_schema=cached.environment_schema, ) end @@ -7185,7 +7188,8 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.environment_bindings = _refresh_environment_bindings!( model, simulation.compiled, - environment_owner, + environment_owner; + environment_schema=simulation.environment_bindings.environment_schema, ) _runtime_performance_finish!( simulation.performance, @@ -7306,7 +7310,8 @@ function _refresh_simulation_runtime!(simulation::Simulation) simulation.environment_bindings = _refresh_environment_bindings!( model, simulation.compiled, - environment_owner, + environment_owner; + environment_schema=simulation.environment_bindings.environment_schema, ) _runtime_performance_finish!( simulation.performance, @@ -7826,7 +7831,7 @@ function _prepare_simulation!( constants, outputs, performance::Bool=false, - environment_plan_schema=nothing, + environment_schema=_environment_schema(getfield(model, :environment_binding_cache)), ) performance_counters = performance ? RuntimePerformanceCounters() : nothing initial_composite_started_at = @@ -7897,8 +7902,7 @@ function _prepare_simulation!( ) started_at = _runtime_performance_start(performance_counters) cached_environment = getfield(model, :environment_binding_cache)::Union{Nothing,CompiledEnvironmentBindings} - plan_schema = _preparation_environment_plan_schema(environment_plan_schema, cached_environment) - env_bindings = _refresh_environment_bindings!(model, compiled, cached_environment; plan_schema) + env_bindings = _refresh_environment_bindings!(model, compiled, cached_environment; environment_schema) _runtime_performance_finish!( performance_counters, :initial_environment_compile, diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 292d61425..4fac9157d 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -556,14 +556,16 @@ end owner = simulation.environment_bindings bindings = owner.bindings I = keytype(model.registry.objects) - schema = PSE._environment_plan_schema_from_types(typeof(plan) for plan in owner.application_plans) + collected = PSE._collecting_environment_binding_schema() + PSE._check_environment_schema_owner(collected, owner.application_plans, owner.bindings) + schema = PSE._freeze_environment_binding_schema(collected) references = (PSE.refvalue(model_status(model, 1), :x), PSE.refvalue(model_status(model, :leaf), :x)) states = (NamedTuple(model_status(model, 1)), NamedTuple(model_status(model, :leaf))) ids = [binding.object_id for binding in bindings] for table in (simulation.compiled.applications_by_id, Dict(application.id => application for application in simulation.compiled.applications)) - @test PSE._validate_model_environment_inputs!(bindings, table, I; plan_schema=schema) === nothing + @test PSE._validate_model_environment_inputs!(bindings, table, I; environment_schema=schema) === nothing @test [binding.object_id for binding in bindings] == ids @test PSE.refvalue(model_status(model, 1), :x) === references[1] @test PSE.refvalue(model_status(model, :leaf), :x) === references[2] diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 9341322a5..74aae94c3 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -1,6 +1,7 @@ module EnvironmentBindingsIdentityChecks using PlantSimEngine using Serialization +using Dates using Test const PSE = PlantSimEngine const EA = PSE.EnvironmentAPI @@ -53,7 +54,7 @@ function PSE.run!(::Leaf, status, environment, constants, context) return nothing end -function fixture(::Type{T}; steps=1, environment_plan_schema=nothing) where {T} +function fixture(::Type{T}; steps=1, environment_schema=PSE.EnvironmentBindingSchema()) where {T} capture = Ref{Any}() backend = Backend(Dict(:a => T(10), :b => T(20)), 0) model = CompositeModel( @@ -69,11 +70,11 @@ function fixture(::Type{T}; steps=1, environment_plan_schema=nothing) where {T} ModelSpec(Leaf(zero(T)); name=:manual_probe, on=Many(kind=:manual), environment=Environment(provider=:shell_probe)), ), environment=backend) - simulation = if isnothing(environment_plan_schema) + simulation = if PSE._is_open_environment_schema(environment_schema) run!(model; steps, outputs=:all) else prepared = PSE._prepare_simulation!(model; steps, outputs=:all, - constants=PSE.Constants(), environment_plan_schema) + constants=PSE.Constants(), environment_schema) PSE._continue_scene!(prepared, steps) end batch = only(batch for batch in simulation.execution_plan.batches @@ -82,10 +83,10 @@ function fixture(::Type{T}; steps=1, environment_plan_schema=nothing) where {T} return (; model, simulation, capture, backend, batch, kept) end -function fixture_plan_schema(::Type{T}) where {T} - initial = fixture(T; steps=0) - return PSE._environment_plan_schema_from_types( - typeof(plan) for plan in initial.simulation.environment_bindings.application_plans) +function fixture_environment_schema(::Type{T}) where {T} + schema = PSE._collecting_environment_binding_schema() + fixture(T; steps=0, environment_schema=schema) + return PSE._freeze_environment_binding_schema(schema) end function checkpoint_copy(simulation) @@ -96,8 +97,8 @@ function checkpoint_copy(simulation) end @testset "checkpointed environment owners preserve application identity" begin - for schema in (nothing, fixture_plan_schema(Float32)), copy_simulation in (deepcopy, checkpoint_copy) - data = fixture(Float32; environment_plan_schema=schema) + for schema in (PSE.EnvironmentBindingSchema(), fixture_environment_schema(Float32)), copy_simulation in (deepcopy, checkpoint_copy) + data = fixture(Float32; environment_schema=schema) simulation = data.simulation original_context = data.capture[] original_targets = only(original_context.calls) @@ -112,10 +113,10 @@ end if group.application.id === :owner) context = only(only(owner.batches).targets).context targets = only(context.calls) - @test typeof(environment_bindings.application_plan_schema) === - typeof(simulation.environment_bindings.application_plan_schema) - @test context.environment_bindings.application_plan_schema === - environment_bindings.application_plan_schema + @test typeof(environment_bindings.environment_schema) === + typeof(simulation.environment_bindings.environment_schema) + @test context.environment_bindings.environment_schema === + environment_bindings.environment_schema cached_batches = PSE._cached_call_execution_batches(targets) @test !isnothing(cached_batches) @@ -284,8 +285,8 @@ end end @testset "the typed boundary selects the current model cache after public refresh" begin - for schema in (nothing, fixture_plan_schema(Float32)) - data = fixture(Float32; environment_plan_schema=schema) + for schema in (PSE.EnvironmentBindingSchema(), fixture_environment_schema(Float32)) + data = fixture(Float32; environment_schema=schema) simulation = data.simulation prepared = simulation.environment_bindings @test PSE._current_environment_binding_owner(data.model, prepared) === prepared @@ -304,7 +305,7 @@ end @test data.backend.samples == samples mark_environment_binding_dirty!(data.model) - @test isnothing(schema) ? + @test PSE._is_open_environment_schema(schema) ? isnothing(PSE._current_environment_binding_owner(data.model, prepared)) : PSE._current_environment_binding_owner(data.model, prepared) === partial full = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) @@ -328,7 +329,7 @@ end @test is_current_alternate @test length(current.bindings) == 2 @test current.compiled_applications === alternate_compiled.applications - @test current.application_plan_schema === schema + @test current.environment_schema === schema samples = data.backend.samples restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) is_restored = restored === PSE.compiled_environment_bindings(data.model) @@ -404,15 +405,15 @@ end end @testset "a pending move reconciles an authoritative Advanced subset cache" begin - for schema in (nothing, fixture_plan_schema(Float32)) - data = fixture(Float32; environment_plan_schema=schema) + for schema in (PSE.EnvironmentBindingSchema(), fixture_environment_schema(Float32)) + data = fixture(Float32; environment_schema=schema) simulation = data.simulation alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( ModelSpec(Leaf(0.0f0); name=:manual_probe, on=Many(kind=:manual), environment=Environment(provider=:shell_probe)), )) alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) - @test alternate.application_plan_schema === schema + @test alternate.environment_schema === schema @test length(alternate.bindings) == 1 @test !haskey(alternate.application_plans_by_id, :scheduled_probe) move_object!(data.model, :scheduled_move, (cell=:b,)) @@ -625,19 +626,19 @@ function policy_model(variable=:T; active=true) applications=(policy_spec(variable; active),), environment=source) return (; model, source, backend) end -function prepare_policy(data; schema=nothing) +function prepare_policy(data; schema=PSE.EnvironmentBindingSchema()) return PSE._prepare_simulation!(data.model; steps=0, outputs=:all, - constants=PSE.Constants(), environment_plan_schema=schema) + constants=PSE.Constants(), environment_schema=schema) end policy_counts(data) = (data.source.normalizations, data.backend.binds, data.backend.samples) policy_types(simulation) = [typeof(plan) for plan in simulation.environment_bindings.application_plans] @testset "fixed environment policies admit plans before any initial bind" begin initial = policy_model(:T) - first_simulation = prepare_policy(initial; schema=Val(:collect)) + first_simulation = prepare_policy(initial; schema=PSE._collecting_environment_binding_schema()) first_types = policy_types(first_simulation) - initial_schema = PSE._environment_plan_schema_from_types(first_types) - @test first_simulation.environment_bindings.application_plan_schema === nothing + initial_schema = PSE._freeze_environment_binding_schema(first_simulation.environment_bindings.environment_schema) + @test PSE._is_collecting_environment_schema(first_simulation.environment_bindings.environment_schema) for active in (false, true) missing = policy_model(:U; active) @test_throws "policy_probe` is outside its prepared family schema" prepare_policy(missing; schema=initial_schema) @@ -650,7 +651,7 @@ policy_types(simulation) = [typeof(plan) for plan in simulation.environment_bind compiled = prepare_policy(fixed; schema=initial_schema) @test policy_counts(fixed) == policy_counts(ordinary) @test fixed.backend.binds == 2 - @test compiled.environment_bindings.application_plan_schema === initial_schema + @test compiled.environment_bindings.environment_schema === initial_schema @test map(binding -> binding.object_id, compiled.environment_bindings.bindings) == map(binding -> binding.object_id, control.environment_bindings.bindings) @test Set(binding.object_id for binding in compiled.environment_bindings.bindings) == @@ -665,13 +666,13 @@ end @testset "zero-target plans and observed future families obey the fixed union" begin a = policy_model(:T; active=false) - simulation = prepare_policy(a; schema=Val(:collect)) + simulation = prepare_policy(a; schema=PSE._collecting_environment_binding_schema()) first_types = policy_types(simulation) - first_schema = PSE._environment_plan_schema_from_types(first_types) + first_schema = PSE._freeze_environment_binding_schema(simulation.environment_bindings.environment_schema) alternate = PSE.Advanced.compile_composite_model(a.model, (policy_spec(:U; active=false),)) future = PSE.Advanced.refresh_environment_bindings!(a.model, alternate; force=true) @test isempty(future.bindings) - @test future.application_plan_schema === nothing + @test PSE._is_collecting_environment_schema(future.environment_schema) future_types = [typeof(plan) for plan in future.application_plans] @test first_types != future_types b = policy_model(:T; active=false) @@ -679,22 +680,22 @@ end alternate_b = PSE.Advanced.compile_composite_model(b.model, (policy_spec(:U; active=false),)) @test_throws "policy_probe` is outside its prepared family schema" PSE.Advanced.refresh_environment_bindings!(b.model, alternate_b) @test b.backend.binds == 0 - union_schema = PSE._environment_plan_schema_from_types(vcat(first_types, future_types)) + union_schema = PSE._freeze_environment_binding_schema(simulation.environment_bindings.environment_schema) c = policy_model(:T; active=false) admitted = prepare_policy(c; schema=union_schema) E = typeof(admitted.environment_bindings) alternate_c = PSE.Advanced.compile_composite_model(c.model, (policy_spec(:U; active=false),)) current = PSE.Advanced.refresh_environment_bindings!(c.model, alternate_c; force=true) @test typeof(current) === E - @test current.application_plan_schema === union_schema + @test current.environment_schema === union_schema @test only(typeof.(current.application_plans)) in future_types @test only(policy_types(admitted)) in first_types @test c.backend.binds == c.backend.samples == 0 end @testset "collection can reopen clean and dirty fixed environment owners" begin - observed = prepare_policy(policy_model()) - schema = PSE._environment_plan_schema_from_types(policy_types(observed)) + observed = prepare_policy(policy_model(); schema=PSE._collecting_environment_binding_schema()) + schema = PSE._freeze_environment_binding_schema(observed.environment_bindings.environment_schema) for dirty in (false, true) data = policy_model() simulation = prepare_policy(data; schema) @@ -706,9 +707,9 @@ end end before = policy_counts(data) current = PSE._refresh_environment_bindings!(data.model, simulation.compiled, owner; - plan_schema=nothing) + environment_schema=PSE._collecting_environment_binding_schema()) delta = policy_counts(data) .- before - @test current.application_plan_schema === nothing + @test PSE._is_collecting_environment_schema(current.environment_schema) @test current.application_plans === owner.application_plans || dirty @test current.bindings === owner.bindings || dirty @test data.backend.binds == before[2] + (dirty ? 2 : 0) @@ -722,30 +723,30 @@ end data = policy_model() previous = prepare_policy(data; schema) dirty && mark_environment_binding_dirty!(data.model) - collected = prepare_policy(data; schema=Val(:collect)) - @test collected.environment_bindings.application_plan_schema === nothing + collected = prepare_policy(data; schema=PSE._collecting_environment_binding_schema()) + @test PSE._is_collecting_environment_schema(collected.environment_bindings.environment_schema) alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) refreshed = PSE.Advanced.refresh_environment_bindings!(data.model, alternate) - @test refreshed.application_plan_schema === nothing + @test PSE._is_collecting_environment_schema(refreshed.environment_schema) @test only(refreshed.application_plans).compiled_sampling_rules != only(previous.environment_bindings.application_plans).compiled_sampling_rules end end @testset "dirty fixed policies survive checkpoints and rebuild handles" begin - schema = fixture_plan_schema(Float32) + schema = fixture_environment_schema(Float32) for copy_simulation in (deepcopy, checkpoint_copy) - data = fixture(Float32; environment_plan_schema=schema) + data = fixture(Float32; environment_schema=schema) move_object!(data.model, :scheduled_move, (cell=:b,)) mark_environment_binding_dirty!(data.model) restored = copy_simulation(data.simulation) retained = restored.environment_bindings @test restored.model.environment_binding_cache === retained - S = typeof(retained.application_plan_schema) + S = typeof(retained.environment_schema) current = PSE.Advanced.refresh_environment_bindings!(restored.model, restored.compiled) @test current !== retained - @test typeof(current.application_plan_schema) === S - @test current.application_plan_schema === retained.application_plan_schema + @test typeof(current.environment_schema) === S + @test current.environment_schema === retained.environment_schema moved = current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))] @test moved.handle.cell === :b @test moved.handle !== retained.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle @@ -754,4 +755,242 @@ end end end + +@testset "reconciliation collects binding families and preserves live handle aliases" begin + evidence = PSE._collecting_environment_binding_schema() + control = policy_model(:T) + observed = prepare_policy(control; schema=evidence) + old_plan = only(observed.environment_bindings.application_plans) + alternate = PSE.Advanced.compile_composite_model(control.model, (policy_spec(:U),)) + future = PSE.Advanced.refresh_environment_bindings!(control.model, alternate; force=true) + new_plan = only(future.application_plans) + @test typeof(new_plan) !== typeof(old_plan) + @test PSE._same_environment_plan_configuration(old_plan, new_plan) + @test evidence === future.environment_schema + schema = PSE._freeze_environment_binding_schema(evidence) + @test all(P -> P in evidence.plans, typeof.(future.application_plans)) + @test all(B -> B in evidence.bindings, typeof.(future.bindings)) + + for policy in (PSE.EnvironmentBindingSchema(), schema) + data = policy_model(:T) + simulation = prepare_policy(data; schema=policy) + owner = simulation.environment_bindings + alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) + before = policy_counts(data) + refreshed = PSE.Advanced.refresh_environment_bindings!(data.model, alternate) + @test refreshed !== owner + @test refreshed.environment_schema === policy + @test policy_counts(data) == (before[1] + 1, before[2], before[3]) + @test typeof(only(refreshed.application_plans)) !== typeof(only(owner.application_plans)) + for object_id in (ObjectId(:leaf), ObjectId(1)) + old = owner.by_target[(:policy_probe, object_id)] + binding = refreshed.by_target[(:policy_probe, object_id)] + @test binding !== old + @test binding.plan === only(refreshed.application_plans) + @test binding.handle === old.handle + @test binding.object_id === object_id + @test binding.context.object_id === object_id + @test binding.geometry_source_object_id === old.geometry_source_object_id + @test binding.geometry_source === old.geometry_source + binding.handle.cell = :b + @test old.handle.cell === :b + @test PSE._model_environment_for_model(refreshed, + alternate.applications_by_id[:policy_probe], object_id, 1) == (U=20f0,) + end + data.backend.values = (T=11f0, U=29f0) + @test PSE._model_environment_for_model(refreshed, + alternate.applications_by_id[:policy_probe], ObjectId(:leaf), 1) == (U=29f0,) + sampled = policy_counts(data) + @test sampled == (before[1] + 1, before[2], before[3] + 3) + @test PSE.Advanced.refresh_environment_bindings!(data.model, alternate) === refreshed + @test policy_counts(data) == sampled + end + + # Explicitly widened Advanced fields are admitted as their real old EB; + # the usual outer constructor still infers the new plan/handle/context. + before = policy_counts(control) + process = first(observed.environment_bindings.bindings).context.process + for object_id in (ObjectId(:leaf), ObjectId(1)) + narrow = EA.EnvironmentContext(:policy_probe, object_id, :Leaf, process) + wide = EA.EnvironmentContext{Any}(:policy_probe, object_id, :Leaf, process) + for (old_context, context) in ((wide, narrow), (narrow, wide)), + plan_field_type in (typeof(old_plan), Any) + handle = Handle(:a) + old = PSE.CompiledEnvironmentBinding{plan_field_type,Any,typeof(old_context)}( + old_plan, object_id, handle, old_context, object_id, :self) + collected = PSE._collecting_environment_binding_schema() + expected = PSE._new_environment_binding(collected, new_plan, + object_id, handle, context, object_id, :self) + PSE._with_environment_binding(identity, collected, old) + fixed = PSE._freeze_environment_binding_schema(collected) + for policy in (PSE.EnvironmentBindingSchema(), collected, fixed) + binding = PSE._reconcile_environment_binding(policy, old, new_plan, + object_id, context, object_id, :self, ObjectId) + @test typeof(binding) === typeof(expected) + @test fieldtype(typeof(binding), :handle) === Handle + @test binding.plan === new_plan + @test binding.context === context + @test binding.object_id === object_id + @test binding.geometry_source_object_id === object_id + @test binding.handle === old.handle === handle + binding.handle.cell = :b + @test old.handle.cell === :b + end + end + end + @test policy_counts(control) == before +end + +@testset "collection seeds existing bindings without replaying providers" begin + data = policy_model() + simulation = prepare_policy(data) + cached = simulation.environment_bindings + evidence = PSE._collecting_environment_binding_schema() + before = policy_counts(data) + current = PSE._refresh_environment_bindings!(data.model, simulation.compiled, cached; + environment_schema=evidence) + @test policy_counts(data) == before + @test current.bindings === cached.bindings + @test current.by_target === cached.by_target + @test current.sample_cache === cached.sample_cache + @test Set(evidence.plans) == Set(typeof.(cached.application_plans)) + @test Set(evidence.bindings) == Set(typeof.(cached.bindings)) + E = typeof(current) + mark_environment_binding_dirty!(data.model) + @test data.model.environment_binding_cache === current + rebuilt = PSE.Advanced.refresh_environment_bindings!(data.model, simulation.compiled) + @test typeof(rebuilt) === E + @test rebuilt.environment_schema === evidence + @test data.backend.binds == before[2] + 2 +end + +@testset "discarded reconciliation temporaries remain part of collected evidence" begin + data = policy_model(:T) + evidence = PSE._collecting_environment_binding_schema() + simulation = prepare_policy(data; schema=evidence) + owner = simulation.environment_bindings + alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) + ids = only(alternate.applications).target_ids + first_id, later_id = first(ids), last(ids) + # A stale later context makes the metadata fast path give up, after the + # first actual binding has already been constructed for the new plan. + old = owner.by_target[(:policy_probe, later_id)] + wrong_context = EA.EnvironmentContext(:stale_application, later_id, + old.context.scale, old.context.process) + owner.by_target[(:policy_probe, later_id)] = PSE.CompiledEnvironmentBinding( + old.plan, later_id, old.handle, wrong_context, + old.geometry_source_object_id, old.geometry_source) + before = policy_counts(data) + result = PSE._reconcile_environment_binding_metadata(data.model, alternate, owner) + @test isnothing(result) + @test policy_counts(data) == (before[1] + 1, before[2], before[3]) + new_plan_types = filter(P -> P !== typeof(old.plan), evidence.plans) + @test length(new_plan_types) == 1 + @test any(B -> fieldtype(B, :plan) === only(new_plan_types) && + fieldtype(B, :context) === typeof(EA.EnvironmentContext(:policy_probe, + first_id, :Leaf, old.context.process)), evidence.bindings) + @test data.model.environment_binding_cache === owner +end + +@testset "frozen evidence is detached and rejects an undeclared handle family" begin + evidence = PSE._collecting_environment_binding_schema() + data = policy_model() + simulation = prepare_policy(data; schema=evidence) + binding = first(simulation.environment_bindings.bindings) + fixed = PSE._freeze_environment_binding_schema(evidence) + @test fixed.plans isa NamedTuple + @test fixed.bindings isa NamedTuple + @test all(witness -> witness isa Val, values(fixed.plans)) + @test all(witness -> witness isa Val, values(fixed.bindings)) + plan_count, binding_count = length(fixed.plans), length(fixed.bindings) + different = PSE._new_environment_binding(evidence, binding.plan, + binding.object_id, Ref(:a), binding.context, + binding.geometry_source_object_id, binding.geometry_source) + @test length(evidence.bindings) == binding_count + 1 + @test length(fixed.plans) == plan_count + @test length(fixed.bindings) == binding_count + @test_throws "outside its prepared family schema" PSE._with_environment_binding(identity, fixed, different) + @test_throws "no witnessed constructor family" PSE._new_environment_binding(fixed, + binding.plan, binding.object_id, different.handle, binding.context, + binding.geometry_source_object_id, binding.geometry_source) + @test PSE._with_environment_binding(identity, PSE.EnvironmentBindingSchema(), different) === different + merged = PSE._collecting_environment_binding_schema() + @test PSE._merge_environment_binding_schema!(merged, evidence) === merged + @test merged.plans == evidence.plans + @test merged.bindings == evidence.bindings + empty!(evidence.plans) + empty!(evidence.bindings) + @test length(merged.plans) == plan_count + @test length(merged.bindings) == binding_count + 1 + @test_throws ArgumentError PSE.EnvironmentBindingSchema(nothing, DataType[]) + owner_handle = PSE._new_environment_binding(merged, binding.plan, + binding.object_id, simulation.environment_bindings, binding.context, + binding.geometry_source_object_id, binding.geometry_source) + @test owner_handle.handle === simulation.environment_bindings + @test PSE._with_environment_binding(identity, PSE.EnvironmentBindingSchema(), owner_handle) === owner_handle + @test_throws "embeds execution-owner/target/context types" PSE._freeze_environment_binding_schema(merged) +end + + +struct InitializingOwner{C} <: AbstractEnvironment_Shell_OwnerModel + capture::C +end +PSE.inputs_(::InitializingOwner) = NamedTuple() +PSE.outputs_(::InitializingOwner) = (created=false, initialized=-1f0) +function PSE.run!(model::InitializingOwner, status, environment, constants, context) + status.created && return nothing + object = register_object!(runtime_model(context), Object(:newborn; scale=:Leaf, + parent=:scene, status=Status(seen=0f0, calls=0))) + initialized = run_initializer!(context, :newborn, object) + status.initialized = initialized.seen + status.created = true + model.capture[] = context + return nothing +end + +function initialization_fixture(schema) + capture = Ref{Any}() + model = CompositeModel(Object(:scene; scale=:Scene); + applications=( + ModelSpec(InitializingOwner(capture); name=:create, on=One(id=:scene), + every=Hour(1), calls=(newborn=Initializer(One(scale=:Leaf, application=:leaf)),)), + ModelSpec(Leaf(0f0); name=:leaf, on=Many(scale=:Leaf), every=Hour(1)), + ), environment=(T=10f0, duration=Hour(1))) + simulation = PSE._prepare_simulation!(model; steps=1, outputs=:all, + constants=PSE.Constants(), environment_schema=schema) + return (; model, simulation, capture) +end + +@testset "newborn targeted initialization collects before fresh closed preparations" begin + evidence = PSE._collecting_environment_binding_schema() + a = initialization_fixture(evidence) + initial_owner = a.simulation.environment_bindings + @test :leaf in map(plan -> plan.application_id, initial_owner.application_plans) + @test !haskey(initial_owner.by_target, (:leaf, ObjectId(:newborn))) + initial_binding_types = copy(evidence.bindings) + E = typeof(initial_owner) + step!(a.simulation) + @test typeof(a.simulation.environment_bindings) === E + @test a.simulation.environment_bindings.environment_schema === evidence + newborn = a.simulation.environment_bindings.by_target[(:leaf, ObjectId(:newborn))] + @test typeof(newborn) in evidence.bindings + @test all(B -> B in evidence.bindings, initial_binding_types) + @test model_status(a.model, :scene).initialized === 10f0 + @test model_status(a.model, :newborn).seen === 10f0 + fixed = PSE._freeze_environment_binding_schema(evidence) + # Both worlds start from the scenario source, before their own caches and + # calls exist. Only Val{Type} witnesses cross from A to B/P. + b, p = initialization_fixture(fixed), initialization_fixture(fixed) + @test b.model !== p.model !== a.model + @test b.simulation.environment_bindings !== p.simulation.environment_bindings + for fresh in (b, p) + @test fresh.simulation.environment_bindings.environment_schema === fixed + step!(fresh.simulation) + @test fresh.simulation.environment_bindings.environment_schema === fixed + @test typeof(fresh.simulation.environment_bindings.by_target[(:leaf, ObjectId(:newborn))]) in evidence.bindings + @test final_state(fresh.simulation, Many()) == final_state(a.simulation, Many()) + @test isequal(collect_outputs(fresh.simulation), collect_outputs(a.simulation)) + end +end + end diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index 0471452d9..a4156d358 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -67,7 +67,7 @@ function close_registry(model::CompositeModel) ) end -function fixture(closed::Bool) +function fixture(closed::Bool; environment_schema=PSE.EnvironmentBindingSchema()) backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, Any[], nothing) model = CompositeModel( Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), @@ -78,7 +78,9 @@ function fixture(closed::Bool) applications=(ModelSpec(Probe(); name=:probe, on=Many(scale=:Leaf), environment=Environment(provider=:identity_probe)),), environment=backend) closed && (model = close_registry(model)) - simulation = run!(model; steps=1, outputs=:all) + simulation = PSE._prepare_simulation!(model; steps=1, outputs=:all, + constants=PSE.Constants(), environment_schema) + PSE._continue_scene!(simulation, 1) return (; model, simulation, backend) end @@ -129,20 +131,20 @@ end (collector::ApplicationIDCollector)(application) = push!(collector.ids, application.id) @testset "environment backend admission preserves discovery and index callback order" begin - observed = index_discovery_fixture(false) + observed = index_discovery_fixture(true) control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, - constants=PSE.Constants()) + constants=PSE.Constants(), environment_schema=PSE._collecting_environment_binding_schema()) plan_types = unique(typeof.(control.environment_bindings.application_plans)) # Two distinct plan families share the same backend type. One index callback # must not be repeated for each matching family witness. @test count(P -> fieldtype(P, :backend) === Backend, plan_types) == 2 - schema = PSE._environment_plan_schema_from_types(plan_types) + schema = PSE._freeze_environment_binding_schema(control.environment_bindings.environment_schema) for fixed in (false, true) data = index_discovery_fixture(fixed) model, events = data.model, data.events - active_schema = fixed ? schema : nothing + active_schema = fixed ? schema : PSE.EnvironmentBindingSchema() simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, - constants=PSE.Constants(), environment_plan_schema=active_schema) + constants=PSE.Constants(), environment_schema=active_schema) compiled = simulation.compiled application_ids = Symbol[] collector = ApplicationIDCollector(application_ids) @@ -154,7 +156,7 @@ end # Initial preparation has its existing discovery pass, then index calls, # then the separate existing application-plan normalization pass. @test index_trace(events) == vcat(discoveries, indexed, discoveries) - @test simulation.environment_bindings.application_plan_schema === active_schema + @test simulation.environment_bindings.environment_schema === active_schema empty!(events) PSE._update_model_environment_indices!(model, compiled) @@ -175,7 +177,7 @@ end empty!(events) mark_environment_binding_dirty!(model) owner = PSE.Advanced.refresh_environment_bindings!(model, compiled) - @test owner.application_plan_schema === active_schema + @test owner.environment_schema === active_schema @test index_trace(events) == vcat(discoveries, indexed, discoveries) # A different current geometry owner must preserve its schema and the @@ -189,7 +191,7 @@ end empty!(events) update_geometry!(model, 1, (cell=:b,)) restored = PSE.Advanced.refresh_environment_bindings!(model, compiled) - @test restored.application_plan_schema === active_schema + @test restored.environment_schema === active_schema @test index_trace(events) == vcat(discoveries, [(:index, objectid(data.backend_a))]) @test only(last(events).entities).geometry == (cell=:b,) @@ -202,15 +204,14 @@ end end @testset "environment discovery retains actual values beyond 32 applications" begin - observed = index_discovery_fixture(false) + observed = index_discovery_fixture(true) control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, - constants=PSE.Constants()) - schema = PSE._environment_plan_schema_from_types( - unique(typeof.(control.environment_bindings.application_plans))) + constants=PSE.Constants(), environment_schema=PSE._collecting_environment_binding_schema()) + schema = PSE._freeze_environment_binding_schema(control.environment_bindings.environment_schema) for fixed in (false, true) data = index_discovery_fixture(fixed; extra_applications=36) simulation = PSE._prepare_simulation!(data.model; steps=0, outputs=:none, - constants=PSE.Constants(), environment_plan_schema=fixed ? schema : nothing) + constants=PSE.Constants(), environment_schema=fixed ? schema : PSE.EnvironmentBindingSchema()) compiled = simulation.compiled names = [:first, :shared, :other, [Symbol(:extra_, index) for index in 1:36]...] discoveries = [(:discover, name) for name in names] @@ -235,16 +236,15 @@ end end @testset "partial index updates snapshot selected plans and retain previous application IDs" begin - observed = index_discovery_fixture(false) + observed = index_discovery_fixture(true) control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, - constants=PSE.Constants()) - schema = PSE._environment_plan_schema_from_types( - unique(typeof.(control.environment_bindings.application_plans))) + constants=PSE.Constants(), environment_schema=PSE._collecting_environment_binding_schema()) + schema = PSE._freeze_environment_binding_schema(control.environment_bindings.environment_schema) for fixed in (false, true) data = index_discovery_fixture(fixed) model, events = data.model, data.events simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, - constants=PSE.Constants(), environment_plan_schema=fixed ? schema : nothing) + constants=PSE.Constants(), environment_schema=fixed ? schema : PSE.EnvironmentBindingSchema()) compiled, owner = simulation.compiled, simulation.environment_bindings # A previous target remains relevant even when the supplied compiled @@ -478,8 +478,11 @@ end end @testset "partial growth and retirement update the same environment indexes" begin - for closed in (false, true) - data = fixture(closed) + evidence = PSE._collecting_environment_binding_schema() + fixture(true; environment_schema=evidence) + fixed = PSE._freeze_environment_binding_schema(evidence) + for closed in (false, true), schema in (PSE.EnvironmentBindingSchema(), evidence, fixed) + data = fixture(closed; environment_schema=schema) model, simulation = data.model, data.simulation previous = simulation.environment_bindings register_object!(model, Object(2; scale=:Leaf, parent=:root, geometry=(cell=:a,), @@ -489,6 +492,7 @@ end @test current.by_target === previous.by_target @test current.positions_by_target === previous.positions_by_target @test current.targets_by_object === previous.targets_by_object + @test current.environment_schema === previous.environment_schema === schema @test length(current.bindings) == 3 @test model_status(model, 2).seen === 13.0f0 @test model_status(model, 2).visits == 1 @@ -571,7 +575,7 @@ end @testset "discovered backend is independent of the later normalized plan family" begin opened = fixture(false) open_simulation = PSE._prepare_simulation!(opened.model; steps=0, outputs=:none, - constants=PSE.Constants(), environment_plan_schema=Val(:collect)) + constants=PSE.Constants(), environment_schema=PSE._collecting_environment_binding_schema()) @test opened.source.calls == 2 @test [(event.phase, event.tag) for event in opened.events] == [(:discover, :A), (:index, :A), (:discover, :B)] @@ -580,11 +584,11 @@ end plan_types = unique(typeof.(open_simulation.environment_bindings.application_plans)) @test length(plan_types) == 1 @test fieldtype(only(plan_types), :backend) === typeof(opened.b) - schema = PSE._environment_plan_schema_from_types(plan_types) + schema = PSE._freeze_environment_binding_schema(open_simulation.environment_bindings.environment_schema) closed = fixture(true) simulation = PSE._prepare_simulation!(closed.model; steps=0, outputs=:none, - constants=PSE.Constants(), environment_plan_schema=schema) + constants=PSE.Constants(), environment_schema=schema) @test closed.source.calls == 2 @test [(event.phase, event.tag) for event in closed.events] == [(:discover, :A), (:index, :A), (:discover, :B)] @@ -593,6 +597,6 @@ end @test only(updates).entity_ids == [:root] @test only(updates).removed_count == 0 @test only(simulation.environment_bindings.application_plans).backend === closed.b - @test simulation.environment_bindings.application_plan_schema === schema + @test simulation.environment_bindings.environment_schema === schema end end diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 8178f7879..7e0de6ca5 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -385,13 +385,14 @@ memo_preparations(source) = (source.sampler_preparations, source.source_preparat @testset "source-plan memo shares preparation and preserves current application metadata" begin observed_source = MemoPreparationSource(10f0, 20f0, Hour(1), 0, 0) - observed = run!(memo_source_model(observed_source); steps=0, outputs=:none) - schema = PSE._environment_plan_schema_from_types(typeof.(observed.environment_bindings.application_plans)) + observed = PSE._prepare_simulation!(memo_source_model(observed_source); steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=PSE._collecting_environment_binding_schema()) + schema = PSE._freeze_environment_binding_schema(observed.environment_bindings.environment_schema) for fixed in (false, true) source = MemoPreparationSource(10f0, 20f0, Hour(1), 0, 0) model = memo_source_model(source) simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, - constants=PSE.Constants(), environment_plan_schema=fixed ? schema : nothing) + constants=PSE.Constants(), environment_schema=fixed ? schema : PSE.EnvironmentBindingSchema()) compiled, owner = simulation.compiled, simulation.environment_bindings @test memo_preparations(source) == (1, 1) raw, mapped = owner.application_plans_by_id[:raw], owner.application_plans_by_id[:mapped] @@ -406,7 +407,7 @@ memo_preparations(source) = (source.sampler_preparations, source.source_preparat current, by_id = PSE._compile_environment_application_plans(model, compiled.applications, compiled.applications_by_id; previous_plans_by_id=owner.application_plans_by_id, - plan_schema=owner.application_plan_schema) + environment_schema=owner.environment_schema) @test memo_preparations(source) == (1, 1) @test map(plan -> plan.application_id, current) == [:raw, :mapped] for original in (raw, mapped) @@ -434,20 +435,23 @@ memo_preparations(source) = (source.sampler_preparations, source.source_preparat @test memo_preparations(source) == (1, 1) if fixed @test all(plan -> PSE._with_environment_plan(identity, schema, plan) === plan, current) - mapped_schema = PSE._environment_plan_schema_from_types([typeof(mapped)]) + mapped_evidence = PSE._collecting_environment_binding_schema() + PSE._check_environment_schema_owner(mapped_evidence, [mapped], + [owner.by_target[(:mapped, ObjectId(:b))]]) + mapped_schema = PSE._freeze_environment_binding_schema(mapped_evidence) @test_throws "raw` is outside its prepared family schema" PSE._refresh_environment_bindings!( - model, compiled, owner; plan_schema=mapped_schema) + model, compiled, owner; environment_schema=mapped_schema) @test model.environment_binding_cache === owner alternate = PSE.Advanced.compile_composite_model(model, (model.applications[2],)) replacement = PSE._refresh_environment_bindings!(model, alternate, owner; - plan_schema=mapped_schema) - @test replacement.application_plan_schema === mapped_schema + environment_schema=mapped_schema) + @test replacement.environment_schema === mapped_schema @test only(replacement.application_plans).application_id === :mapped @test memo_preparations(source) == (2, 2) again, _ = PSE._compile_environment_application_plans(model, alternate.applications, alternate.applications_by_id; previous_plans_by_id=replacement.application_plans_by_id, - plan_schema=replacement.application_plan_schema) + environment_schema=replacement.environment_schema) @test only(again).prepared_source === source @test memo_preparations(source) == (2, 2) end @@ -474,10 +478,12 @@ end end previous = Dict(:initial => initial, :newer => newer) expected = last(collect(values(previous))) - for schema in (nothing, PSE._environment_plan_schema_from_types(typeof.(fresh))) + collected = PSE._collecting_environment_binding_schema() + foreach(plan -> PSE._with_environment_plan(identity, collected, plan), fresh) + for schema in (PSE.EnvironmentBindingSchema(), PSE._freeze_environment_binding_schema(collected)) reused, _ = PSE._compile_environment_application_plans(data.model, compiled.applications, compiled.applications_by_id; - previous_plans_by_id=previous, plan_schema=schema) + previous_plans_by_id=previous, environment_schema=schema) @test map(plan -> plan.application_id, reused) == [:probe, :other] @test all(plan -> plan.sampler === expected.sampler, reused) @test all(plan -> plan.prepared_source === expected.prepared_source, reused) From 2827d5266534a7693e57697731e3de079803870a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 17:36:05 +0100 Subject: [PATCH 065/324] Preserve registry identity types in distributed output bindings --- src/composite_model/compilation.jl | 32 ++-- test/test-model-distributed-output-runtime.jl | 142 ++++++++++++++++++ 2 files changed, 160 insertions(+), 14 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 23686c4ef..6a3af2329 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -262,18 +262,18 @@ Base.propertynames(plan::CompiledModelOutputDestinationPlan) = (fieldnames(typeof(plan))..., :variable_names) """Real effective declarations and membership before status references are constructed.""" -struct ResolvedModelOutputDestination{P,D} +struct ResolvedModelOutputDestination{P,D,I<:ObjectId} plan::P declarations::D execution_object_id::ObjectId - destination_ids::Vector{ObjectId} + destination_ids::Vector{I} end """Compiled columnar references for one execution object and output group.""" -mutable struct CompiledModelOutputDestinationBinding{P,C,I} +mutable struct CompiledModelOutputDestinationBinding{P,C,I,ID<:ObjectId} const plan::P const execution_object_id::ObjectId - destination_ids::Vector{ObjectId} + destination_ids::Vector{ID} columns::C destination_index::I membership_generation::UInt64 @@ -5338,11 +5338,14 @@ function _resolve_model_output_destinations( declarations = _model_output_destination_declarations( application, execution_object_id, plan, ) - destination_ids = _dependency_object_ids( + destination_ids = _application_target_ids( model, - plan.selector, - plan.matcher, - execution_object_id, + _dependency_object_ids( + model, + plan.selector, + plan.matcher, + execution_object_id, + ), ) sizehint!(destination_ids, length(destination_ids) + 1) push!( @@ -6379,8 +6382,8 @@ function _model_output_destination_columns( return NamedTuple{names}(Tuple(columns)) end -function _model_output_destination_index(destination_ids) - index = Dict{ObjectId,Int}() +function _model_output_destination_index(destination_ids::AbstractVector{I}) where {I<:ObjectId} + index = Dict{I,Int}() sizehint!(index, length(destination_ids)) for (position, object_id) in pairs(destination_ids) haskey(index, object_id) && error( @@ -6437,8 +6440,9 @@ function _compile_model_output_destination_bindings( return bindings, by_execution_target end -function _index_model_output_destination_ids(bindings) - index = Dict{Tuple{Symbol,Symbol},Vector{ObjectId}}() +function _index_model_output_destination_ids(model::CompositeModel, bindings) + I = keytype(model.registry.objects) + index = Dict{Tuple{Symbol,Symbol},Vector{I}}() merged_keys = Set{Tuple{Symbol,Symbol}}() for binding in bindings for variable_ in binding.plan.variable_names @@ -6512,7 +6516,7 @@ function _compile_model_distributed_outputs( bindings, by_execution_target, ownership, - _index_model_output_destination_ids(bindings), + _index_model_output_destination_ids(model, bindings), ) end @@ -6592,7 +6596,7 @@ function _incremental_distributed_output_addition!( model, binding.execution_object_id, ) - destination_ids = ObjectId[ + destination_ids = keytype(model.registry.objects)[ object_id for object_id in added_ids if _selector_matches_object_id( model, diff --git a/test/test-model-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index c6fc57ecc..fb58af6d4 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1226,3 +1226,145 @@ end [:distributed_runtime_policy_updater] @test binding.policy isa Aggregate end + + +# Same closure mechanism used by the maintained finite-registry fixtures. Every +# status family here is an actual fully initialized object in this small scene. +function _distributed_runtime_closed_destination_registry(model::CompositeModel) + PSE = PlantSimEngine + previous = model.registry + registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), + previous.by_scale, previous.by_kind, previous.by_species, + previous.ancestor_ids_by_object) + return PSE.CompositeModel(registry, model.applications, model.environment, + model.instances, model.source_adapter, model.status_conversion, + model.status_conversion_records, model.status_source_owners, + model.status_source_identities, model.scenario_plan_cache, + model.binding_cache, model.environment_binding_cache, model.bindings_dirty, + model.environment_bindings_dirty, model.lifecycle_delta, + model.input_default_status_variables, model.runtime_revision, + model.revision, model.environment_revision) +end + +@testset "Closed distributed memberships retain the registry ID domain and live carriers" begin + PSE = PlantSimEngine + for (scene, leaves, added) in ((10, (20,), 30), + (:scene, (:leaf_a,), :leaf_z), (:scene, (20, :leaf_a), :leaf_z)) + model = CompositeModel( + Object(scene; scale=:Scene, status=Status(private_runs=0)), + (Object(id; scale=:Leaf, parent=scene, status=Status(incident_par=0.0)) for id in leaves)...; + applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); + name=:closed_destination_writer, on=One(id=scene), + outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope()); vars=(:incident_par,)),)),), + environment=(duration=Hour(1),)) + model = _distributed_runtime_closed_destination_registry(model) + simulation = run!(model; steps=0, outputs=:all, performance=true) + I = keytype(model.registry.objects) + binding = only(simulation.compiled.distributed_outputs.bindings) + ids = binding.destination_ids + index = simulation.compiled.distributed_outputs.destination_ids_by_application_variable + @test ids isa Vector{I} + @test fieldtype(typeof(binding), :destination_ids) === typeof(ids) + @test keytype(binding.destination_index) === I + @test index[(:closed_destination_writer, :incident_par)] === ids + @test object_ids(PSE.OutputTargets(binding, 1)).ids === ids + application = simulation.compiled.applications_by_id[:closed_destination_writer] + declarations = PSE._model_output_destination_declarations(application, binding.execution_object_id, binding.plan) + resolved = PSE.ResolvedModelOutputDestination(binding.plan, declarations, binding.execution_object_id, ids) + @test resolved.destination_ids === ids + @test fieldtype(typeof(resolved), :destination_ids) === typeof(ids) + carrier = binding.columns.incident_par + references = parent(carrier) + old_references = Tuple(references) + continue!(simulation) + register_object!(model, Object(added; scale=:Leaf, status=Status(incident_par=0.0)); parent=scene) + continue!(simulation) + current = only(simulation.compiled.distributed_outputs.bindings) + @test current === binding + @test current.destination_ids === ids + @test current.columns.incident_par === carrier + @test parent(carrier) === references + @test all(references[i] === old_references[i] for i in eachindex(old_references)) + @test simulation.compiled.distributed_outputs.destination_ids_by_application_variable[ + (:closed_destination_writer, :incident_par)] === ids + @test eltype(ids) === I + @test ids == PSE._sort_object_ids!(ObjectId.([leaves..., added])) + @test all(references[i] === PSE.refvalue(model_status(model, ids[i]), :incident_par) for i in eachindex(ids)) + @test all(model_status(model, id).incident_par == 102.0 for id in ids) + @test outputs(simulation)[(:closed_destination_writer, ObjectId(first(leaves)), :incident_par)] == [(1.0, 101.0), (2.0, 102.0)] + @test outputs(simulation)[(:closed_destination_writer, ObjectId(added), :incident_par)] == [(2.0, 102.0)] + end +end + +@testset "Closed distributed context and Self destinations share their normalized IDs" begin + PSE = PlantSimEngine + for (scene, other) in ((1, 2), (:scene, :other), (1, :other)), + selector in (Many(), Many(within=Self())) + model = CompositeModel( + Object(scene; scale=:Scene, status=Status(private_runs=0, incident_par=0.0)), + Object(other; scale=:Other, status=Status(private_runs=0, incident_par=0.0)); + applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); + name=:closed_context_writer, on=One(id=scene), + outputs_to=(OutputTo(selector; vars=(:incident_par,)),)),)) + model = _distributed_runtime_closed_destination_registry(model) + simulation = run!(model; steps=0, outputs=:all) + binding = only(simulation.compiled.distributed_outputs.bindings) + I = keytype(model.registry.objects) + @test eltype(binding.destination_ids) === I + @test keytype(binding.destination_index) === I + @test binding.destination_ids == ObjectId[ObjectId(scene)] + @test simulation.compiled.distributed_outputs.destination_ids_by_application_variable[ + (:closed_context_writer, :incident_par)] === binding.destination_ids + continue!(simulation) + @test model_status(model, scene).incident_par == 101.0 + @test model_status(model, other).incident_par == 0.0 + end +end + +@testset "Closed empty and merged distributed indices preserve membership ownership" begin + PSE = PlantSimEngine + # The spare object declares the real leaf status family without selecting it. + empty_model = CompositeModel( + Object(1; scale=:Scene, status=Status(private_runs=0)), + Object(2; scale=:Spare, status=Status(incident_par=0.0)); + applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); + name=:closed_empty_writer, on=One(id=1), + outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope()); vars=(:incident_par,)),)),)) + empty_model = _distributed_runtime_closed_destination_registry(empty_model) + simulation = run!(empty_model; steps=0, outputs=:all) + binding = only(simulation.compiled.distributed_outputs.bindings) + @test isempty(binding.destination_ids) + @test eltype(binding.destination_ids) === keytype(empty_model.registry.objects) + @test simulation.compiled.distributed_outputs.destination_ids_by_application_variable[ + (:closed_empty_writer, :incident_par)] === binding.destination_ids + register_object!(empty_model, Object(3; scale=:Leaf, status=Status(incident_par=0.0)); parent=1) + continue!(simulation) + binding = only(simulation.compiled.distributed_outputs.bindings) + @test binding.destination_ids == ObjectId[ObjectId(3)] + @test simulation.compiled.distributed_outputs.destination_ids_by_application_variable[ + (:closed_empty_writer, :incident_par)] === binding.destination_ids + @test outputs(simulation)[(:closed_empty_writer, ObjectId(3), :incident_par)] == [(1.0, 101.0)] + + merged_model = CompositeModel( + Object(1; scale=:Plant, status=Status(private_runs=0)), + Object(2; scale=:Plant, status=Status(private_runs=0)), + Object(10; scale=:Leaf, parent=1, status=Status(incident_par=0.0)), + Object(20; scale=:Leaf, parent=2, status=Status(incident_par=0.0)); + applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); + name=:closed_merged_writer, on=Many(scale=:Plant), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:incident_par,)),)),)) + merged_model = _distributed_runtime_closed_destination_registry(merged_model) + simulation = run!(merged_model; steps=0, outputs=:all) + bindings = simulation.compiled.distributed_outputs.bindings + combined = simulation.compiled.distributed_outputs.destination_ids_by_application_variable[ + (:closed_merged_writer, :incident_par)] + @test length(bindings) == 2 + @test combined == ObjectId.(Int[10, 20]) + @test all(combined !== binding.destination_ids for binding in bindings) + @test [copy(binding.destination_ids) for binding in bindings] == [ObjectId.([10]), ObjectId.([20])] + register_object!(merged_model, Object(30; scale=:Leaf, status=Status(incident_par=0.0)); parent=2) + continue!(simulation) + @test combined == ObjectId.(Int[10, 20, 30]) + @test all(combined !== binding.destination_ids for binding in bindings) + @test model_status(merged_model, 30).incident_par == 101.0 +end From bfd20df56cebf2471f54bf761e3144f8a35c37e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 8 Nov 2026 17:36:17 +0100 Subject: [PATCH 066/324] Fix installation example and historical documentation links --- CHANGELOG.md | 6 +++--- docs/src/prerequisites/installing_plantsimengine.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 017986e0b..b45986193 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -374,9 +374,9 @@ to migrate mapping code to the newer API. `Integrate()` and `Aggregate()` behavior. - A dedicated benchmark suite for the multi-rate implementation. - A new multi-rate documentation track: - [introduction](/Users/rvezy/Documents/dev/PlantSimEngine/docs/src/multirate/introduction.md), - [step-by-step tutorial](/Users/rvezy/Documents/dev/PlantSimEngine/docs/src/multirate/multirate_tutorial.md), - and [advanced configuration](/Users/rvezy/Documents/dev/PlantSimEngine/docs/src/multirate/advanced_configuration.md). + [introduction](https://github.com/VirtualPlantLab/PlantSimEngine.jl/blob/v0.14.0/docs/src/multirate/introduction.md), + [step-by-step tutorial](https://github.com/VirtualPlantLab/PlantSimEngine.jl/blob/v0.14.0/docs/src/multirate/multirate_tutorial.md), + and [advanced configuration](https://github.com/VirtualPlantLab/PlantSimEngine.jl/blob/v0.14.0/docs/src/multirate/advanced_configuration.md). ### Changed diff --git a/docs/src/prerequisites/installing_plantsimengine.md b/docs/src/prerequisites/installing_plantsimengine.md index 8be50276b..d7c2b1c33 100644 --- a/docs/src/prerequisites/installing_plantsimengine.md +++ b/docs/src/prerequisites/installing_plantsimengine.md @@ -10,7 +10,7 @@ environment (a folder that records the packages used for this simulation), open ```julia using Pkg Pkg.activate(".") -Pkg.add(["PlantMeteo", "DataFrames", "CairoMakie", "PlantSimEngine.jl"]) +Pkg.add(["PlantMeteo", "DataFrames", "CairoMakie", "PlantSimEngine"]) ``` PlantMeteo supplies weather data, DataFrames organizes the results, and From a67056d3c8452ebaa223442697aeddf1fe4b4431 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 9 Nov 2026 01:58:00 +0100 Subject: [PATCH 067/324] Defer prepared Many call batches until requested Preserve strict vector and tuple schemas while leaving unrequested full call memberships cold. Use canonical materialization and admission for generated full and selected calls. Cover lifecycle refresh, clones, inference, empty selections, rejected status variants and source publication parity. --- .../execution_batch_schemas.jl | 52 +++- src/composite_model/runtime_outputs.jl | 29 ++- src/composite_model/source_compilation.jl | 53 +++- test/test-model-prepared-call-schemas.jl | 233 +++++++++++++++++- test/test-model-source-compilation.jl | 123 +++++++++ 5 files changed, 454 insertions(+), 36 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 6e233faa2..c69c0bbd2 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -61,7 +61,7 @@ function _validate_prepared_context_calls(::Type{C}) where {C<:Tuple} BT = only(S.parameters) _prepared_execution_batch_types(BT) actual = fieldtype(CT, :execution_batches) - expected = _prepared_call_mode(fieldtype(CT, :binding)) === :initializer ? Tuple{} : BT + expected = _prepared_call_batch_storage_type(fieldtype(CT, :binding), BT) actual === expected || throw(ArgumentError("Prepared call container and explicit batch schema disagree.")) end return nothing @@ -212,6 +212,22 @@ function _prepared_application_schema_order(compiled::CompiledCompositeModel, sc return Tuple(order) end +@inline _materialize_call_execution_batches!(::OpenExecutionBatchSchema, targets::CallTargets) = + _materialize_open_call_execution_batches!(targets) + +function _prepared_call_batch_storage_type(::Type{B}, ::Type{BT}) where {B, BT} + _prepared_call_mode(B) === :initializer && return Tuple{} + Selector = fieldtype(fieldtype(B, :plan), :selector) + return BT <: Tuple && Selector <: Many ? Union{Nothing, BT} : BT +end +@inline _call_execution_batch_storage_type(::OpenExecutionBatchSchema, binding, batches) = typeof(batches) +@inline _call_execution_batch_storage_type(::PreparedExecutionBatchSchema{BT}, binding, batches) where {BT} = + _prepared_call_batch_storage_type(typeof(binding), BT) + +@inline _call_execution_batches_start_materialized(::OpenExecutionBatchSchema, binding) = true +@inline _call_execution_batches_start_materialized(::PreparedExecutionBatchSchema, binding) = + _compiled_call_mode(binding) === :initializer || binding.multiplicity !== :many + Base.@nospecializeinfer function _call_execution_batches_for_schema( ::OpenExecutionBatchSchema, compiled, environment_bindings, binding, temporal_streams, output_retention, constants, tracks_full_membership, @@ -231,6 +247,12 @@ function _call_execution_batches_for_schema(schema::PreparedExecutionBatchSchema output_retention, constants, tracks_full_membership, ) _compiled_call_mode(binding) === :initializer && return () + # The full membership stays cold until the same materialization entry point + # is requested. Explicit objects= calls do not admit unused existing rows. + if binding.multiplicity === :many + BT = only(typeof(schema).parameters) + return BT <: Tuple ? nothing : _execution_batch_buffer(schema) + end if tracks_full_membership _observe_compiled_call_membership!(compiled, binding; resolve_current=!bindings_dirty(compiled.model)) @@ -293,15 +315,22 @@ end @inline _clone_call_execution_batches(batches::Vector{B}) where {B<:CompiledExecutionBatch} = copy(batches) -function _materialize_prepared_call_execution_batches!(schema::PreparedExecutionBatchSchema, +@inline function _cached_call_execution_batches( + targets::CallTargets{CS, EB, B, TS, OR, C, BT, S}, +) where {CS, EB, B, TS, OR, C, BT, S<:PreparedExecutionBatchSchema} + return targets.execution_batches_materialized ? something(targets.execution_batches) : nothing +end + +function _materialize_call_execution_batches!(schema::PreparedExecutionBatchSchema, targets::CallTargets, ) if targets.tracks_full_membership _synchronize_tracked_call_targets!(targets) end - _call_targets_preparation_is_current(targets, targets.compiled, - targets.environment_bindings, targets.temporal_streams, - targets.output_retention, targets.constants) && return targets.execution_batches + targets.execution_batches_materialized && + _call_targets_preparation_is_current(targets, targets.compiled, + targets.environment_bindings, targets.temporal_streams, + targets.output_retention, targets.constants) && return something(targets.execution_batches) if targets.tracks_full_membership _observe_compiled_call_membership!(targets.compiled, targets.binding; resolve_current=!bindings_dirty(targets.compiled.model)) @@ -314,12 +343,15 @@ function _materialize_prepared_call_execution_batches!(schema::PreparedExecution _retire_call_cohort_targets!(targets.temporal_streams, targets.binding, batches; schema=_execution_cohort_schema(schema), batch_schema=schema) end - # Publish a complete validated replacement, preserving retained lease shells. - targets.execution_batches = batches - targets.last_single_snapshot = nothing - targets.preparation = _call_targets_preparation(targets.compiled, + preparation = _call_targets_preparation(targets.compiled, targets.environment_bindings, targets.binding, targets.temporal_streams, targets.output_retention, targets.constants) + # Publish only the complete validated replacement; no call separates these + # stores. A retained lease keeps its own shell and shared execution payloads. + targets.execution_batches = batches + targets.preparation = preparation + targets.last_single_snapshot = nothing + targets.execution_batches_materialized = true return batches end @@ -593,7 +625,7 @@ function _execution_batch_type_with_call_schemas(::Type{B}, schemas::NamedTuple) schema = getproperty(schemas,_prepared_call_name(Binding)) schema isa PreparedExecutionBatchSchema || throw(ArgumentError("Calls need explicit batch schemas.")) BT = only(typeof(schema).parameters) - actual_batches = _prepared_call_mode(Binding) === :initializer ? Tuple{} : BT + actual_batches = _prepared_call_batch_storage_type(Binding, BT) return CallTargets{fieldtype(CT,:compiled),fieldtype(CT,:environment_bindings),Binding, fieldtype(CT,:temporal_streams),fieldtype(CT,:output_retention), fieldtype(CT,:constants),actual_batches,typeof(schema)} diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 218065326..f2daa58c1 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -640,6 +640,10 @@ mutable struct CallTargets{CS,EB,B,TS,OR,C,BT,S} <: AbstractVector{CallTarget} # may legitimately change its concrete type between invocations. environment::Any execution_batches::BT + # Readiness of prepared storage only; ordinary Lazy batches retain their + # existing cache state. A strict empty buffer may be cold, independently of + # context freshness, so targeted calls do not invalidate pending full Many. + execution_batches_materialized::Bool const batch_schema::S const tracks_full_membership::Bool preparation::CallTargetsPreparation{CS,EB,TS,OR,C} @@ -673,7 +677,8 @@ function CallTargets( output_retention, constants, tracks_full_membership) return _prepared_call_targets(compiled, environment_bindings, binding, temporal_streams, output_retention, time, constants, publication_allowed, - environment, execution_batches, batch_schema, tracks_full_membership) + environment, execution_batches, batch_schema, tracks_full_membership, + _call_execution_batches_start_materialized(batch_schema, binding)) end # Both graph preparation and a leased context's clone use this fully specified @@ -682,12 +687,17 @@ end @inline function _prepared_call_targets( compiled, environment_bindings, binding, temporal_streams, output_retention, time, constants, publication_allowed, environment, execution_batches, - batch_schema, tracks_full_membership::Bool, -) - targets = CallTargets( + batch_schema, tracks_full_membership::Bool, execution_batches_materialized::Bool, +) + Storage = _call_execution_batch_storage_type(batch_schema, binding, execution_batches) + targets = CallTargets{ + typeof(compiled), typeof(environment_bindings), typeof(binding), + typeof(temporal_streams), typeof(output_retention), typeof(constants), + Storage, typeof(batch_schema) + }( compiled, environment_bindings, binding, temporal_streams, output_retention, float(time), constants, publication_allowed, environment, execution_batches, - batch_schema, tracks_full_membership, + execution_batches_materialized, batch_schema, tracks_full_membership, _call_targets_preparation( compiled, environment_bindings, binding, temporal_streams, output_retention, constants, ), @@ -732,6 +742,7 @@ end end @inline _clone_call_execution_batches(batches::Tuple) = batches +@inline _clone_call_execution_batches(::Nothing) = nothing @inline function _clone_call_execution_batches(batches::LazyCallExecutionBatches) # A lazy wrapper points at its owning CallTargets. Share its prepared state, @@ -753,6 +764,7 @@ end output_retention, time, constants, publication_allowed, environment, _clone_call_execution_batches(prototype.execution_batches), prototype.batch_schema, prototype.tracks_full_membership, + prototype.execution_batches_materialized, ) remaining = _clone_runtime_call_targets( Base.tail(calls), compiled, environment_bindings, temporal_streams, @@ -923,9 +935,10 @@ function _record_extended_call_execution_batch_cache!( return targets end -function _materialize_call_execution_batches!(targets::CallTargets) - targets.batch_schema isa PreparedExecutionBatchSchema && - return _materialize_prepared_call_execution_batches!(targets.batch_schema, targets) +@inline _materialize_call_execution_batches!(targets::CallTargets) = + _materialize_call_execution_batches!(targets.batch_schema, targets) + +function _materialize_open_call_execution_batches!(targets::CallTargets) cached = targets.execution_batches cached isa LazyCallExecutionBatches || return cached if targets.tracks_full_membership diff --git a/src/composite_model/source_compilation.jl b/src/composite_model/source_compilation.jl index e039b5abd..4a654e034 100644 --- a/src/composite_model/source_compilation.jl +++ b/src/composite_model/source_compilation.jl @@ -1107,19 +1107,29 @@ function _compiled_source_run_call!( selected_environment = environment isa NoEnvironmentOverride ? context.environment : environment + return _compiled_source_run_call_targets!(source_id, targets, publish, + sampled_environment, selected_environment) +end + +function _compiled_source_run_call_targets!(source_id::Val, targets::CallTargets, + publish::Bool, sampled_environment, selected_environment, +) frame = _active_call_evaluation() - for batch in targets.execution_batches - for target in batch.targets - _compiled_source_run_call_target!( - source_id, - targets, - batch.application, - target, - publish, - sampled_environment, - selected_environment, - frame, - ) + batches = _materialize_call_execution_batches!(targets) + for index in eachindex(batches) + _with_call_execution_batch(targets, batches, index) do batch + for target in batch.targets + _compiled_source_run_call_target!( + source_id, + targets, + batch.application, + target, + publish, + sampled_environment, + selected_environment, + frame, + ) + end end end if publish && targets.publication_allowed @@ -1133,6 +1143,18 @@ function _compiled_source_run_call!( return targets end +function _compiled_source_run_call_targets!(source_id::Val, + targets::AbstractVector{<:CallTarget}, publish::Bool, sampled_environment, selected_environment, +) + for target in targets + _with_call_target_entry(targets, target) do actual + _compiled_source_run_call_target!(source_id, actual, publish, + sampled_environment, selected_environment) + end + end + return targets +end + function _compiled_source_run_call!( source_id::Val, target::CallTarget; @@ -1150,6 +1172,13 @@ function _compiled_source_run_call!( end selected_environment = environment isa NoEnvironmentOverride ? target.environment : environment + return _compiled_source_run_call_target!(source_id, target, publish, + sampled_environment, selected_environment) +end + +function _compiled_source_run_call_target!(source_id::Val, target::CallTarget, + publish::Bool, sampled_environment, selected_environment, +) frame = _record_call_execution!(target.context_cache) status = _materialize_model_inputs!( target.status, diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl index cc069a6ab..e3a3408f7 100644 --- a/test/test-model-prepared-call-schemas.jl +++ b/test/test-model-prepared-call-schemas.jl @@ -144,7 +144,10 @@ function assert_prepared_tree(simulation) @test middle_calls.batch_schema isa PSE.PreparedExecutionBatchSchema @test middle_calls.execution_batches isa Vector @test middle_calls.tracks_full_membership - for middle_batch in middle_calls.execution_batches, middle in middle_batch.targets + middle_batches = PSE._materialize_call_execution_batches!(middle_calls) + @test middle_calls.execution_batches_materialized + @test middle_batches === middle_calls.execution_batches + for middle_batch in middle_batches, middle in middle_batch.targets @test middle_batch.targets.store === simulation.execution_plan.cohorts @test middle.status_view.canonical_status === model_status(simulation.model, middle.object_id) @test !middle.call_context_cache.in_use @@ -152,7 +155,10 @@ function assert_prepared_tree(simulation) @test leaves.batch_schema isa PSE.PreparedExecutionBatchSchema @test leaves.execution_batches isa Vector @test leaves.tracks_full_membership - for leaf_batch in leaves.execution_batches, leaf in leaf_batch.targets + leaf_batches = PSE._materialize_call_execution_batches!(leaves) + @test leaves.execution_batches_materialized + @test leaf_batches === leaves.execution_batches + for leaf_batch in leaf_batches, leaf in leaf_batch.targets @test leaf_batch.targets.store === simulation.execution_plan.cohorts @test leaf.status_view.canonical_status === model_status(simulation.model, leaf.object_id) @test PSE.refvalue(leaf.status_view.status, :value) === @@ -194,10 +200,218 @@ end @test Set(keys(outputs(prepared))) == Set(keys(streams)) @test all(outputs(prepared)[key] === stream for (key, stream) in streams) assert_same_cells(data.model, cells) - assert_prepared_tree(prepared) + pending = call_targets(root_target(prepared).context, :middle) + @test pending.execution_batches isa Vector{learned.MiddleB} + @test isempty(pending.execution_batches) + @test !pending.execution_batches_materialized + @test !PSE._call_execution_batches_materialized(pending) + @test PSE._cached_call_execution_batches(pending) === nothing + @test PSE._call_targets_preparation_is_current(pending, pending.compiled, + pending.environment_bindings, pending.temporal_streams, pending.output_retention, pending.constants) + # Retrieving or explaining the call does not request the complete view. + @test call_targets(root_target(prepared).context, :middle) === pending + PSE.Diagnostics.explain_calls(prepared.compiled) + @test !PSE._call_execution_batches_materialized(pending) + # A full Middle request constructs its contexts, not their Leaf memberships. + middle_batches = PSE._materialize_call_execution_batches!(pending) + for batch in middle_batches, middle in batch.targets + leaves = call_targets(middle.context, :leaf) + @test !PSE._call_execution_batches_materialized(leaves) + @test PSE._cached_call_execution_batches(leaves) === nothing + @test call_targets(middle.context, :leaf) === leaves + PSE.Diagnostics.explain_calls(prepared.compiled) + @test !PSE._call_execution_batches_materialized(leaves) + end + assert_prepared_tree(prepared) # Full inspection is explicit and still metadata-only. + @test scientific_state(data.model) == before + @test rng_probe(data.rng) == random_state + assert_same_cells(data.model, cells) @test typeof(root_target(prepared)) === eltype(fieldtype(learned.RootB, :targets)) end +@testset "prepared Many selection and cloned shells leave complete membership cold" begin + witness = fixture() + learned = observed_schemas(witness.simulation) + ordinary, activated = fixture(), fixture() # No membership/cache/RNG owner is borrowed. + prepared = PSE._prepare_execution_batch_schemas(activated.simulation, learned.schemas) + prototype = call_targets(root_target(prepared).context, :middle) + @test !PSE._call_execution_batches_materialized(prototype) + @test !PSE._compiled_call_membership_is_observed(prototype.binding) + owner = root_target(prepared).context + cloned_calls = @inferred PSE._clone_runtime_call_targets(owner.calls, + owner.compiled, owner.environment_bindings, owner.temporal_streams, + owner.output_retention, owner.time, owner.constants, owner.publication_allowed, owner.environment) + cloned = only(cloned_calls) + @test typeof(cloned_calls) === typeof(owner.calls) + @test cloned !== prototype && cloned.binding === prototype.binding + @test cloned.execution_batches !== prototype.execution_batches + @test !cloned.execution_batches_materialized + @test PSE._cached_call_execution_batches(cloned) === nothing + @test isnothing(cloned.evaluation) && isnothing(cloned.target_buffer_cache) + + for (data, simulation) in ((ordinary, ordinary.simulation), (activated, prepared)) + step!(simulation) + full = call_targets(data.capture[], :middle) + selected = only(call_targets(data.capture[], :middle; objects=(:middle_a,))) + @test !PSE._call_execution_batches_materialized(full) + @test !PSE._compiled_call_membership_is_observed(full.binding) + run_call!(selected; publish=false) + @test data.kernels == Dict(:root => 1, :middle => 1, :leaf => 1) + @test model_status(data.model, :middle_b).visits == 0 + @test model_status(data.model, :leaf_b).visits == 0 + @test !selected.context_cache.in_use + @test call_targets(data.capture[], :middle) === full + @test !PSE._call_execution_batches_materialized(full) + @test !PSE._compiled_call_membership_is_observed(full.binding) + state, random_state = scientific_state(data.model), rng_probe(data.rng) + @test getproperty.(collect(full), :object_id) == ObjectId[ObjectId(:middle_a), ObjectId(:middle_b)] + @test PSE._call_execution_batches_materialized(full) + @test PSE._compiled_call_membership_is_observed(full.binding) + @test scientific_state(data.model) == state + @test rng_probe(data.rng) == random_state + end + @test scientific_state(ordinary.model) == scientific_state(activated.model) + @test rng_probe(ordinary.rng) == rng_probe(activated.rng) + @test history(ordinary.simulation) == history(prepared) + + warm = call_targets(activated.capture[], :middle) + warm_owner = activated.capture[] + warm_clone = only(@inferred PSE._clone_runtime_call_targets(warm_owner.calls, + warm_owner.compiled, warm_owner.environment_bindings, warm_owner.temporal_streams, + warm_owner.output_retention, warm_owner.time, warm_owner.constants, + warm_owner.publication_allowed, warm_owner.environment)) + @test warm_clone.execution_batches_materialized + @test warm_clone.execution_batches !== warm.execution_batches + @test length(PSE._cached_call_execution_batches(warm_clone)) == length(warm.execution_batches) + @test isnothing(warm_clone.evaluation) && isnothing(warm_clone.target_buffer_cache) +end + +@testset "prepared Many stays cold through growth removal and newborn selection" begin + witness = fixture() + learned = observed_schemas(witness.simulation) + ordinary, activated = fixture(), fixture() + prepared = PSE._prepare_execution_batch_schemas(activated.simulation, learned.schemas) + for (data, simulation) in ((ordinary, ordinary.simulation), (activated, prepared)) + step!(simulation) + retained = call_targets(data.capture[], :middle) + @test !PSE._call_execution_batches_materialized(retained) + @test !PSE._compiled_call_membership_is_observed(retained.binding) + register_object!(data.model, Object(:middle_new; scale=:Branch, parent=:root, + status=Status(visits=0, total=0.0))) + register_object!(data.model, Object(:leaf_new; scale=:Leaf, parent=:middle_new, + status=Status(visits=0, value=0.0, payload=zeros(2)))) + remove_object!(data.model, :leaf_b) + remove_object!(data.model, :middle_b) + continue!(simulation; steps=1) + full = call_targets(data.capture[], :middle) + @test full === retained + @test !PSE._call_execution_batches_materialized(full) + @test !PSE._compiled_call_membership_is_observed(full.binding) + newborn = only(call_targets(data.capture[], :middle; objects=(:middle_new,))) + @test newborn.object_id == ObjectId(:middle_new) + @test newborn.status === model_status(data.model, :middle_new) + run_call!(newborn; publish=true) + @test data.kernels == Dict(:root => 2, :middle => 1, :leaf => 1) + @test model_status(data.model, :middle_a).visits == 0 + @test model_status(data.model, :leaf_a).visits == 0 + @test !newborn.context_cache.in_use + @test !PSE._call_execution_batches_materialized(full) + @test !PSE._compiled_call_membership_is_observed(full.binding) + state, random_state, streams = scientific_state(data.model), rng_probe(data.rng), history(simulation) + @test getproperty.(collect(full), :object_id) == ObjectId[ObjectId(:middle_a), ObjectId(:middle_new)] + @test PSE._call_execution_batches_materialized(full) + @test PSE._compiled_call_membership_is_observed(full.binding) + @test scientific_state(data.model) == state + @test rng_probe(data.rng) == random_state + @test history(simulation) == streams + end + @test scientific_state(ordinary.model) == scientific_state(activated.model) + @test rng_probe(ordinary.rng) == rng_probe(activated.rng) + @test history(ordinary.simulation) == history(prepared) +end + +@testset "pending prepared Many does not admit an unselected Status variant" begin + witness = fixture() + learned = observed_schemas(witness.simulation) + data = fixture() + # A real registered object, never a fabricated Type witness. The existing + # Middle kernel is unchanged; its extra canonical field is outside learned. + register_object!(data.model, Object(:middle_z_extra; scale=:Branch, parent=:root, + status=Status(visits=0, total=0.0, unselected_marker=0))) + fresh = run!(data.model; steps=0, outputs=:all) + # Check owner compatibility before activation: only the real Status variant + # is outside the learned target schema, not another owner/ABI fixture. + ExpectedTarget = eltype(fieldtype(learned.MiddleB, :targets)) + ExpectedContext = fieldtype(ExpectedTarget, :context) + fresh_owner = root_target(fresh).context + @test fresh.compiled.applications_by_id[:middle] isa fieldtype(ExpectedContext, :application) + for name in (:compiled, :environment_bindings, :temporal_streams, + :output_retention, :constants, :environment) + @test getfield(fresh_owner, name) isa fieldtype(ExpectedContext, name) + end + prepared = PSE._prepare_execution_batch_schemas(fresh, learned.schemas) + step!(prepared) + full = call_targets(data.capture[], :middle) + PSE.Diagnostics.explain_calls(prepared.compiled) + @test !PSE._call_execution_batches_materialized(full) + selected = only(call_targets(data.capture[], :middle; objects=(:middle_a,))) + run_call!(selected; publish=false) + @test data.kernels == Dict(:root => 1, :middle => 1, :leaf => 1) + @test model_status(data.model, :middle_z_extra).visits == 0 + @test !PSE._call_execution_batches_materialized(full) + @test PSE._cached_call_execution_batches(full) === nothing + state, random_state, cells = scientific_state(data.model), rng_probe(data.rng), status_cells(data.model) + @test_throws ArgumentError PSE._materialize_call_execution_batches!(full) + @test !full.execution_batches_materialized + @test PSE._cached_call_execution_batches(full) === nothing + @test isempty(full.execution_batches) # No partial vector is published on rejection. + @test scientific_state(data.model) == state + @test rng_probe(data.rng) == random_state + assert_same_cells(data.model, cells) +end + +@testset "a nonempty Tuple batch schema keeps prepared Many pending" begin + witness = fixture() + learned = observed_schemas(witness.simulation) + leaf_schema = PSE.PreparedExecutionBatchSchema{Tuple{learned.LeafB}}() + MiddleB = PSE._execution_batch_type_with_call_schemas(learned.MiddleB, (leaf=leaf_schema,)) + middle_schema = PSE.PreparedExecutionBatchSchema{Tuple{MiddleB}}() + RootB = PSE._execution_batch_type_with_call_schemas(learned.RootB, (middle=middle_schema,)) + schemas = (root=PSE.PreparedExecutionBatchSchema{Vector{RootB}}(), + middle=middle_schema, leaf=leaf_schema) + ordinary, activated = fixture(), fixture() + prepared = PSE._prepare_execution_batch_schemas(activated.simulation, schemas) + owner = root_target(prepared).context + pending = call_targets(owner, :middle) + @test pending.batch_schema === middle_schema + @test !pending.execution_batches_materialized + @test PSE._cached_call_execution_batches(pending) === nothing + cloned = only(@inferred PSE._clone_runtime_call_targets(owner.calls, + owner.compiled, owner.environment_bindings, owner.temporal_streams, + owner.output_retention, owner.time, owner.constants, owner.publication_allowed, owner.environment)) + @test typeof(cloned) === typeof(pending) + @test !cloned.execution_batches_materialized + @test PSE._cached_call_execution_batches(cloned) === nothing + for (data, simulation) in ((ordinary, ordinary.simulation), (activated, prepared)) + step!(simulation) + run_call!(data.capture[], :middle; publish=true) + @test data.kernels == Dict(:root => 1, :middle => 2, :leaf => 2) + end + warm_owner = activated.capture[] + warm = call_targets(warm_owner, :middle) + @test warm.execution_batches_materialized + @test warm.execution_batches isa Tuple{MiddleB} + warm_clone = only(@inferred PSE._clone_runtime_call_targets(warm_owner.calls, + warm_owner.compiled, warm_owner.environment_bindings, warm_owner.temporal_streams, + warm_owner.output_retention, warm_owner.time, warm_owner.constants, + warm_owner.publication_allowed, warm_owner.environment)) + @test warm_clone.execution_batches_materialized + @test PSE._cached_call_execution_batches(warm_clone) === warm.execution_batches + @test scientific_state(ordinary.model) == scientific_state(activated.model) + @test rng_probe(ordinary.rng) == rng_probe(activated.rng) + @test history(ordinary.simulation) == history(prepared) +end + @testset "cold real Many calls retain public evaluation, history and lease behavior" begin ordinary, activated = fixture(), fixture() learned = observed_schemas(activated.simulation) @@ -297,13 +511,20 @@ end @test empty.kernels == Dict(:root => 0, :middle => 0, :leaf => 0) @test isempty(object_ids(empty.model; scale=:Leaf)) assert_same_cells(empty.model, cells) - assert_prepared_tree(prepared) - for batch in call_targets(root_target(prepared).context, :middle).execution_batches, - target in batch.targets + middle_calls = call_targets(root_target(prepared).context, :middle) + @test !PSE._call_execution_batches_materialized(middle_calls) + for batch in PSE._materialize_call_execution_batches!(middle_calls), target in batch.targets leaves = call_targets(target.context, :leaf) @test isempty(leaves.execution_batches) @test eltype(leaves.execution_batches) === real_leaf_batch + @test !leaves.execution_batches_materialized + @test PSE._cached_call_execution_batches(leaves) === nothing + @test isempty(PSE._materialize_call_execution_batches!(leaves)) + @test leaves.execution_batches_materialized + @test PSE._call_execution_batches_materialized(leaves) + @test isempty(PSE._cached_call_execution_batches(leaves)) end + assert_prepared_tree(prepared) step!(prepared) evaluation = evaluate_call!(empty.capture[], :middle) @test empty.kernels == Dict(:root => 1, :middle => 2, :leaf => 0) diff --git a/test/test-model-source-compilation.jl b/test/test-model-source-compilation.jl index 1e418f383..cea4e2149 100644 --- a/test/test-model-source-compilation.jl +++ b/test/test-model-source-compilation.jl @@ -627,6 +627,129 @@ end end + +@testset "Readable source prepared Many and newborn selection parity" begin + PSE = PlantSimEngine + # Reuse the maintained kernels; only the application wiring differs. + make_simulation = function (; leaves=true) + objects = Object[Object(:scene; scale=:Scene)] + if leaves + append!(objects, (Object(:leaf_a; scale=:Leaf, parent=:scene, + status=Status(grandchild_value=0.0)), + Object(:leaf_b; scale=:Leaf, parent=:scene, + status=Status(grandchild_value=0.0)))) + end + model = CompositeModel(objects...; applications=( + ModelSpec(SourceCompilerSignalModel(); name=:owner, on=One(id=:scene), + calls=(children=Many(scale=:Leaf, within=Subtree(), + application=:grandchild),)), + ModelSpec(SourceCompilerGrandchildModel(); name=:grandchild, + on=Many(scale=:Leaf)), + ), environment=(T=0.0, duration=Hour(1))) + request = OutputRequest(Many(scale=:Leaf), :grandchild_value; + name=:seen, application=:grandchild, policy=HoldLast(), clock=Hour(1)) + return run!(model; steps=0, outputs=[request]) + end + root_target = sim -> only(only(only(sim.execution_plan.groups).batches).targets) + # A concrete inherited environment must remain distinct from an explicit + # override when the caller supplies an already sampled row. + inherited_context = function (sim) + target = root_target(sim) + context = target.context + return PSE._prepare_model_execution_context!(context, sim.compiled, + sim.environment_bindings, context.application, target.object_id, + target.bound_inputs, target.output_targets, target.call_bindings, + sim.temporal_streams, sim.output_retention, context.time, + sim.constants, true, (T=99.0,); fresh=true) + end + + witness = make_simulation() + witnessed_calls = call_targets(inherited_context(witness), :children) + ChildB = typeof(only(PSE._materialize_call_execution_batches!(witnessed_calls))) + child_schema = PSE.PreparedExecutionBatchSchema{Vector{ChildB}}() + RootB = PSE._execution_batch_type_with_call_schemas( + typeof(only(only(witness.execution_plan.groups).batches)), + (children=child_schema,)) + schemas = (owner=PSE.PreparedExecutionBatchSchema{Vector{RootB}}(), + grandchild=child_schema) + source = Authoring.compiled_model_source(witness; + function_name=:prepared_many_source_model!) + source_path = tempname() * ".jl" + write(source_path, source) + Base.include(Module(gensym(:PreparedManySourceModel)), source_path) + source_id = Val(PSE._compiled_source_id( + PSE._compiled_source_scenario_signature(witness.compiled))) + + for leaves in (true, false) + ordinary = make_simulation(; leaves) + generated = make_simulation(; leaves) + generated = PSE._prepare_execution_batch_schemas(generated, schemas) + step!(ordinary) + step!(generated) # Signal never asks for children; the Many remains cold. + ordinary_context = inherited_context(ordinary) + generated_context = inherited_context(generated) + prepared_calls = call_targets(generated_context, :children) + @test !PSE._call_execution_batches_materialized(prepared_calls) + @test isnothing(PSE._cached_call_execution_batches(prepared_calls)) + + # The full call must materialize a cold prepared Many, including the + # genuinely empty case and its accepted-call clock. + actual = Base.invokelatest(PSE._compiled_source_run_call!, source_id, + generated_context, :children; sampled_environment=(T=3.0,), publish=true) + expected = run_call!(ordinary_context, :children; + sampled_environment=(T=3.0,), publish=true) + @test [target.object_id for target in actual] == + [target.object_id for target in expected] + @test PSE._call_execution_batches_materialized(prepared_calls) + @test generated.output_retention.accepted_call_times == + ordinary.output_retention.accepted_call_times + if leaves + @test model_status(runtime_model(generated), :leaf_a).grandchild_value == 3.0 + @test model_status(runtime_model(generated), :leaf_b).grandchild_value == 3.0 + stream = outputs(generated)[(:grandchild, ObjectId(:leaf_a), :grandchild_value)] + @test !isempty(stream) && last(stream)[2] == 3.0 + @test isequal(stream, outputs(ordinary)[(:grandchild, ObjectId(:leaf_a), :grandchild_value)]) + end + + @test isequal(collect_outputs(generated; sink=nothing), + collect_outputs(ordinary; sink=nothing)) + end + + # This independent Open pair exercises the private newborn Vector path. + # Its inherited environment is not part of the full prepared batch family. + ordinary, generated = make_simulation(), make_simulation() + step!(ordinary) + step!(generated) + ordinary_context = inherited_context(ordinary) + generated_context = inherited_context(generated) + full = call_targets(generated_context, :children) + @test !PSE._call_execution_batches_materialized(full) + generated_newborn = register_object!(runtime_model(generated), + Object(:newborn; scale=:Leaf, parent=:scene, + status=Status(grandchild_value=0.0))) + ordinary_newborn = register_object!(runtime_model(ordinary), + Object(:newborn; scale=:Leaf, parent=:scene, + status=Status(grandchild_value=0.0))) + selected = Base.invokelatest(PSE._compiled_source_run_call!, source_id, + generated_context, :children; objects=generated_newborn, + sampled_environment=(T=7.0,), publish=true) + reference = run_call!(ordinary_context, :children; objects=ordinary_newborn, + sampled_environment=(T=7.0,), publish=true) + @test selected isa Vector{<:CallTarget} + @test only(selected).object_id == only(reference).object_id == ObjectId(:newborn) + @test model_status(runtime_model(generated), :newborn).grandchild_value == 7.0 + stream = outputs(generated)[(:grandchild, ObjectId(:newborn), :grandchild_value)] + @test !isempty(stream) && last(stream)[2] == 7.0 + @test isequal(stream, outputs(ordinary)[(:grandchild, ObjectId(:newborn), :grandchild_value)]) + @test generated.output_retention.accepted_call_times == + ordinary.output_retention.accepted_call_times + @test isequal(final_state(generated, :newborn), final_state(ordinary, :newborn)) + @test isequal(collect_outputs(generated; sink=nothing), + collect_outputs(ordinary; sink=nothing)) + + @test !PSE._call_execution_batches_materialized(full) +end + @testset "Readable source newborn initializer parity" begin model = source_compiler_initializer_fixture() signature = PlantSimEngine._compiled_source_scenario_signature( From 3ff3542900c5995539e75d82ece8962b59f40065 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 9 Nov 2026 03:08:24 +0100 Subject: [PATCH 068/324] Request deferred call memberships explicitly in schema tests Materialize the memberships inspected by extension tests and require descendant admission when the descendant is requested. Preserve Float32 rejection, prepared schemas, reference identity, RNG and cohort atomicity checks. --- ...est-model-finite-call-extension-intents.jl | 17 +++++++++-- ...st-model-prepared-missing-future-schema.jl | 30 ++++++++++++++----- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl index 9cc2bf38b..174f40ac7 100644 --- a/test/test-model-finite-call-extension-intents.jl +++ b/test/test-model-finite-call-extension-intents.jl @@ -110,8 +110,19 @@ function extend!(algorithm, target, owners, simulation) simulation.temporal_streams, simulation.output_retention, simulation.constants) end +# These tests inspect/extend concrete memberships, rather than merely obtain +# a lazy CallTargets wrapper. Initializer bindings are deliberately untouched. +function materialize_manual_calls!(target) + for calls in target.context.calls + PSE._compiled_call_mode(calls.binding) === :manual || continue + PSE._materialize_call_execution_batches!(calls) + end + return nothing +end + function call_snapshot(simulation) target = root_target(simulation) + materialize_manual_calls!(target) return [(calls=calls, binding=calls.binding, preparation=calls.preparation, batches=calls.execution_batches, rows=[(rows=batch.targets, indices=copy(batch.targets.indices), @@ -140,6 +151,7 @@ random_state(rng) = rand(copy(rng), UInt64, 8) ordinary, data = fixture(; prepared=false, wide), fixture(; wide) simulation = data.simulation target = root_target(simulation) + materialize_manual_calls!(target) scope = PSE._context_call_schema(target.context) @test scope isa PSE.PreparedContextCallSchema append_buffer = PSE._execution_append_intent_buffer(scope) @@ -207,6 +219,7 @@ end data = fixture(; prepared, wide=true) simulation = data.simulation target = root_target(simulation) + materialize_manual_calls!(target) add_leaves!(data) @test extend!(:prefix, target, refreshed_owners(data), simulation) === true rows = [only(call_targets(target.context, name).execution_batches).targets @@ -307,8 +320,8 @@ end target = root_target(data.simulation) scope = PSE._context_call_schema(target.context) left, right = call_targets(target.context, :a), call_targets(target.context, :alias_a) - rows = only(right.execution_batches).targets - candidate = only(only(left.execution_batches).targets) + rows = only(PSE._materialize_call_execution_batches!(right)).targets + candidate = only(only(PSE._materialize_call_execution_batches!(left)).targets) staged = PSE._execution_append_intent_buffer(scope) @test !PSE._stage_execution_append!(staged, scope, left, left.binding, rows, candidate) @test isempty(staged) diff --git a/test/test-model-prepared-missing-future-schema.jl b/test/test-model-prepared-missing-future-schema.jl index efa9018a2..a2c6e0e94 100644 --- a/test/test-model-prepared-missing-future-schema.jl +++ b/test/test-model-prepared-missing-future-schema.jl @@ -3,7 +3,7 @@ using PlantSimEngine, Test const PSE = PlantSimEngine const Fixtures = getfield(parentmodule(@__MODULE__),:ColdCallSchemaActivationChecks) -function recorded_views(simulation) +function recorded_views(simulation, selected) views = PSE.ExecutionCohortRows[] function visit(batch) push!(views,batch.targets) @@ -18,6 +18,9 @@ function recorded_views(simulation) for group in simulation.execution_plan.groups, batch in group.batches visit(batch) end + for batch in PSE._cached_call_execution_batches(selected) + visit(batch) + end return [(view=view,indices=copy(view.indices)) for view in views] end @@ -26,20 +29,33 @@ end schemas = Fixtures.observed_schemas(data.simulation).schemas simulation = PSE._prepare_execution_batch_schemas(data.simulation,schemas) step!(simulation) + # Demand the real descendants whose existing rows the atomicity check saves. + middles = call_targets(data.capture[],:middle) + for batch in PSE._materialize_call_execution_batches!(middles), middle in batch.targets + PSE._materialize_call_execution_batches!(call_targets(middle.context,:leaf)) + end cells = Fixtures.status_cells(data.model) science = Fixtures.scientific_state(data.model) random_state = Fixtures.rng_probe(data.rng) - store = simulation.execution_plan.cohorts - locations = copy(store.locations) - payloads = Dict(key=>PSE._execution_cohort_target(location) for (key,location) in locations) - views = recorded_views(simulation) # An output declaration is not a supplied-reference storage constraint. # This is a real registered organ with a Float32 Ref, not a dummy witness. newborn = register_object!(data.model,Object(:leaf_bad;scale=:Leaf, parent=:middle_a,status=Status(visits=0,value=0f0,payload=zeros(2)))) @test newborn.status.value isa Float32 - @test_throws "prepared execution schema" call_targets(data.capture[],:middle; - objects=(:middle_a,)) + selected = call_targets(data.capture[],:middle;objects=(:middle_a,)) + @test selected.batch_schema isa PSE.PreparedExecutionBatchSchema + middle = only(only(PSE._materialize_call_execution_batches!(selected)).targets) + # Selecting Middle does not demand its Leaf Many. Reject the Float32 Ref + # only when this test explicitly requests that descendant membership. + leaves = call_targets(middle.context,:leaf) + @test leaves.batch_schema isa PSE.PreparedExecutionBatchSchema + # Parent selection is now legal. Save the cohort baseline immediately before + # the descendant demand that must reject, including its live selected views. + store = simulation.execution_plan.cohorts + locations = copy(store.locations) + payloads = Dict(key=>PSE._execution_cohort_target(location) for (key,location) in locations) + views = recorded_views(simulation, selected) + @test_throws "prepared execution schema" PSE._materialize_call_execution_batches!(leaves) @test Set(keys(store.locations)) == Set(keys(locations)) @test all(store.locations[key] === location for (key,location) in locations) @test all(PSE._execution_cohort_target(store.locations[key]) === target for (key,target) in payloads) From 71a45d68e56838ac8175e4fed42c894e160cf406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 9 Nov 2026 06:22:14 +0100 Subject: [PATCH 069/324] Defer publication admission for empty execution memberships --- src/composite_model/runtime_outputs.jl | 11 ++ test/test-model-temporal-initial-typing.jl | 178 +++++++++++++++++++++ 2 files changed, 189 insertions(+) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f2daa58c1..e0d0cce0b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3529,6 +3529,17 @@ function _model_execution_batches( membership::ExecutionCohortMembership,output_retention,previous_group=nothing; batch_schema=OpenExecutionBatchSchema(), ) + # An empty membership has no publication. Validate the future publication + # schema when an actual batch is needed. + if isempty(membership.runs) + empty_batches = if !isnothing(previous_group) && previous_group.application === application && + isempty(previous_group.batches) + previous_group.batches + else + _execution_batch_buffer(batch_schema) + end + return (batches=empty_batches,batches_constructed=0) + end publication = _batch_output_publication(batch_schema,output_retention,application) if _execution_batches_match_membership(env_bindings,application,membership, publication,previous_group,batch_schema) diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 1e3135004..21812b99b 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -139,3 +139,181 @@ end end end end + +module PreparedPublicationChecks +using Dates, Random, Test, PlantSimEngine +const PSE = PlantSimEngine +import ..TemporalInitialTypingChecks: AbstractTyped_Initial_SourceModel, Consumer +struct PublicationSource{T,R} <: AbstractTyped_Initial_SourceModel + initial::T + rng::R +end +PSE.outputs_(model::PublicationSource) = (signal=model.initial, visits=0) +function PSE.run!(model::PublicationSource, status, environment, constants, context) + status.signal += rand(model.rng, typeof(status.signal)) + status.visits += 1 + return nothing +end + +# A model-owned RNG and an unconsumed output distinguish the :none and :all +# publication shapes while keeping both future applications initially empty. +function scene(; leaf=false, outputs=:none) + rng = Xoshiro(917) + objects = Object[Object(:scene; scale=:Scene, status=Status(signals=Float64[]))] + leaf && push!(objects, Object(:leaf; scale=:Leaf, parent=:scene, + status=Status(signal=2.0, visits=0, signals=Float64[]))) + model = CompositeModel(objects...; applications=( + ModelSpec(PublicationSource(0.0, rng); name=:source, on=Many(scale=:Leaf)), + ModelSpec(Consumer{Float64}(); name=:consumer, on=Many(scale=:Leaf), + inputs=(PreviousTimeStep(:signals) => Many(scale=:Leaf, within=SceneScope(), + application=:source, var=:signal),)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; steps=0, outputs) + return (; model, simulation, rng) +end + +group(simulation, id) = only(group for group in simulation.execution_plan.groups + if group.application.id === id) +real_batch(simulation, id) = only(group(simulation, id).batches) +schema(batch) = PSE.PreparedExecutionBatchSchema{Vector{typeof(batch)}}() +variables(simulation, id) = Tuple(get( + simulation.output_retention.retained_outputs_by_application, id, ())) +states(data) = Dict(object.id => deepcopy(NamedTuple(object.status)) + for object in model_objects(data.model)) +history(data) = Dict(key => [(time, deepcopy(value)) for (time, value) in stream] + for (key, stream) in outputs(data.simulation)) +rng_probe(data) = rand(copy(data.rng), UInt64, 8) +function assert_parity(ordinary, prepared) + @test current_step(ordinary.simulation) == current_step(prepared.simulation) + @test states(ordinary) == states(prepared) + @test history(ordinary) == history(prepared) + @test rng_probe(ordinary) == rng_probe(prepared) +end + +function check_initially_empty_publication() + witness = scene(; leaf=true) + before_rng = rng_probe(witness) + future_batch = real_batch(witness.simulation, :source) + future_schema = schema(future_batch) + @test rng_probe(witness) == before_rng + @test !isempty(variables(witness.simulation, :source)) + + ordinary, candidate = scene(), scene() + # The schema is learned from a real nonempty scene before either target exists. + @test isempty(variables(candidate.simulation, :source)) + application = candidate.simulation.compiled.applications_by_id[:source] + @test isempty(application.target_ids) + @test typeof(application) === fieldtype(typeof(future_batch), :application) + future_consumer = real_batch(witness.simulation, :consumer) + schemas = (source=future_schema, consumer=schema(future_consumer)) + before = states(candidate) + before_random = rng_probe(candidate) + cells = Dict((object.id, name) => PSE.refvalue(object.status, name) + for object in model_objects(candidate.model) for name in keys(object.status)) + current_variables = variables(candidate.simulation, :source) + future_variables = variables(witness.simulation, :source) + valid_preconditions = isempty(current_variables) && !isempty(future_variables) && + isempty(application.target_ids) && + typeof(application) === fieldtype(typeof(future_batch), :application) + @test valid_preconditions + valid_preconditions || return nothing + prepared = PSE._prepare_execution_batch_schemas(candidate.simulation, schemas) + @test prepared isa PSE.Simulation + candidate = merge(candidate, (simulation=prepared,)) + @test states(candidate) == before + @test rng_probe(candidate) == before_random + @test all(PSE.refvalue(model_status(candidate.model, id), name) === cell + for ((id, name), cell) in cells) + @test isempty(group(prepared, :source).batches) + + step!(ordinary.simulation) + step!(candidate.simulation) + assert_parity(ordinary, candidate) + for data in (ordinary, candidate) + register_object!(data.model, Object(:newborn; scale=:Leaf, parent=:scene, + status=Status(signal=7.0, visits=0, signals=Float64[]))) + end + for _ in 1:3 + step!(ordinary.simulation) + step!(candidate.simulation) + assert_parity(ordinary, candidate) + batch = real_batch(candidate.simulation, :source) + @test batch isa typeof(future_batch) + target = only(batch.targets) + status = model_status(candidate.model, :newborn) + @test target.status_view.canonical_status === status + @test PSE.refvalue(target.status_view.status, :signal) === PSE.refvalue(status, :signal) + end + source_group = group(candidate.simulation, :source) + previous_batches = source_group.batches + previous_rows = only(previous_batches).targets + retired = PSE.cohort_location(previous_rows.store, :source, ObjectId(:newborn); + owner=previous_rows.cohort.owner) + before_empty_rng = (rng_probe(ordinary), rng_probe(candidate)) + retained_histories = [Dict(key => value for (key, value) in history(data) + if first(key) === :source) for data in (ordinary, candidate)] + for data in (ordinary, candidate) + remove_object!(data.model, :newborn) + step!(data.simulation) + end + assert_parity(ordinary, candidate) + @test rng_probe(ordinary) == before_empty_rng[1] + @test rng_probe(candidate) == before_empty_rng[2] + @test group(candidate.simulation, :source) === source_group + @test source_group.batches === previous_batches + @test isempty(source_group.batches) + @test isnothing(PSE.cohort_location(previous_rows.store, :source, ObjectId(:newborn); + owner=previous_rows.cohort.owner)) + @test isnothing(retired.cohort.rows[retired.row]) + for (data, old_history) in zip((ordinary, candidate), retained_histories) + @test all(history(data)[key] == values for (key, values) in old_history) + register_object!(data.model, Object(:regrown; scale=:Leaf, parent=:scene, + status=Status(signal=11.0, visits=0, signals=Float64[]))) + step!(data.simulation) + end + assert_parity(ordinary, candidate) + @test group(candidate.simulation, :source) === source_group + regrown_batch = only(source_group.batches) + @test regrown_batch isa typeof(future_batch) + @test regrown_batch.targets.cohort === previous_rows.cohort + regrown = PSE.cohort_location(previous_rows.store, :source, ObjectId(:regrown); + owner=previous_rows.cohort.owner) + @test regrown.cohort === retired.cohort + @test regrown.row != retired.row + @test isnothing(retired.cohort.rows[retired.row]) + regrown_status = model_status(candidate.model, :regrown) + @test only(regrown_batch.targets).status_view.canonical_status === regrown_status + @test PSE.refvalue(only(regrown_batch.targets).status_view.status, :signal) === + PSE.refvalue(regrown_status, :signal) + for (data, old_history) in zip((ordinary, candidate), retained_histories) + @test all(history(data)[key] == values for (key, values) in old_history) + end +end + +@testset "a real future publication schema admits an initially empty scheduled source" begin + check_initially_empty_publication() +end + +@testset "a nonempty real batch keeps strict publication-shape rejection" begin + current = scene(; leaf=true, outputs=:none) + different = scene(; leaf=true, outputs=:all) + actual_group = group(current.simulation, :source) + actual_batch = only(actual_group.batches) + different_batch = real_batch(different.simulation, :source) + @test !isempty(actual_batch.targets) + @test typeof(actual_group.application) === fieldtype(typeof(different_batch), :application) + @test length(variables(current.simulation, :source)) != + length(variables(different.simulation, :source)) + before, before_history, before_rng = states(current), history(current), rng_probe(current) + original_batches = actual_group.batches + @test_throws "Retained publication shape is outside its prepared batch schema." PSE._model_execution_batches( + current.simulation.environment_bindings, actual_group.application, + actual_group.membership, current.simulation.output_retention, actual_group; + batch_schema=schema(different_batch)) + @test actual_group.batches === original_batches + @test only(actual_group.batches) === actual_batch + @test states(current) == before + @test history(current) == before_history + @test rng_probe(current) == before_rng +end +end From bbebfb17f18f206d8d1a5255d0a9e9675e052951 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 9 Nov 2026 15:17:41 +0100 Subject: [PATCH 070/324] Specialize growth selector bucket lookups --- src/composite_model/compilation.jl | 49 ++++++++++----------- test/test-selector-candidate-empty-scope.jl | 40 +++++++++++++++++ 2 files changed, 64 insertions(+), 25 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6a3af2329..ae493fa45 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -555,6 +555,18 @@ function _index_selector_candidate!( return index end +# Keep each dictionary/key pair concrete at its lookup rather than joining +# heterogeneous label buckets inside this growth-time query. +@inline function _union_selector_bucket!(candidates, groups, value) + isnothing(value) || union!(candidates, get(groups, value, ())) + return candidates +end + +@inline function _union_selector_bucket!(candidates, groups, anchor, label, value) + isnothing(value) || _union_selector_bucket!(candidates, groups, (anchor, label, value)) + return candidates +end + function _union_selector_candidates!( candidates::Set{Int}, index::SelectorCandidateIndex, @@ -563,33 +575,20 @@ function _union_selector_candidates!( ) union!(candidates, index.wildcard) object = _model_object(model, object_id) - for (groups, value) in ( - (index.by_id, object.id), - (index.by_scale, object.scale), - (index.by_kind, object.kind), - (index.by_species, object.species), - ) - isnothing(value) || union!(candidates, get(groups, value, ())) - end + id, scale, kind, species = object.id, object.scale, object.kind, object.species + _union_selector_bucket!(candidates, index.by_id, id) + _union_selector_bucket!(candidates, index.by_scale, scale) + _union_selector_bucket!(candidates, index.by_kind, kind) + _union_selector_bucket!(candidates, index.by_species, species) # Ancestors cannot contribute without any scoped selector entries. isempty(index.by_scope_anchor) && return candidates for anchor in _object_ancestor_ids(model.registry, object_id) - union!(candidates, get(index.by_scope_anchor, anchor, ())) - for (label, value) in ( - (:id, object.id), - (:scale, object.scale), - (:kind, object.kind), - (:species, object.species), - ) - isnothing(value) || union!( - candidates, - get( - index.by_scope_anchor, - (anchor, label, value), - (), - ), - ) - end + _union_selector_bucket!(candidates, index.by_scope_anchor, anchor) + id, scale, kind, species = object.id, object.scale, object.kind, object.species + _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :id, id) + _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :scale, scale) + _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :kind, kind) + _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :species, species) end return candidates end @@ -7505,7 +7504,7 @@ function _matching_input_source_applications( else resolved = Symbol[] for source_id in source_ids - for application in get(applications_by_object, source_id, Any[]) + for application in get(applications_by_object, source_id, ()) source_var in _model_output_names(application) || continue isnothing(process_filter) || application.process == process_filter || continue isnothing(application_filter) || application.id == application_filter || continue diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 1508575ea..4241ea299 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -91,3 +91,43 @@ using Test end end end + +@testset "Typed selector buckets preserve numeric and mixed identities" begin + for ids in ((10, 11, 12, 13), (0, :plant, "axis", 17)) + scene_id, plant_id, axis_id, leaf_id = ids + for (kind, species) in ((:photosynthetic, :rauh), (nothing, nothing)) + model = CompositeModel( + Object(scene_id; scale=:Scene), + Object(plant_id; scale=:Plant, parent=scene_id), + Object(axis_id; scale=:Axis, parent=plant_id), + Object(leaf_id; scale=:Leaf, kind, species, parent=axis_id), + ) + index = PlantSimEngine._selector_candidate_index() + selectors = ( + Many(id=leaf_id), + Many(scale=(:Leaf, :Fruit)), + Many(kind=:photosynthetic), + Many(species=:rauh), + Many(scale=:Leaf, within=Subtree()), + Many(within=Subtree()), + Many(id=scene_id), + ) + for (position, selector) in pairs(selectors) + matcher = PlantSimEngine._compile_selector_matcher(model, selector) + PlantSimEngine._index_selector_candidate!( + index, model, matcher, position; context=ObjectId(plant_id), + ) + end + expected = Set([1, 2, 5, 6]) + isnothing(kind) || push!(expected, 3) + isnothing(species) || push!(expected, 4) + for candidate_index in (index, PlantSimEngine._freeze_selector_candidate_index(index)) + candidates = Set([99]) + @test PlantSimEngine._union_selector_candidates!( + candidates, candidate_index, model, ObjectId(leaf_id), + ) === candidates + @test candidates == union(expected, Set([99])) + end + end + end +end From 5f3fe05cac903efba8c55fd8b9375c5a4b5ad128 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 9 Nov 2026 15:17:59 +0100 Subject: [PATCH 071/324] Avoid returning unused status from execution worker --- src/composite_model/runtime_outputs.jl | 2 +- test/test-model-api-stabilization.jl | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index e0d0cce0b..4adc2ed0f 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2923,7 +2923,7 @@ end _model_publish_runtime_outputs!(target.output_bindings, time) _runtime_performance_finish!(performance, :output_publication, started_at) end - return status + return nothing end @inline _model_execution_batch_environment( diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 12a07627d..5b329a463 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -2736,7 +2736,10 @@ end simulation.constants, )) float32_target = first(original_leaf_batch.targets) - @test PlantSimEngine._run_model_execution_target!( + original_status = float32_target.status_view.status + original_signal = original_status.signal + original_samples = copy(outputs(simulation)[(:leaf_source, ObjectId(:leaf_1), :signal)]) + @test isnothing(PlantSimEngine._run_model_execution_target!( simulation.compiled, simulation.environment_bindings, original_leaf_batch.application, @@ -2747,7 +2750,10 @@ end simulation.output_retention, nothing, false, - ) === float32_target.status_view.status + )) + @test float32_target.status_view.status === original_status + @test original_status.signal == original_signal + 1 + @test outputs(simulation)[(:leaf_source, ObjectId(:leaf_1), :signal)] == original_samples @test float32_target.context.time == Float64(float32_time) end From 88c1c9e0dfb5afb06565a502e2f2212ab0d85ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 15:16:45 +0100 Subject: [PATCH 072/324] Avoid duplicate object registry lookups --- src/composite_model/registry_topology.jl | 5 +++-- test/test-object-families.jl | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index fa3905f51..b2bc0682c 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1124,8 +1124,9 @@ end function _model_object(model::CompositeModel, id) oid = ObjectId(id) - haskey(model.registry.objects, oid) || error("No model object with id `$(oid.value)`.") - return model.registry.objects[oid] + object = get(model.registry.objects, oid, nothing) + isnothing(object) && error("No model object with id `$(oid.value)`.") + return object end """ diff --git a/test/test-object-families.jl b/test/test-object-families.jl index f519b0465..40e6a415a 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -19,6 +19,19 @@ const PSE = PlantSimEngine @test store.catalog isa PSE.OpenObjectFamilyCatalog @test length(store.catalog.families) == 3 @test model_object(model, 1) === first + for object in (first, second, empty) + @test model_object(model, object.id) === object + @test model_object(model, object.id.value) === object + end + for id in (17, :absent, (:plant, 4)), query in (id, ObjectId(id)) + failure = try + model_object(model, query) + catch exception + exception + end + @test failure isa ErrorException + @test sprint(showerror, failure) == "No model object with id `$(id)`." + end @test model_status(model, 1) === supplied @test PSE.refvalue(model_status(model, supplied), :value) === reference @test isnothing(model_status(model, (:plant, 3))) From c4060148d496048985476dfa10a3106bd8e34819 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 15:27:01 +0100 Subject: [PATCH 073/324] Specialize batches after shared environment sampling --- src/composite_model/runtime_outputs.jl | 28 +++++++- ...-model-global-environment-sample-schema.jl | 72 +++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 4adc2ed0f..2d4e79330 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3002,6 +3002,32 @@ end batch_time, constants, ) + return _run_model_execution_batch_targets!( + batch, + compiled, + env_bindings, + batch_time, + constants, + temporal_streams, + output_retention, + shared_environment, + performance, + ) +end + +# Weather sampling may return different row schemas. Cross that dispatch +# boundary once per batch, so every target kernel receives a concrete row. +@noinline function _run_model_execution_batch_targets!( + batch::CompiledExecutionBatch, + compiled::CompiledCompositeModel, + env_bindings::CompiledEnvironmentBindings, + time::Real, + constants, + temporal_streams, + output_retention, + shared_environment, + performance::Union{Nothing,RuntimePerformanceCounters}, +) publish_outputs = batch.output_publication.enabled for target in batch.targets _run_model_execution_target!( @@ -3009,7 +3035,7 @@ end env_bindings, batch.application, target, - batch_time, + time, constants, temporal_streams, output_retention, diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 7e0de6ca5..1078087fe 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -271,6 +271,78 @@ function table_probe(source; remap=false) return run!(model; steps=3, outputs=:all) end +@testset "shared batches accept changing environment row schemas" begin + source = Any[ + (T=1.25f0, duration=Hour(1)), + (T=4.5, duration=Hour(1)), + (T=2.5f0, duration=Hour(1)), + ] + model = CompositeModel(Object(:a; scale=:Leaf), Object(:b; scale=:Leaf); + applications=(ModelSpec(Probe(0.0); name=:probe, on=Many(scale=:Leaf)),), + environment=source) + simulation = run!(model; steps=3, outputs=:all) + for id in (:a, :b) + @test model_status(model, id).seen === 2.5 + @test model_status(model, id).visits == 3 + @test outputs(simulation)[(:probe, ObjectId(id), :seen)] == + [(1.0, 1.25), (2.0, 4.5), (3.0, 2.5)] + end +end + +function prepared_environment_batch(object_count) + source = Any[(T=1.25f0, duration=Hour(1)), (T=4.5, duration=Hour(1))] + model = CompositeModel( + (Object(id; scale=:Leaf) for id in 1:object_count)...; + applications=(ModelSpec(Probe(0.0); name=:probe, on=Many(scale=:Leaf)),), + environment=source, + ) + simulation = run!(model; steps=0, outputs=:none) + return (; model, simulation, batch=only(simulation.execution_plan.batches)) +end + +@noinline function execute_environment_batch!(simulation, batch, time) + PSE._run_model_execution_batch!( + batch, + simulation.compiled, + simulation.environment_bindings, + time, + simulation.constants, + simulation.temporal_streams, + simulation.output_retention, + ) + return nothing +end + +environment_batch_allocations(simulation, batch, time) = + @allocated execute_environment_batch!(simulation, batch, time) + +@testset "sampled rows cross the allocation boundary once per batch" begin + small = prepared_environment_batch(8) + large = prepared_environment_batch(128) + for data in (small, large), time in (1.0, 2.0), _ in 1:2 + execute_environment_batch!(data.simulation, data.batch, time) + environment_batch_allocations(data.simulation, data.batch, time) + end + visits_before = model_status(small.model, 1).visits + @test model_status(large.model, 1).visits == visits_before + + for (time, expected) in ((1.0, 1.25), (2.0, 4.5)) + small_allocations = environment_batch_allocations( + small.simulation, small.batch, time, + ) + large_allocations = environment_batch_allocations( + large.simulation, large.batch, time, + ) + @test large_allocations <= small_allocations + 1024 + for data in (small, large) + @test all(object -> object.status.seen === expected, model_objects(data.model)) + end + end + for data in (small, large) + @test all(object -> object.status.visits == visits_before + 2, model_objects(data.model)) + end +end + @testset "DataFrame preparation keeps table samples Any and preserves every Float32 row" begin temperatures = Float32[1.25, 2.5, 4] unused = Int32[11, 22, 33] From 33b868cf016240ddb440a20a9f27d65f08baf1fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 17:38:52 +0100 Subject: [PATCH 074/324] Use Ubuntu archive for Playwright dependencies --- .github/workflows/CI.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index a90e19bde..d544103e7 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -132,7 +132,10 @@ jobs: } - name: Install Playwright browser working-directory: frontend - run: npx playwright install --with-deps chromium + run: | + # Avoid the Azure mirror that intermittently fails DNS on hosted runners. + printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null + npx playwright install --with-deps chromium - name: Run graph editor E2E tests working-directory: frontend run: npm run test:e2e From 9b449e33a6d8498b0a3fea9db57aee16f6ef40ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 17:58:18 +0100 Subject: [PATCH 075/324] Use matching Playwright container for graph tests --- .github/workflows/CI.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index d544103e7..39660df60 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -91,6 +91,10 @@ jobs: if: ${{ github.event_name != 'workflow_dispatch' || !inputs.juliac_safe }} name: Graph editor E2E runs-on: ubuntu-latest + container: + # Keep the browser image aligned with frontend/package-lock.json. + image: mcr.microsoft.com/playwright:v1.60.0-noble + options: --ipc=host timeout-minutes: 30 permissions: actions: write @@ -130,12 +134,6 @@ jobs: echo "frontend/dist is stale. Run npm run build in frontend/ and commit the rebuilt assets."; exit 1; } - - name: Install Playwright browser - working-directory: frontend - run: | - # Avoid the Azure mirror that intermittently fails DNS on hosted runners. - printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null - npx playwright install --with-deps chromium - name: Run graph editor E2E tests working-directory: frontend run: npm run test:e2e From e6c428a60028d844796b3eafed87ebb061987120 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 18:09:50 +0100 Subject: [PATCH 076/324] Run graph asset check in trusted workspace --- .github/workflows/CI.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 39660df60..6a39f9811 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -130,7 +130,7 @@ jobs: run: npm run build - name: Check committed graph editor assets run: | - git diff --exit-code -- frontend/dist || { + git -c safe.directory="$GITHUB_WORKSPACE" -C "$GITHUB_WORKSPACE" diff --exit-code -- frontend/dist || { echo "frontend/dist is stale. Run npm run build in frontend/ and commit the rebuilt assets."; exit 1; } From de6922def71d2b4132b8aac27b3be85eb683b054 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 21:56:04 +0100 Subject: [PATCH 077/324] Validate retained outputs against typed destination views --- .../execution_batch_schemas.jl | 4 +- src/composite_model/runtime_outputs.jl | 101 +++++++----------- test/test-model-runtime-stream-extensions.jl | 59 +++++++++- 3 files changed, 95 insertions(+), 69 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index c69c0bbd2..e927b977b 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -463,7 +463,7 @@ end end @generated function _prepared_runtime_outputs(::Type{O}, status_view::CompiledModelStatusView, output_targets, - application, object_id, compiled, streams, retention, initialize_missing, + application, object_id, streams, retention, initialize_missing, ) where {O<:Tuple} entries = Expr[] for R in fieldtypes(O) @@ -496,7 +496,7 @@ end local_count == length(outputs) || throw(ArgumentError("Prepared newborn retained output count changed.")) else - _model_execution_outputs_match(outputs,status_view,compiled,application,object_id, + _model_execution_outputs_match(outputs,status_view,output_targets,application,object_id, retention,streams) || throw(ArgumentError("Prepared retained output names or ownership changed.")) end return outputs diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 2d4e79330..e50ce1fba 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3466,7 +3466,7 @@ function _new_model_execution_target(::Val{Target}, actual_application, actual, (local_outputs...,distributed_outputs...) else _prepared_runtime_outputs(fieldtype(Target,:output_bindings),actual.status_view, - actual.output_targets,actual_application,actual.object_id,owner.compiled, + actual.output_targets,actual_application,actual.object_id, owner.temporal_streams,owner.output_retention,false) end context = if isnothing(owner.temporal_streams) && isempty(actual.output_targets) @@ -3781,7 +3781,7 @@ end function _model_execution_outputs_match( runtime_outputs::Tuple, status_view::CompiledModelStatusView, - compiled::CompiledCompositeModel, + output_targets::NamedTuple, application::CompiledModelApplication, object_id::ObjectId, output_retention, @@ -3819,66 +3819,41 @@ function _model_execution_outputs_match( end additions = Tuple{Int,Vector{Any}}[] - if compiled.distributed_outputs isa CompiledDistributedOutputs - groups = get( - compiled.distributed_outputs.by_execution_target, - (application.id, object_id), - nothing, - ) - if !isnothing(groups) - isnothing(temporal_streams) && return false - for binding in values(groups) - for variable_ in binding.plan.variable_names - variable = Symbol(variable_) - variable in variables || continue - output_index += 1 - output_index <= length(runtime_outputs) || return false - output = runtime_outputs[output_index] - output isa RuntimeDistributedOutputStream || return false - _runtime_output_variable(output) == variable || return false - output.binding === binding || return false - output.references === - getproperty(binding.columns, variable) || return false - expected_horizon = isnothing(dependency_horizons) ? - 0.0 : - get( - dependency_horizons, - (application.id, variable), - 0.0, - ) - output.dependency_horizon == expected_horizon || return false - destination_ids = binding.destination_ids - runtime_streams = output.streams - length(runtime_streams) <= length(destination_ids) || - return false - for index in eachindex(runtime_streams) - key = _model_stream_key( - application.id, - destination_ids[index], - variable, - ) - runtime_streams[index] === - get(temporal_streams, key, nothing) || return false - end - length(runtime_streams) == length(destination_ids) && - continue - runtime_streams isa Vector || return false - new_streams = Any[] - for index in (length(runtime_streams) + 1):length(destination_ids) - key = _model_stream_key( - application.id, - destination_ids[index], - variable, - ) - stream = get(temporal_streams, key, nothing) - isnothing(stream) && return false - stream isa eltype(runtime_streams) || return false - push!(new_streams, stream) - end - push!(additions, (output_index, new_streams)) - end - end + # These views have already admitted the current destination bindings. Their + # names retain the compiler's group/variable order, including shared bindings. + for variable in keys(output_targets) + variable in variables || continue + isnothing(temporal_streams) && return false + binding = getproperty(output_targets, variable).binding + output_index += 1 + output_index <= length(runtime_outputs) || return false + output = runtime_outputs[output_index] + output isa RuntimeDistributedOutputStream || return false + _runtime_output_variable(output) == variable || return false + output.binding === binding || return false + output.references === getproperty(binding.columns, variable) || return false + expected_horizon = isnothing(dependency_horizons) ? + 0.0 : + get(dependency_horizons, (application.id, variable), 0.0) + output.dependency_horizon == expected_horizon || return false + destination_ids = binding.destination_ids + runtime_streams = output.streams + length(runtime_streams) <= length(destination_ids) || return false + for index in eachindex(runtime_streams) + key = _model_stream_key(application.id, destination_ids[index], variable) + runtime_streams[index] === get(temporal_streams, key, nothing) || return false end + length(runtime_streams) == length(destination_ids) && continue + runtime_streams isa Vector || return false + new_streams = Any[] + for index in (length(runtime_streams) + 1):length(destination_ids) + key = _model_stream_key(application.id, destination_ids[index], variable) + stream = get(temporal_streams, key, nothing) + isnothing(stream) && return false + stream isa eltype(runtime_streams) || return false + push!(new_streams, stream) + end + push!(additions, (output_index, new_streams)) end output_index == length(runtime_outputs) || return false for addition in additions @@ -4022,7 +3997,7 @@ function _model_execution_target_change_reason( _model_execution_outputs_match( target.output_bindings, status_view, - compiled, + target.output_targets, application, object_id, output_retention, @@ -6130,7 +6105,7 @@ function _append_targeted_newborn_target!(::Val{Target}, actual_application, act actual.object_id,owner.temporal_streams,owner.output_retention,true) : _prepared_runtime_outputs(fieldtype(Target,:output_bindings), actual.status_view,actual.output_targets,actual_application, - actual.object_id,owner.compiled,owner.temporal_streams, + actual.object_id,owner.temporal_streams, owner.output_retention,true) # Narrow a retained cache before use; no new owner is published # until all real fields have passed the same target admission. diff --git a/test/test-model-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl index 7c01e5dcc..bb01b32a3 100644 --- a/test/test-model-runtime-stream-extensions.jl +++ b/test/test-model-runtime-stream-extensions.jl @@ -103,14 +103,14 @@ end # Both genuine owners have staged additions, then this extra genuine entry # makes the final shape check fail. Neither vector may change on rejection. extra_entry = (staged..., first(staged)) - @test !PSE._model_execution_outputs_match(extra_entry, target.status_view, simulation.compiled, + @test !PSE._model_execution_outputs_match(extra_entry, target.status_view, target.output_targets, target.context.application, target.object_id, simulation.output_retention, simulation.temporal_streams) @test all(length(streams) == 1 for streams in original_vectors) @test all(first(streams) === first_stream for (streams, first_stream) in zip(original_vectors, first_streams)) - @test PSE._model_execution_outputs_match(staged, target.status_view, simulation.compiled, + @test PSE._model_execution_outputs_match(staged, target.status_view, target.output_targets, target.context.application, target.object_id, simulation.output_retention, simulation.temporal_streams) for (index, output) in enumerate(staged) @@ -121,6 +121,20 @@ end @test length(streams) == 2 @test streams[2] === outputs(simulation)[(:writer, ObjectId(2), variable)] end + # Recreate prepared descriptors after real growth without replaying kernels. + # Their source vectors may be fresh; each binding, column and stream stays live. + prepared = @inferred PSE._prepared_runtime_outputs(typeof(target.output_bindings), + target.status_view, target.output_targets, target.context.application, + target.object_id, simulation.temporal_streams, simulation.output_retention, false) + @test typeof(prepared) === typeof(target.output_bindings) + @test Tuple(PSE._runtime_output_variable(output) for output in prepared) == (:a, :z) + @test first(prepared).binding === last(prepared).binding + for (actual, original) in zip(prepared, target.output_bindings) + @test actual.binding === original.binding + @test actual.references === original.references + @test length(actual.streams) == length(original.streams) == 2 + @test all(current === previous for (current, previous) in zip(actual.streams, original.streams)) + end @test histories(simulation) == before_history @test runs[] == 2 @test outputs(simulation)[(:writer, ObjectId(2), :a)] == [(2.0, 4f0)] @@ -129,6 +143,43 @@ end check_append_allocations!(Any[first(first_streams)], Any[last(first(original_vectors))]) end +@testset "prepared local outputs keep concrete owners in a distributed scene" begin + for retention in (:none, :all) + runs = Ref(0) + model = CompositeModel(Object(0; scale=:Scene), + Object(1; scale=:Leaf, parent=0, status=Status(a=0f0, z=0.0)), + Object(2; scale=:Source, parent=0, status=Status(a=1f0, z=10.0)); + applications=( + ModelSpec(Distributor(Ref(0)); name=:writer, on=One(id=0), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree())),)), + ModelSpec(Source(runs); name=:source, on=One(id=2)), + )) + simulation = run!(model; steps=1, outputs=retention) + target = execution_target(simulation, :source, 2) + @test simulation.compiled.distributed_outputs isa PSE.CompiledDistributedOutputs + @test isempty(target.output_targets) + before = histories(simulation) + prepared = @inferred PSE._prepared_runtime_outputs(typeof(target.output_bindings), + target.status_view, target.output_targets, target.context.application, + target.object_id, simulation.temporal_streams, + simulation.output_retention, false) + @test typeof(prepared) === typeof(target.output_bindings) + @test PSE._model_execution_outputs_match(prepared, target.status_view, + target.output_targets, target.context.application, target.object_id, + simulation.output_retention, simulation.temporal_streams) + for (actual, original) in zip(prepared, target.output_bindings) + @test actual.stream === original.stream + @test actual.reference === original.reference + end + @test histories(simulation) == before + @test runs[] == 1 + step!(simulation) + @test runs[] == 2 + @test model_status(model, 2).a === 3f0 + @test model_status(model, 2).z === 30.0 + end +end + @testset "temporal stream extension retains validation atomicity and live owners" begin source_runs, reader_runs = Ref(0), Ref(0) model = CompositeModel(Object(0; scale=:Scene, status=Status(lag_a=Float32[], lag_z=Float64[])), @@ -190,10 +241,10 @@ end other_target = execution_target(simulation, :source, 2) application = source_target.context.application @test PSE._model_execution_outputs_match(source_target.output_bindings, - source_target.status_view, simulation.compiled, application, + source_target.status_view, source_target.output_targets, application, source_target.object_id, simulation.output_retention, simulation.temporal_streams) @test !PSE._model_execution_outputs_match(source_target.output_bindings, - other_target.status_view, simulation.compiled, application, + other_target.status_view, source_target.output_targets, application, source_target.object_id, simulation.output_retention, simulation.temporal_streams) # Missing-view handling stays at the two existing gateways. Restore the From 5c5c17b145ba02b0ec5b42ab4e6ca8b0393244e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 23:00:45 +0100 Subject: [PATCH 078/324] Admit destination groups before constructing typed views --- .../execution_batch_schemas.jl | 36 ++++- src/composite_model/runtime_outputs.jl | 140 +++++++++--------- test/test-model-prepared-growth-schemas.jl | 3 +- test/test-model-runtime-stream-extensions.jl | 109 ++++++++++++++ 4 files changed, 210 insertions(+), 78 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index e927b977b..ca10bed40 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -130,6 +130,31 @@ end return closed ? :(PreparedContextCallSchema{$C}()) : :(OpenContextCallSchema()) end +# Recover the prepared group schema from its real views. Several variables of +# one group share one binding and assignment cache; group/variable order matters. +function _output_target_binding_groups_type(::Type{T}) where {T<:NamedTuple} + groups, bindings, names, views = Symbol[], Type[], Symbol[], Type[] + for View in fieldtypes(T) + View <: OutputTargets && isconcretetype(View) || + throw(ArgumentError("Prepared output destinations require concrete OutputTargets views.")) + Binding = fieldtype(View, :binding) + Plan = fieldtype(Binding, :plan) + group, variables = Plan.parameters[1], Plan.parameters[2] + if group in groups + Binding === bindings[findfirst(==(group), groups)] || + throw(ArgumentError("A prepared output group has inconsistent binding types.")) + continue + end + push!(groups, group) + push!(bindings, Binding) + append!(names, variables) + append!(views, fill(View, length(variables))) + end + Tuple(names) === fieldnames(T) && Tuple(views) === fieldtypes(T) || + throw(ArgumentError("Prepared output views must retain their group and variable order.")) + return NamedTuple{Tuple(groups),Tuple{bindings...}} +end + # Admit the real status view before reading its parameterized fields. The # ordinary function barrier specializes its actual V; prepared execution uses # the same existing finite target schema before assembling the same fields. @@ -138,7 +163,7 @@ end ) where {F,V<:CompiledModelStatusView} actual_fields = (object_id=fields.object_id, model=fields.model, status_view=status_view, bound_inputs=status_view.bound_inputs, - output_targets=fields.output_targets, call_bindings=fields.call_bindings, + output_targets=_runtime_model_output_targets(fields.output_groups), call_bindings=fields.call_bindings, environment_binding=fields.environment_binding) return f(Val{nothing}(), application, actual_fields, owners, OpenContextCallSchema()) end @@ -158,18 +183,23 @@ end closed_calls && _validate_prepared_context_calls(Calls) CallSchema = closed_calls ? PreparedContextCallSchema{Calls} : OpenContextCallSchema V = fieldtype(Target, :status_view) - checks = Expr[:(application isa $(fieldtype(Context, :application)))] + Views = fieldtype(Target, :output_targets) + Groups = _output_target_binding_groups_type(Views) + checks = Expr[:(application isa $(fieldtype(Context, :application))), + :(getproperty(fields, :output_groups) isa $Groups)] values = Expr[] for name in names value = if name === :status_view :status_view + elseif name === :output_targets + :(_runtime_model_output_targets(getproperty(fields, :output_groups)::$Groups)::$Views) elseif name === :bound_inputs # The earlier status_view check short-circuits before this read. :((status_view::$V).bound_inputs) else :(getproperty(fields, $(QuoteNode(name)))) end - push!(checks, :($value isa $(fieldtype(Target, name)))) + name === :output_targets || push!(checks, :($value isa $(fieldtype(Target, name)))) push!(values, :($value::$(fieldtype(Target, name)))) end for name in (:compiled, :environment_bindings, :temporal_streams, :output_retention, :constants, :environment) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index e50ce1fba..6e62fd804 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3349,50 +3349,46 @@ function _runtime_model_distributed_output_streams( ) end -_runtime_model_output_targets( - compiled, - application, - object_id, - ::NoCompiledDistributedOutputs, -) = NamedTuple() - -function _runtime_model_output_targets( - compiled, - application, - object_id, - distributed_outputs::CompiledDistributedOutputs, -) - groups = get( - distributed_outputs.by_execution_target, - (application.id, object_id), - nothing, - ) - isnothing(groups) && return NamedTuple() - names = Symbol[] - targets = Any[] - anchors = Any[] - for binding in values(groups) - alignment_id = findfirst(anchor -> anchor.destination_ids == binding.destination_ids, anchors) - if isnothing(alignment_id) - push!(anchors, binding) - alignment_id = length(anchors) - end - target = OutputTargets(binding, alignment_id) - for name in binding.plan.variable_names - push!(names, name) - push!(targets, target) +_runtime_model_output_groups(application, object_id, ::NoCompiledDistributedOutputs) = NamedTuple() + +function _runtime_model_output_groups(application, object_id, outputs::CompiledDistributedOutputs) + isempty(_model_distributed_output_names(application)) && return NamedTuple() + return get(outputs.by_execution_target, (application.id, object_id), NamedTuple()) +end + +_runtime_model_output_groups(compiled, application, object_id) = + _runtime_model_output_groups(application, object_id, compiled.distributed_outputs) + +@generated function _runtime_model_output_targets(groups::G) where {G<:NamedTuple} + names, targets, statements = Symbol[], Symbol[], Expr[] + binding_vars, target_vars = Symbol[], Symbol[] + for (index, Binding) in enumerate(fieldtypes(G)) + Plan = fieldtype(Binding, :plan) + group, variables = Plan.parameters[1], Plan.parameters[2] + group === fieldnames(G)[index] || error("An output group does not match its binding plan.") + binding, target = gensym(:binding), gensym(:target) + alignment = :(alignment_count + 1) + for previous in reverse(eachindex(binding_vars)) + alignment = :( $binding.destination_ids == $(binding_vars[previous]).destination_ids ? + $(target_vars[previous]).alignment_id : $alignment ) end + push!(statements, :($binding = getfield(groups, $index))) + push!(statements, :($target = OutputTargets($binding, $alignment))) + push!(statements, :(alignment_count = max(alignment_count, $target.alignment_id))) + append!(names, variables) + append!(targets, fill(target, length(variables))) + push!(binding_vars, binding) + push!(target_vars, target) + end + return quote + alignment_count = 0 + $(statements...) + return NamedTuple{$(QuoteNode(Tuple(names)))}($(Expr(:tuple, targets...))) end - return NamedTuple{Tuple(names)}(Tuple(targets)) end _runtime_model_output_targets(compiled, application, object_id) = - _runtime_model_output_targets( - compiled, - application, - object_id, - compiled.distributed_outputs, - ) + _runtime_model_output_targets(_runtime_model_output_groups(compiled, application, object_id)) function _compiled_model_execution_target( compiled::CompiledCompositeModel, @@ -3438,10 +3434,10 @@ function _new_model_execution_target( ) status_view = _model_status_view_for_application(compiled, application, object_id) model = _application_model(application, object_id) - distributed_targets = _runtime_model_output_targets(compiled, application, object_id) + output_groups = _runtime_model_output_groups(compiled, application, object_id) call_bindings = get(compiled.call_bindings_by_target, (application.id, object_id), ()) environment_binding = _environment_binding_for(env_bindings, application.id, object_id) - fields = (object_id=object_id, model=model, output_targets=distributed_targets, + fields = (object_id=object_id, model=model, output_groups=output_groups, call_bindings=call_bindings, environment_binding=environment_binding) owners = (compiled=compiled, environment_bindings=env_bindings, temporal_streams=temporal_streams, @@ -3880,41 +3876,37 @@ function _model_execution_output_targets_match( return isempty(targets) end -function _model_execution_output_targets_match( - targets, - compiled, - application, - object_id, +@generated function _model_execution_output_targets_match( + targets::T, compiled, application, object_id, distributed_outputs::CompiledDistributedOutputs, -) - bindings = get( - distributed_outputs.by_execution_target, - (application.id, object_id), - nothing, - ) - isnothing(bindings) && return isempty(targets) - count = 0 - ordered_bindings = values(bindings) - for (index, binding) in enumerate(ordered_bindings) - for name in binding.plan.variable_names - hasproperty(targets, name) || return false - target = getproperty(targets, name) - target.binding === binding || return false - count += 1 +) where {T<:NamedTuple} + G = _output_target_binding_groups_type(T) + checks = Expr[] + for (index, Binding) in enumerate(fieldtypes(G)) + variables = fieldtype(Binding, :plan).parameters[2] + binding = :(getfield(bindings, $index)) + current = :(getproperty(targets, $(QuoteNode(first(variables))))) + for name in variables + push!(checks, :(getproperty(targets, $(QuoteNode(name))).binding === $binding || return false)) end - # A monotonic addition can extend existing columns and streams in place. - # Rebuild only if it changes which destination declarations are aligned. - current = getproperty(targets, first(binding.plan.variable_names)) - for previous_index in 1:(index - 1) - previous = ordered_bindings[previous_index] - previous_target = getproperty(targets, first(previous.plan.variable_names)) - was_aligned = current.alignment_id == previous_target.alignment_id - now_aligned = binding.destination_ids == previous.destination_ids - was_aligned == now_aligned || return false + # In-place growth preserves the view only while group alignments agree. + for previous in 1:(index - 1) + previous_name = first(fieldtype(fieldtype(G, previous), :plan).parameters[2]) + previous_target = :(getproperty(targets, $(QuoteNode(previous_name)))) + previous_binding = :(getfield(bindings, $previous)) + push!(checks, quote + ($current.alignment_id == $previous_target.alignment_id) == + ($binding.destination_ids == $previous_binding.destination_ids) || return false + end) end end - length(targets) == count || return false - return true + return quote + bindings = _runtime_model_output_groups(application, object_id, distributed_outputs) + bindings isa $G || return false + bindings = bindings::$G + $(checks...) + return true + end end function _model_execution_output_targets_match( @@ -6077,11 +6069,11 @@ function _append_targeted_newborn_targets!( object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, targeted_runtime.application_positions,compiled.distributed_outputs; execution_stamp=stamp)::CompiledModelStatusView - output_targets = _runtime_model_output_targets(compiled,application,object_id) + output_groups = _runtime_model_output_groups(compiled,application,object_id) environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) call_bindings = () # targeted admission has rejected nested callees fields = (object_id=object_id,model=_application_model(application,object_id), - output_targets=output_targets,call_bindings=call_bindings, + output_groups=output_groups,call_bindings=call_bindings, environment_binding=environment_binding) owners = (compiled=compiled,environment_bindings=environment_bindings, temporal_streams=context.temporal_streams, diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index f55eeeb81..ebc9fb2f2 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -265,7 +265,8 @@ call_key(target) = (target.application.id, target.object_id.value) foreign_owner = foreign.simulation.environment_bindings @test !(foreign_owner isa typeof(partial_owner)) fields = (object_id=target.object_id, model=target.model, - output_targets=target.output_targets, + output_groups=PSE._runtime_model_output_groups(target.compiled, + target.application, target.object_id), call_bindings=target.execution_target.call_bindings, environment_binding=target.environment_binding) owners = (compiled=target.compiled, environment_bindings=foreign_owner, diff --git a/test/test-model-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl index bb01b32a3..69fa014ef 100644 --- a/test/test-model-runtime-stream-extensions.jl +++ b/test/test-model-runtime-stream-extensions.jl @@ -143,6 +143,115 @@ end check_append_allocations!(Any[first(first_streams)], Any[last(first(original_vectors))]) end +struct SplitDistributor <: AbstractStream_Extension_DistributorModel + runs::Base.RefValue{Int} +end +PSE.inputs_(::SplitDistributor) = NamedTuple() +PSE.outputs_(::SplitDistributor) = (a=Distributed(Default(0f0)), + b=Distributed(Default(0f0)), z=Distributed(Default(0.0))) +function PSE.run!(model::SplitDistributor, status, environment, constants, context) + model.runs[] += 1 + leaves = output_targets(context, (:a, :b)) + for index in eachindex(leaves) + leaves.columns.a[index] = Float32(context.time) + leaves.columns.b[index] = 2f0 * Float32(context.time) + end + first_leaf = output_targets(context, (:z,)) + for index in eachindex(first_leaf) + first_leaf.columns.z[index] = 10.0 * context.time + end + return nothing +end + +function split_fixture(; split=true) + runs = Ref(0) + routes = split ? ( + OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:a, :b)), + OutputTo(One(id=1, within=SceneScope()); vars=(:z,)), + ) : (OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:a, :b, :z)),) + model = CompositeModel(Object(0; scale=:Scene), + Object(1; scale=:Leaf, parent=0, status=Status(a=0f0, b=0f0, z=0.0)); + applications=(ModelSpec(SplitDistributor(runs); name=:split, + on=One(id=0), outputs_to=routes),)) + return (; model, runs, simulation=run!(model; steps=1, outputs=:all)) +end + +function check_reconstructed_groups(data, alignment) + simulation = data.simulation + target = execution_target(simulation, :split, 0) + application = target.context.application + before = histories(simulation) + runs = data.runs[] + @test PSE._model_execution_output_targets_match(target.output_targets, + simulation.compiled, application, target.object_id) + schema = PSE._closed_execution_cohort_schema(Tuple{typeof(target)}) + for admission in (PSE.OpenExecutionCohortSchema(), schema) + rebuilt = PSE._new_model_execution_target(simulation.compiled, + simulation.environment_bindings, application, target.object_id, + simulation.temporal_streams, simulation.output_retention, + simulation.constants; target_schema=admission) + views = rebuilt.output_targets + @test typeof(rebuilt) === typeof(target) + @test keys(views) == (:a, :b, :z) + @test views.a === views.b + @test views.a !== views.z + @test views.a.assignment_cache === views.b.assignment_cache + @test (views.a.alignment_id, views.z.alignment_id) == alignment + for variable in keys(views) + actual, original = getproperty(views, variable), getproperty(target.output_targets, variable) + @test actual.binding === original.binding + @test actual.columns === original.columns + @test collect(object_ids(actual)) == collect(object_ids(original)) + end + for (actual, original) in zip(rebuilt.output_bindings, target.output_bindings) + @test actual.binding === original.binding + @test actual.references === original.references + @test length(actual.streams) == length(original.streams) + @test all(left === right for (left, right) in zip(actual.streams, original.streams)) + end + @test data.runs[] == runs + @test histories(simulation) == before + end + return target +end + +@testset "typed output groups preserve ownership and changing destination alignment" begin + data = split_fixture() + original = check_reconstructed_groups(data, (1, 1)) + @test collect(object_ids(output_targets(original.context, (:a, :z)))) == [ObjectId(1)] + a_reference = PSE.refvalue(model_status(data.model, 1), :a) + + register_object!(data.model, Object(2; scale=:Leaf, parent=0, + status=Status(a=0f0, b=0f0, z=0.0))) + step!(data.simulation) + grown = check_reconstructed_groups(data, (1, 2)) + @test grown !== original + @test_throws ArgumentError output_targets(grown.context, (:a, :z)) + @test PSE.refvalue(model_status(data.model, 1), :a) === a_reference + @test model_status(data.model, 2).a === 2f0 + @test outputs(data.simulation)[(:split, ObjectId(2), :a)] == [(2.0, 2f0)] + + remove_object!(data.model, 2) + step!(data.simulation) + reduced = check_reconstructed_groups(data, (1, 1)) + @test reduced !== grown + @test collect(object_ids(output_targets(reduced.context, (:a, :z)))) == [ObjectId(1)] + @test PSE.refvalue(model_status(data.model, 1), :a) === a_reference + @test outputs(data.simulation)[(:split, ObjectId(2), :a)] == [(2.0, 2f0)] + @test data.runs[] == 3 + + # Real bindings from another owner must fail even when their schema matches. + foreign = split_fixture() + @test !PSE._model_execution_output_targets_match(reduced.output_targets, + foreign.simulation.compiled, + execution_target(foreign.simulation, :split, 0).context.application, ObjectId(0)) + # A different genuine grouping is rejected before accessing its columns. + regrouped = split_fixture(; split=false) + @test !PSE._model_execution_output_targets_match(reduced.output_targets, + regrouped.simulation.compiled, + execution_target(regrouped.simulation, :split, 0).context.application, ObjectId(0)) +end + @testset "prepared local outputs keep concrete owners in a distributed scene" begin for retention in (:none, :all) runs = Ref(0) From 81de927c07b7f17643212cacb51a1b8f02e814c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 11 Nov 2026 23:51:19 +0100 Subject: [PATCH 079/324] Inline finite admission before dispatching typed target factories --- .../execution_batch_schemas.jl | 20 +++++++++++-------- src/composite_model/runtime_outputs.jl | 14 ++++++------- test/test-model-prepared-growth-schemas.jl | 10 ++++------ 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index ca10bed40..1f7d12418 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -159,17 +159,21 @@ end # ordinary function barrier specializes its actual V; prepared execution uses # the same existing finite target schema before assembling the same fields. @inline function _with_execution_target_type(f::F, ::OpenExecutionCohortSchema, - application, status_view::V, fields, owners, + application, status_view::V, object_id, model, output_groups, call_bindings, + environment_binding, owners, ) where {F,V<:CompiledModelStatusView} - actual_fields = (object_id=fields.object_id, model=fields.model, + actual_fields = (object_id=object_id, model=model, status_view=status_view, bound_inputs=status_view.bound_inputs, - output_targets=_runtime_model_output_targets(fields.output_groups), call_bindings=fields.call_bindings, - environment_binding=fields.environment_binding) + output_targets=_runtime_model_output_targets(output_groups), call_bindings=call_bindings, + environment_binding=environment_binding) return f(Val{nothing}(), application, actual_fields, owners, OpenContextCallSchema()) end +# Incoming metadata can be abstract: callers inline these finite checks before +# dispatching the typed factory, without a runtime generated-method fallback. @generated function _with_execution_target_type(f, ::ClosedExecutionCohortSchema{T}, - application, status_view::CompiledModelStatusView, fields, owners, + application, status_view::CompiledModelStatusView, object_id, model, output_groups, + call_bindings, environment_binding, owners, ) where {T} branches = Expr[] names = (:object_id, :model, :status_view, :bound_inputs, @@ -186,18 +190,18 @@ end Views = fieldtype(Target, :output_targets) Groups = _output_target_binding_groups_type(Views) checks = Expr[:(application isa $(fieldtype(Context, :application))), - :(getproperty(fields, :output_groups) isa $Groups)] + :(output_groups isa $Groups)] values = Expr[] for name in names value = if name === :status_view :status_view elseif name === :output_targets - :(_runtime_model_output_targets(getproperty(fields, :output_groups)::$Groups)::$Views) + :(_runtime_model_output_targets(output_groups::$Groups)::$Views) elseif name === :bound_inputs # The earlier status_view check short-circuits before this read. :((status_view::$V).bound_inputs) else - :(getproperty(fields, $(QuoteNode(name)))) + name end name === :output_targets || push!(checks, :($value isa $(fieldtype(Target, name)))) push!(values, :($value::$(fieldtype(Target, name)))) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 6e62fd804..62945e0c1 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3437,14 +3437,13 @@ function _new_model_execution_target( output_groups = _runtime_model_output_groups(compiled, application, object_id) call_bindings = get(compiled.call_bindings_by_target, (application.id, object_id), ()) environment_binding = _environment_binding_for(env_bindings, application.id, object_id) - fields = (object_id=object_id, model=model, output_groups=output_groups, - call_bindings=call_bindings, environment_binding=environment_binding) owners = (compiled=compiled, environment_bindings=env_bindings, temporal_streams=temporal_streams, output_retention=output_retention, constants=constants, environment=_NO_ENVIRONMENT_OVERRIDE) - return _with_execution_target_type(_new_model_execution_target, target_schema, - application, status_view, fields, owners) + return Base.@inline _with_execution_target_type(_new_model_execution_target, target_schema, + application, status_view, object_id, model, output_groups, call_bindings, + environment_binding, owners) end function _new_model_execution_target(::Val{Target}, actual_application, actual, owner, @@ -6072,14 +6071,13 @@ function _append_targeted_newborn_targets!( output_groups = _runtime_model_output_groups(compiled,application,object_id) environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) call_bindings = () # targeted admission has rejected nested callees - fields = (object_id=object_id,model=_application_model(application,object_id), - output_groups=output_groups,call_bindings=call_bindings, - environment_binding=environment_binding) + model = _application_model(application,object_id) owners = (compiled=compiled,environment_bindings=environment_bindings, temporal_streams=context.temporal_streams, output_retention=context.output_retention,constants=context.constants, environment=context.environment) - _with_execution_target_type(admission,application,status_view,fields,owners) do target_type,actual_application,actual,owner,call_schema + Base.@inline _with_execution_target_type(admission,application,status_view,object_id,model, + output_groups,call_bindings,environment_binding,owners) do target_type,actual_application,actual,owner,call_schema _append_targeted_newborn_target!(target_type,actual_application,actual,owner, call_schema,targets,context,cache,stamp,targeted_runtime,key) end diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index ebc9fb2f2..0e19c0486 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -264,11 +264,6 @@ call_key(target) = (target.application.id, target.object_id.value) foreign = prepare_schema_growth(; environment=(T=3f0,)) foreign_owner = foreign.simulation.environment_bindings @test !(foreign_owner isa typeof(partial_owner)) - fields = (object_id=target.object_id, model=target.model, - output_groups=PSE._runtime_model_output_groups(target.compiled, - target.application, target.object_id), - call_bindings=target.execution_target.call_bindings, - environment_binding=target.environment_binding) owners = (compiled=target.compiled, environment_bindings=foreign_owner, temporal_streams=target.temporal_streams, output_retention=target.output_retention, constants=target.constants, @@ -277,7 +272,10 @@ call_key(target) = (target.application.id, target.object_id.value) PSE.OpenExecutionCohortSchema()) @test_throws ArgumentError PSE._with_execution_target_type( (args...) -> error("foreign owner entered target factory"), admission, - target.application, target.execution_target.status_view, fields, owners) + target.application, target.execution_target.status_view, + target.object_id, target.model, + PSE._runtime_model_output_groups(target.compiled, target.application, target.object_id), + target.execution_target.call_bindings, target.environment_binding, owners) @test canonical.visits == 0 && canonical.value == 0.0 @test isempty(PSE.lifecycle_delta(simulation.model).initialized_targets) end From 032eece8c55cdce1409c67a4781554fa8889439e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 12 Nov 2026 14:04:47 +0100 Subject: [PATCH 080/324] Preserve prepared types during environment refresh and output setup Retain the context environment schema when resolving current-topology calls, inline the finite environment-plan admission boundary, and admit output IDs through the registry identity schema. Six whole maintained files pass: 1774 assertions, including closed cohorts, prepared calls/growth and environment-owner refresh. Full scientific JuliaC qualification remains pending. --- src/composite_model/environment_bindings.jl | 2 +- src/composite_model/runtime_outputs.jl | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index d00fc4ccd..0c2bfa707 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -478,7 +478,7 @@ function _compile_environment_bindings_for_applications( application_id = application.id application_process = application.process target_ids = application.target_ids - _with_environment_plan(environment_schema, plans_by_id[application_id]) do plan + Base.@inline _with_environment_plan(environment_schema, plans_by_id[application_id]) do plan for object_id in target_ids object = _model_object(model, object_id) context = _object_environment_context(application_id, application_process, object, object_id) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 62945e0c1..1b61e8d87 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1953,12 +1953,13 @@ function _initialize_model_output_streams!( application, variable, ) + id = _index_object_id(compiled.model.registry.objects, object_id) _initialize_model_output_stream!( streams, compiled, retention, application, - object_id, + id, variable, sizehint_steps, ) @@ -6191,7 +6192,12 @@ function _current_topology_call_targets( ) isnothing(targeted) || return targeted compiled = _refresh_runtime_bindings!(model, context.compiled) - environment_bindings = refresh_environment_bindings!(model, compiled) + environment_bindings = _refresh_environment_bindings!( + model, + compiled, + _current_environment_binding_owner(model, context.environment_bindings); + environment_schema=context.environment_bindings.environment_schema, + ) bindings = get( compiled.call_bindings_by_target, (context.application.id, context.object_id), From 9477cb259459534b21e560675a92303a6aa1f121 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 12 Nov 2026 14:28:04 +0100 Subject: [PATCH 081/324] Prepare typed global environment sampling recipes Resolve raw, projected and window sampling once in the environment plan, preserving a raw row type witness and the shared weather sampler. Reuse one sampling worker and remove the former runtime selector and its unused application argument. Refresh same-type recipe values correctly and preserve reducer factories versus mutable instances. Validation: 1815 assertions in nine whole maintained files, including new Weather inference, shared cadence, same-type rebind and reducer-state regressions. Source/input guards and process termination pass. Full XPalm native parity and updated performance remain pending. --- src/composite_model/compilation.jl | 11 +- src/composite_model/environment_bindings.jl | 46 ++++-- src/composite_model/runtime_outputs.jl | 56 ++++---- src/native_compilation.jl | 2 +- src/time/runtime/environment_sampling.jl | 46 ++---- ...-model-global-environment-sample-schema.jl | 134 +++++++++++++++++- 6 files changed, 213 insertions(+), 82 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index ae493fa45..0f3c0f076 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1730,9 +1730,12 @@ struct CompiledEnvironmentSamplingRule{T,S} end CompiledEnvironmentSamplingRule(target::Symbol, source::Symbol) = CompiledEnvironmentSamplingRule{target,source}() -# A value-type witness narrows the existing shared Any-valued sample memo. -# It carries no sampled state and does not change cache ownership or resets. -struct GlobalEnvironmentSampleSchema{R} end +# The result witness admits the existing shared Any-valued sample memo. +# Kind, window and transforms are prepared metadata, never sampled values. +struct GlobalEnvironmentSampleSchema{R,Kind,W,T} + window::W + transforms::T +end @inline _global_environment_sample_value(::GlobalEnvironmentSampleSchema{R}, value) where {R} = value::R struct CompiledEnvironmentApplicationPlan{B,C,RI,SI,PO,R,CR,S,P,GS} @@ -5133,7 +5136,7 @@ function _model_environment_bindings_with_environment_sources( resolved = Pair{Symbol,Any}[] for target in targets rule = haskey(bindings, target) ? - _normalize_environment_binding_rule(target, bindings[target]) : + _normalize_environment_binding_rule(target, bindings[target], _normalize_environment_reducer) : (source=target, reducer=PlantMeteo.MeanWeighted()) source = haskey(sources, target) ? Symbol(sources[target]) : rule.source push!(resolved, target => (source=source, reducer=rule.reducer)) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 0c2bfa707..8bbb17149 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -205,16 +205,32 @@ function _environment_source_variable_names(sampling_rules) return Tuple(Symbol(source) for (_, source) in sampling_rules) end -# Raw singleton sampling returns the source itself. Other sampling recipes -# retain Any until their result schema is known; preparation never samples a -# custom source merely to discover its return type. -function _global_environment_sample_schema(backend, source, sampler, uses_raw::Bool, prepare_runtime::Bool) - if prepare_runtime && isnothing(sampler) && uses_raw && - backend isa GlobalConstant && - DataFormat(environment_source(backend)) isa SingletonAlike - return GlobalEnvironmentSampleSchema{typeof(source)}() +# Resolve the same raw/window decision once per application. Source samplers +# stay shared across applications, including applications with different clocks. +function _global_environment_sample_schema( + backend, source, sampler, uses_raw::Bool, prepare_runtime::Bool, application, +) + window = nothing + transforms = nothing + kind = if isnothing(sampler) + uses_raw ? :raw : :projected + else + transforms = _environment_transforms_for_model(application.spec) + window = _runtime_environment_window(environment_window(application.spec)) + if float(application.clock.dt) <= 1.0 && isnothing(transforms) && + (isnothing(window) || window isa PlantMeteo.RollingWindow) + window = nothing + :raw + else + window = _environment_sampling_window(application.clock, application.spec) + :window + end end - return GlobalEnvironmentSampleSchema{Any}() + R = prepare_runtime && backend isa GlobalConstant && kind === :raw ? + _global_environment_raw_sample_type(source) : Any + return GlobalEnvironmentSampleSchema{R,kind,typeof(window),typeof(transforms)}( + window, transforms, + ) end function _compile_environment_application_plans( @@ -267,7 +283,7 @@ function _compile_environment_application_plans( prepared_source, uses_raw_global_source, _global_environment_sample_schema( - backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, + backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, application, ), ) end @@ -570,6 +586,12 @@ end step::Int, ) = @inbounds prepared.rows[step] +# These are row-type declarations, not calls to sample arbitrary providers. +_global_environment_raw_sample_type(source) = + DataFormat(source) isa SingletonAlike ? typeof(source) : Any +_global_environment_raw_sample_type(source::TimeStepTable) = eltype(source) +_global_environment_raw_sample_type(source::PreparedGlobalEnvironmentRows) = eltype(source.rows) + # Rule names are fixed in the compiled plan's tuple type. Materializing this # zero-size schema is a compiler constant, not a scan or a sampled-value cache. @generated function _prepared_environment_inputs(::R) where {R<:Tuple} @@ -735,7 +757,9 @@ function _same_environment_application_plan(a, b) a.sampler === b.sampler && a.prepared_source === b.prepared_source && a.uses_raw_global_source == b.uses_raw_global_source && - typeof(a.sample_schema) === typeof(b.sample_schema) + typeof(a.sample_schema) === typeof(b.sample_schema) && + isequal(a.sample_schema.window, b.sample_schema.window) && + isequal(a.sample_schema.transforms, b.sample_schema.transforms) end function _reconciled_environment_application_plans( diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 1b61e8d87..28aca53bd 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2713,11 +2713,7 @@ function _model_environment_for_binding( return _global_environment_sample_value( binding.plan.sample_schema, env_bindings.sample_cache[key], ) - sampled = _sample_compiled_global_environment( - binding, - application, - step, - ) + sampled = _sample_compiled_global_environment(binding, step) env_bindings.sample_cache[key] = sampled return _global_environment_sample_value(binding.plan.sample_schema, sampled) end @@ -2729,29 +2725,35 @@ function _model_environment_for_binding( ) end -@inline function _sample_compiled_global_environment( - binding, - application, - step::Int, -) +@inline function _sample_compiled_global_environment(binding, step::Int) raw_row = _environment_row_at_step(binding.prepared_source, step) - sampler = binding.sampler - if !isnothing(sampler) - return _sample_environment_for_model( - sampler, - raw_row, - step, - application.clock, - application.spec, - ) - end - binding.uses_raw_global_source && return raw_row - return _sample_compiled_global_environment_row( - raw_row, - binding.compiled_sampling_rules, + return _sample_compiled_global_environment( + binding.plan.sample_schema, binding, raw_row, step, ) end +@inline function _sample_compiled_global_environment( + schema::GlobalEnvironmentSampleSchema{R,:raw}, binding, raw_row, step::Int, +) where {R} + return _global_environment_sample_value(schema, raw_row) +end + +@inline function _sample_compiled_global_environment( + schema::GlobalEnvironmentSampleSchema{R,:projected}, binding, raw_row, step::Int, +) where {R} + return _global_environment_sample_value(schema, _sample_compiled_global_environment_row( + raw_row, binding.compiled_sampling_rules, + )) +end + +@inline function _sample_compiled_global_environment( + schema::GlobalEnvironmentSampleSchema{R,:window}, binding, raw_row, step::Int, +) where {R} + return _global_environment_sample_value(schema, PlantMeteo.sample_weather( + binding.sampler, step; window=schema.window, transforms=schema.transforms, + )) +end + # The execution payload owns the already resolved current call bindings. # Context creation never rediscovers that dependency schema through a global map. # A fresh shell either clones a current prototype or rebuilds from those bindings; @@ -2968,11 +2970,7 @@ end application, time, ) - return _sample_compiled_global_environment( - provider.binding, - application, - Int(round(time)), - ) + return _sample_compiled_global_environment(provider.binding, Int(round(time))) end @inline function _run_model_execution_batch!( diff --git a/src/native_compilation.jl b/src/native_compilation.jl index d450302f9..faf445c30 100644 --- a/src/native_compilation.jl +++ b/src/native_compilation.jl @@ -66,7 +66,7 @@ function _check_target(application, target) # Validate the same environment row that the canonical batch sampler uses. binding = target.environment_binding environment = isnothing(binding) ? nothing : - PSE._sample_compiled_global_environment(binding, application, 1) + PSE._sample_compiled_global_environment(binding, 1) isbits(environment) || _unsupported(application.id, "sampled environment must be an immutable bits-valued row") return nothing diff --git a/src/time/runtime/environment_sampling.jl b/src/time/runtime/environment_sampling.jl index fdad4abf2..b761ed262 100644 --- a/src/time/runtime/environment_sampling.jl +++ b/src/time/runtime/environment_sampling.jl @@ -30,13 +30,18 @@ end _normalize_environment_reducer(reducer) = _normalize_policy_reducer(reducer) -function _normalize_environment_binding_rule(target::Symbol, rule) +# Keep a declared reducer type as a factory. PlantMeteo instantiates it for +# each sampled window, while an authored instance retains its own live state. +_environment_reducer_recipe(reducer::Type{<:PlantMeteo.AbstractTimeReducer}) = reducer +_environment_reducer_recipe(reducer) = _normalize_environment_reducer(reducer) + +function _normalize_environment_binding_rule(target::Symbol, rule, normalize_reducer) if rule isa NamedTuple src = haskey(rule, :source) ? Symbol(rule.source) : target - reducer = haskey(rule, :reducer) ? _normalize_environment_reducer(rule.reducer) : PlantMeteo.MeanWeighted() + reducer = haskey(rule, :reducer) ? normalize_reducer(rule.reducer) : PlantMeteo.MeanWeighted() return (source=src, reducer=reducer) elseif rule isa Function || rule isa PlantMeteo.AbstractTimeReducer || rule isa DataType - return (source=target, reducer=_normalize_environment_reducer(rule)) + return (source=target, reducer=normalize_reducer(rule)) end error( @@ -178,38 +183,9 @@ function _environment_transforms_for_model(model_spec) pairs_out = Pair{Symbol,Any}[] for (target, rule) in pairs(bindings) - push!(pairs_out, target => _normalize_environment_binding_rule(target, rule)) + push!(pairs_out, target => _normalize_environment_binding_rule( + target, rule, _environment_reducer_recipe, + )) end return (; pairs_out...) end - -function _sample_environment_for_model( - environment_sampler, - environment, - i::Int, - model_clock::ClockSpec, - model_spec -) - transforms = _environment_transforms_for_model(model_spec) - window = _runtime_environment_window(environment_window(model_spec)) - - isnothing(environment_sampler) && begin - if !isnothing(transforms) || !isnothing(window) - @warn string( - "Environment sampling rules were provided but the weather sampler API is unavailable or the source is not TimeStepTable{Atmosphere}. ", - "Falling back to raw environment rows." - ) maxlog = 1 - end - return environment - end - - # Fast-path: default 1:1 weather step with no custom transforms. - if float(model_clock.dt) <= 1.0 && - isnothing(transforms) && - (isnothing(window) || window isa PlantMeteo.RollingWindow) - return environment - end - - window = _environment_sampling_window(model_clock, model_spec) - return PlantMeteo.sample_weather(environment_sampler, i; window=window, transforms=transforms) -end diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 1078087fe..24c517eed 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -343,7 +343,7 @@ environment_batch_allocations(simulation, batch, time) = end end -@testset "DataFrame preparation keeps table samples Any and preserves every Float32 row" begin +@testset "DataFrame preparation admits raw row types and preserves every Float32 row" begin temperatures = Float32[1.25, 2.5, 4] unused = Int32[11, 22, 33] durations = fill(Hour(1), 3) @@ -359,7 +359,8 @@ end control = table_probe(rows; remap) plan = simulation.environment_bindings.application_plans_by_id[:probe] @test plan.prepared_source isa PSE.PreparedGlobalEnvironmentRows - @test plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{Any} + R = remap ? Any : eltype(rows) + @test plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{R} @test current_step(simulation) == current_step(control) == 3 @test final_state(simulation) == final_state(control) == (seen=4f0, visits=3) @test outputs(simulation)[(:probe, ObjectId(:a), :seen)] == @@ -563,4 +564,133 @@ end end end + +function recipe_weather() + return PSE.PlantMeteo.Weather([ + PSE.PlantMeteo.Atmosphere(date=DateTime(2025, 1, 1) + Hour(index - 1), + T=temperature, Wind=1.0, Rh=0.5, duration=Hour(1)) + for (index, temperature) in enumerate((10.0, 20.0, 30.0, 40.0)) + ]) +end + +@testset "prepared raw Weather rows stay inferred and share the window sampler" begin + weather = recipe_weather() + specs = ( + ModelSpec(Probe(0.0); name=:raw, on=One(id=:a), every=Hour(1)), + ModelSpec(Probe(0.0); name=:window, on=One(id=:b), every=Hour(2)), + ) + make_model() = CompositeModel(Object(:a; scale=:Leaf), Object(:b; scale=:Leaf); + applications=specs, environment=weather) + collected = PSE._collecting_environment_binding_schema() + PSE._prepare_simulation!(make_model(); steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=collected) + frozen = PSE._freeze_environment_binding_schema(collected) + for schema in (PSE.EnvironmentBindingSchema(), frozen) + model = make_model() + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=schema) + owner = simulation.environment_bindings + raw = owner.by_target[(:raw, ObjectId(:a))] + window = owner.by_target[(:window, ObjectId(:b))] + raw_batch = only(batch for batch in simulation.execution_plan.batches + if batch.application.id === :raw) + @test raw.sampler === window.sampler + @test raw.prepared_source === window.prepared_source === weather + @test raw.plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{eltype(weather)} + for time in (1, 2, 4) + row = @inferred PSE._model_execution_batch_environment( + raw_batch.environment_provider, owner, raw_batch.application, time, + ) + @test row === weather[time] + @test parent(row) === weather + @test row.T === (10.0, 20.0, 30.0, 40.0)[time] + end + cached_row = @inferred PSE._model_environment_for_binding( + owner, raw_batch.application, raw, 2.0, + ) + @test cached_row === weather[2] + PSE.continue!(simulation; steps=4) + @test model_status(model, :a).seen === 40.0 + @test model_status(model, :a).visits == 4 + @test model_status(model, :b).seen === 25.0 + @test model_status(model, :b).visits == 2 + @test raw.sampler === window.sampler + end +end + +struct RecipeOffsetReducer <: PSE.PlantMeteo.AbstractTimeReducer + offset::Float64 +end +(reducer::RecipeOffsetReducer)(values, durations) = + PSE.PlantMeteo.MeanWeighted()(values, durations) + reducer.offset + +mutable struct RecipeCountingReducer <: PSE.PlantMeteo.AbstractTimeReducer + calls::Int +end +RecipeCountingReducer() = RecipeCountingReducer(0) +function (reducer::RecipeCountingReducer)(values, durations) + reducer.calls += 1 + return PSE.PlantMeteo.MeanWeighted()(values, durations) + reducer.calls +end + +function recipe_window_spec(width, offset) + return ModelSpec(Probe(0.0); name=:probe, on=One(id=:a), every=Hour(3), + environment_window=PSE.PlantMeteo.RollingWindow(width), + environment_bindings=(T=(source=:T, reducer=RecipeOffsetReducer(offset)),)) +end + +@testset "reconciled same-type Weather recipes use new window and transform values" begin + weather = recipe_weather() + initial_spec = recipe_window_spec(2.0, 0.0) + make_model() = CompositeModel(Object(:a; scale=:Leaf); + applications=(initial_spec,), environment=weather) + collected = PSE._collecting_environment_binding_schema() + PSE._prepare_simulation!(make_model(); steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=collected) + frozen = PSE._freeze_environment_binding_schema(collected) + for schema in (PSE.EnvironmentBindingSchema(), frozen), + (width, offset, expected) in ((3.0, 0.0, 20.0), (2.0, 7.0, 32.0)) + model = make_model() + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=schema) + owner = simulation.environment_bindings + old = owner.by_target[(:probe, ObjectId(:a))] + # Bypass the app/time memo here: this must test recipe reconciliation, + # while keeping the source sampler and its own window-keyed cache live. + @test PSE._sample_compiled_global_environment(old, 3).T === 25.0 + replacement = recipe_window_spec(width, offset) + @test typeof(replacement) === typeof(initial_spec) + compiled = PSE.Advanced.compile_composite_model(model, (replacement,)) + refreshed = PSE._refresh_environment_bindings!(model, compiled, owner) + current = refreshed.by_target[(:probe, ObjectId(:a))] + @test model.environment_binding_cache === refreshed + @test refreshed.environment_schema === schema + @test current.plan !== old.plan + @test typeof(current.plan.sample_schema) === typeof(old.plan.sample_schema) + @test current.sampler === old.sampler + @test current.prepared_source === old.prepared_source === weather + @test current.sampling_rules == old.sampling_rules + @test isempty(refreshed.sample_cache) + @test PSE._sample_compiled_global_environment(current, 3).T === expected + application = compiled.applications_by_id[:probe] + @test PSE._model_environment_for_binding( + refreshed, application, current, 3.0, + ).T === expected + end + + # A type requests a fresh reducer for every sample. An explicit instance + # shares its state between samples, as before recipe preparation. + instance = RecipeCountingReducer() + for (reducer, expected) in ((RecipeCountingReducer, 26.0), (instance, 27.0)) + model = CompositeModel(Object(:a; scale=:Leaf); environment=recipe_weather(), + applications=(ModelSpec(Probe(0.0); name=:probe, on=One(id=:a), + every=Hour(2), environment_bindings=(T=reducer,)),)) + simulation = run!(model; steps=3, outputs=:all) + @test outputs(simulation)[(:probe, ObjectId(:a), :seen)] == + [(1.0, 11.0), (3.0, expected)] + @test model_status(model, :a).seen === expected + end + @test instance.calls == 2 +end + end # module GlobalEnvironmentSampleSchemaChecks From c5f80627340043f05b995a8052ab06e2dd9becd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 12 Nov 2026 14:50:12 +0100 Subject: [PATCH 082/324] Keep environment variable inventories concretely typed Construct the global variable-name set with an explicit Symbol element type so closed input validation can resolve membership and collection operations. Verify the public environment query inference on real Weather alongside the maintained backend and prepared-input checks (354 assertions). --- src/time/runtime/environment_backends.jl | 2 +- test/test-model-global-environment-sample-schema.jl | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index b622ecbfe..b7461cfed 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -102,7 +102,7 @@ end function _available_environment_variables(source) row = _first_environment_row(source) isnothing(row) && return nothing - return Set(Symbol.(propertynames(row))) + return Set{Symbol}(Symbol.(propertynames(row))) end """ diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 24c517eed..7dc3b81bf 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -575,6 +575,10 @@ end @testset "prepared raw Weather rows stay inferred and share the window sampler" begin weather = recipe_weather() + available = @inferred Nothing PSE.EnvironmentAPI.environment_variables( + PSE.GlobalConstant(weather), + ) + @test :T in available specs = ( ModelSpec(Probe(0.0); name=:raw, on=One(id=:a), every=Hour(1)), ModelSpec(Probe(0.0); name=:window, on=One(id=:b), every=Hour(2)), From c3587789f70cc98befaac019ffbf0ca1f00f8b10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 12 Nov 2026 15:10:07 +0100 Subject: [PATCH 083/324] Keep missing-environment diagnostics concretely typed Format a missing-input location and its available variable names as bounded strings, replacing the large mixed vararg call and runtime-sized tuple. Preserve application, object, process, target and source details. Three whole maintained files pass 355 assertions, including a public missing-source regression. --- src/composite_model/environment_bindings.jl | 23 +++++++++---------- ...-model-global-environment-sample-schema.jl | 7 ++++++ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 8bbb17149..012bc6871 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -538,6 +538,15 @@ function _compile_environment_bindings( ) end +function _missing_model_environment_input_detail( + application_id, process, object_id, target, source, available, +) + location = string(application_id, "/", object_id.value, " (", process, ")") + variables = join(sort!(collect(available); by=string), ", ") + return string(location, " needs `", target, "` from source `", source, + "`; available=(", variables, ")") +end + function _validate_model_environment_inputs!(bindings, applications_by_id, ::Type{I}; environment_schema=EnvironmentBindingSchema(), ) where {I<:ObjectId} @@ -556,18 +565,8 @@ function _validate_model_environment_inputs!(bindings, applications_by_id, application = applications_by_id[application_id] for (target, source) in plan.sampling_rules source in available && continue - push!(missing_details, string( - application_id, - "/", - object_id.value, - " (", - application.process, - ") needs `", - target, - "` from source `", - source, - "`; available=", - Tuple(sort!(collect(available); by=string)), + push!(missing_details, _missing_model_environment_input_detail( + application_id, application.process, object_id, target, source, available, )) end end diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 7dc3b81bf..99e5694f8 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -573,6 +573,13 @@ function recipe_weather() ]) end +@testset "missing Weather sources identify the application, input and available names" begin + model = CompositeModel(Object(:leaf; scale=:Leaf); environment=recipe_weather(), + applications=(ModelSpec(Probe(0.0); name=:probe, on=One(id=:leaf), + environment=Environment(sources=(T=:absent,))),)) + @test_throws r"probe/leaf .*needs `T` from source `absent`; available=\([^)]*\bT\b" run!(model; steps=1) +end + @testset "prepared raw Weather rows stay inferred and share the window sampler" begin weather = recipe_weather() available = @inferred Nothing PSE.EnvironmentAPI.environment_variables( From d790bffdf980cb91cf97a203b94081cbf6939e3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 12 Nov 2026 15:28:06 +0100 Subject: [PATCH 084/324] Collect environment names without tuple broadcasting Fill the Symbol set directly so weather column names with runtime tuple length do not require broadcast result inference. Preserve Symbol conversion and the existing variable inventory. Three whole maintained files pass 355 assertions with source/input guards and process termination verified. --- src/time/runtime/environment_backends.jl | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index b7461cfed..8a128fd0e 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -102,7 +102,11 @@ end function _available_environment_variables(source) row = _first_environment_row(source) isnothing(row) && return nothing - return Set{Symbol}(Symbol.(propertynames(row))) + variables = Set{Symbol}() + for name in propertynames(row) + push!(variables, Symbol(name)) + end + return variables end """ From a9b6a774719f2f9f611580579b02c0064ff00727 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 12 Nov 2026 16:41:15 +0100 Subject: [PATCH 085/324] Admit environment plan fields before typed construction --- src/composite_model/environment_bindings.jl | 197 +++++++++++++----- ...test-model-environment-binding-identity.jl | 8 +- ...-model-global-environment-sample-schema.jl | 65 ++++++ 3 files changed, 214 insertions(+), 56 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 012bc6871..72f64bd8e 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -202,35 +202,144 @@ function _environment_variable_names(vars) end function _environment_source_variable_names(sampling_rules) - return Tuple(Symbol(source) for (_, source) in sampling_rules) + return map(rule -> Symbol(last(rule)), Tuple(sampling_rules)) end -# Resolve the same raw/window decision once per application. Source samplers -# stay shared across applications, including applications with different clocks. -function _global_environment_sample_schema( +# Construct only after any closed-schema admission of these argument types. +@inline function _global_environment_sample_schema( + ::Type{R}, ::Val{Kind}, window::W, transforms::T, +) where {R,Kind,W,T} + return GlobalEnvironmentSampleSchema{R,Kind,W,T}(window, transforms) +end + +# Select prepared metadata without constructing a schema or a plan. The caller +# admits its raw fields before invoking the shared schema/plan constructors. +function _prepare_environment_application_plan( backend, source, sampler, uses_raw::Bool, prepare_runtime::Bool, application, + schema, config, required_inputs, produced_outputs, sampling_rules, ) - window = nothing - transforms = nothing - kind = if isnothing(sampler) - uses_raw ? :raw : :projected + if isnothing(sampler) + if !uses_raw + return Base.@inline _new_environment_application_plan(schema, + application.id, backend, config, required_inputs, produced_outputs, + sampling_rules, sampler, source, uses_raw, Any, + Val(:projected), nothing, nothing) + end else transforms = _environment_transforms_for_model(application.spec) window = _runtime_environment_window(environment_window(application.spec)) - if float(application.clock.dt) <= 1.0 && isnothing(transforms) && - (isnothing(window) || window isa PlantMeteo.RollingWindow) - window = nothing - :raw - else + if !(float(application.clock.dt) <= 1.0 && isnothing(transforms) && + (isnothing(window) || window isa PlantMeteo.RollingWindow)) window = _environment_sampling_window(application.clock, application.spec) - :window + return Base.@inline _new_environment_application_plan(schema, + application.id, backend, config, required_inputs, produced_outputs, + sampling_rules, sampler, source, uses_raw, Any, + Val(:window), window, transforms) end end - R = prepare_runtime && backend isa GlobalConstant && kind === :raw ? - _global_environment_raw_sample_type(source) : Any - return GlobalEnvironmentSampleSchema{R,kind,typeof(window),typeof(transforms)}( - window, transforms, - ) + if prepare_runtime && backend isa GlobalConstant + return Base.@inline _new_environment_application_plan(schema, + application.id, backend, config, required_inputs, produced_outputs, + sampling_rules, sampler, source, uses_raw, + _global_environment_raw_sample_type(source), Val(:raw), nothing, nothing) + end + return Base.@inline _new_environment_application_plan(schema, + application.id, backend, config, required_inputs, produced_outputs, + sampling_rules, sampler, source, uses_raw, Any, Val(:raw), nothing, nothing) +end + +# Open preparation derives the rule family from current routing values. Frozen +# preparation reaches the same assembly with a previously admitted plan type. +_compiled_environment_sampling_rules(::Val{nothing}, rules::Tuple) = + map(rule -> CompiledEnvironmentSamplingRule(first(rule), last(rule)), rules) + +@generated function _compiled_environment_sampling_rules(::Val{P}, rules::Tuple) where {P} + CR = fieldtype(P, :compiled_sampling_rules) + return Expr(:tuple, [:( $(Rule)() ) for Rule in fieldtypes(CR)]...) +end + +function _construct_environment_application_plan( + schema, witness::Val{P}, application_id, backend, config, required_inputs, + produced_outputs, sampling_rules, sampler, prepared_source, uses_raw, + row_type::Type{R}, kind::Val{Kind}, window, transforms, +) where {P,R,Kind} + source_inputs = _environment_source_variable_names(sampling_rules) + compiled_rules = _compiled_environment_sampling_rules(witness, sampling_rules) + sample_schema = _global_environment_sample_schema(row_type, kind, window, transforms) + plan = CompiledEnvironmentApplicationPlan(application_id, backend, config, + required_inputs, source_inputs, produced_outputs, sampling_rules, + compiled_rules, sampler, prepared_source, uses_raw, sample_schema) + if P === nothing + return _with_environment_plan(identity, schema, plan) + end + typeof(plan) === P || throw(ArgumentError("Environment-plan fields changed after admission.")) + return plan::P +end + +function _new_environment_application_plan( + schema::Union{EnvironmentBindingSchema{Nothing,Nothing},EnvironmentBindingSchema{Vector{DataType},Vector{DataType}}}, + application_id, backend, config, required_inputs, produced_outputs, + sampling_rules, sampler, prepared_source, uses_raw, row_type, kind, window, transforms, +) + return _construct_environment_application_plan(schema, Val(nothing), + application_id, backend, config, required_inputs, produced_outputs, + sampling_rules, sampler, prepared_source, uses_raw, row_type, kind, window, transforms) +end + +# Admit actual fields and routing before constructing any parameterized rule, +# sample schema or plan. A widened old record is not a new-constructor family. +@generated function _new_environment_application_plan( + schema::EnvironmentBindingSchema{PT,BT}, application_id::Symbol, + backend, config, required_inputs, produced_outputs, sampling_rules, + sampler, prepared_source, uses_raw::Bool, row_type, kind, window, transforms, +) where {PT<:NamedTuple,BT<:NamedTuple} + branches = Expr[] + names = (:backend, :config, :required_inputs, :produced_outputs, + :sampling_rules, :sampler, :prepared_source) + for Witness in fieldtypes(PT) + Witness <: Val || error("Environment-plan metadata must contain type witnesses only.") + P = only(Witness.parameters) + P isa DataType && isconcretetype(P) && P <: CompiledEnvironmentApplicationPlan || + error("Environment-plan metadata needs actual concrete normalized plan types.") + fields = [fieldtype(P, name) for name in names] + SI, CR, GS = (fieldtype(P, name) for name in + (:source_inputs, :compiled_sampling_rules, :sample_schema)) + all(isconcretetype, (fields..., SI, CR, GS)) || continue + CR <: Tuple && GS <: GlobalEnvironmentSampleSchema || continue + N = fieldcount(CR) + fieldtype(P, :required_inputs) === NTuple{N,Symbol} || continue + SI === NTuple{N,Symbol} || continue + Rules = fieldtype(P, :sampling_rules) + Rules <: Tuple && fieldcount(Rules) == N || continue + tags = fieldtypes(CR) + all(T -> T <: CompiledEnvironmentSamplingRule && + length(T.parameters) == 2 && all(x -> x isa Symbol, T.parameters), tags) || continue + R, Kind, W, T = GS.parameters + all(isconcretetype, (W, T)) || continue + checks = Expr[:($(name) isa $(Type)) for (name, Type) in zip(names, fields)] + append!(checks, [:(row_type === $R), :(kind isa Val{$(QuoteNode(Kind))}), + :(window isa $W), :(transforms isa $T)]) + for (index, Tag) in enumerate(tags) + target, source = Tag.parameters + push!(checks, :(getfield(sampling_rules::$Rules, $index) == + $(QuoteNode(target => source)))) + end + values = [:( $(name)::$(Type) ) for (name, Type) in zip(names, fields)] + condition = foldl((a,b) -> :($a && $b), checks) + b, c, ri, po, rules, s, ps = values + push!(branches, quote + if $condition + return _construct_environment_application_plan(schema, Val{$P}(), + application_id, $b, $c, $ri, $po, $rules, $s, $ps, + uses_raw, $R, Val{$(QuoteNode(Kind))}(), window::$W, transforms::$T) + end + end) + end + return quote + $(branches...) + throw(ArgumentError(string("The normalized environment plan for application `", + application_id, "` is outside its prepared family schema. Prepare a new compilation schema for this configuration."))) + end end function _compile_environment_application_plans( @@ -258,53 +367,37 @@ function _compile_environment_application_plans( bindings, environment_sources = _environment_sampling_configuration(application.spec) required_inputs = _model_environment_input_names(application) sampling_rules = Tuple(_environment_sampling_rules(bindings, environment_sources, required_inputs)) - compiled_sampling_rules = Tuple( - CompiledEnvironmentSamplingRule(target, source) - for (target, source) in sampling_rules - ) - source_inputs = _environment_source_variable_names(sampling_rules) produced_outputs = _model_environment_output_names(application) - function build_plan(sampler, prepared_source) - has_bindings = !isempty(keys(bindings)) - has_source_overrides = !isempty(keys(environment_sources)) - uses_raw_global_source = backend isa GlobalConstant && - isnothing(sampler) && - !has_bindings && !has_source_overrides - return CompiledEnvironmentApplicationPlan( - application.id, - backend, - config, - required_inputs, - source_inputs, - produced_outputs, - sampling_rules, - compiled_sampling_rules, - sampler, - prepared_source, - uses_raw_global_source, - _global_environment_sample_schema( - backend, prepared_source, sampler, uses_raw_global_source, prepare_runtime, application, - ), - ) - end + uses_raw_global_source = backend isa GlobalConstant && + isempty(keys(bindings)) && isempty(keys(environment_sources)) plan = if prepare_runtime && backend isa GlobalConstant source = environment_source(backend) cached_plan = get(plans_by_source, source, nothing) if isnothing(cached_plan) sampler = _prepare_environment_sampler(source) prepared_source = _prepare_global_environment(source) - prepared_plan = build_plan(sampler, prepared_source) + prepared_plan = _prepare_environment_application_plan( + backend, prepared_source, + sampler, uses_raw_global_source && isnothing(sampler), prepare_runtime, + application, environment_schema, config, required_inputs, + produced_outputs, sampling_rules) plans_by_source[source] = prepared_plan prepared_plan else - _with_environment_plan(environment_schema, cached_plan) do admitted_plan - build_plan(admitted_plan.sampler, admitted_plan.prepared_source) + Base.@inline _with_environment_plan(environment_schema, cached_plan) do admitted_plan + _prepare_environment_application_plan( + backend, admitted_plan.prepared_source, + admitted_plan.sampler, uses_raw_global_source && isnothing(admitted_plan.sampler), + prepare_runtime, application, environment_schema, config, + required_inputs, produced_outputs, sampling_rules) end end else - build_plan(nothing, nothing) + _prepare_environment_application_plan( + backend, nothing, nothing, + uses_raw_global_source, prepare_runtime, application, + environment_schema, config, required_inputs, produced_outputs, sampling_rules) end - _with_environment_plan(identity, environment_schema, plan) push!(plans, plan) haskey(plans_by_id, application.id) && error( "Environment application-plan compilation produced duplicate application id `$(application.id)`.", diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 74aae94c3..be0058970 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -549,13 +549,13 @@ end expected = if local_backend "Composite model environment is missing required source inputs: leaf/one " * "(environment_shell_leaf) needs `T` from source `missing`; " * - "available=(:other,); leaf/two (environment_shell_leaf) needs `T` from source" * - " `missing`; available=(:other,)" + "available=(other); leaf/two (environment_shell_leaf) needs `T` from source" * + " `missing`; available=(other)" else "Composite model environment is missing required source inputs: leaf/one " * - "(environment_shell_leaf) needs `T` from source `missing`; available=(:T,); " * + "(environment_shell_leaf) needs `T` from source `missing`; available=(T); " * "leaf/two (environment_shell_leaf) needs `T` from source `missing`; " * - "available=(:T,)" + "available=(T)" end for table in tables failure = try diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 99e5694f8..488350d94 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -704,4 +704,69 @@ end @test instance.calls == 2 end +@testset "closed plan factories distinguish same-type source remaps" begin + source = (T=10f0, U=20f0, V=30f0, duration=Hour(1)) + specs = map((:T, :U, :V)) do name + ModelSpec(Probe(0f0); name=:probe, on=One(id=:a), + environment=Environment(sources=(T=name,))) + end + make_model(spec) = CompositeModel(Object(:a; scale=:Leaf); + applications=(spec,), environment=source) + @test all(spec -> typeof(spec) === typeof(first(specs)), specs) + @test all(spec -> typeof(PSE.environment_config(spec)) === + typeof(PSE.environment_config(first(specs))), specs) + + collected = PSE._collecting_environment_binding_schema() + observed = map(specs[1:2]) do spec + PSE._prepare_simulation!(make_model(spec); steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=collected) + end + plans = map(simulation -> only(simulation.environment_bindings.application_plans), observed) + @test plans[1].sampling_rules == (:T => :T,) + @test plans[2].sampling_rules == (:T => :U,) + @test typeof(plans[1].sampling_rules) === typeof(plans[2].sampling_rules) === + typeof((:T => :V,)) + @test typeof(plans[1].config) === typeof(plans[2].config) + @test typeof(plans[1].compiled_sampling_rules) !== typeof(plans[2].compiled_sampling_rules) + schema = PSE._freeze_environment_binding_schema(collected) + + fresh = PSE._prepare_simulation!(make_model(specs[2]); steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=schema) + continue!(fresh; steps=1) + @test model_status(fresh.model, :a).seen === 20f0 + + model = make_model(specs[1]) + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_schema=schema) + owner = simulation.environment_bindings + application = simulation.compiled.applications_by_id[:probe] + binding = owner.by_target[(:probe, ObjectId(:a))] + @test PSE._model_environment_for_binding(owner, application, binding, 1.0).T === 10f0 + + compiled = PSE.Advanced.compile_composite_model(model, (specs[2],)) + refreshed = PSE._refresh_environment_bindings!(model, compiled, owner) + binding = refreshed.by_target[(:probe, ObjectId(:a))] + @test model.environment_binding_cache === refreshed + @test refreshed.environment_schema === schema + @test isempty(refreshed.sample_cache) + @test binding.plan.sampling_rules == (:T => :U,) + @test typeof(binding.plan.compiled_sampling_rules) === typeof(plans[2].compiled_sampling_rules) + @test binding.prepared_source === source + @test PSE._model_environment_for_binding(refreshed, + compiled.applications_by_id[:probe], binding, 1.0).T === 20f0 + + admitted_application = compiled.applications_by_id[:probe] + unadmitted = PSE.Advanced.compile_composite_model(model, (specs[3],)) + @test_throws "probe` is outside its prepared family schema" PSE._refresh_environment_bindings!( + model, unadmitted, refreshed) + @test model.environment_binding_cache === refreshed + @test refreshed.compiled_applications === compiled.applications + @test refreshed.compiled_applications !== unadmitted.applications + @test compiled.applications_by_id[:probe] === admitted_application + @test refreshed.by_target[(:probe, ObjectId(:a))] === binding + @test refreshed.application_plans_by_id[:probe] === binding.plan + @test PSE._model_environment_for_binding(refreshed, + admitted_application, binding, 1.0).T === 20f0 +end + end # module GlobalEnvironmentSampleSchemaChecks From d5df2b6117476f314b00567f6701772c5ca5c8f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 08:16:56 +0100 Subject: [PATCH 086/324] Grow temporal buffers through typed output carriers --- .../execution_batch_schemas.jl | 2 +- src/composite_model/runtime_outputs.jl | 52 +++++++++++++------ test/test-model-multirate-integration.jl | 27 ++++++++-- 3 files changed, 62 insertions(+), 19 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 1f7d12418..36eb3c589 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -533,7 +533,7 @@ end _model_execution_outputs_match(outputs,status_view,output_targets,application,object_id, retention,streams) || throw(ArgumentError("Prepared retained output names or ownership changed.")) end - return outputs + return _prepare_runtime_output_capacity!(outputs) end end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 28aca53bd..e1bdc7b95 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -165,6 +165,33 @@ end _runtime_output_variable(::RuntimeDistributedOutputStream{V}) where {V} = V +# Capacity changes belong to the already admitted runtime output carriers. +# All readers/publishers retain the same buffer when its horizon grows. +_prepare_runtime_output_capacity!(outputs::Tuple{}) = outputs +function _prepare_runtime_output_capacity!(outputs::Tuple) + _prepare_runtime_output_capacity!(first(outputs)) + _prepare_runtime_output_capacity!(Base.tail(outputs)) + return outputs +end + +function _prepare_runtime_output_capacity!(output::RuntimeOutputStream) + _prepare_runtime_stream_capacity!(output.stream, output.dependency_horizon) + return output +end + +function _prepare_runtime_output_capacity!(output::RuntimeDistributedOutputStream) + for stream in output.streams + _prepare_runtime_stream_capacity!(stream, output.dependency_horizon) + end + return output +end + +_prepare_runtime_stream_capacity!(stream, horizon::Float64) = nothing +function _prepare_runtime_stream_capacity!(stream::TemporalDependencyBuffer, horizon::Float64) + _grow_temporal_dependency_buffer!(stream, _model_dependency_capacity(horizon)) + return nothing +end + struct CompiledOutputPublication{V} variables::V enabled::Bool @@ -1734,13 +1761,15 @@ end _model_dependency_only_output(::Nothing, application_id::Symbol, variable::Symbol) = false +_model_dependency_capacity(horizon::Float64) = max(1, ceil(Int, horizon)) + function _model_dependency_capacity( retention::OutputRetentionPlan, application_id::Symbol, variable::Symbol, ) horizon = get(retention.dependency_horizons, (application_id, variable), 0.0) - return max(1, ceil(Int, horizon)) + return _model_dependency_capacity(horizon) end function _model_new_output_stream( @@ -1828,16 +1857,7 @@ function _initialize_model_output_stream!( sizehint_steps::Integer, ) key = _model_stream_key(application.id, object_id, variable) - if haskey(streams, key) - stream = streams[key] - if stream isa TemporalDependencyBuffer - _grow_temporal_dependency_buffer!( - stream, - _model_dependency_capacity(retention, application.id, variable), - ) - end - return streams - end + haskey(streams, key) && return streams reference = _model_output_reference( compiled, application, @@ -1879,7 +1899,8 @@ function _initialize_changed_model_output_streams!( sizehint_steps::Integer, target_keys, ) - for (application_id, object_id) in target_keys + for (application_id, target_id) in target_keys + object_id = _index_object_id(compiled.model.registry.objects, target_id) variables = get( retention.retained_outputs_by_application, application_id, @@ -1914,12 +1935,13 @@ function _initialize_changed_model_output_streams!( variable = Symbol(variable_) variable in variables || continue for destination_id in binding.destination_ids + id = _index_object_id(compiled.model.registry.objects, destination_id) _initialize_model_output_stream!( streams, compiled, retention, application, - destination_id, + id, variable, sizehint_steps, ) @@ -3206,7 +3228,7 @@ Base.@nospecializeinfer function _runtime_model_output_streams( ) push!(runtime_streams, runtime_stream) end - return Tuple(runtime_streams) + return _prepare_runtime_output_capacity!(Tuple(runtime_streams)) end function _runtime_model_output_streams( @@ -3328,7 +3350,7 @@ function _runtime_model_distributed_output_streams( ) end end - return Tuple(outputs) + return _prepare_runtime_output_capacity!(Tuple(outputs)) end function _runtime_model_distributed_output_streams( diff --git a/test/test-model-multirate-integration.jl b/test/test-model-multirate-integration.jl index b68dcece6..5c9495771 100644 --- a/test/test-model-multirate-integration.jl +++ b/test/test-model-multirate-integration.jl @@ -159,7 +159,7 @@ end @testset "new consumers expand wrapped temporal buffers without replacing them" begin totals = Float64[] - for retention in (:none, :all) + for retention in (:none, :all), prepared in (false, true) short_history, long_history = Float64[], Float64[] consumer_spec(name, scale, window, history) = ModelSpec( TemporalRetentionProbeModel(history); name=name, on=Many(scale=scale), @@ -179,7 +179,28 @@ end consumer_spec(:long, :Long, 5.0, long_history), ), ) - simulation = run!(model; steps=5, outputs=retention) + simulation = if prepared + # Observe real future-target types from this same fresh scenario. + witnessed_model = deepcopy(model) + register_object!(witnessed_model, Object(:long; scale=:Long)) + witnessed = run!(witnessed_model; steps=0, outputs=retention) + names = (:source, :short, :long) + schemas = NamedTuple{names}(map(names) do name + group = only(group for group in witnessed.execution_plan.groups + if group.application.id === name) + B = typeof(only(group.batches)) + PlantSimEngine.PreparedExecutionBatchSchema{Vector{B}}() + end) + initial = run!(model; steps=0, outputs=retention) + closed = PlantSimEngine._prepare_execution_batch_schemas(initial, schemas) + @test all(group -> group.membership.schema isa PlantSimEngine.ClosedExecutionCohortSchema, + closed.execution_plan.groups) + @test isempty(only(group for group in closed.execution_plan.groups + if group.application.id === :long).batches) + continue!(closed; steps=5) + else + run!(model; steps=5, outputs=retention) + end key = (:source, ObjectId(:source), :signal) stream = outputs(simulation)[key] if retention === :none @@ -202,7 +223,7 @@ end @test length(stream.times) == 5 end end - @test totals == [40.0, 40.0] + @test totals == fill(40.0, 4) end @testset "48-hour hourly/daily stack and plant isolation" begin From 939e30d7688dcfbd59f32556328433f88dafcfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 08:41:15 +0100 Subject: [PATCH 087/324] Read canonical outputs through typed status storage --- src/composite_model/runtime_outputs.jl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index e1bdc7b95..73eb5ccec 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1830,6 +1830,7 @@ function _model_output_reference( variable::Symbol, ) if variable in _model_output_names(application) && + !(variable in _model_canonical_output_names(application)) && haskey( compiled.status_views_by_target, (application.id, object_id), @@ -1842,7 +1843,7 @@ function _model_output_reference( return refvalue(status, variable) end return refvalue( - _model_object(compiled.model, object_id).status, + model_status(compiled.model, object_id), variable, ) end From 143ed96e52276fb9c0a4b70480b738509b29b46f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 09:58:25 +0100 Subject: [PATCH 088/324] Keep retention metadata and lifecycle identities concrete --- src/composite_model/compilation.jl | 5 +- src/composite_model/runtime_outputs.jl | 111 +++++++++++++++---------- 2 files changed, 69 insertions(+), 47 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 0f3c0f076..eb883dcae 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3898,7 +3898,8 @@ function _remove_stale_status_views!( candidate_keys, ) for key in candidate_keys - application_id, object_id = key + application_id, target_id = key + object_id = _index_object_id(compiled.model.registry.objects, target_id) application = compiled.applications_by_id[application_id] first( _sorted_object_id_position( @@ -3906,7 +3907,7 @@ function _remove_stale_status_views!( object_id, ), ) && continue - delete!(compiled.status_views_by_target, key) + delete!(compiled.status_views_by_target, (application_id, object_id)) end return compiled end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 73eb5ccec..e76edc464 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1829,7 +1829,8 @@ function _model_output_reference( object_id::ObjectId, variable::Symbol, ) - if variable in _model_output_names(application) && + if _model_output_names(application) !== _model_canonical_output_names(application) && + variable in _model_output_names(application) && !(variable in _model_canonical_output_names(application)) && haskey( compiled.status_views_by_target, @@ -2274,14 +2275,18 @@ function _model_duration_steps(duration, timeline) return nothing end -function _model_input_window_steps(binding::CompiledModelInputBinding, application::CompiledModelApplication, timeline) - explicit = _model_duration_steps(getfield(binding, :plan).window, timeline) +function _model_input_window_steps(window, integrates::Bool, application::CompiledModelApplication, timeline) + explicit = _model_duration_steps(window, timeline) !isnothing(explicit) && return explicit - getfield(binding, :policy) isa Union{Integrate,Aggregate} && - return float(application.clock.dt) + integrates && return float(application.clock.dt) return 1.0 end +function _model_input_window_steps(binding::CompiledModelInputBinding, application::CompiledModelApplication, timeline) + return _model_input_window_steps(getfield(binding, :plan).window, + getfield(binding, :policy) isa Union{Integrate,Aggregate}, application, timeline) +end + function _model_temporal_source_value( streams, application_id::Symbol, @@ -4677,40 +4682,64 @@ function explain_execution_plan(model::CompositeModel) end function _model_temporal_retention_horizon( - binding, + input_plan::CompiledModelInputPlan, + integrates::Bool, + interpolates::Bool, consumer, source, timeline, ) - window_steps = _model_input_window_steps(binding, consumer, timeline) - return if binding.policy isa Union{Integrate,Aggregate} + window_steps = _model_input_window_steps(input_plan.window, integrates, consumer, timeline) + return if integrates float(window_steps) + max(0.0, float(source.clock.dt) - 1.0) - elseif binding.policy isa Union{Interpolate,PreviousTimeStep} + elseif interpolates max(2.0, float(source.clock.dt) + 1.0) else 0.0 end end +# Binding carriers are irrelevant to retention. Extract its concrete scalar +# metadata before callbacks, and select the current plan inside its typed owner +# before reading a possibly heterogeneous window. +function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, + binding::CompiledModelInputBinding, +) where {F} + input_plan = getfield(binding, :plan) + application_id, plan_slot = input_plan.application_id, input_plan.slot + input_name = input_plan.input + source_var = input_plan.source_var + source_application_ids = getfield(binding, :source_application_ids) + policy = getfield(binding, :policy) + integrates = policy isa Union{Integrate,Aggregate} + interpolates = policy isa Union{Interpolate,PreviousTimeStep} + return _compiled_application_by_id(compiled, application_id) do consumer + _with_metadata_entry(compiled.scenario_plan.input_plans, plan_slot) do actual_plan + actual_plan.application_id === application_id && actual_plan.input === input_name && + actual_plan.source_var === source_var || + throw(ArgumentError("A temporal retention binding is outside its current input plan owner.")) + for source_application_id in source_application_ids + covered = _compiled_application_by_id(compiled, source_application_id) do source + required = _model_temporal_retention_horizon(actual_plan, + integrates, interpolates, consumer, source, compiled.scenario_plan.timeline) + f(source_application_id, source_var, required) + end + covered || return false + end + return true + end + end +end + function _model_output_retention_covers_binding( plan::OutputRetentionPlan, compiled::CompiledCompositeModel, - binding, + binding::CompiledModelInputBinding, ) plan.retain_all && return true - return _compiled_application_by_id(compiled, binding.application_id) do consumer - for source_application_id in binding.source_application_ids - covered = _compiled_application_by_id(compiled, source_application_id) do source - required = _model_temporal_retention_horizon( - binding, consumer, source, compiled.scenario_plan.timeline, - ) - key = (source_application_id, binding.source_var) - key in plan.temporal_dependencies && - get(plan.dependency_horizons, key, -Inf) >= required - end - covered || return false - end - return true + return _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required + key = (source_application_id, source_var) + key in plan.temporal_dependencies && get(plan.dependency_horizons, key, -Inf) >= required end end @@ -4718,15 +4747,16 @@ function _model_output_retention_covers_addition( plan::OutputRetentionPlan, compiled::CompiledCompositeModel, ) - for key in compiled.changed_execution_target_ids - view = get(compiled.status_views_by_target, key, nothing) + for (application_id, object_id) in compiled.changed_execution_target_ids + id = _index_object_id(compiled.model.registry.objects, object_id) + view = get(compiled.status_views_by_target, (application_id, id), nothing) isnothing(view) && continue - for temporal_input in view.temporal_inputs - _model_output_retention_covers_binding( - plan, - compiled, - temporal_input.binding, - ) || return false + view isa CompiledModelStatusView || throw(ArgumentError("Invalid compiled status view for temporal retention.")) + temporal_inputs = getfield(view, :temporal_inputs)::Tuple + for temporal_input in temporal_inputs + temporal_input isa CompiledTemporalInput || throw(ArgumentError("Invalid temporal retention input.")) + binding = getfield(temporal_input, :binding)::CompiledModelInputBinding + _model_output_retention_covers_binding(plan, compiled, binding) || return false end end return true @@ -4813,22 +4843,13 @@ function compile_model_output_retention( ) temporal_dependencies = Set{Tuple{Symbol,Symbol}}() dependency_horizons = Dict{Tuple{Symbol,Symbol},Float64}() - timeline = compiled.scenario_plan.timeline for binding in compiled.input_bindings binding.carrier_hint == :temporal_stream || continue - _compiled_application_by_id(compiled, binding.application_id) do consumer - for source_application_id in binding.source_application_ids - _compiled_application_by_id(compiled, source_application_id) do source - required = _model_temporal_retention_horizon( - binding, consumer, source, timeline, - ) - key = (source_application_id, binding.source_var) - push!(temporal_dependencies, key) - dependency_horizons[key] = max( - get(dependency_horizons, key, 0.0), required, - ) - end - end + _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required + key = (source_application_id, source_var) + push!(temporal_dependencies, key) + dependency_horizons[key] = max(get(dependency_horizons, key, 0.0), required) + return true end end From 6c28bc139e2abe83032c90747c4c4fc249861870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 10:24:30 +0100 Subject: [PATCH 089/324] Preserve concrete input refresh and output preallocation --- src/composite_model/compilation.jl | 43 +++++++++++-------- .../execution_batch_schemas.jl | 3 +- src/composite_model/runtime_outputs.jl | 35 +++++++-------- 3 files changed, 42 insertions(+), 39 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index eb883dcae..956a234ab 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4244,12 +4244,13 @@ function _extend_compiled_scene( ) started_at = _runtime_performance_start(performance) - added_input_binding_capacity = sum( - length(_model_input_names(application)) * - length(application.target_ids) - for application in added_applications; - init=0, - ) + added_input_binding_capacity = 0 + for application in added_applications + input_count = _compiled_application_by_id(compiled, application.id) do current + length(_model_input_names(current)) + end + added_input_binding_capacity += input_count * length(application.target_ids) + end input_bindings = compiled.input_bindings sizehint!( input_bindings, @@ -4286,12 +4287,14 @@ function _extend_compiled_scene( end if !isempty(forced_input_binding_keys) for (binding_index, binding) in pairs(input_bindings) - key = (binding.application_id, binding.consumer_id, binding.input) + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + key = (binding.application_id, consumer_id, binding.input) key in forced_input_binding_keys && push!(candidate_binding_indices, binding_index) end end - for object_id in added_ids + for target_id in added_ids + object_id = _index_object_id(model.registry.objects, target_id) _union_selector_candidates!( candidate_binding_indices, compiled.dynamic_input_binding_indices, @@ -4311,14 +4314,16 @@ function _extend_compiled_scene( index = pending_binding_indices[pending_binding_position] pending_binding_position += 1 binding = input_bindings[index] - binding_key = (binding.application_id, binding.consumer_id, binding.input) + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + source_ids = _input_binding_source_ids(model.registry.objects, binding.source_ids) + binding_key = (binding.application_id, consumer_id, binding.input) force_rebuild = !isempty(forced_input_binding_keys) && binding_key in forced_input_binding_keys if !force_rebuild && binding.multiplicity == :many && haskey(processed_many_sources, binding.source_ids) if binding.carrier_hint == :temporal_stream - key = (binding.application_id, binding.consumer_id) + key = (binding.application_id, consumer_id) push!(affected_temporal_keys, key) previous_temporal_sources[( key..., @@ -4328,12 +4333,12 @@ function _extend_compiled_scene( continue end previous_source_ids = binding.carrier_hint == :temporal_stream ? - copy(binding.source_ids) : + copy(source_ids) : ObjectId[] binding.multiplicity == :many && binding.carrier_hint == :temporal_stream && - (previous_shared_many_sources[binding.source_ids] = copy(binding.source_ids)) - default_scope = _default_dependency_scope(model, binding.consumer_id) + (previous_shared_many_sources[binding.source_ids] = copy(source_ids)) + default_scope = _default_dependency_scope(model, consumer_id) if !pure_addition && (isnothing(writer_rebind_keys) || !(binding_key in writer_rebind_keys)) structural_update = _update_structural_many_sources!( @@ -4354,7 +4359,7 @@ function _extend_compiled_scene( model, binding.matcher, added_ids; - context=binding.consumer_id, + context=consumer_id, default_to_context=true, default_scope=default_scope, ) || continue @@ -4376,7 +4381,7 @@ function _extend_compiled_scene( if appended_sources if binding.carrier_hint == :temporal_stream && previous_source_ids != binding.source_ids - key = (binding.application_id, binding.consumer_id) + key = (binding.application_id, consumer_id) push!(affected_temporal_keys, key) previous_temporal_sources[( key..., @@ -4407,7 +4412,7 @@ function _extend_compiled_scene( model, application.id, application.process, - binding.consumer_id, + consumer_id, binding.plan, applications_by_object, applications_by_id, @@ -4426,16 +4431,16 @@ function _extend_compiled_scene( ) input_bindings[index] = replacement_binding push!(changed_bindings, replacement_binding) - push!(rewired_consumer_ids, binding.consumer_id) + push!(rewired_consumer_ids, consumer_id) if binding.carrier_hint == :temporal_stream - key = (binding.application_id, binding.consumer_id) + key = (binding.application_id, consumer_id) push!(affected_temporal_keys, key) previous_temporal_sources[( key..., binding.input, )] = previous_source_ids end - target = (binding.application_id, binding.consumer_id) + target = (binding.application_id, consumer_id) input_bindings_by_target[target] = Tuple( existing === binding ? replacement_binding : existing for existing in get(input_bindings_by_target, target, ()) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 36eb3c589..4b8d5c113 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -450,7 +450,8 @@ function _prepared_local_runtime_output(::Type{O}, status, application, object_i stream = get(streams, key, nothing) if isnothing(stream) initialize_missing || throw(ArgumentError("A prepared retained output has no initialized stream.")) - stream = _model_new_output_stream(getproperty(status,V), retention, application.id, V) + stream = _model_new_output_stream(getproperty(status,V), retention, + application.id, V, 0, application.clock.dt) stream isa S || throw(ArgumentError("A newborn output stream is outside its prepared schema.")) streams[key] = stream end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index e76edc464..677c1dcd5 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1773,16 +1773,22 @@ function _model_dependency_capacity( end function _model_new_output_stream( - value, + value::T, retention, application_id::Symbol, variable::Symbol, -) + sizehint_steps::Integer, + clock_dt::Real, +) where {T} if _model_dependency_only_output(retention, application_id, variable) capacity = _model_dependency_capacity(retention, application_id, variable) - return TemporalDependencyBuffer{typeof(value)}(capacity) + return TemporalDependencyBuffer{T}(capacity) end - return Tuple{Float64,typeof(value)}[] + stream = Tuple{Float64,T}[] + if sizehint_steps > 0 + sizehint!(stream, max(1, ceil(Int, float(sizehint_steps) / float(clock_dt)))) + end + return stream end function _model_output_object_ids( @@ -1876,20 +1882,9 @@ function _initialize_model_output_stream!( retention, application.id, variable, + sizehint_steps, + application.clock.dt, ) - if stream isa Vector && sizehint_steps > 0 - sizehint!( - stream, - max( - 1, - ceil( - Int, - float(sizehint_steps) / - float(application.clock.dt), - ), - ), - ) - end streams[key] = stream return streams end @@ -3215,6 +3210,8 @@ Base.@nospecializeinfer function _runtime_model_output_streams( output_retention, application.id, variable, + 0, + application.clock.dt, ) streams[key] = stream end @@ -4737,7 +4734,7 @@ function _model_output_retention_covers_binding( binding::CompiledModelInputBinding, ) plan.retain_all && return true - return _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required + return Base.@inline _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required key = (source_application_id, source_var) key in plan.temporal_dependencies && get(plan.dependency_horizons, key, -Inf) >= required end @@ -4845,7 +4842,7 @@ function compile_model_output_retention( dependency_horizons = Dict{Tuple{Symbol,Symbol},Float64}() for binding in compiled.input_bindings binding.carrier_hint == :temporal_stream || continue - _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required + Base.@inline _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required key = (source_application_id, source_var) push!(temporal_dependencies, key) dependency_horizons[key] = max(get(dependency_horizons, key, 0.0), required) From 5af8f825594286400ca9c94a40919a208baff0f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 11:33:36 +0100 Subject: [PATCH 090/324] Preserve input binding families through canonical lifecycle refresh --- src/composite_model/compilation.jl | 365 ++++++++++++++--------- src/composite_model/runtime_outputs.jl | 63 ++-- test/test-model-input-binding-storage.jl | 200 +++++++++++++ test/test_groups.jl | 1 + 4 files changed, 457 insertions(+), 172 deletions(-) create mode 100644 test/test-model-input-binding-storage.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 956a234ab..f288d2d4e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1604,6 +1604,40 @@ Base.propertynames(binding::CompiledModelInputBinding) = ( propertynames(binding.plan)..., ) +# The existing storage element type owns any finite binding family. Tracing +# storage may retain the ordinary open element type during host preparation. +function _model_input_binding_family_types(B) + B === Union{} && return () + families = Tuple(Base.uniontypes(B)) + all(T -> isconcretetype(T) && T <: CompiledModelInputBinding, families) || + throw(ArgumentError("Input binding storage requires concrete canonical binding types.")) + return families +end + +_model_input_binding_storage(::Nothing) = CompiledModelInputBinding[] +function _model_input_binding_storage(prototype::AbstractVector) + isempty(prototype) || throw(ArgumentError("Input binding storage must be an empty prototype.")) + B = eltype(prototype) + B === CompiledModelInputBinding || _model_input_binding_family_types(B) + return similar(prototype, 0) +end + +@inline function _with_model_input_binding(f::F, + ::AbstractVector{CompiledModelInputBinding}, binding, args::Vararg{Any,N}, +) where {F,N} + return f(binding, args...) +end +@generated function _with_model_input_binding(f::F, ::AbstractVector{B}, binding, + args::Vararg{Any,N}, +) where {F,B,N} + families = _model_input_binding_family_types(B) + branches = [:(binding isa $T && return f(binding::$T, args...)) for T in families] + return quote + $(branches...) + throw(ArgumentError("The input binding is outside its prepared storage family.")) + end +end + struct CompiledTemporalInput{B,S,I,R} binding::B source_applications::S @@ -1877,15 +1911,29 @@ function refresh_bindings!( force::Bool=false, performance=nothing, ) - specs === model.applications || return compile_composite_model(model, specs; performance) + return _refresh_bindings!(model, specs; force, performance) +end + +function _refresh_bindings!( + model::CompositeModel, + specs=model.applications; + force::Bool=false, + performance=nothing, + input_binding_storage=nothing, +) + if specs !== model.applications + raw_specs = specs isa Tuple ? specs : specs isa AbstractVector ? Tuple(specs) : (specs,) + return _compile_scene(model, raw_specs; performance, input_binding_storage) + end + rebuild = force || !isnothing(input_binding_storage) preparation = _scenario_preparation(model; force) _validate_authored_scenario(preparation) previous = model.binding_cache prepared = preparation.resolved owner_changed = !isnothing(previous) && previous.scenario_plan.authoring.preparation !== preparation - if owner_changed || _binding_refresh_required(model, previous, prepared, force) - if owner_changed || !_can_extend_binding_refresh(model, previous, prepared, force) + if owner_changed || _binding_refresh_required(model, previous, prepared, rebuild) + if owner_changed || !_can_extend_binding_refresh(model, previous, prepared, rebuild) if owner_changed || isnothing(prepared) plan, applications = _resolve_prepared_scenario( model, preparation, _model_timeline(model); performance, @@ -1895,7 +1943,8 @@ function refresh_bindings!( end end end - return _refresh_prepared_bindings!(model, previous, prepared; force, performance) + return _refresh_prepared_bindings!(model, previous, prepared; + force=rebuild, performance, input_binding_storage) end _binding_refresh_required(model, previous, prepared, force) = @@ -1913,7 +1962,7 @@ end # declaration metadata and live membership; it does not invoke author hooks. function _refresh_prepared_bindings!( model::CompositeModel, previous, prepared; - force::Bool=false, performance=nothing, + force::Bool=false, performance=nothing, input_binding_storage=nothing, ) _binding_refresh_required(model, previous, prepared, force) || return previous delta = model.lifecycle_delta @@ -1935,7 +1984,7 @@ function _refresh_prepared_bindings!( _remove_stale_status_views!(refreshed, structural.changed_target_ids) else prepared isa PreparedScenario || _unprepared_runtime_configuration() - refreshed = _compile_scene(model, prepared; performance) + refreshed = _compile_scene(model, prepared; performance, input_binding_storage) if !force && !isnothing(previous) && previous.distributed_outputs isa CompiledDistributedOutputs _preserve_recompiled_model_status_views!(refreshed, previous) end @@ -2412,9 +2461,11 @@ function _compile_scene( raw_specs; validate_required_inputs::Bool=true, performance=nothing, + input_binding_storage=nothing, ) scenario_plan, applications = _build_scenario_plan(model, raw_specs, _model_timeline(model); performance) - return _compile_scene(model, scenario_plan, applications; validate_required_inputs, performance) + return _compile_scene(model, scenario_plan, applications; + validate_required_inputs, performance, input_binding_storage) end function _compile_scene(model::CompositeModel, prepared::PreparedScenario; kwargs...) @@ -2428,6 +2479,7 @@ function _compile_scene( applications; validate_required_inputs::Bool=true, performance=nothing, + input_binding_storage=nothing, ) timeline = scenario_plan.timeline started_at = _runtime_performance_start(performance) @@ -2455,7 +2507,8 @@ function _compile_scene( applications, scenario_plan.manual_application_ids, scenario_plan.input_recipes_by_application, - distributed_outputs, + distributed_outputs; + input_binding_storage, ) many_input_binding_cache = _share_many_input_bindings!(model, input_bindings) @@ -3793,7 +3846,7 @@ function _prepare_structural_compiled_delta( delete!(applications_by_object, object_id) end - input_bindings = CompiledModelInputBinding[] + input_bindings = similar(compiled.input_bindings, 0) sizehint!(input_bindings, length(compiled.input_bindings)) for binding in compiled.input_bindings if binding.consumer_id in dirty @@ -4113,6 +4166,149 @@ function _refresh_scene_call_bindings!( observed_manual_call_binding_indices_by_callee_target end +# One existing-binding lifecycle operation; admission precedes this worker. +function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S) where {B<:CompiledModelInputBinding,S} + (; + model, input_bindings, input_bindings_by_target, many_binding_cache, + changed_bindings, rewired_consumer_ids, affected_temporal_keys, previous_temporal_sources, + processed_many_sources, previous_shared_many_sources, forced_input_binding_keys, pure_addition, + writer_rebind_keys, structural_dirty_ids, applications_by_object, applications_by_id, + distributed_outputs, added_ids, performance, queued_binding_indices, + pending_binding_indices, + ) = state + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + source_ids = _input_binding_source_ids(model.registry.objects, binding.source_ids) + binding_key = (binding.application_id, consumer_id, binding.input) + force_rebuild = !isempty(forced_input_binding_keys) && + binding_key in forced_input_binding_keys + if !force_rebuild && + binding.multiplicity == :many && + haskey(processed_many_sources, binding.source_ids) + if binding.carrier_hint == :temporal_stream + key = (binding.application_id, consumer_id) + push!(affected_temporal_keys, key) + previous_temporal_sources[( + key..., + binding.input, + )] = previous_shared_many_sources[binding.source_ids] + end + return false + end + previous_source_ids = binding.carrier_hint == :temporal_stream ? + copy(source_ids) : + ObjectId[] + binding.multiplicity == :many && + binding.carrier_hint == :temporal_stream && + (previous_shared_many_sources[binding.source_ids] = copy(source_ids)) + default_scope = _default_dependency_scope(model, consumer_id) + if !pure_addition && + (isnothing(writer_rebind_keys) || !(binding_key in writer_rebind_keys)) + structural_update = _update_structural_many_sources!( + model, + binding, + structural_dirty_ids, + applications_by_object, + applications_by_id, + distributed_outputs, + ) + if structural_update != :fallback + processed_many_sources[binding.source_ids] = nothing + return false + end + end + if !force_rebuild && binding.multiplicity != :many + _selector_matches_any_object_id( + model, + binding.matcher, + added_ids; + context=consumer_id, + default_to_context=true, + default_scope=default_scope, + ) || return false + end + appended_sources = if force_rebuild + false + else + _append_added_many_sources!( + model, + binding, + added_ids, + applications_by_object, + applications_by_id, + distributed_outputs, + ; + performance=performance, + ) + end + if appended_sources + if binding.carrier_hint == :temporal_stream && + previous_source_ids != binding.source_ids + key = (binding.application_id, consumer_id) + push!(affected_temporal_keys, key) + previous_temporal_sources[( + key..., + binding.input, + )] = previous_source_ids + end + processed_many_sources[binding.source_ids] = nothing + return false + end + # The reverse selector index keeps only one representative for a + # same-rate `Many(...)` group whose mutable source storage is shared. + # Appending updates every consumer at once. A rebuild replaces the + # carrier, however, so enqueue every member of that exact identity + # group and rewire them through the existing general path. + for shared_index in _shared_same_rate_many_binding_indices( + input_bindings, + binding, + ) + shared_index in queued_binding_indices && continue + push!(queued_binding_indices, shared_index) + push!(pending_binding_indices, shared_index) + end + application = applications_by_id[binding.application_id] + replacement = similar(input_bindings, 0) + _resolve_materialize_input_route!( + replacement, + model, + application.id, + application.process, + consumer_id, + binding.plan, + applications_by_object, + applications_by_id, + nothing, + distributed_outputs, + ) + old_cache_key = _many_binding_share_key(model, binding) + if !isnothing(old_cache_key) && + get(many_binding_cache, old_cache_key, nothing) === binding + delete!(many_binding_cache, old_cache_key) + end + replacement_binding = _share_many_input_binding!( + many_binding_cache, + model, + only(replacement), + ) + input_bindings[index] = replacement_binding + push!(changed_bindings, replacement_binding) + push!(rewired_consumer_ids, consumer_id) + if binding.carrier_hint == :temporal_stream + key = (binding.application_id, consumer_id) + push!(affected_temporal_keys, key) + previous_temporal_sources[( + key..., + binding.input, + )] = previous_source_ids + end + target = (binding.application_id, consumer_id) + input_bindings_by_target[target] = Tuple( + existing === binding ? replacement_binding : existing + for existing in get(input_bindings_by_target, target, ()) + ) + return true +end + function _extend_compiled_scene( model::CompositeModel, compiled::CompiledCompositeModel, @@ -4263,7 +4459,7 @@ function _extend_compiled_scene( # replace an initially empty binding without rebuilding the whole scene. input_bindings_by_target = compiled.input_bindings_by_target many_binding_cache = compiled.many_input_binding_cache - changed_bindings = CompiledModelInputBinding[] + changed_bindings = similar(input_bindings, 0) rewired_consumer_ids = Set{ObjectId}() affected_temporal_keys = Set{Tuple{Symbol,ObjectId}}() previous_temporal_sources = copy(previous_temporal_sources_seed) @@ -4310,141 +4506,23 @@ function _extend_compiled_scene( queued_binding_indices = copy(candidate_binding_indices) pending_binding_indices = sort!(collect(candidate_binding_indices)) pending_binding_position = 1 + binding_refresh = (; + model, input_bindings, input_bindings_by_target, many_binding_cache, + changed_bindings, rewired_consumer_ids, affected_temporal_keys, previous_temporal_sources, + processed_many_sources, previous_shared_many_sources, forced_input_binding_keys, pure_addition, + writer_rebind_keys, structural_dirty_ids, applications_by_object, applications_by_id, + distributed_outputs, added_ids, performance, queued_binding_indices, + pending_binding_indices, + ) while pending_binding_position <= length(pending_binding_indices) index = pending_binding_indices[pending_binding_position] pending_binding_position += 1 - binding = input_bindings[index] - consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) - source_ids = _input_binding_source_ids(model.registry.objects, binding.source_ids) - binding_key = (binding.application_id, consumer_id, binding.input) - force_rebuild = !isempty(forced_input_binding_keys) && - binding_key in forced_input_binding_keys - if !force_rebuild && - binding.multiplicity == :many && - haskey(processed_many_sources, binding.source_ids) - if binding.carrier_hint == :temporal_stream - key = (binding.application_id, consumer_id) - push!(affected_temporal_keys, key) - previous_temporal_sources[( - key..., - binding.input, - )] = previous_shared_many_sources[binding.source_ids] - end - continue - end - previous_source_ids = binding.carrier_hint == :temporal_stream ? - copy(source_ids) : - ObjectId[] - binding.multiplicity == :many && - binding.carrier_hint == :temporal_stream && - (previous_shared_many_sources[binding.source_ids] = copy(source_ids)) - default_scope = _default_dependency_scope(model, consumer_id) - if !pure_addition && - (isnothing(writer_rebind_keys) || !(binding_key in writer_rebind_keys)) - structural_update = _update_structural_many_sources!( - model, - binding, - structural_dirty_ids, - applications_by_object, - applications_by_id, - distributed_outputs, - ) - if structural_update != :fallback - processed_many_sources[binding.source_ids] = nothing - continue - end - end - if !force_rebuild && binding.multiplicity != :many - _selector_matches_any_object_id( - model, - binding.matcher, - added_ids; - context=consumer_id, - default_to_context=true, - default_scope=default_scope, - ) || continue - end - appended_sources = if force_rebuild - false - else - _append_added_many_sources!( - model, - binding, - added_ids, - applications_by_object, - applications_by_id, - distributed_outputs, - ; - performance=performance, - ) - end - if appended_sources - if binding.carrier_hint == :temporal_stream && - previous_source_ids != binding.source_ids - key = (binding.application_id, consumer_id) - push!(affected_temporal_keys, key) - previous_temporal_sources[( - key..., - binding.input, - )] = previous_source_ids - end - processed_many_sources[binding.source_ids] = nothing - continue - end - rebuild_dynamic_input_index = true - # The reverse selector index keeps only one representative for a - # same-rate `Many(...)` group whose mutable source storage is shared. - # Appending updates every consumer at once. A rebuild replaces the - # carrier, however, so enqueue every member of that exact identity - # group and rewire them through the existing general path. - for shared_index in _shared_same_rate_many_binding_indices( - input_bindings, - binding, - ) - shared_index in queued_binding_indices && continue - push!(queued_binding_indices, shared_index) - push!(pending_binding_indices, shared_index) - end - application = applications_by_id[binding.application_id] - replacement = CompiledModelInputBinding[] - _resolve_materialize_input_route!( - replacement, - model, - application.id, - application.process, - consumer_id, - binding.plan, - applications_by_object, - applications_by_id, - nothing, - distributed_outputs, - ) - old_cache_key = _many_binding_share_key(model, binding) - if !isnothing(old_cache_key) && - get(many_binding_cache, old_cache_key, nothing) === binding - delete!(many_binding_cache, old_cache_key) - end - replacement_binding = _share_many_input_binding!( - many_binding_cache, - model, - only(replacement), - ) - input_bindings[index] = replacement_binding - push!(changed_bindings, replacement_binding) - push!(rewired_consumer_ids, consumer_id) - if binding.carrier_hint == :temporal_stream - key = (binding.application_id, consumer_id) - push!(affected_temporal_keys, key) - previous_temporal_sources[( - key..., - binding.input, - )] = previous_source_ids - end - target = (binding.application_id, consumer_id) - input_bindings_by_target[target] = Tuple( - existing === binding ? replacement_binding : existing - for existing in get(input_bindings_by_target, target, ()) + raw_binding = input_bindings[index] + rebuilt = Base.@inline _with_model_input_binding( + _refresh_existing_scene_input_binding!, input_bindings, + raw_binding, index, binding_refresh, ) + rebuild_dynamic_input_index |= rebuilt end previous_binding_count = length(input_bindings) recorder = _AddedConsumerInputBindings( @@ -8186,9 +8264,10 @@ function _compile_model_input_bindings( applications, manual_application_ids, input_recipes_by_application, - distributed_outputs=NoCompiledDistributedOutputs(), + distributed_outputs=NoCompiledDistributedOutputs(); + input_binding_storage=nothing, ) - bindings = CompiledModelInputBinding[] + bindings = _model_input_binding_storage(input_binding_storage) by_object = _applications_by_object(applications, model.registry.objects) by_id = _applications_by_id(applications) for application in applications diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 677c1dcd5..f1f7751a1 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2270,16 +2270,16 @@ function _model_duration_steps(duration, timeline) return nothing end -function _model_input_window_steps(window, integrates::Bool, application::CompiledModelApplication, timeline) +function _model_input_window_steps(window, integrates::Bool, consumer_dt::Real, timeline) explicit = _model_duration_steps(window, timeline) !isnothing(explicit) && return explicit - integrates && return float(application.clock.dt) + integrates && return float(consumer_dt) return 1.0 end function _model_input_window_steps(binding::CompiledModelInputBinding, application::CompiledModelApplication, timeline) return _model_input_window_steps(getfield(binding, :plan).window, - getfield(binding, :policy) isa Union{Integrate,Aggregate}, application, timeline) + getfield(binding, :policy) isa Union{Integrate,Aggregate}, application.clock.dt, timeline) end function _model_temporal_source_value( @@ -4679,26 +4679,22 @@ function explain_execution_plan(model::CompositeModel) end function _model_temporal_retention_horizon( - input_plan::CompiledModelInputPlan, + window_steps::Real, integrates::Bool, interpolates::Bool, - consumer, - source, - timeline, + source_dt::Real, ) - window_steps = _model_input_window_steps(input_plan.window, integrates, consumer, timeline) return if integrates - float(window_steps) + max(0.0, float(source.clock.dt) - 1.0) + float(window_steps) + max(0.0, float(source_dt) - 1.0) elseif interpolates - max(2.0, float(source.clock.dt) + 1.0) + max(2.0, float(source_dt) + 1.0) else 0.0 end end -# Binding carriers are irrelevant to retention. Extract its concrete scalar -# metadata before callbacks, and select the current plan inside its typed owner -# before reading a possibly heterogeneous window. +# Owner callbacks return only clock/window scalars. Binding carriers and whole +# application/plan values never cross into the retention computation. function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, binding::CompiledModelInputBinding, ) where {F} @@ -4710,22 +4706,29 @@ function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, policy = getfield(binding, :policy) integrates = policy isa Union{Integrate,Aggregate} interpolates = policy isa Union{Interpolate,PreviousTimeStep} - return _compiled_application_by_id(compiled, application_id) do consumer - _with_metadata_entry(compiled.scenario_plan.input_plans, plan_slot) do actual_plan - actual_plan.application_id === application_id && actual_plan.input === input_name && - actual_plan.source_var === source_var || - throw(ArgumentError("A temporal retention binding is outside its current input plan owner.")) - for source_application_id in source_application_ids - covered = _compiled_application_by_id(compiled, source_application_id) do source - required = _model_temporal_retention_horizon(actual_plan, - integrates, interpolates, consumer, source, compiled.scenario_plan.timeline) - f(source_application_id, source_var, required) - end - covered || return false - end - return true + consumer_dt = _compiled_application_by_id(compiled, application_id) do consumer + consumer.clock.dt + end + # The old loop resolves its consumer/plan owner but does not validate a + # window when no real producer is selected. + has_sources = !isempty(source_application_ids) + timeline = compiled.scenario_plan.timeline + window_steps = _with_metadata_entry(compiled.scenario_plan.input_plans, plan_slot) do actual_plan + actual_plan.application_id === application_id && actual_plan.input === input_name && + actual_plan.source_var === source_var || + throw(ArgumentError("A temporal retention binding is outside its current input plan owner.")) + has_sources || return nothing + _model_input_window_steps(actual_plan.window, integrates, consumer_dt, timeline) + end + has_sources || return true + for source_application_id in source_application_ids + source_dt = _compiled_application_by_id(compiled, source_application_id) do source + source.clock.dt end + required = _model_temporal_retention_horizon(window_steps, integrates, interpolates, source_dt) + f(source_application_id, source_var, required) || return false end + return true end function _model_output_retention_covers_binding( @@ -6012,7 +6015,7 @@ function _prepare_targeted_newborn_targets( _prepare_model_output_statuses_batched!(model, output_applications) application_set.outputs_prepared = true end - input_bindings = CompiledModelInputBinding[] + input_bindings = similar(compiled.input_bindings, 0) for application in callee_applications isempty(application.target_ids) && continue recipe = _application_plans( @@ -7892,6 +7895,7 @@ function _prepare_simulation!( outputs, performance::Bool=false, environment_schema=_environment_schema(getfield(model, :environment_binding_cache)), + input_binding_storage=nothing, ) performance_counters = performance ? RuntimePerformanceCounters() : nothing initial_composite_started_at = @@ -7915,9 +7919,10 @@ function _prepare_simulation!( _prepare_scenario_plan(model, timeline; force=true, performance=performance_counters) end end - compiled = refresh_bindings!( + compiled = _refresh_bindings!( model; performance=performance_counters, + input_binding_storage, ) compiled.execution_generation += UInt64(1) _runtime_performance_finish!( diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl new file mode 100644 index 000000000..d2dbc5c0f --- /dev/null +++ b/test/test-model-input-binding-storage.jl @@ -0,0 +1,200 @@ +module ModelInputBindingStorageChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "input_binding_storage_reader" verbose=false +PSE.@process "input_binding_storage_capture" verbose=false + +struct Reader <: AbstractInput_Binding_Storage_ReaderModel end +PSE.inputs_(::Reader) = (single=Required(Float32), values=Default(Float64[])) +PSE.outputs_(::Reader) = (total=0.0,) +function PSE.run!(::Reader, status, environment, constants, context) + status.total = Float64(status.single) + sum(bound_input(context, :values); init=0.0) + return nothing +end + +struct Capture <: AbstractInput_Binding_Storage_CaptureModel + context::Base.RefValue{Any} +end +PSE.inputs_(::Capture) = NamedTuple() +PSE.outputs_(::Capture) = (visits=0,) +function PSE.run!(model::Capture, status, environment, constants, context) + model.context[] = context + status.visits += 1 + return nothing +end + +function fixture(; called=false) + capture = Ref{Any}(nothing) + reader = ModelSpec(Reader(); name=:reader, on=Many(scale=:Reader), inputs=( + single=One(id=:anchor, within=SceneScope(), var=:x, from_status=true), + values=Many(scale=:Leaf, within=SceneScope(), var=:x, from_status=true), + )) + applications = called ? ( + ModelSpec(Capture(capture); name=:capture, on=One(id=:scene), calls=( + readers=Many(scale=:Reader, within=Subtree(), application=:reader),)), + reader, + ) : (reader,) + model = CompositeModel( + Object(:scene; scale=:Scene), + Object(:anchor; scale=:Anchor, parent=:scene, status=Status(x=3f0)), + Object(:a; scale=:Reader, parent=:scene), + Object(:b; scale=:Reader, parent=:scene); + applications, + ) + return (; model, capture, called) +end + +prepare(model, prototype=nothing) = PSE._prepare_simulation!(model; + steps=0, outputs=:none, constants=PSE.Constants(), input_binding_storage=prototype) + +binding(simulation, object, input) = only(binding for binding in simulation.compiled.input_bindings + if binding.consumer_id == ObjectId(object) && binding.input === input) + +function observe_families!(families, simulation) + for binding in simulation.compiled.input_bindings + B = typeof(binding) + B in families || push!(families, B) + end + return families +end + +storage_prototype(families) = Vector{Union{families...}}() + +function check_carriers(data, simulation) + anchor = PSE.refvalue(model_status(data.model, :anchor), :x) + first, second = binding(simulation, :a, :values), binding(simulation, :b, :values) + @test binding(simulation, :a, :single).carrier === anchor + @test binding(simulation, :b, :single).carrier === anchor + @test first.carrier === second.carrier + @test first.source_ids === second.source_ids + @test all(reference === PSE.refvalue(model_status(data.model, id), :x) + for (id, reference) in zip(first.source_ids, parent(first.carrier))) + return first +end + +function advance!(data, simulation) + step!(simulation) + data.called && run_call!(data.capture[], :readers; publish=true) + return (model_status(data.model, :a).total, model_status(data.model, :b).total) +end + +function birth!(model, id, value) + status = Status(x=value) + register_object!(model, Object(id; scale=:Leaf, parent=:scene, status)) + return PSE.refvalue(status, :x) +end + +# Record all real raw bindings, including One, before and after actual births. +# This deliberately does not infer a family from a batch or a model default. +function ordinary_control(; called=false) + data = fixture(; called) + simulation = prepare(data.model) + families = observe_families!(DataType[], simulation) + initial_families = copy(families) + @test eltype(simulation.compiled.input_bindings) === PSE.CompiledModelInputBinding + @test isempty(check_carriers(data, simulation).carrier) + totals = [advance!(data, simulation)] + birth!(data.model, :leaf_1, 7.0) + push!(totals, advance!(data, simulation)) + observe_families!(families, simulation) + future = binding(simulation, :a, :values) + @test !(typeof(future) in initial_families) + first = check_carriers(data, simulation) + carrier, source_ids = first.carrier, first.source_ids + birth!(data.model, :leaf_2, 11.0) + push!(totals, advance!(data, simulation)) + observe_families!(families, simulation) + current = check_carriers(data, simulation) + @test current.carrier === carrier + @test current.source_ids === source_ids + @test totals == [(3.0, 3.0), (10.0, 10.0), (21.0, 21.0)] + return (; families, initial_families, future, totals) +end + +@testset "real One and shared Many families close before compilation" begin + control = ordinary_control() + prototype = storage_prototype(control.families) + data = fixture() + simulation = prepare(data.model, prototype) + @test simulation.compiled.input_bindings !== prototype + @test eltype(simulation.compiled.input_bindings) === eltype(prototype) + @test isempty(check_carriers(data, simulation).carrier) + totals = [advance!(data, simulation)] + first_reference = birth!(data.model, :leaf_1, 7.0) + push!(totals, advance!(data, simulation)) + first = check_carriers(data, simulation) + @test only(parent(first.carrier)) === first_reference + carrier, source_ids = first.carrier, first.source_ids + second_reference = birth!(data.model, :leaf_2, 11.0) + push!(totals, advance!(data, simulation)) + current = check_carriers(data, simulation) + @test current.carrier === carrier + @test current.source_ids === source_ids + @test all(actual === expected for (actual, expected) in + zip(parent(current.carrier), (first_reference, second_reference))) + @test totals == control.totals + @test all(binding -> typeof(binding) in control.families, + simulation.compiled.input_bindings) + @test isempty(prototype) + + incomplete = storage_prototype(control.initial_families) + @test_throws "outside its prepared storage family" PSE._with_model_input_binding( + identity, incomplete, control.future) +end + +@testset "explicit storage is admitted even after a clean zero-step preparation" begin + control = ordinary_control() + data = fixture() + previous = prepare(data.model) + anchor = PSE.refvalue(model_status(data.model, :anchor), :x) + prototype = storage_prototype(control.families) + current = prepare(data.model, prototype) + @test current.compiled !== previous.compiled + @test current.compiled.input_bindings !== previous.compiled.input_bindings + @test eltype(current.compiled.input_bindings) === eltype(prototype) + @test current_step(current) == 0 + @test PSE.refvalue(model_status(data.model, :anchor), :x) === anchor + check_carriers(data, current) + @test isempty(prototype) + + nonempty = [control.future] + @test_throws "Input binding storage must be an empty prototype" prepare(fixture().model, nonempty) +end + +@testset "zero input plans use the real empty binding family" begin + model = CompositeModel(Object(:only; status=Status(value=1f0))) + prototype = Vector{Union{}}() + simulation = prepare(model, prototype) + @test simulation.compiled.input_bindings isa Vector{Union{}} + @test simulation.compiled.input_bindings !== prototype + @test isempty(simulation.compiled.input_bindings) + step!(simulation) + @test current_step(simulation) == 1 + @test model_status(model, :only).value === 1f0 + @test isempty(prototype) +end + +@testset "targeted calls keep the admitted input storage and live references" begin + control = ordinary_control(; called=true) + data = fixture(; called=true) + prototype = storage_prototype(control.families) + simulation = prepare(data.model, prototype) + step!(simulation) + reference = birth!(data.model, :leaf_1, 7.0) + step!(simulation) + selected = call_targets(data.capture[], :readers; objects=(:a,)) + target = only(selected) + @test target.object_id === ObjectId(:a) + @test PSE.refvalue(target.status, :single) === PSE.refvalue(model_status(data.model, :anchor), :x) + @test only(parent(target.status.values)) === reference + run_call!(target; publish=true) + @test model_status(data.model, :a).total == 10.0 + @test model_status(data.model, :b).total == 0.0 + @test eltype(simulation.compiled.input_bindings) === eltype(prototype) + check_carriers(data, simulation) + @test isempty(prototype) +end + +end # module ModelInputBindingStorageChecks diff --git a/test/test_groups.jl b/test/test_groups.jl index 61b607cb4..1f209ce0d 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -65,6 +65,7 @@ const TEST_GROUPS = ( "test-compilation-metadata.jl", "test-model-input-recipes.jl", "test-model-binding-index-identities.jl", + "test-model-input-binding-storage.jl", "test-model-output-retention-owners.jl", "test-input-default-values.jl", "test-application-membership-slots.jl", From 29674485f76eb6ce1b42af6ed42b99b5699b36a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 12:09:20 +0100 Subject: [PATCH 091/324] Admit lifecycle applications through their prepared metadata --- src/composite_model/compilation.jl | 386 ++++++++++++----------- src/composite_model/runtime_outputs.jl | 2 + src/visualization/model_graph_view.jl | 3 +- test/test-model-input-binding-storage.jl | 76 +++++ 4 files changed, 290 insertions(+), 177 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f288d2d4e..32e76be23 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2108,14 +2108,15 @@ function _index_dynamic_call_bindings(model::CompositeModel, bindings) end function _push_observed_manual_call_binding_index!( - index, + index::AbstractDict{Tuple{Symbol,I}}, callee_application_id::Symbol, callee_object_id::ObjectId, binding_index::Int, -) +) where {I<:ObjectId} + callee_object_id isa I || throw(ArgumentError("A manual call target identity is outside its prepared registry schema.")) binding_indices = get!( index, - (callee_application_id, callee_object_id), + (callee_application_id, callee_object_id::I), ) do Int[] end @@ -2222,8 +2223,9 @@ end function _index_observed_manual_call_bindings_by_callee_target( bindings, applications_by_id, -) - index = Dict{Tuple{Symbol,ObjectId},Vector{Int}}() + objects::ObjectFamilyStore{I}, +) where {I<:ObjectId} + index = Dict{Tuple{Symbol,I},Vector{Int}}() for (binding_index, binding) in pairs(bindings) _index_observed_manual_call_binding_by_callee_target!( index, @@ -2514,9 +2516,9 @@ function _compile_scene( _share_many_input_bindings!(model, input_bindings) # Materialize each final status once, rather than compiling a progressively # wider NamedTuple for every default and resolved input reference. - _prepare_model_input_statuses_batched!(model, applications, input_bindings) + _prepare_model_input_statuses_batched!(model, applications, applications_by_id, input_bindings) validate_required_inputs && - _validate_model_required_inputs!(model, applications, input_bindings) + _validate_model_required_inputs!(model, applications, applications_by_id, input_bindings) _runtime_performance_finish!( performance, :input_binding_compile, @@ -2573,6 +2575,7 @@ function _compile_scene( _index_observed_manual_call_bindings_by_callee_target( call_bindings, applications_by_id, + model.registry.objects, ), many_input_binding_cache, distributed_outputs, @@ -3729,16 +3732,20 @@ function _append_added_many_call_targets!( end function _propagate_changed_manual_call_owners!( + objects::ObjectFamilyStore{I}, changed_target_ids, changed_callee_target_ids, call_bindings, observed_manual_call_binding_indices_by_callee_target, performance=nothing, -) - frontier = Tuple{Symbol,ObjectId}[ - key for key in changed_callee_target_ids - ] - seen_owner_keys = Set{Tuple{Symbol,ObjectId}}(changed_callee_target_ids) +) where {I<:ObjectId} + Key = Tuple{Symbol,I} + frontier = Key[] + for (application_id, raw_id) in changed_callee_target_ids + object_id = _index_object_id(objects, raw_id) + push!(frontier, (application_id, object_id)) + end + seen_owner_keys = Set{Key}(frontier) while !isempty(frontier) _runtime_performance_count!( performance, @@ -3755,14 +3762,15 @@ function _propagate_changed_manual_call_owners!( union!(candidate_binding_indices, binding_indices) end isempty(candidate_binding_indices) && break - next_frontier = Tuple{Symbol,ObjectId}[] + next_frontier = Key[] for binding_index in candidate_binding_indices _runtime_performance_count!( performance, :lifecycle_manual_call_owner_binding_candidates, ) binding = call_bindings[binding_index] - owner_key = (binding.application_id, binding.consumer_id) + consumer_id = _index_object_id(objects, binding.consumer_id) + owner_key = (binding.application_id, consumer_id) owner_key in seen_owner_keys && continue push!(seen_owner_keys, owner_key) push!(changed_target_ids, owner_key) @@ -3917,6 +3925,7 @@ function _prepare_structural_compiled_delta( _index_observed_manual_call_bindings_by_callee_target( call_bindings, compiled.applications_by_id, + model.registry.objects, ), many_input_binding_cache, compiled.distributed_outputs, @@ -4144,6 +4153,7 @@ function _refresh_scene_call_bindings!( _index_observed_manual_call_bindings_by_callee_target( call_bindings, applications_by_id, + model.registry.objects, ) end first_new_call_binding = length(call_bindings) - length(new_call_bindings) + 1 @@ -4528,16 +4538,19 @@ function _extend_compiled_scene( recorder = _AddedConsumerInputBindings( model, many_binding_cache, changed_bindings, input_bindings_by_target, ) - for application in added_applications - isempty(application.target_ids) && continue - recipe = _application_plans( - compiled.scenario_plan.input_recipes_by_application, application.id, - ) - _compile_application_consumer_bindings!( - input_bindings, model, application, recipe, manual_application_ids, - applications_by_object, applications_by_id, distributed_outputs, - many_binding_cache, performance, recorder, - ) + for partial in added_applications + isempty(partial.target_ids) && continue + _with_model_application(applications_by_id, partial) do application + _with_metadata_entry( + compiled.scenario_plan.input_recipes_by_application, application.id, + ) do recipe + _compile_application_consumer_bindings!( + input_bindings, model, application, recipe, manual_application_ids, + applications_by_object, applications_by_id, distributed_outputs, + many_binding_cache, performance, recorder, + ) + end + end end dynamic_input_binding_indices = if rebuild_dynamic_input_index many_binding_cache = @@ -4567,12 +4580,9 @@ function _extend_compiled_scene( else rewired_applications = CompiledModelApplication[] targets_by_application = Dict{Symbol,Vector{ObjectId}}() - for object_id in rewired_consumer_ids - for application in get( - applications_by_object, - object_id, - (), - ) + for raw_id in rewired_consumer_ids + object_id = _index_object_id(model.registry.objects, raw_id) + _foreach_object_application(compiled, object_id) do application push!( get!( targets_by_application, @@ -4597,13 +4607,12 @@ function _extend_compiled_scene( end (added_applications..., rewired_applications...) end - final_input_references = pure_addition ? - _model_input_status_references(changed_bindings) : - nothing if pure_addition + final_input_references = _model_input_status_references(changed_bindings) _prepare_model_input_statuses_batched!( model, affected_input_applications, + applications_by_id, changed_bindings; final_references=final_input_references, performance=performance, @@ -4611,19 +4620,19 @@ function _extend_compiled_scene( else _prepare_model_input_defaults!( model, - affected_input_applications; - final_references=final_input_references, + affected_input_applications, + applications_by_id; performance=performance, ) _wire_model_input_carriers!( model, - changed_bindings; - final_references=final_input_references, + changed_bindings, ) end _validate_model_required_inputs!( model, affected_input_applications, + applications_by_id, changed_bindings, ) _runtime_performance_finish!( @@ -4673,14 +4682,11 @@ function _extend_compiled_scene( ) union!(changed_execution_target_ids, changed_target_ids_seed) union!(changed_execution_target_ids, changed_call_target_keys) - for object_id in rewired_consumer_ids - union!( - changed_execution_target_ids, - ( - (application.id, object_id) - for application in get(applications_by_object, object_id, ()) - ), - ) + for raw_id in rewired_consumer_ids + object_id = _index_object_id(model.registry.objects, raw_id) + _foreach_object_application(compiled, object_id) do application + push!(changed_execution_target_ids, (application.id, object_id)) + end end changed_manual_target_ids = Set{Tuple{Symbol,ObjectId}}( key for key in changed_execution_target_ids @@ -4694,6 +4700,7 @@ function _extend_compiled_scene( ), ) _propagate_changed_manual_call_owners!( + model.registry.objects, changed_execution_target_ids, changed_manual_target_ids, call_bindings, @@ -6953,69 +6960,73 @@ end function _prepare_model_input_defaults!( model::CompositeModel, - applications; + applications, + applications_by_id; final_references=nothing, performance=nothing, ) - for application in applications - schema = _model_input_schema(application) - defaults = _input_default_values(schema) - for object_id in application.target_ids - status = _ensure_model_object_status!(model, object_id) - for (variable, value) in pairs(defaults) - variable = Symbol(variable) - variable in propertynames(status) && continue - reference = isnothing(final_references) ? - nothing : - get( - final_references, - (application.id, object_id, variable), - nothing, - ) - if !isnothing(reference) - # Preserve conversion callbacks, validation, and diagnostic - # records while avoiding a default Status that the resolved - # carrier would replace immediately below. - _no_status_conversion(model.status_conversion) || - _materialize_status_value( - model, + for partial in applications + _with_model_application(applications_by_id, partial) do application + schema = _model_input_schema(application) + defaults = _input_default_values(schema) + for object_id in application.target_ids + status = _ensure_model_object_status!(model, object_id) + for (variable, value) in pairs(defaults) + variable = Symbol(variable) + variable in propertynames(status) && continue + reference = isnothing(final_references) ? + nothing : + get( + final_references, + (application.id, object_id, variable), + nothing, + ) + if !isnothing(reference) + # Preserve conversion callbacks, validation, and diagnostic + # records while avoiding a default Status that the resolved + # carrier would replace immediately below. + _no_status_conversion(model.status_conversion) || + _materialize_status_value( + model, + variable, + value; + object_id=object_id, + application_id=application.id, + origin=:model_input_default, + private_copy=true, + ) + status = _status_with_reference( + status, variable, - value; - object_id=object_id, - application_id=application.id, - origin=:model_input_default, - private_copy=true, + reference, + ) + _runtime_performance_count!( + performance, + :input_default_status_rewrites_avoided, ) - status = _status_with_reference( + continue + end + status = _status_with_default( + model, status, + object_id, variable, - reference, + value; + application_id=application.id, + origin=:model_input_default, ) - _runtime_performance_count!( - performance, - :input_default_status_rewrites_avoided, + push!( + get!( + model.input_default_status_variables, + object_id, + Set{Symbol}(), + ), + variable, ) - continue end - status = _status_with_default( - model, - status, - object_id, - variable, - value; - application_id=application.id, - origin=:model_input_default, - ) - push!( - get!( - model.input_default_status_variables, - object_id, - Set{Symbol}(), - ), - variable, - ) + _replace_model_object_status!(model, object_id, status) end - _replace_model_object_status!(model, object_id, status) + return nothing end end return model @@ -7079,6 +7090,7 @@ end function _prepare_model_input_statuses_batched!( model::CompositeModel, applications, + applications_by_id, bindings; final_references=nothing, performance=nothing, @@ -7090,70 +7102,74 @@ function _prepare_model_input_statuses_batched!( Dict{Any,Any}() default_status_updates = Dict{Tuple{ObjectId,Symbol},Bool}() input_default_rewrites_avoided = 0 - for application in applications - schema = _model_input_schema(application) - defaults = _input_default_values(schema) - for object_id in application.target_ids - preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - for (variable_, value) in pairs(defaults) - variable = Symbol(variable_) - if preparation isa Status - variable in propertynames(preparation) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - else - _status_recipe_has_variable(preparation, variable) && continue - end - reference = isnothing(final_references) ? - nothing : - get( - final_references, - (application.id, object_id, variable), - nothing, + for partial in applications + input_default_rewrites_avoided += _with_model_application(applications_by_id, partial) do application + rewrites_avoided = 0 + schema = _model_input_schema(application) + defaults = _input_default_values(schema) + for object_id in application.target_ids + preparation = _status_preparation_for_object!( + recipes, + recipe_order, + model, + object_id, ) - if !isnothing(reference) - # Preserve conversion callbacks, validation, and diagnostic - # records even though the resolved carrier owns storage. - _no_status_conversion(model.status_conversion) || - _materialize_status_value( + for (variable_, value) in pairs(defaults) + variable = Symbol(variable_) + if preparation isa Status + variable in propertynames(preparation) && continue + preparation = _status_recipe_for_object!( + recipes, + recipe_order, model, + object_id, + ) + else + _status_recipe_has_variable(preparation, variable) && continue + end + reference = isnothing(final_references) ? + nothing : + get( + final_references, + (application.id, object_id, variable), + nothing, + ) + if !isnothing(reference) + # Preserve conversion callbacks, validation, and diagnostic + # records even though the resolved carrier owns storage. + _no_status_conversion(model.status_conversion) || + _materialize_status_value( + model, + variable, + value; + object_id=object_id, + application_id=application.id, + origin=:model_input_default, + private_copy=true, + conversion_records=conversion_records, + ) + _status_recipe_set_reference!( + preparation, variable, - value; - object_id=object_id, - application_id=application.id, - origin=:model_input_default, - private_copy=true, - conversion_records=conversion_records, + reference, ) - _status_recipe_set_reference!( + rewrites_avoided += 1 + continue + end + _status_recipe_add_default!( + model, preparation, + object_id, variable, - reference, + value; + application_id=application.id, + origin=:model_input_default, + conversion_records=conversion_records, ) - input_default_rewrites_avoided += 1 - continue + default_status_updates[(object_id, variable)] = true end - _status_recipe_add_default!( - model, - preparation, - object_id, - variable, - value; - application_id=application.id, - origin=:model_input_default, - conversion_records=conversion_records, - ) - default_status_updates[(object_id, variable)] = true end + return rewrites_avoided end end @@ -8656,27 +8672,30 @@ function _status_has_variable(model::CompositeModel, object_id::ObjectId, variab return variable in propertynames(object.status) end -function _validate_model_required_inputs!(model::CompositeModel, applications, input_bindings) +function _validate_model_required_inputs!(model::CompositeModel, applications, applications_by_id, input_bindings) bound = _bound_model_inputs(input_bindings) missing = NamedTuple[] - for application in applications - schema = _model_input_schema(application) - for object_id in application.target_ids - for (input_, declaration) in pairs(schema) - declaration isa Required || continue - input = Symbol(input_) - (application.id, object_id, input) in bound && continue - _status_has_variable(model, object_id, input) && continue - push!( - missing, - ( - application_id=application.id, - object_id=object_id.value, - input=input, - process=application.process, - ), - ) + for partial in applications + _with_model_application(applications_by_id, partial) do application + schema = _model_input_schema(application) + for object_id in application.target_ids + for (input_, declaration) in pairs(schema) + declaration isa Required || continue + input = Symbol(input_) + (application.id, object_id, input) in bound && continue + _status_has_variable(model, object_id, input) && continue + push!( + missing, + ( + application_id=application.id, + object_id=object_id.value, + input=input, + process=application.process, + ), + ) + end end + return nothing end end isempty(missing) && return nothing @@ -8749,10 +8768,10 @@ end # Consume metadata inside its exact schema branch. Runtime Symbols select # identities; integer keys select positions local to this owner, never model slots. -@generated function _with_metadata_entry(f, table::CompiledMetadataTable{T}, key::K) where {T,K<:Union{Symbol,Integer}} +@generated function _with_metadata_entry(f, table::CompiledMetadataTable{T}, key::K, args::Vararg{Any,N}) where {T,K<:Union{Symbol,Integer},N} entry_keys = K <: Symbol ? fieldnames(T) : ntuple(identity, fieldcount(T)) branches = [:(key == $(QuoteNode(entry_key)) && - return f(getfield(getfield(table, :entries), $index))) + return f(getfield(getfield(table, :entries), $index), args...)) for (index, entry_key) in enumerate(entry_keys)] missing = K <: Symbol ? :(throw(KeyError(key))) : :(throw(BoundsError(table, key))) return quote @@ -8764,8 +8783,8 @@ end # Execution plans already have a typed tuple boundary; its callback uses the # same scalar-entry operation as fixed metadata owners. Never unwrap an owner # into a tuple to enter this method. -@generated function _with_metadata_entry(f, entries::T, key::K) where {T<:Tuple,K<:Integer} - branches = [:(key == $index && return f(getfield(entries, $index))) +@generated function _with_metadata_entry(f, entries::T, key::K, args::Vararg{Any,N}) where {T<:Tuple,K<:Integer,N} + branches = [:(key == $index && return f(getfield(entries, $index), args...)) for index in 1:fieldcount(T)] return quote $(branches...) @@ -8773,8 +8792,23 @@ end end end -@inline _with_metadata_entry(f, entries::AbstractVector, key::Integer) = f(entries[key]) -@inline _with_metadata_entry(f, entries::AbstractDict, key::Symbol) = f(entries[key]) +@inline _with_metadata_entry(f, entries::AbstractVector, key::Integer, args::Vararg{Any,N}) where {N} = f(entries[key], args...) +@inline _with_metadata_entry(f, entries::AbstractDict, key::Symbol, args::Vararg{Any,N}) where {N} = f(entries[key], args...) + +# Partial target selections borrow their existing target vector. Admit them +# against their current metadata owner before reading model-specific fields. +function _call_admitted_model_application(current::A, partial, f::F, args::Vararg{Any,N}) where {A<:CompiledModelApplication,F,N} + partial isa A && getfield(partial, :plan) === getfield(current, :plan) || + throw(ArgumentError("The application is outside its compiled metadata owner.")) + return f(partial::A, args...) +end + +function _with_model_application(f::F, applications_by_id, partial, args::Vararg{Any,N}) where {F,N} + return Base.@inline _with_metadata_entry( + _call_admitted_model_application, applications_by_id, partial.id, + partial, f, args..., + ) +end function _foreach_object_application(f::F, compiled::CompiledCompositeModel, object_id::ObjectId) where {F} slots = _application_membership_slots(compiled, object_id) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f1f7751a1..e59325c36 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6031,12 +6031,14 @@ function _prepare_targeted_newborn_targets( _prepare_model_input_statuses_batched!( model, callee_applications, + compiled.applications_by_id, input_bindings; final_references=final_input_references, ) _validate_model_required_inputs!( model, callee_applications, + compiled.applications_by_id, input_bindings, ) unsupported_temporal_inputs = Symbol[ diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 82bdd55f2..373b4f621 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -205,6 +205,7 @@ function _model_graph_compiled( _index_observed_manual_call_bindings_by_callee_target( call_bindings, applications_by_id, + model.registry.objects, ), many_input_binding_cache, distributed_outputs, @@ -426,7 +427,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) ) end _model_graph_phase!(diagnostics, :input_status, nothing) do - _prepare_model_input_defaults!(model, applications) + _prepare_model_input_defaults!(model, applications, _applications_by_id(applications)) _wire_model_input_carriers!(model, input_bindings) end diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index d2dbc5c0f..4ec525e6f 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -197,4 +197,80 @@ end @test isempty(prototype) end +@testset "observed manual call owners keep the real closed identity domain" begin + ordinary = fixture(; called=true) + baseline = prepare(ordinary.model) + @test advance!(ordinary, baseline) == (3.0, 3.0) + expected_index = baseline.compiled.observed_manual_call_binding_indices_by_callee_target + + data = fixture(; called=true) + prepare(data.model) # Close only the actual complete statuses on these objects. + previous = data.model.registry + registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), + previous.by_scale, previous.by_kind, previous.by_species, + previous.ancestor_ids_by_object) + original = data.model + model = PSE.CompositeModel(registry, original.applications, original.environment, + original.instances, original.source_adapter, original.status_conversion, + original.status_conversion_records, original.status_source_owners, + original.status_source_identities, nothing, nothing, nothing, true, + true, original.lifecycle_delta, + original.input_default_status_variables, original.runtime_revision, + original.revision, original.environment_revision) + @test all(model_object(model, id) === model_object(original, id) + for id in (:scene, :anchor, :a, :b)) + closed = merge(data, (; model)) + simulation = prepare(model) + @test advance!(closed, simulation) == (3.0, 3.0) + index = simulation.compiled.observed_manual_call_binding_indices_by_callee_target + @test keytype(index) === Tuple{Symbol,ObjectId{Symbol}} + @test Set(keys(index)) == Set(keys(expected_index)) + @test all(index[key] == values for (key, values) in expected_index) + @test Set(keys(index)) == Set(((:reader, ObjectId(:a)), (:reader, ObjectId(:b)))) + check_carriers(closed, simulation) + + before = (model_status(model, :a).total, model_status(model, :b).total, + model_status(model, :scene).visits, model_status(model, :anchor).x) + changed = Set{Tuple{Symbol,ObjectId{Symbol}}}() + callees = Set(((:reader, ObjectId(:a)),)) + @test PSE._propagate_changed_manual_call_owners!(model.registry.objects, + changed, callees, simulation.compiled.call_bindings, index) === changed + @test changed == Set(((:capture, ObjectId(:scene)),)) + @test (model_status(model, :a).total, model_status(model, :b).total, + model_status(model, :scene).visits, model_status(model, :anchor).x) === before + check_carriers(closed, simulation) +end + +@testset "partial applications retain their exact target selection and metadata owner" begin + data = fixture() + simulation = prepare(data.model) + owner = simulation.compiled.applications_by_id + current = owner[:reader] + partial = PSE._partial_model_application(current, [ObjectId(:a)]) + targets = partial.target_ids + @test typeof(partial) === typeof(current) + @test PSE._with_model_application(identity, owner, partial) === partial + @test partial.target_ids === targets + @test partial.target_ids == [ObjectId(:a)] + @test current.target_ids == [ObjectId(:a), ObjectId(:b)] + + # Keep exactly the same application type and ID while changing the plan. + plan = current.plan + fields = ntuple(index -> index == 1 ? plan.slot + 1 : getfield(plan, index), + fieldcount(typeof(plan))) + foreign_plan = typeof(plan)(fields...) + foreign = typeof(current)(foreign_plan, targets) + @test typeof(foreign) === typeof(current) + @test foreign.id === current.id + @test foreign.plan !== current.plan + visits = Ref(0) + @test_throws "outside its compiled metadata owner" PSE._with_model_application( + owner, foreign) do application + visits[] += 1 + end + @test visits[] == 0 + @test partial.target_ids === targets + check_carriers(data, simulation) +end + end # module ModelInputBindingStorageChecks From 81d065511a04805b57da096538284cf1ab01733a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 12:21:22 +0100 Subject: [PATCH 092/324] Keep the lifecycle input cache capture concrete --- src/composite_model/compilation.jl | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 32e76be23..4766a53fd 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4535,20 +4535,22 @@ function _extend_compiled_scene( rebuild_dynamic_input_index |= rebuilt end previous_binding_count = length(input_bindings) - recorder = _AddedConsumerInputBindings( - model, many_binding_cache, changed_bindings, input_bindings_by_target, - ) - for partial in added_applications - isempty(partial.target_ids) && continue - _with_model_application(applications_by_id, partial) do application - _with_metadata_entry( - compiled.scenario_plan.input_recipes_by_application, application.id, - ) do recipe - _compile_application_consumer_bindings!( - input_bindings, model, application, recipe, manual_application_ids, - applications_by_object, applications_by_id, distributed_outputs, - many_binding_cache, performance, recorder, - ) + let many_binding_cache = many_binding_cache + recorder = _AddedConsumerInputBindings( + model, many_binding_cache, changed_bindings, input_bindings_by_target, + ) + for partial in added_applications + isempty(partial.target_ids) && continue + _with_model_application(applications_by_id, partial) do application + _with_metadata_entry( + compiled.scenario_plan.input_recipes_by_application, application.id, + ) do recipe + _compile_application_consumer_bindings!( + input_bindings, model, application, recipe, manual_application_ids, + applications_by_object, applications_by_id, distributed_outputs, + many_binding_cache, performance, recorder, + ) + end end end end From 82f85acec5bd8c8f6822225a76bf0413493cbe69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 12:51:55 +0100 Subject: [PATCH 093/324] Retain binding families in lifecycle target indexes --- src/composite_model/compilation.jl | 129 ++++++++++++-------- test/test-model-binding-index-identities.jl | 6 +- test/test-model-input-binding-storage.jl | 4 + 3 files changed, 86 insertions(+), 53 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 4766a53fd..63066a605 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2304,19 +2304,19 @@ end return (getfield(plan, :application_id), getfield(binding, :consumer_id)::I) end -function _index_model_bindings(bindings, ::Type{I}) where {I<:ObjectId} +function _index_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B,I<:ObjectId} K = Tuple{Symbol,I} - grouped = Dict{K,Vector{Any}}() + grouped = Dict{K,Vector{B}}() for binding in bindings key = _model_binding_target_key(binding, I) values = get!(grouped, key) do - Any[] + B[] end push!(values, binding) end - # Lifecycle changes may replace a binding tuple with a new carrier schema. - # Only values are open; every consumer identity belongs to this registry. - return Dict{K,Any}(key => Tuple(values) for (key, values) in grouped) + # Membership length remains dynamic; records retain the same current/future + # family as their canonical storage, including all families in open scenes. + return Dict{K,Tuple{Vararg{B}}}(key => Tuple(values) for (key, values) in grouped) end """ @@ -3592,7 +3592,6 @@ function _extend_model_status_views( compiled::CompiledCompositeModel, applications, applications_by_id, - applications_by_object, input_bindings_by_target, application_order, new_targets, @@ -3603,15 +3602,23 @@ function _extend_model_status_views( previous_views=compiled.status_views_by_target, ) views = compiled.status_views_by_target - affected_keys = Set{Tuple{Symbol,ObjectId}}(affected_temporal_keys) + Key = Tuple{Symbol,keytype(model.registry.objects)} + affected_keys = Set{Key}() + for (application_id, raw_id) in affected_temporal_keys + object_id = _index_object_id(model.registry.objects, raw_id) + push!(affected_keys, (application_id, object_id)) + end for application in applications - for object_id in get(new_targets, application.id, ObjectId[]) + for raw_id in get(new_targets, application.id, ObjectId[]) + object_id = _index_object_id(model.registry.objects, raw_id) push!(affected_keys, (application.id, object_id)) end end - for object_id in rewired_consumer_ids - for application in get(applications_by_object, object_id, ()) - push!(affected_keys, (application.id, object_id)) + for raw_id in rewired_consumer_ids + let object_id = _index_object_id(model.registry.objects, raw_id) + _foreach_object_application(compiled, object_id) do application + push!(affected_keys, (application.id, object_id)) + end end end @@ -3619,7 +3626,9 @@ function _extend_model_status_views( application_id => index for (index, application_id) in pairs(application_order) ) - for key in affected_temporal_keys + for (application_id, raw_id) in affected_temporal_keys + object_id = _index_object_id(model.registry.objects, raw_id) + key = (application_id, object_id) view = get(views, key, nothing) isnothing(view) && continue if _extend_temporal_many_inputs_in_place!( @@ -3785,20 +3794,30 @@ function _propagate_changed_manual_call_owners!( return changed_target_ids end +@inline function _is_previous_time_step_binding(binding::CompiledModelInputBinding, input::Symbol) + return binding.carrier_hint === :temporal_stream && binding.input === input && + binding.policy isa PreviousTimeStep +end + function _changed_previous_time_step_targets( + objects::ObjectFamilyStore{I}, previous_temporal_sources, status_views_by_target, -) - changed_target_ids = Set{Tuple{Symbol,ObjectId}}() - for (application_id, object_id, input) in keys(previous_temporal_sources) + input_bindings, + input_bindings_by_target, +) where {I<:ObjectId} + changed_target_ids = Set{Tuple{Symbol,I}}() + for (application_id, raw_id, input) in keys(previous_temporal_sources) + object_id = _index_object_id(objects, raw_id) target_key = (application_id, object_id) - view = get(status_views_by_target, target_key, nothing) - isnothing(view) && continue - any(view.temporal_inputs) do temporal_input - temporal_input.binding.input == input && - temporal_input.binding.policy isa PreviousTimeStep - end || continue - push!(changed_target_ids, target_key) + isnothing(get(status_views_by_target, target_key, nothing)) && continue + for raw_binding in get(input_bindings_by_target, target_key, ()) + previous = Base.@inline _with_model_input_binding( + _is_previous_time_step_binding, input_bindings, raw_binding, input) + previous || continue + push!(changed_target_ids, target_key) + break + end end return changed_target_ids end @@ -4400,11 +4419,11 @@ function _extend_compiled_scene( new_targets, pure_addition, ) - union!(changed_target_ids_seed, changed_distributed_output_target_ids) - union!( - changed_application_ids_seed, - (first(key) for key in changed_distributed_output_target_ids), - ) + for (application_id, raw_id) in changed_distributed_output_target_ids + object_id = _index_object_id(model.registry.objects, raw_id) + push!(changed_target_ids_seed, (application_id, object_id)) + push!(changed_application_ids_seed, application_id) + end _runtime_performance_finish!( performance, :application_target_refresh, @@ -4578,9 +4597,9 @@ function _extend_compiled_scene( affected_input_applications = if pure_addition || isempty(rewired_consumer_ids) - Tuple(added_applications) + added_applications else - rewired_applications = CompiledModelApplication[] + rewired_applications = copy(added_applications) targets_by_application = Dict{Symbol,Vector{ObjectId}}() for raw_id in rewired_consumer_ids object_id = _index_object_id(model.registry.objects, raw_id) @@ -4607,7 +4626,7 @@ function _extend_compiled_scene( _partial_model_application(application, target_ids), ) end - (added_applications..., rewired_applications...) + rewired_applications end if pure_addition final_input_references = _model_input_status_references(changed_bindings) @@ -4658,7 +4677,6 @@ function _extend_compiled_scene( compiled, applications, applications_by_id, - applications_by_object, input_bindings_by_target, application_order, new_targets, @@ -4673,32 +4691,43 @@ function _extend_compiled_scene( :status_view_refresh, started_at, ) - changed_execution_target_ids = Set{Tuple{Symbol,ObjectId}}( - (application_id, object_id) - for (application_id, object_ids) in new_targets - for object_id in object_ids - ) - union!( - changed_execution_target_ids, - affected_temporal_keys, - ) - union!(changed_execution_target_ids, changed_target_ids_seed) - union!(changed_execution_target_ids, changed_call_target_keys) + # Keep the published owner's storage type, while admitting each incoming + # identity before constructing the key consumed by its Set operations. + changed_execution_target_ids = Set{Tuple{Symbol,ObjectId}}() + for (application_id, object_ids) in new_targets + for raw_id in object_ids + object_id = _index_object_id(model.registry.objects, raw_id) + push!(changed_execution_target_ids, (application_id, object_id)) + end + end + for incoming in (affected_temporal_keys, changed_target_ids_seed, changed_call_target_keys) + for (application_id, raw_id) in incoming + object_id = _index_object_id(model.registry.objects, raw_id) + push!(changed_execution_target_ids, (application_id, object_id)) + end + end for raw_id in rewired_consumer_ids - object_id = _index_object_id(model.registry.objects, raw_id) - _foreach_object_application(compiled, object_id) do application - push!(changed_execution_target_ids, (application.id, object_id)) + let object_id = _index_object_id(model.registry.objects, raw_id) + _foreach_object_application(compiled, object_id) do application + push!(changed_execution_target_ids, (application.id, object_id)) + end end end - changed_manual_target_ids = Set{Tuple{Symbol,ObjectId}}( - key for key in changed_execution_target_ids - if first(key) in manual_application_ids - ) + Key = Tuple{Symbol,keytype(model.registry.objects)} + changed_manual_target_ids = Set{Key}() + for (application_id, raw_id) in changed_execution_target_ids + application_id in manual_application_ids || continue + object_id = _index_object_id(model.registry.objects, raw_id) + push!(changed_manual_target_ids, (application_id, object_id)) + end union!( changed_manual_target_ids, _changed_previous_time_step_targets( + model.registry.objects, previous_temporal_sources, status_views_by_target, + input_bindings, + input_bindings_by_target, ), ) _propagate_changed_manual_call_owners!( diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 4fac9157d..77c6ecffc 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -78,10 +78,10 @@ end function check_index(model, bindings, index) I = keytype(model.registry.objects) @test keytype(index) === Tuple{Symbol,I} - @test valtype(index) === Any + @test valtype(index) === Tuple{Vararg{eltype(bindings)}} rebuilt = PSE._index_model_bindings(bindings, I) @test keytype(rebuilt) === Tuple{Symbol,I} - @test valtype(rebuilt) === Any + @test valtype(rebuilt) === Tuple{Vararg{eltype(bindings)}} @test Set(keys(rebuilt)) == Set(keys(index)) for (key, values) in rebuilt expected = Tuple(binding for binding in bindings @@ -93,7 +93,7 @@ function check_index(model, bindings, index) empty_index = PSE._index_model_bindings(empty(bindings), I) @test isempty(empty_index) @test keytype(empty_index) === Tuple{Symbol,I} - @test valtype(empty_index) === Any + @test valtype(empty_index) === Tuple{Vararg{eltype(bindings)}} return nothing end diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 4ec525e6f..cac4832c9 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -118,6 +118,8 @@ end prototype = storage_prototype(control.families) data = fixture() simulation = prepare(data.model, prototype) + input_cache = simulation.compiled.input_bindings_by_target + @test valtype(input_cache) === Tuple{Vararg{eltype(prototype)}} @test simulation.compiled.input_bindings !== prototype @test eltype(simulation.compiled.input_bindings) === eltype(prototype) @test isempty(check_carriers(data, simulation).carrier) @@ -125,6 +127,8 @@ end first_reference = birth!(data.model, :leaf_1, 7.0) push!(totals, advance!(data, simulation)) first = check_carriers(data, simulation) + @test simulation.compiled.input_bindings_by_target === input_cache + @test any(cached -> cached === first, input_cache[(:reader, ObjectId(:a))]) @test only(parent(first.carrier)) === first_reference carrier, source_ids = first.carrier, first.source_ids second_reference = birth!(data.model, :leaf_2, 11.0) From 06537839fd5df5c078b4eeff92eba6c1b74551d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 14:51:22 +0100 Subject: [PATCH 094/324] Construct model status views from prepared type families --- src/composite_model/bound_many.jl | 25 - src/composite_model/compilation.jl | 332 ++++-------- src/composite_model/runtime_outputs.jl | 11 +- .../status_view_construction.jl | 496 ++++++++++++++++++ src/composite_model_api.jl | 1 + src/visualization/model_graph_view.jl | 5 +- test/test-model-output-retention-owners.jl | 135 ++++- test/test-model-temporal-initial-typing.jl | 47 +- 8 files changed, 800 insertions(+), 252 deletions(-) create mode 100644 src/composite_model/status_view_construction.jl diff --git a/src/composite_model/bound_many.jl b/src/composite_model/bound_many.jl index 2c206d29e..0ef02cb8a 100644 --- a/src/composite_model/bound_many.jl +++ b/src/composite_model/bound_many.jl @@ -120,31 +120,6 @@ end _bound_many_object_position(values, object_id), ) -_compiled_bound_many_inputs(::Tuple{}, ::Status) = NamedTuple() - -Base.@nospecializeinfer function _compiled_bound_many_inputs(bindings::Tuple, status::Status) - # Compile the cold binding assembly once, not once per tuple × status schema. - # Each returned BoundMany and the final NamedTuple remain concretely typed. - @nospecialize bindings status - names = Symbol[] - values = Any[] - for binding in bindings - binding.multiplicity == :many || continue - input = binding.input - input in names && error( - "Compiled application input `$(input)` has more than one Many binding.", - ) - carrier = getproperty(status, input) - carrier isa AbstractVector || error( - "Compiled Many input `$(input)` has non-vector runtime value " * - "`$(typeof(carrier))`.", - ) - push!(names, input) - push!(values, _compiled_bound_many(binding.source_ids, carrier)) - end - return NamedTuple{Tuple(names)}(Tuple(values)) -end - _rebind_compiled_bound_many_inputs(::NamedTuple{()}, ::Status) = NamedTuple() function _rebind_compiled_bound_many_inputs( diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 63066a605..04e28b7a0 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1659,6 +1659,45 @@ mutable struct CompiledModelStatusView{S,C,T,P,BI} const bound_inputs::BI end +# Per-application view families are metadata only. A host-owned tracing schema +# may extend this narrow callback operation; no unknown schema falls back open. +@inline function _with_model_status_view(f::F, ::Nothing, application_id::Symbol, + view, args::Vararg{Any,N}, +) where {F,N} + return f(view, args...) +end + +function _model_status_view_family_types(V) + V === Union{} && return () + families = Tuple(Base.uniontypes(V)) + all(T -> isconcretetype(T) && T <: CompiledModelStatusView, families) || + throw(ArgumentError("Status view families require concrete canonical view types.")) + return families +end + +@generated function _with_model_status_view_family(prototype::AbstractVector{V}, f::F, + view, args::Vararg{Any,N}, +) where {V,F,N} + families = _model_status_view_family_types(V) + branches = [:(view isa $T && return f(view::$T, args...)) for T in families] + return quote + isempty(prototype) || throw(ArgumentError("Status view family prototypes must be empty.")) + $(branches...) + throw(ArgumentError("The status view is outside its prepared application family.")) + end +end + +@inline function _with_model_status_view(f::F, schema::CompiledMetadataTable, + application_id::Symbol, view, args::Vararg{Any,N}, +) where {F,N} + return Base.@inline _with_metadata_entry(_with_model_status_view_family, + schema, application_id, f, view, args...) +end + +# This hook is also called for newly constructed ephemeral/private views. +@inline _admit_model_status_view!(schema, application_id::Symbol, view) = + Base.@inline _with_model_status_view(identity, schema, application_id, view) + struct CompiledModelCallBinding{P<:CompiledModelCallPlan,I<:ObjectId,J<:ObjectId} plan::P consumer_id::I @@ -1872,7 +1911,7 @@ end # scenario plan and application plans remain immutable values; only their # runtime shell is reference-backed so passing it across a batch boundary does # not box and copy the complete typed scenario-plan tuple. -mutable struct CompiledCompositeModel{SC,SP,AP,AI,OA,ABO,IB,CB,IBI,CBI,DBI,DCBI,MCBI,MBC,DO,CO,AC,SVI,CE,CET,PA,AO} +mutable struct CompiledCompositeModel{SC,SP,AP,AI,OA,ABO,IB,CB,IBI,CBI,DBI,DCBI,MCBI,MBC,DO,CO,AC,SVI,SVS,CE,CET,PA,AO} model::SC scenario_plan::SP applications::AP @@ -1894,6 +1933,7 @@ mutable struct CompiledCompositeModel{SC,SP,AP,AI,OA,ABO,IB,CB,IBI,CBI,DBI,DCBI, call_owners::CO application_children::AC status_views_by_target::SVI + status_view_schema::SVS changed_execution_application_ids::CE changed_execution_target_ids::CET status_view_refresh_is_pure_addition::PA @@ -1920,12 +1960,13 @@ function _refresh_bindings!( force::Bool=false, performance=nothing, input_binding_storage=nothing, + status_view_schema=nothing, ) if specs !== model.applications raw_specs = specs isa Tuple ? specs : specs isa AbstractVector ? Tuple(specs) : (specs,) - return _compile_scene(model, raw_specs; performance, input_binding_storage) + return _compile_scene(model, raw_specs; performance, input_binding_storage, status_view_schema) end - rebuild = force || !isnothing(input_binding_storage) + rebuild = force || !isnothing(input_binding_storage) || !isnothing(status_view_schema) preparation = _scenario_preparation(model; force) _validate_authored_scenario(preparation) previous = model.binding_cache @@ -1944,7 +1985,7 @@ function _refresh_bindings!( end end return _refresh_prepared_bindings!(model, previous, prepared; - force=rebuild, performance, input_binding_storage) + force=rebuild, performance, input_binding_storage, status_view_schema) end _binding_refresh_required(model, previous, prepared, force) = @@ -1963,6 +2004,7 @@ end function _refresh_prepared_bindings!( model::CompositeModel, previous, prepared; force::Bool=false, performance=nothing, input_binding_storage=nothing, + status_view_schema=nothing, ) _binding_refresh_required(model, previous, prepared, force) || return previous delta = model.lifecycle_delta @@ -1984,7 +2026,7 @@ function _refresh_prepared_bindings!( _remove_stale_status_views!(refreshed, structural.changed_target_ids) else prepared isa PreparedScenario || _unprepared_runtime_configuration() - refreshed = _compile_scene(model, prepared; performance, input_binding_storage) + refreshed = _compile_scene(model, prepared; performance, input_binding_storage, status_view_schema) if !force && !isnothing(previous) && previous.distributed_outputs isa CompiledDistributedOutputs _preserve_recompiled_model_status_views!(refreshed, previous) end @@ -2464,10 +2506,11 @@ function _compile_scene( validate_required_inputs::Bool=true, performance=nothing, input_binding_storage=nothing, + status_view_schema=nothing, ) scenario_plan, applications = _build_scenario_plan(model, raw_specs, _model_timeline(model); performance) return _compile_scene(model, scenario_plan, applications; - validate_required_inputs, performance, input_binding_storage) + validate_required_inputs, performance, input_binding_storage, status_view_schema) end function _compile_scene(model::CompositeModel, prepared::PreparedScenario; kwargs...) @@ -2482,6 +2525,7 @@ function _compile_scene( validate_required_inputs::Bool=true, performance=nothing, input_binding_storage=nothing, + status_view_schema=nothing, ) timeline = scenario_plan.timeline started_at = _runtime_performance_start(performance) @@ -2547,8 +2591,10 @@ function _compile_scene( applications, applications_by_id, input_bindings_by_target, + input_bindings, application_order, - distributed_outputs, + distributed_outputs; + status_view_schema, ) _runtime_performance_finish!( performance, @@ -2582,6 +2628,7 @@ function _compile_scene( call_owners, application_children, status_views_by_target, + status_view_schema, Set{Symbol}(application.id for application in applications), Set(keys(status_views_by_target)), false, @@ -3458,17 +3505,50 @@ function _preserve_model_status_view_temporal_state!( ) end +function _preserve_model_status_view_with_previous!(previous, schema, application_id, + current, previous_temporal_sources, key, +) + return Base.@inline _with_model_status_view(_preserve_model_status_view_temporal_state!, + schema, application_id, current, previous, previous_temporal_sources, key) +end + +function _preserve_model_status_view_temporal_state!(schema, application_id::Symbol, + current, previous, previous_temporal_sources, key, +) + view = Base.@inline _with_model_status_view(_preserve_model_status_view_with_previous!, + schema, application_id, previous, schema, application_id, + current, previous_temporal_sources, key) + return _admit_model_status_view!(schema, application_id, view) +end + +function _record_previous_temporal_source!(input::CompiledTemporalInput, sources, key) + binding = input.binding + source_key = (key..., binding.input) + haskey(sources, source_key) || (sources[source_key] = copy(binding.source_ids)) + return nothing +end + +function _record_previous_temporal_sources!(view::CompiledModelStatusView, sources, key) + for index in eachindex(view.temporal_inputs) + Base.@inline _with_metadata_entry(_record_previous_temporal_source!, + view.temporal_inputs, index, sources, key) + end + return nothing +end + function _preserve_recompiled_model_status_views!( current::CompiledCompositeModel, previous::CompiledCompositeModel, ) previous_temporal_sources = Dict{Tuple{Symbol,ObjectId,Symbol},Vector{ObjectId}}() - for (key, current_view) in current.status_views_by_target + for ((application_id, raw_id), current_view) in current.status_views_by_target + object_id = _index_object_id(current.model.registry.objects, raw_id) + key = (application_id, object_id) previous_view = get(previous.status_views_by_target, key, nothing) isnothing(previous_view) && continue current.status_views_by_target[key] = _preserve_model_status_view_temporal_state!( - current_view, + current.status_view_schema, first(key), current_view, previous_view, previous_temporal_sources, key, @@ -3544,8 +3624,8 @@ function _stage_temporal_many_extension( end function _extend_temporal_many_inputs_in_place!( - model::CompositeModel, view::CompiledModelStatusView, + model::CompositeModel, key, previous_temporal_sources, applications_by_id, @@ -3631,15 +3711,10 @@ function _extend_model_status_views( key = (application_id, object_id) view = get(views, key, nothing) isnothing(view) && continue - if _extend_temporal_many_inputs_in_place!( - model, - view, - key, - previous_temporal_sources, - applications_by_id, - positions, - distributed_outputs, - ) + extended = Base.@inline _with_model_status_view(_extend_temporal_many_inputs_in_place!, + compiled.status_view_schema, application_id, view, model, key, + previous_temporal_sources, applications_by_id, positions, distributed_outputs) + if extended delete!(affected_keys, key) end end @@ -3648,14 +3723,9 @@ function _extend_model_status_views( application = applications_by_id[application_id] previous_view = get(previous_views, key, nothing) if !isnothing(previous_view) - for temporal_input in previous_view.temporal_inputs - get!( - previous_temporal_sources, - (key..., temporal_input.binding.input), - ) do - copy(temporal_input.binding.source_ids) - end - end + Base.@inline _with_model_status_view(_record_previous_temporal_sources!, + compiled.status_view_schema, application_id, previous_view, + previous_temporal_sources, key) end current_view = _compile_model_status_view( model, @@ -3665,12 +3735,14 @@ function _extend_model_status_views( applications_by_id, positions, distributed_outputs; - execution_stamp=_status_view_execution_stamp(model, key, previous_view), + execution_stamp=_status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema), + status_view_schema=compiled.status_view_schema, + input_binding_storage=compiled.input_bindings, ) views[key] = isnothing(previous_view) ? current_view : _preserve_model_status_view_temporal_state!( - current_view, + compiled.status_view_schema, application_id, current_view, previous_view, previous_temporal_sources, key, @@ -3951,6 +4023,7 @@ function _prepare_structural_compiled_delta( compiled.call_owners, compiled.application_children, compiled.status_views_by_target, + compiled.status_view_schema, changed_application_ids, removed_target_keys, false, @@ -4765,6 +4838,7 @@ function _extend_compiled_scene( call_owners, application_children, status_views_by_target, + compiled.status_view_schema, changed_execution_application_ids, changed_execution_target_ids, status_view_refresh_is_pure_addition, @@ -7285,67 +7359,6 @@ function _private_temporal_value(value) return deepcopy(value) end -# Initial values are private snapshots, but their concrete element schema is -# already known after binding. Preserve it for the first-step/missing-sample -# branch of the numerical executor without converting heterogeneous values. -function _typed_temporal_initial_values(values::Vector{Any}) - isempty(values) && return values - value_type = typeof(first(values)) - all(value -> typeof(value) === value_type, values) || return values - typed = Vector{value_type}(undef, length(values)) - copyto!(typed, values) - return typed -end - -function _temporal_input_initial(binding::CompiledModelInputBinding, status::Status) - initial = _input_value(binding.carrier) - if isnothing(initial) - binding.input in propertynames(status) || error( - "Temporal input `$(binding.input)` on application ", - "`$(binding.application_id)` has neither a resolved source carrier nor an ", - "initialized status value. Resolved source objects: ", - "`$(Tuple(id.value for id in binding.source_ids))`.", - ) - initial = status[binding.input] - end - if binding.multiplicity == :many - initial isa AbstractVector || error( - "Temporal `Many` input `$(binding.input)` on application ", - "`$(binding.application_id)` requires a vector-like initialized value; got ", - "`$(typeof(initial))`.", - ) - if length(initial) == length(binding.source_ids) - return _typed_temporal_initial_values( - Any[_private_temporal_value(value) for value in initial], - ) - end - binding.policy isa PreviousTimeStep && error( - "Temporal `Many` input `$(binding.input)` on application ", - "`$(binding.application_id)` resolved $(length(binding.source_ids)) source ", - "objects but has $(length(initial)) initialized values.", - ) - isempty(binding.source_ids) && return Any[] - isempty(initial) && error( - "Temporal `Many` input `$(binding.input)` on application ", - "`$(binding.application_id)` needs an initialized element to preallocate ", - "$(length(binding.source_ids)) temporal values.", - ) - return _typed_temporal_initial_values(Any[ - _private_temporal_value(first(initial)) - for _ in binding.source_ids - ]) - end - return _private_temporal_value(initial) -end - -function _private_temporal_storage(binding::CompiledModelInputBinding, initial) - binding.multiplicity == :many || - return _private_temporal_value(initial) - isempty(initial) && return RefVector{Any}() - references = Base.RefValue[Ref(_private_temporal_value(value)) for value in initial] - return _ref_vector_carrier(references) -end - function _temporal_source_application( binding::CompiledModelInputBinding, source_id::ObjectId, @@ -7428,142 +7441,22 @@ function _distributed_temporal_source_application( return isnothing(owner) ? nothing : owner.application_id end -function _validate_temporal_input_output_overlap!( - application::CompiledModelApplication, - temporal_bindings, -) - isempty(temporal_bindings) && return nothing - output_names = Set(_model_output_names(application)) - for binding in temporal_bindings - binding.input in output_names || continue - error( - "Application `$(application.id)` declares `$(binding.input)` as both a ", - "temporal input and an output. A temporal input uses application-local ", - "storage while outputs publish through canonical status, so this overlap ", - "is ambiguous. Use distinct names such as `previous_$(binding.input)` for ", - "the lagged input and `$(binding.input)` for the current output, then map ", - "the source explicitly.", - ) - end - return nothing -end - -Base.@nospecializeinfer function _compile_model_status_view( - model::CompositeModel, - application::CompiledModelApplication, - object_id::ObjectId, - input_bindings, - applications_by_id, - application_positions, - distributed_outputs=NoCompiledDistributedOutputs(); - execution_stamp::Base.RefValue{UInt64}, -) - # This is cold assembly, not a kernel: avoid inferring the whole view - # constructor for every application and heterogeneous binding tuple. - # The assembled Status and CompiledModelStatusView still have concrete types. - @nospecialize application input_bindings - canonical_status = _ensure_model_object_status!(model, object_id) - has_temporal_inputs = false - for binding in input_bindings - if binding.carrier_hint == :temporal_stream - has_temporal_inputs = true - break - end - end - # Ordinary applications use the canonical status directly. Avoid preparing - # temporal/private scratch storage and validating a nonexistent overlap. - if !has_temporal_inputs && isempty(output_routing(application.spec)) - return CompiledModelStatusView( - execution_stamp, - canonical_status, - canonical_status, - (), - NamedTuple(), - _compiled_bound_many_inputs(input_bindings, canonical_status), - ) - end - temporal_bindings = CompiledModelInputBinding[] - for binding in input_bindings - binding.carrier_hint == :temporal_stream && push!(temporal_bindings, binding) - end - _validate_temporal_input_output_overlap!(application, temporal_bindings) - output_defaults = _local_output_schema(application.spec) - private_output_names = Symbol[] - for variable in keys(output_defaults) - _publish_mode_for_output(application.spec, variable) == :stream_only && - push!(private_output_names, Symbol(variable)) - end - if isempty(temporal_bindings) && isempty(private_output_names) - return CompiledModelStatusView( - execution_stamp, - canonical_status, - canonical_status, - (), - NamedTuple(), - _compiled_bound_many_inputs(input_bindings, canonical_status), - ) - end - # Use storage-neutral scratch vectors during assembly. Generators capturing - # heterogeneous binding tuples specialize again even across the cold boundary. - temporal_inputs = CompiledTemporalInput[] - for binding in temporal_bindings - initial = _temporal_input_initial(binding, canonical_status) - source_applications = Union{Nothing,Symbol}[] - for source_id in binding.source_ids - push!(source_applications, _temporal_source_application( - binding, source_id, applications_by_id, application_positions, - distributed_outputs, - )) - end - push!(temporal_inputs, CompiledTemporalInput( - binding, source_applications, initial, - Ref(_private_temporal_storage(binding, initial)), - )) - end - private_references = Ref[] - for name in private_output_names - initial, _, _ = _materialize_status_value( - model, - name, - getproperty(output_defaults, name); - object_id=object_id, - application_id=application.id, - origin=:stream_only_private_default, - private_copy=true, - reuse=true, - ) - push!(private_references, Ref(initial)) - end - private_outputs = NamedTuple{Tuple(private_output_names)}(Tuple(private_references)) - recipe = _CanonicalStatusRecipe(canonical_status) - for (name, reference) in pairs(private_outputs) - _status_recipe_set_reference!(recipe, name, reference) - end - for input in temporal_inputs - _status_recipe_set_reference!(recipe, input.binding.input, input.reference) - end - return _finish_status_recipe(model.registry.objects.layout_cache, recipe) do status - CompiledModelStatusView( - execution_stamp, - status, - canonical_status, - Tuple(temporal_inputs), - private_outputs, - _compiled_bound_many_inputs(input_bindings, status), - ) - end +_status_view_execution_stamp(previous::CompiledModelStatusView, model, key) = previous.execution_stamp +function _status_view_execution_stamp(model, key, previous, schema) + isnothing(previous) && return _targeted_call_execution_stamp(model, key) + return Base.@inline _with_model_status_view(_status_view_execution_stamp, + schema, first(key), previous, model, key) end -_status_view_execution_stamp(model, key, previous::CompiledModelStatusView) = previous.execution_stamp -_status_view_execution_stamp(model, key, ::Nothing) = _targeted_call_execution_stamp(model, key) - function _compile_model_status_views( model::CompositeModel, applications, applications_by_id, input_bindings_by_target, + input_binding_storage, application_order, - distributed_outputs=NoCompiledDistributedOutputs(), + distributed_outputs=NoCompiledDistributedOutputs(); + status_view_schema, ) views = Dict{Tuple{Symbol,ObjectId},Any}() previous = getfield(model, :binding_cache) @@ -7584,7 +7477,8 @@ function _compile_model_status_views( positions, distributed_outputs; execution_stamp=_status_view_execution_stamp(model, key, - isnothing(previous_views) ? nothing : get(previous_views, key, nothing)), + isnothing(previous_views) ? nothing : get(previous_views, key, nothing), status_view_schema), + status_view_schema, input_binding_storage, ) end end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index e59325c36..333fc7a2b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1728,12 +1728,14 @@ end application::CompiledModelApplication, object_id::ObjectId, ) - key = (application.id, object_id) + id = _index_object_id(compiled.model.registry.objects, object_id) + key = (application.id, id) haskey(compiled.status_views_by_target, key) || error( "No compiled status view for application `$(application.id)` on object ", "`$(object_id.value)`.", ) - return compiled.status_views_by_target[key]::CompiledModelStatusView + return Base.@inline _with_model_status_view(identity, compiled.status_view_schema, + application.id, compiled.status_views_by_target[key]) end function _set_status_if_present!(status::Status, variable::Symbol, value) @@ -6112,7 +6114,8 @@ function _append_targeted_newborn_targets!( status_view = _compile_model_status_view(runtime_model(context),partial_application, object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, targeted_runtime.application_positions,compiled.distributed_outputs; - execution_stamp=stamp)::CompiledModelStatusView + execution_stamp=stamp, status_view_schema=compiled.status_view_schema, + input_binding_storage=compiled.input_bindings)::CompiledModelStatusView output_groups = _runtime_model_output_groups(compiled,application,object_id) environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) call_bindings = () # targeted admission has rejected nested callees @@ -7898,6 +7901,7 @@ function _prepare_simulation!( performance::Bool=false, environment_schema=_environment_schema(getfield(model, :environment_binding_cache)), input_binding_storage=nothing, + status_view_schema=nothing, ) performance_counters = performance ? RuntimePerformanceCounters() : nothing initial_composite_started_at = @@ -7925,6 +7929,7 @@ function _prepare_simulation!( model; performance=performance_counters, input_binding_storage, + status_view_schema, ) compiled.execution_generation += UInt64(1) _runtime_performance_finish!( diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl new file mode 100644 index 000000000..00aa0bd2a --- /dev/null +++ b/src/composite_model/status_view_construction.jl @@ -0,0 +1,496 @@ +# Transient values gathered once by the canonical view compiler. These records +# carry real bindings and private snapshots; they are not runtime view owners. +struct _TemporalStatusViewRecipe + input::Symbol + binding::Any + source_applications::Vector{Union{Nothing,Symbol}} + initial::Any + storage::Any + many::Bool +end + +# Project copy payloads from real per-input view/carrier metadata, before +# either private snapshot. This is transient metadata, not another owner. +function _temporal_copy_payload_types(V, B, C) + types = Any[] + add(T) = isconcretetype(T) && T !== Union{} && !(T in types) && push!(types, T) + Plan = fieldtype(B, :plan) + input = fieldtype(Plan, :route).parameters[1] + many = fieldtype(Plan, :selector) <: Many + Carrier = fieldtype(B, :carrier) + if Carrier <: Base.RefValue + add(eltype(Carrier)) + elseif Carrier <: RefVector + add(eltype(Carrier)) + elseif Carrier <: ObjectRefVector + References = eltype(fieldtype(Carrier, :refs)) + for R in Base.uniontypes(References) + R <: Base.RefValue && isconcretetype(R) && add(eltype(R)) + end + end + if C <: Status && input in _status_schema_names(C) + index = findfirst(isequal(input), _status_schema_names(C)) + Value = eltype(fieldtype(_status_schema_references(C), index)) + add(many && Value <: AbstractVector ? eltype(Value) : Value) + end + for View in _model_status_view_family_types(V), TI in fieldtypes(fieldtype(View, :temporal_inputs)) + Other = fieldtype(TI, :binding) + fieldtype(fieldtype(Other, :plan), :route).parameters[1] === input || continue + Initial = fieldtype(TI, :initial) + Storage = eltype(fieldtype(TI, :reference)) + add(many && Initial <: AbstractVector ? eltype(Initial) : Initial) + add(many && Storage <: AbstractVector ? eltype(Storage) : Storage) + end + return Tuple{types...} +end + +@inline function _with_temporal_copy_payloads(f::F, ::Nothing, binding, status, + args::Vararg{Any,N}, +) where {F,N} + return f(nothing, binding, status, args...) +end +@generated function _with_temporal_copy_payload_family(prototype::AbstractVector{V}, + f::F, binding::B, status::C, args::Vararg{Any,N}, +) where {V,F,B,C,N} + Payloads = _temporal_copy_payload_types(V, B, C) + token = Val{Payloads}() + return quote + isempty(prototype) || throw(ArgumentError("Status view family prototypes must be empty.")) + return f($(QuoteNode(token)), binding, status, args...) + end +end +@inline function _with_temporal_copy_payloads(f::F, schema::CompiledMetadataTable, + binding, status, args::Vararg{Any,N}, +) where {F,N} + return Base.@inline _with_metadata_entry(_with_temporal_copy_payload_family, + schema, binding.application_id, f, binding, status, args...) +end + +@inline _copy_temporal_status_value(::Nothing, value) = _private_temporal_value(value) +@generated function _copy_temporal_status_value(::Val{Payloads}, value) where {Payloads} + branches = [:(typeof(value) === $T && return _private_temporal_value(value::$T)) + for T in fieldtypes(Payloads)] + return quote + $(branches...) + throw(ArgumentError("The temporal snapshot payload is outside its prepared input family.")) + end +end + +function _gather_temporal_initial(binding::CompiledModelInputBinding, status::Status, payloads) + initial = _input_value(binding.carrier) + if isnothing(initial) + binding.input in propertynames(status) || error( + "Temporal input `$(binding.input)` on application ", + "`$(binding.application_id)` has neither a resolved source carrier nor an ", + "initialized status value. Resolved source objects: ", + "`$(Tuple(id.value for id in binding.source_ids))`.", + ) + initial = status[binding.input] + end + binding.multiplicity == :many || return _copy_temporal_status_value(payloads, initial) + initial isa AbstractVector || error( + "Temporal `Many` input `$(binding.input)` on application ", + "`$(binding.application_id)` requires a vector-like initialized value; got ", + "`$(typeof(initial))`.", + ) + if length(initial) == length(binding.source_ids) + return Any[_copy_temporal_status_value(payloads, value) for value in initial] + end + binding.policy isa PreviousTimeStep && error( + "Temporal `Many` input `$(binding.input)` on application ", + "`$(binding.application_id)` resolved $(length(binding.source_ids)) source ", + "objects but has $(length(initial)) initialized values.", + ) + isempty(binding.source_ids) && return Any[] + isempty(initial) && error( + "Temporal `Many` input `$(binding.input)` on application ", + "`$(binding.application_id)` needs an initialized element to preallocate ", + "$(length(binding.source_ids)) temporal values.", + ) + return Any[_copy_temporal_status_value(payloads, first(initial)) for _ in binding.source_ids] +end + +function _collect_status_view_binding!(binding::CompiledModelInputBinding, + temporal_bindings, many_names, many_ids, +) + binding.carrier_hint == :temporal_stream && push!(temporal_bindings, binding) + if binding.multiplicity == :many + push!(many_names, binding.input) + push!(many_ids, binding.source_ids) + end + return nothing +end + +function _validate_status_view_temporal_binding!(binding::CompiledModelInputBinding, + application, output_names, +) + binding.input in output_names || return nothing + error( + "Application `$(application.id)` declares `$(binding.input)` as both a ", + "temporal input and an output. A temporal input uses application-local ", + "storage while outputs publish through canonical status, so this overlap ", + "is ambiguous. Use distinct names such as `previous_$(binding.input)` for ", + "the lagged input and `$(binding.input)` for the current output, then map ", + "the source explicitly.", + ) +end + +function _gather_status_view_temporal!(binding::CompiledModelInputBinding, + recipes, canonical_status, applications_by_id, application_positions, + distributed_outputs, status_view_schema, +) + return Base.@inline _with_temporal_copy_payloads(_gather_admitted_status_view_temporal!, + status_view_schema, binding, canonical_status, recipes, applications_by_id, + application_positions, distributed_outputs) +end + +function _gather_admitted_status_view_temporal!(payloads, binding::CompiledModelInputBinding, + canonical_status, recipes, applications_by_id, application_positions, + distributed_outputs, +) + initial = _gather_temporal_initial(binding, canonical_status, payloads) + source_applications = Union{Nothing,Symbol}[] + for source_id in binding.source_ids + push!(source_applications, _temporal_source_application( + binding, source_id, applications_by_id, application_positions, + distributed_outputs, + )) + end + many = binding.multiplicity == :many + storage = many ? Any[_copy_temporal_status_value(payloads, value) for value in initial] : + _copy_temporal_status_value(payloads, initial) + push!(recipes, _TemporalStatusViewRecipe(binding.input, binding, + source_applications, initial, storage, many)) + return nothing +end + +function _compile_model_status_view(model::CompositeModel, + application::CompiledModelApplication, object_id::ObjectId, + input_bindings::Tuple, applications_by_id, application_positions, + distributed_outputs=NoCompiledDistributedOutputs(); + execution_stamp::Base.RefValue{UInt64}, status_view_schema, + input_binding_storage, +) + return _with_model_application(applications_by_id, application) do admitted_application + raw_status = _ensure_model_object_status!(model, object_id) + return _with_registered_status(model.registry.objects.catalog, raw_status) do canonical_status + _assemble_model_status_view(model, admitted_application, object_id, + input_bindings, canonical_status, applications_by_id, + application_positions, distributed_outputs, execution_stamp, + status_view_schema, input_binding_storage) + end + end +end + +# All modes gather the same values, in the original conversion/snapshot order. +# Selection below concerns exact component construction, never scientific logic. +function _assemble_model_status_view(model, application, object_id, + input_bindings, canonical_status, applications_by_id, application_positions, + distributed_outputs, execution_stamp, status_view_schema, input_binding_storage, +) + temporal_bindings = similar(input_binding_storage, 0) + many_names, many_ids = Symbol[], Any[] + for binding in input_bindings + Base.@inline _with_model_input_binding(_collect_status_view_binding!, + input_binding_storage, binding, temporal_bindings, many_names, many_ids) + end + if !isempty(temporal_bindings) + output_names = Set(_model_output_names(application)) + for binding in temporal_bindings + Base.@inline _with_model_input_binding(_validate_status_view_temporal_binding!, + input_binding_storage, binding, application, output_names) + end + end + private_names = Symbol[] + # Preserve the existing cheap metadata path without a second constructor. + output_defaults = if isempty(temporal_bindings) && isempty(output_routing(application.spec)) + NamedTuple() + else + defaults = _local_output_schema(application.spec) + for variable in keys(defaults) + _publish_mode_for_output(application.spec, variable) == :stream_only && + push!(private_names, Symbol(variable)) + end + defaults + end + temporal = _TemporalStatusViewRecipe[] + for binding in temporal_bindings + Base.@inline _with_model_input_binding(_gather_status_view_temporal!, + input_binding_storage, binding, temporal, canonical_status, + applications_by_id, application_positions, distributed_outputs, + status_view_schema) + end + private_values = Any[] + for name in private_names + initial, _, _ = _materialize_status_value(model, name, + getproperty(output_defaults, name); object_id, + application_id=application.id, origin=:stream_only_private_default, + private_copy=true, reuse=true) + push!(private_values, initial) + end + seen_many = Set{Symbol}() + for name in many_names + name in seen_many && error( + "Compiled application input `$(name)` has more than one Many binding.") + push!(seen_many, name) + end + parts = (; canonical_status, temporal, private_names, private_values, + many_names, many_ids, execution_stamp, + layout_cache=model.registry.objects.layout_cache) + view = _construct_model_status_view(status_view_schema, application.id, parts) + return _admit_model_status_view!(status_view_schema, application.id, view) +end + +# A homogeneous initial snapshot has the same exact schema as before. Matching +# never constructs a type from an Any value in the finite construction path. +function _status_view_initial_matches(::Type{I}, value, many::Bool) where {I} + many || return typeof(value) === I + value isa Vector{Any} || return false + isempty(value) && return I === Vector{Any} + first_type = typeof(first(value)) + homogeneous = all(item -> item isa first_type, value) + I <: Vector || return false + return homogeneous ? first_type === eltype(I) : I === Vector{Any} +end + +function _construct_status_view_initial(::Type{I}, value, many::Bool) where {I} + _status_view_initial_matches(I, value, many) || throw(ArgumentError( + "The temporal initial snapshot is outside its prepared view schema.")) + many || return value::I + values = value::Vector{Any} + I === Vector{Any} && return values + T = eltype(I) + return T[item::T for item in values] +end + +function _status_view_storage_matches(::Type{S}, recipe::_TemporalStatusViewRecipe) where {S} + recipe.many || return typeof(recipe.storage) === S + values = recipe.storage + values isa Vector{Any} || return false + isempty(values) && return S === RefVector{Any} + first_type = typeof(first(values)) + homogeneous = all(value -> value isa first_type, values) + return homogeneous ? S <: RefVector && eltype(S) === first_type : + S === ObjectRefVector{Vector{Base.RefValue}} +end + +function _construct_status_view_storage(::Type{S}, recipe::_TemporalStatusViewRecipe) where {S} + _status_view_storage_matches(S, recipe) || throw(ArgumentError( + "The temporal storage is outside its prepared view schema.")) + recipe.many || return recipe.storage::S + values = recipe.storage::Vector{Any} + return _construct_status_view_storage(S, values) +end +function _construct_status_view_storage(::Type{RefVector{T}}, values::Vector{Any}) where {T} + return RefVector{T}(Base.RefValue{T}[Ref(value::T) for value in values]) +end +# Ordinary JIT supports the same heterogeneous values as before. A finite view +# family cannot infer each erased reference payload from ObjectRefVector alone; +# such candidates are explicitly excluded below, never redirected to this path. +function _construct_status_view_storage(::Type{ObjectRefVector{Vector{Base.RefValue}}}, + values::Vector{Any}, +) + return ObjectRefVector(Base.RefValue[Ref(value) for value in values]) +end + +function _construct_status_view_reference(::Type{R}, value) where {T,R<:Base.RefValue{T}} + typeof(value) === T || throw(ArgumentError( + "The private value is outside its prepared reference schema.")) + return R(value::T) +end + +function _construct_status_view_temporal(::Type{TI}, recipe::_TemporalStatusViewRecipe) where {TI<:CompiledTemporalInput} + B, SA = fieldtype(TI, :binding), fieldtype(TI, :source_applications) + I, R = fieldtype(TI, :initial), fieldtype(TI, :reference) + S = eltype(R) + recipe.binding isa B && recipe.source_applications isa SA || throw(ArgumentError( + "The temporal input is outside its prepared view schema.")) + initial = _construct_status_view_initial(I, recipe.initial, recipe.many) + storage = _construct_status_view_storage(S, recipe) + reference = _construct_status_view_reference(R, storage) + return TI(recipe.binding::B, recipe.source_applications::SA, initial, reference) +end + +# Metadata only: the same exact factory is reused for canonical and private +# statuses. Private result layouts do not enter the canonical registry catalog. +function _status_view_reference_factory(::Type{V}) where {V<:CompiledModelStatusView} + S, C = fieldtype(V, :status), fieldtype(V, :canonical_status) + T, P = fieldtype(V, :temporal_inputs), fieldtype(V, :private_outputs) + BI = fieldtype(V, :bound_inputs) + isconcretetype(S) && S <: Status && isconcretetype(C) && C <: Status && + isconcretetype(T) && T <: Tuple && isconcretetype(P) && P <: NamedTuple && + isconcretetype(BI) && BI <: NamedTuple || throw(ArgumentError( + "A view constructor requires concrete canonical component schemas.")) + all(R -> isconcretetype(R) && R <: Base.RefValue, fieldtypes(P)) || + throw(ArgumentError("Private output schemas require concrete reference types.")) + temporal_names = map(fieldtypes(T)) do TI + isconcretetype(TI) && TI <: CompiledTemporalInput || + throw(ArgumentError("Temporal view schemas require concrete input records.")) + B = fieldtype(TI, :binding) + Route = fieldtype(fieldtype(B, :plan), :route) + Route.parameters[1] + end + names = (fieldnames(P)..., temporal_names...) + references = Tuple{fieldtypes(P)..., + (fieldtype(TI, :reference) for TI in fieldtypes(T))...} + return ExactReferenceFactory(C, references, S, names) +end + +function _status_view_bound_carrier_matches(::Type{S}, parts, name::Symbol) where {S} + index = findfirst(recipe -> recipe.input === name, parts.temporal) + isnothing(index) || return _status_view_storage_matches(S, parts.temporal[index]) + index = findfirst(isequal(name), parts.private_names) + isnothing(index) || return typeof(parts.private_values[index]) === S + return getproperty(parts.canonical_status, name) isa S +end + +@generated function _status_view_parts_match(::Type{V}, parts) where {V<:CompiledModelStatusView} + C, T = fieldtype(V, :canonical_status), fieldtype(V, :temporal_inputs) + P, BI = fieldtype(V, :private_outputs), fieldtype(V, :bound_inputs) + checks = Expr[:(parts.canonical_status isa $C), :(length(parts.temporal) == $(fieldcount(T))), + :(length(parts.private_names) == $(fieldcount(P))), + :(length(parts.private_values) == $(fieldcount(P))), + :(length(parts.many_names) == $(fieldcount(BI))), + :(length(parts.many_ids) == $(fieldcount(BI)))] + for (index, TI) in enumerate(fieldtypes(T)) + B, SA = fieldtype(TI, :binding), fieldtype(TI, :source_applications) + I, R = fieldtype(TI, :initial), fieldtype(TI, :reference) + input = fieldtype(fieldtype(B, :plan), :route).parameters[1] + append!(checks, [:(parts.temporal[$index].input === $(QuoteNode(input))), + :(parts.temporal[$index].binding isa $B), + :(parts.temporal[$index].source_applications isa $SA), + :(_status_view_initial_matches($I, parts.temporal[$index].initial, parts.temporal[$index].many)), + :(_status_view_storage_matches($(eltype(R)), parts.temporal[$index]))]) + end + for (index, name) in enumerate(fieldnames(P)) + R = fieldtype(P, index) + R <: Base.RefValue || return :(false) + append!(checks, [:(parts.private_names[$index] === $(QuoteNode(name))), + :(typeof(parts.private_values[$index]) === $(eltype(R)))]) + end + for (index, name) in enumerate(fieldnames(BI)) + B = fieldtype(BI, index) + B <: BoundMany || return :(false) + I = fieldtype(fieldtype(B, :ids), :ids) + S = fieldtype(B, :values) + append!(checks, [:(parts.many_names[$index] === $(QuoteNode(name))), + :(parts.many_ids[$index] isa $I), + :(_status_view_bound_carrier_matches($S, parts, $(QuoteNode(name))))]) + end + return foldl((a, b) -> :($a && $b), checks) +end + +@generated function _construct_prepared_model_status_view(::Type{V}, parts) where {V<:CompiledModelStatusView} + factory = _status_view_reference_factory(V) + T, P, BI = fieldtype(V, :temporal_inputs), fieldtype(V, :private_outputs), fieldtype(V, :bound_inputs) + temporal = Expr(:tuple, [:(_construct_status_view_temporal($TI, parts.temporal[$index])) + for (index, TI) in enumerate(fieldtypes(T))]...) + private = Expr(:tuple, [:(_construct_status_view_reference($(fieldtype(P, index)), parts.private_values[$index])) + for index in 1:fieldcount(P)]...) + edited = Expr(:tuple, + [:(getfield(private_outputs, $index)) for index in 1:fieldcount(P)]..., + [:(getfield(getfield(temporal_inputs, $index), :reference)) for index in 1:fieldcount(T)]...) + status = fieldcount(P) + fieldcount(T) == 0 ? :(parts.canonical_status) : + :(_construct_status($(QuoteNode(factory)), parts.canonical_status, $edited)) + bound = Expr(:tuple, [begin + B = fieldtype(BI, index) + I = fieldtype(fieldtype(B, :ids), :ids) + S = fieldtype(B, :values) + :(_compiled_bound_many(parts.many_ids[$index]::$I, + getproperty(status, $(QuoteNode(name)))::$S)) + end for (index, name) in enumerate(fieldnames(BI))]...) + return quote + _status_view_parts_match(V, parts) || throw(ArgumentError( + "The gathered values are outside their prepared application view family.")) + temporal_inputs = $temporal + private_outputs = $P($private) + status = $status + bound_inputs = $BI($bound) + return V(parts.execution_stamp, status, parts.canonical_status, + temporal_inputs, private_outputs, bound_inputs) + end +end + +function _finite_status_view_construction_supported(V) + # ObjectRefVector intentionally erases the individual freshly allocated + # Ref payloads. Existing wrappers still work in BI; creating mixed private + # storage needs additional real source-reference family evidence. + return all(fieldtypes(fieldtype(V, :temporal_inputs))) do TI + !(eltype(fieldtype(TI, :reference)) <: ObjectRefVector) + end +end + +@generated function _construct_model_status_view_family(prototype::AbstractVector{V}, parts) where {V} + families = _model_status_view_family_types(V) + supported = filter(_finite_status_view_construction_supported, families) + branches = [:( _status_view_parts_match($T, parts) && + return _construct_prepared_model_status_view($T, parts) ) for T in supported] + return quote + isempty(prototype) || throw(ArgumentError("Status view family prototypes must be empty.")) + $(branches...) + throw(ArgumentError("The gathered values are outside supported prepared application view families; mixed private ObjectRefVector storage requires source-reference family evidence.")) + end +end + +@inline function _construct_model_status_view(schema::CompiledMetadataTable, + application_id::Symbol, parts, +) + return Base.@inline _with_metadata_entry(_construct_model_status_view_family, + schema, application_id, parts) +end + +# Open preparation discovers the real component types, then uses exactly the +# same typed construction function as a finite family. No scientific replay. +function _open_status_view_initial_type(recipe::_TemporalStatusViewRecipe) + recipe.many || return typeof(recipe.initial) + values = recipe.initial + isempty(values) && return Vector{Any} + T = typeof(first(values)) + return all(value -> value isa T, values) ? Vector{T} : Vector{Any} +end +function _open_status_view_storage_type(recipe::_TemporalStatusViewRecipe) + recipe.many || return typeof(recipe.storage) + values = recipe.storage + isempty(values) && return RefVector{Any} + T = typeof(first(values)) + return all(value -> value isa T, values) ? RefVector{T} : + ObjectRefVector{Vector{Base.RefValue}} +end +function _open_status_view_type(parts) + C = typeof(parts.canonical_status) + temporals = map(parts.temporal) do recipe + CompiledTemporalInput{typeof(recipe.binding), typeof(recipe.source_applications), + _open_status_view_initial_type(recipe), + Base.RefValue{_open_status_view_storage_type(recipe)}} + end + T = Tuple{temporals...} + P = NamedTuple{Tuple(parts.private_names), + Tuple{(Base.RefValue{typeof(value)} for value in parts.private_values)...}} + S = if isempty(parts.private_names) && isempty(parts.temporal) + C + else + factory = _status_construction_recipe!(parts.layout_cache, + propertynames(parts.canonical_status), + (parts.private_names..., (recipe.input for recipe in parts.temporal)...)) + original = _status_schema_references(C) + edited = Tuple{fieldtypes(P)..., (fieldtype(TI, :reference) for TI in temporals)...} + selections = map(action -> _selected_status_reference_type(action, original, edited), factory.actions) + Status{typeof(factory).parameters[1], Tuple{selections...}} + end + bound_types = map(parts.many_names, parts.many_ids) do name, ids + Value = if (index = findfirst(recipe -> recipe.input === name, parts.temporal)) !== nothing + _open_status_view_storage_type(parts.temporal[index]) + elseif (index = findfirst(isequal(name), parts.private_names)) !== nothing + typeof(parts.private_values[index]) + else + typeof(getproperty(parts.canonical_status, name)) + end + Value <: AbstractVector || error("Compiled Many input `$(name)` has non-vector runtime value `$(Value)`.") + BoundMany{eltype(Value), BoundManyObjectIds{eltype(typeof(ids)),typeof(ids)},Value} + end + BI = NamedTuple{Tuple(parts.many_names),Tuple{bound_types...}} + return CompiledModelStatusView{S,C,T,P,BI} +end +function _construct_model_status_view(::Nothing, application_id::Symbol, parts) + return _construct_prepared_model_status_view(_open_status_view_type(parts), parts) +end diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index b7890a742..6d1fa9b79 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -13,6 +13,7 @@ include("composite_model/execution_storage.jl") include("composite_model/execution_cohort_refresh.jl") include("composite_model/compilation.jl") include("composite_model/bound_many.jl") +include("composite_model/status_view_construction.jl") include("composite_model/output_targets.jl") include("composite_model/environment_bindings.jl") include("composite_model/runtime_outputs.jl") diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 373b4f621..5467e92a5 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -180,8 +180,10 @@ function _model_graph_compiled( applications, applications_by_id, input_by_target, + input_bindings, scenario_plan.application_order, - distributed_outputs, + distributed_outputs; + status_view_schema=nothing, ) many_input_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -212,6 +214,7 @@ function _model_graph_compiled( scenario_plan.call_owners, scenario_plan.application_children, status_views, + nothing, Set(application.id for application in applications), Set(keys(status_views)), false, diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl index 06008d213..91626f381 100644 --- a/test/test-model-output-retention-owners.jl +++ b/test/test-model-output-retention-owners.jl @@ -22,7 +22,7 @@ PSE.outputs_(::Reader) = (seen=0f0,) PSE.run!(::Reader, status, environment, constants, context) = (status.seen = sum(status.lag; init=0f0); nothing) -function local_scene(; temporal=false) +function local_scene(; temporal=false, status_transform=nothing) specs = (ModelSpec(Writer(); name=:writer, on=Many(scale=:Leaf), output_routing=(private=:stream_only,)),) if temporal @@ -31,12 +31,143 @@ function local_scene(; temporal=false) application=:writer, var=:private),))) end return CompositeModel(Object(0; scale=:Scene), Object(1; scale=:Leaf, parent=0); - applications=specs) + applications=specs, status_transform) end stream(simulation, application, id, variable) = simulation.temporal_streams[(application, ObjectId(id), variable)] +mutable struct ViewConstructionTrace + families::Dict{Symbol,Vector{DataType}} + views::Vector{Any} +end +ViewConstructionTrace() = ViewConstructionTrace(Dict{Symbol,Vector{DataType}}(), Any[]) +PSE._construct_model_status_view(trace::ViewConstructionTrace, application::Symbol, parts) = + PSE._construct_model_status_view(nothing, application, parts) +@inline function PSE._with_temporal_copy_payloads(f::F, ::ViewConstructionTrace, + binding, status, args::Vararg{Any,N}, +) where {F,N} + return f(nothing, binding, status, args...) +end +function PSE._admit_model_status_view!(trace::ViewConstructionTrace, application::Symbol, view) + types = get!(Vector{DataType}, trace.families, application) + typeof(view) in types || push!(types, typeof(view)) + push!(trace.views, view) + return view +end +function PSE._with_model_status_view(f::F, ::ViewConstructionTrace, application::Symbol, + view, args::Vararg{Any,N}, +) where {F,N} + return f(view, args...) +end +function construction_family_schema(trace) + ids = (:writer, :reader) + return PSE.CompiledMetadataTable(NamedTuple{ids}(map(ids) do id + Vector{Union{trace.families[id]...}}() + end)) +end +function construction_trace(; schema=ViewConstructionTrace(), prototype=nothing) + conversions = Symbol[] + transform = (variable, value) -> (push!(conversions, variable); value) + model = local_scene(; temporal=true, status_transform=transform) + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), status_view_schema=schema, + input_binding_storage=prototype) + bindings = DataType[] + snapshots = Any[] + function checkpoint!() + for binding in simulation.compiled.input_bindings + typeof(binding) in bindings || push!(bindings, typeof(binding)) + end + views = Dict(key => (type=typeof(view), status=deepcopy(NamedTuple(view.status)), + initials=map(input -> deepcopy(input.initial), view.temporal_inputs), + ids=map(input -> copy(input.binding.source_ids), view.temporal_inputs)) + for (key, view) in simulation.compiled.status_views_by_target) + for view in values(simulation.compiled.status_views_by_target), name in propertynames(view.bound_inputs) + @test getproperty(view.bound_inputs, name).values === getproperty(view.status, name) + end + push!(snapshots, (views=views, + history=Dict(key => collect(value) for (key, value) in simulation.temporal_streams))) + end + checkpoint!() + step!(simulation); checkpoint!() + step!(simulation); checkpoint!() + key = (:writer, ObjectId(1)) + private = simulation.compiled.status_views_by_target[key].private_outputs.private + register_object!(model, Object(2; scale=:Leaf, parent=0)) + step!(simulation); checkpoint!() + @test simulation.compiled.status_views_by_target[key].private_outputs.private === private + remove_object!(model, 1) + remove_object!(model, 2) + step!(simulation); checkpoint!() + register_object!(model, Object(3; scale=:Leaf, parent=0)) + step!(simulation); checkpoint!() + + # The actual constructor is also used for a partial, ephemeral target. + compiled = simulation.compiled + current = compiled.applications_by_id[:writer] + partial = PSE._partial_model_application(current, [ObjectId(3)]) + positions = Dict(id => index for (index, id) in pairs(compiled.application_order)) + target_key = (:writer, ObjectId(3)) + previous = compiled.status_views_by_target[target_key] + stamp = Ref(UInt64(0)) + prior_view_count = schema isa ViewConstructionTrace ? length(schema.views) : 0 + ephemeral = PSE._compile_model_status_view(model, partial, ObjectId(3), (), + compiled.applications_by_id, positions, compiled.distributed_outputs; + execution_stamp=stamp, status_view_schema=schema, + input_binding_storage=compiled.input_bindings) + @test ephemeral.execution_stamp === stamp + @test ephemeral.canonical_status === previous.canonical_status + @test PSE.refvalue(ephemeral.status, :live) === PSE.refvalue(previous.status, :live) + @test ephemeral.private_outputs.private isa Base.RefValue{Float32} + @test compiled.status_views_by_target[target_key] === previous + if schema isa ViewConstructionTrace + @test length(schema.views) == prior_view_count + 1 + @test last(schema.views) === ephemeral + end + return (; simulation, schema, bindings, snapshots, conversions) +end + +@testset "real view factories retain private Float32 and temporal Many through lifecycle" begin + control = construction_trace() + schema = construction_family_schema(control.schema) + prototype = Vector{Union{control.bindings...}}() + finite = construction_trace(; schema, prototype) + @test finite.snapshots == control.snapshots + @test finite.conversions == control.conversions + @test isempty(prototype) + @test all(isempty, values(schema)) + @test all(typeof(view) in control.schema.families[application] + for ((application, _), view) in finite.simulation.compiled.status_views_by_target) + + simulation = finite.simulation + compiled = simulation.compiled + reader = only(binding for binding in compiled.input_bindings + if binding.application_id === :reader) + PSE._with_temporal_copy_payloads(schema, reader, + model_status(simulation.model, 0)) do payloads, binding, status + # Each value is deliberately read through Any, as between the copies. + values = Any[2f0] + first_copy = @inferred PSE._copy_temporal_status_value(payloads, values[1]) + second_values = Any[first_copy] + second_copy = @inferred PSE._copy_temporal_status_value(payloads, second_values[1]) + @test first_copy === second_copy === 2f0 + @test_throws "outside its prepared input family" PSE._copy_temporal_status_value(payloads, 2.0) + end + previous_owner = simulation.model.binding_cache + key = (:writer, ObjectId(3)) + before = compiled.status_views_by_target[key] + invalid = PSE.CompiledMetadataTable((writer=Vector{Union{}}(),)) + positions = Dict(id => index for (index, id) in pairs(compiled.application_order)) + @test_throws "outside supported prepared application view families" PSE._compile_model_status_view( + simulation.model, compiled.applications_by_id[:writer], ObjectId(3), (), + compiled.applications_by_id, positions, compiled.distributed_outputs; + execution_stamp=before.execution_stamp, status_view_schema=invalid, + input_binding_storage=compiled.input_bindings) + @test simulation.model.binding_cache === previous_owner + @test compiled.status_views_by_target[key] === before +end + @testset "callback lookup preserves identity and missing-application diagnostics" begin simulation = run!(local_scene(); steps=0, outputs=:none) compiled = simulation.compiled diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 21812b99b..4f6ba590d 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -79,11 +79,11 @@ end end @testset "heterogeneous snapshots never convert values into the first schema" begin mixed = Any[Float32(1.25), Float64(2.5)] - result = PSE._typed_temporal_initial_values(mixed) + result = PSE._construct_status_view_initial(Vector{Any}, mixed, true) @test result === mixed @test typeof.(result) == [Float32, Float64] private = Any[Float32[1, 2], Float32[3, 4]] - typed = PSE._typed_temporal_initial_values(private) + typed = PSE._construct_status_view_initial(Vector{Vector{Float32}}, private, true) @test typed isa Vector{Vector{Float32}} @test typed[1] === private[1] @test typed[2] === private[2] @@ -138,6 +138,48 @@ end @test restored.initial[2] === 2f0 end end +# Ordinary heterogeneous support remains available outside finite preparation. +function mixed_factory_fixture() + return CompositeModel( + Object(:scene; scale=:Scene, status=Status(signals=Any[])), + Object(:a; scale=:Leaf, parent=:scene, status=Status(signal=1.25f0)), + Object(:b; scale=:Leaf, parent=:scene, status=Status(signal=2.5)); + applications=( + ModelSpec(Source(0f0); name=:source, on=Many(scale=:Leaf)), + ModelSpec(Consumer{Float64}(); name=:consumer, on=One(scale=:Scene), + inputs=(PreviousTimeStep(:signals) => Many(scale=:Leaf, + within=SceneScope(), application=:source, var=:signal),)), + ), environment=(duration=Hour(1),)) +end +@testset "mixed private reference creation keeps its explicit finite evidence gap" begin + model = mixed_factory_fixture() + simulation = run!(model; steps=0, outputs=:none) + temporal = input(simulation) + @test temporal.initial isa Vector{Any} + @test typeof.(temporal.initial) == [Float32, Float64] + @test temporal.reference[] isa PSE.ObjectRefVector + @test typeof.(temporal.reference[]) == [Float32, Float64] + for (id, reference) in zip(temporal.binding.source_ids, parent(temporal.reference[])) + @test reference !== PSE.refvalue(model_status(model, id), :signal) + end + compiled = simulation.compiled + source_types = unique(typeof(view) for ((application, _), view) in compiled.status_views_by_target + if application === :source) + schema = PSE.CompiledMetadataTable(( + source=Vector{Union{source_types...}}(), + consumer=Vector{typeof(compiled.status_views_by_target[(:consumer, ObjectId(:scene))])}(), + )) + prototype = Vector{Union{unique(typeof(binding) for binding in compiled.input_bindings)...}}() + before = model.binding_cache + @test_throws "temporal snapshot payload is outside its prepared input family" PSE._prepare_simulation!( + model; steps=0, outputs=:none, constants=PSE.Constants(), + status_view_schema=schema, input_binding_storage=prototype) + @test model.binding_cache === before + @test typeof.(temporal.initial) == [Float32, Float64] + step!(simulation) + @test final_state(simulation, :scene).total === 3.75 +end + end module PreparedPublicationChecks @@ -316,4 +358,5 @@ end @test history(current) == before_history @test rng_probe(current) == before_rng end + end From b4e4a1899cbacfd7e7e7fb59a088cf2d9fc63b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 15:13:15 +0100 Subject: [PATCH 095/324] Keep preparation metadata concrete through binding indexes --- src/composite_model/compilation.jl | 110 ++++++++++++++------ src/composite_model/runtime_outputs.jl | 2 +- src/visualization/model_graph_view.jl | 4 +- test/test-model-binding-index-identities.jl | 42 ++++++-- 4 files changed, 114 insertions(+), 44 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 04e28b7a0..21813d533 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2346,7 +2346,7 @@ end return (getfield(plan, :application_id), getfield(binding, :consumer_id)::I) end -function _index_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B,I<:ObjectId} +function _group_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B,I<:ObjectId} K = Tuple{Symbol,I} grouped = Dict{K,Vector{B}}() for binding in bindings @@ -2356,11 +2356,55 @@ function _index_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B, end push!(values, binding) end - # Membership length remains dynamic; records retain the same current/future - # family as their canonical storage, including all families in open scenes. + return grouped +end + +function _index_model_input_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B<:CompiledModelInputBinding,I<:ObjectId} + K = Tuple{Symbol,I} + grouped = _group_model_bindings(bindings, I) + # Input membership remains dynamic over its canonical current/future family. return Dict{K,Tuple{Vararg{B}}}(key => Tuple(values) for (key, values) in grouped) end +# Hard-call cardinality is fixed by each application's authored call-plan tuple. +# Admit the application before materializing the per-target binding tuple. +@generated function _index_model_call_bindings_for_application!( + application::CompiledModelApplication{P}, index, object_id::I, bindings, + ::Type{J}, +) where {P,I<:ObjectId,J<:ObjectId} + Plans = fieldtype(P, :call_plans) + Types = [CompiledModelCallBinding{Plan,I,J} for Plan in fieldtypes(Plans)] + names = [gensym(:binding) for _ in Types] + admissions = [quote + $(names[position]) = bindings[$position] + $(names[position]) isa $(Types[position]) || throw(ArgumentError( + "A hard-call binding is outside its prepared application declaration.", + )) + end for position in eachindex(Types)] + values = Expr(:tuple, [:( $(names[i])::$(Types[i]) ) for i in eachindex(Types)]...) + return quote + length(bindings) == $(length(Types)) || throw(ArgumentError( + "Hard-call binding count differs from its prepared application declaration.", + )) + $(admissions...) + index[(application.id, object_id)] = $values + return index + end +end + +function _index_model_call_bindings!(index, bindings, applications_by_id, ::Type{I}) where {I<:ObjectId} + for ((application_id, object_id), values) in _group_model_bindings(bindings, I) + Base.@inline _with_metadata_entry(_index_model_call_bindings_for_application!, + applications_by_id, application_id, index, object_id, values, I) + end + return index +end + +function _index_model_call_bindings(bindings, applications_by_id, ::Type{I}) where {I<:ObjectId} + index = Dict{Tuple{Symbol,I},Tuple{Vararg{CompiledModelCallBinding}}}() + return _index_model_call_bindings!(index, bindings, applications_by_id, I) +end + """ compile_composite_model(model[, applications...]) @@ -2572,11 +2616,11 @@ function _compile_scene( # with a concrete carrier type. Keep the per-target index type-stable # across that replacement so an updated compiled scene can be stored in # an existing `Simulation`. - input_bindings_by_target = _index_model_bindings( + input_bindings_by_target = _index_model_input_bindings( input_bindings, keytype(model.registry.objects), ) - call_bindings_by_target = _index_model_bindings( - call_bindings, keytype(model.registry.objects), + call_bindings_by_target = _index_model_call_bindings( + call_bindings, applications_by_id, keytype(model.registry.objects), ) call_owners = scenario_plan.call_owners application_children = scenario_plan.application_children @@ -3547,7 +3591,7 @@ function _preserve_recompiled_model_status_views!( previous_view = get(previous.status_views_by_target, key, nothing) isnothing(previous_view) && continue current.status_views_by_target[key] = - _preserve_model_status_view_temporal_state!( + Base.@inline _preserve_model_status_view_temporal_state!( current.status_view_schema, first(key), current_view, previous_view, previous_temporal_sources, @@ -3741,7 +3785,7 @@ function _extend_model_status_views( ) views[key] = isnothing(previous_view) ? current_view : - _preserve_model_status_view_temporal_state!( + Base.@inline _preserve_model_status_view_temporal_state!( compiled.status_view_schema, application_id, current_view, previous_view, previous_temporal_sources, @@ -3967,7 +4011,7 @@ function _prepare_structural_compiled_delta( previous_temporal_sources[key] = copy(binding.source_ids) end end - input_bindings_by_target = _index_model_bindings( + input_bindings_by_target = _index_model_input_bindings( input_bindings, keytype(model.registry.objects), ) @@ -3990,8 +4034,8 @@ function _prepare_structural_compiled_delta( (binding.application_id, binding.consumer_id), ) end - call_bindings_by_target = _index_model_bindings( - call_bindings, keytype(model.registry.objects), + call_bindings_by_target = _index_model_call_bindings( + call_bindings, compiled.applications_by_id, keytype(model.registry.objects), ) many_input_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -4179,8 +4223,8 @@ function _refresh_scene_call_bindings!( by_object=applications_by_object, plans_by_application=compiled.scenario_plan.call_plans_by_application, ) - replacement_call_bindings_by_target = _index_model_bindings( - replacement_call_bindings, keytype(model.registry.objects), + replacement_call_bindings_by_target = _index_model_call_bindings( + replacement_call_bindings, applications_by_id, keytype(model.registry.objects), ) call_bindings = compiled.call_bindings for key in rebuilt_existing_call_targets @@ -4735,11 +4779,9 @@ function _extend_compiled_scene( started_at, ) call_bindings_by_target = compiled.call_bindings_by_target - isempty(new_call_bindings) || merge!( - call_bindings_by_target, - _index_model_bindings( - new_call_bindings, keytype(model.registry.objects), - ), + isempty(new_call_bindings) || _index_model_call_bindings!( + call_bindings_by_target, new_call_bindings, applications_by_id, + keytype(model.registry.objects), ) call_owners = compiled.scenario_plan.call_owners application_children = compiled.scenario_plan.application_children @@ -6358,12 +6400,13 @@ end function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId) object = _model_object(model, object_id) - isnothing(object.status) && _replace_model_object_status!(model, object, Status()) - object.status isa Status || error( + status = object.status + isnothing(status) && (status = _replace_model_object_status!(model, object, Status())) + status isa Status || error( "Model object `$(object_id.value)` uses model applications but its status has type ", - "`$(typeof(object.status))`. Use `Status(...)` or leave status as `nothing`." + "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." ) - return object.status + return Base.@inline _with_registered_status(identity, model.registry.objects.catalog, status) end function _prepare_model_output_statuses!(model::CompositeModel, applications) @@ -7202,10 +7245,10 @@ function _prepare_model_input_statuses_batched!( ) recipes = Dict{ObjectId,_CanonicalStatusRecipe}() recipe_order = ObjectId[] - conversion_records = _no_status_conversion(model.status_conversion) ? - model.status_conversion_records : - Dict{Any,Any}() - default_status_updates = Dict{Tuple{ObjectId,Symbol},Bool}() + record_conversions = !_no_status_conversion(model.status_conversion) + conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records + I = keytype(model.registry.objects) + default_status_updates = Dict{Tuple{I,Symbol},Bool}() input_default_rewrites_avoided = 0 for partial in applications input_default_rewrites_avoided += _with_model_application(applications_by_id, partial) do application @@ -7332,8 +7375,7 @@ function _prepare_model_input_statuses_batched!( recipe_order; performance=performance, ) - conversion_records === model.status_conversion_records || - merge!(model.status_conversion_records, conversion_records) + record_conversions && merge!(model.status_conversion_records, conversion_records) for ((object_id, variable), is_default) in default_status_updates variables = get!( model.input_default_status_variables, @@ -8599,7 +8641,8 @@ end function _validate_model_required_inputs!(model::CompositeModel, applications, applications_by_id, input_bindings) bound = _bound_model_inputs(input_bindings) - missing = NamedTuple[] + I = keytype(model.registry.objects) + missing = NamedTuple{(:application_id, :object_id, :input),Tuple{Symbol,I,Symbol}}[] for partial in applications _with_model_application(applications_by_id, partial) do application schema = _model_input_schema(application) @@ -8613,9 +8656,8 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a missing, ( application_id=application.id, - object_id=object_id.value, + object_id=_index_object_id(model.registry.objects, object_id), input=input, - process=application.process, ), ) end @@ -8626,7 +8668,7 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a isempty(missing) && return nothing details = join( [ - "`$(row.application_id)` on object `$(row.object_id)` requires `$(row.input)`" + "`$(row.application_id)` on object `$(row.object_id.value)` requires `$(row.input)`" for row in missing ], "; ", @@ -8693,7 +8735,7 @@ end # Consume metadata inside its exact schema branch. Runtime Symbols select # identities; integer keys select positions local to this owner, never model slots. -@generated function _with_metadata_entry(f, table::CompiledMetadataTable{T}, key::K, args::Vararg{Any,N}) where {T,K<:Union{Symbol,Integer},N} +@generated function _with_metadata_entry(f::F, table::CompiledMetadataTable{T}, key::K, args::Vararg{Any,N}) where {F,T,K<:Union{Symbol,Integer},N} entry_keys = K <: Symbol ? fieldnames(T) : ntuple(identity, fieldcount(T)) branches = [:(key == $(QuoteNode(entry_key)) && return f(getfield(getfield(table, :entries), $index), args...)) @@ -8708,7 +8750,7 @@ end # Execution plans already have a typed tuple boundary; its callback uses the # same scalar-entry operation as fixed metadata owners. Never unwrap an owner # into a tuple to enter this method. -@generated function _with_metadata_entry(f, entries::T, key::K, args::Vararg{Any,N}) where {T<:Tuple,K<:Integer,N} +@generated function _with_metadata_entry(f::F, entries::T, key::K, args::Vararg{Any,N}) where {F,T<:Tuple,K<:Integer,N} branches = [:(key == $index && return f(getfield(entries, $index), args...)) for index in 1:fieldcount(T)] return quote diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 333fc7a2b..63b5525c6 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6057,7 +6057,7 @@ function _prepare_targeted_newborn_targets( return nothing end - targeted_input_bindings = _index_model_bindings( + targeted_input_bindings = _index_model_input_bindings( input_bindings, keytype(model.registry.objects), ) diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 5467e92a5..9a40da82e 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -159,8 +159,8 @@ function _model_graph_compiled( ) isempty(diagnostics) || return nothing applications_by_id = _applications_by_id(applications) - input_by_target = _index_model_bindings(input_bindings, keytype(model.registry.objects)) - call_by_target = _index_model_bindings(call_bindings, keytype(model.registry.objects)) + input_by_target = _index_model_input_bindings(input_bindings, keytype(model.registry.objects)) + call_by_target = _index_model_call_bindings(call_bindings, applications_by_id, keytype(model.registry.objects)) timeline = _model_timeline(model) scenario_plan = _compiled_scenario_plan( model, diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 77c6ecffc..4130951ae 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -75,11 +75,16 @@ function call_fixture(closed) return (; model, simulation, capture, context=target.context) end -function check_index(model, bindings, index) +rebuild_index(compiled, bindings::AbstractVector{<:PSE.CompiledModelInputBinding}, I) = + PSE._index_model_input_bindings(bindings, I) +rebuild_index(compiled, bindings::AbstractVector{<:PSE.CompiledModelCallBinding}, I) = + PSE._index_model_call_bindings(bindings, compiled.applications_by_id, I) + +function check_index(model, compiled, bindings, index) I = keytype(model.registry.objects) @test keytype(index) === Tuple{Symbol,I} @test valtype(index) === Tuple{Vararg{eltype(bindings)}} - rebuilt = PSE._index_model_bindings(bindings, I) + rebuilt = rebuild_index(compiled, bindings, I) @test keytype(rebuilt) === Tuple{Symbol,I} @test valtype(rebuilt) === Tuple{Vararg{eltype(bindings)}} @test Set(keys(rebuilt)) == Set(keys(index)) @@ -90,7 +95,7 @@ function check_index(model, bindings, index) @test index[key] === expected @test all(PSE._model_binding_target_key(binding, I) === key for binding in values) end - empty_index = PSE._index_model_bindings(empty(bindings), I) + empty_index = rebuild_index(compiled, empty(bindings), I) @test isempty(empty_index) @test keytype(empty_index) === Tuple{Symbol,I} @test valtype(empty_index) === Tuple{Vararg{eltype(bindings)}} @@ -99,8 +104,8 @@ end function check_indexes(model, simulation) compiled = simulation.compiled - check_index(model, compiled.input_bindings, compiled.input_bindings_by_target) - check_index(model, compiled.call_bindings, compiled.call_bindings_by_target) + check_index(model, compiled, compiled.input_bindings, compiled.input_bindings_by_target) + check_index(model, compiled, compiled.call_bindings, compiled.call_bindings_by_target) end @testset "binding indexes keep registry identities for cold and observed calls" begin @@ -115,8 +120,8 @@ end @test simulation.compiled.call_bindings_by_target[(:capture, ObjectId(:root))] === Tuple(bindings) repeated = [bindings; first(bindings)] - @test PSE._index_model_bindings(repeated, I)[(:capture, ObjectId(:root))] === - Tuple(repeated) + @test_throws "Hard-call binding count differs from its prepared application declaration" PSE._index_model_call_bindings( + repeated, simulation.compiled.applications_by_id, I) @test_throws TypeError PSE._model_binding_target_key(first(bindings), ObjectId{String}) one = call_targets(data.context, :one) many = call_targets(data.context, :many) @@ -632,4 +637,27 @@ PSE.EnvironmentAPI.bind_environment(::GeometryOwnerBackend, object::Object, cont end end +@testset "missing input diagnostics preserve numeric and named object identities" begin + for closed in (false, true) + model = CompositeModel( + Object(:root; scale=:Plant), + Object(1; scale=:Leaf, parent=:root, + status=Status(values=Float64[], total=0.0)), + Object(:feuille; scale=:Leaf, parent=:root, + status=Status(values=Float64[], total=0.0)); + applications=(ModelSpec(Reader(); name=:reader, on=Many(scale=:Leaf)),)) + closed && (model = close_registry(model)) + error = try + run!(model; steps=0, outputs=:none) + nothing + catch exception + exception + end + @test error isa ErrorException + message = sprint(showerror, error) + @test occursin("`reader` on object `1` requires `single`", message) + @test occursin("`reader` on object `feuille` requires `single`", message) + end +end + end From 642ef32dbe13ce93084bdee037f2415b75d0d70b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 15:38:57 +0100 Subject: [PATCH 096/324] Admit lifecycle views and status recipes at typed boundaries --- src/composite_model/compilation.jl | 101 +++++++++++++---------- src/composite_model/registry_topology.jl | 5 +- 2 files changed, 61 insertions(+), 45 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 21813d533..84b55d806 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1675,25 +1675,33 @@ function _model_status_view_family_types(V) return families end -@generated function _with_model_status_view_family(prototype::AbstractVector{V}, f::F, - view, args::Vararg{Any,N}, -) where {V,F,N} - families = _model_status_view_family_types(V) - branches = [:(view isa $T && return f(view::$T, args...)) for T in families] +# Select the application and its exact view in one generated boundary. The raw +# Any-valued dictionary payload never crosses another metadata callback first. +@generated function _with_model_status_view(f::F, schema::CompiledMetadataTable{T}, + application_id::Symbol, view, args::Vararg{Any,N}, +) where {F,T,N} + branches = Expr[] + for (index, application) in enumerate(fieldnames(T)) + Prototype = fieldtype(T, index) + Prototype <: AbstractVector || throw(ArgumentError( + "Status view family prototypes require vector storage.")) + families = _model_status_view_family_types(eltype(Prototype)) + admitted = [:(view isa $V && return f(view::$V, args...)) for V in families] + push!(branches, quote + if application_id === $(QuoteNode(application)) + prototype = getfield(getfield(schema, :entries), $index) + isempty(prototype) || throw(ArgumentError("Status view family prototypes must be empty.")) + $(admitted...) + throw(ArgumentError("The status view is outside its prepared application family.")) + end + end) + end return quote - isempty(prototype) || throw(ArgumentError("Status view family prototypes must be empty.")) $(branches...) - throw(ArgumentError("The status view is outside its prepared application family.")) + throw(KeyError(application_id)) end end -@inline function _with_model_status_view(f::F, schema::CompiledMetadataTable, - application_id::Symbol, view, args::Vararg{Any,N}, -) where {F,N} - return Base.@inline _with_metadata_entry(_with_model_status_view_family, - schema, application_id, f, view, args...) -end - # This hook is also called for newly constructed ephemeral/private views. @inline _admit_model_status_view!(schema, application_id::Symbol, view) = Base.@inline _with_model_status_view(identity, schema, application_id, view) @@ -4717,7 +4725,8 @@ function _extend_compiled_scene( added_applications else rewired_applications = copy(added_applications) - targets_by_application = Dict{Symbol,Vector{ObjectId}}() + I = keytype(model.registry.objects) + targets_by_application = Dict{Symbol,Vector{I}}() for raw_id in rewired_consumer_ids object_id = _index_object_id(model.registry.objects, raw_id) _foreach_object_application(compiled, object_id) do application @@ -4725,7 +4734,7 @@ function _extend_compiled_scene( get!( targets_by_application, application.id, - ObjectId[], + I[], ), object_id, ) @@ -6210,9 +6219,10 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end -# Private application views do not become canonical registry rows. Keep their -# construction independent of the canonical ownership/admission catalog. -function _finish_status_recipe(f, cache, recipe::_CanonicalStatusRecipe) +# Open canonical construction discovers the reference layout in the same cache. +function _finish_canonical_status_recipe(f::Callback, ::OpenObjectFamilyCatalog, + cache, recipe::_CanonicalStatusRecipe, +) where {Callback} recipe.changed || return f(recipe.original) original = recipe.original existing_names = isnothing(original) ? () : propertynames(original) @@ -6225,15 +6235,16 @@ function _finish_status_recipe(f, cache, recipe::_CanonicalStatusRecipe) return f(_construct_status(construction, existing_references, Tuple(recipe.edit_references))) end -function _finish_canonical_status_recipe(f, model::CompositeModel, recipe::_CanonicalStatusRecipe) - return _finish_canonical_status_recipe(f, model.registry.objects.catalog, +function _finish_canonical_status_recipe(f::Callback, model::CompositeModel, + recipe::_CanonicalStatusRecipe, +) where {Callback} + return Base.@inline _finish_canonical_status_recipe(f, model.registry.objects.catalog, model.registry.objects.layout_cache, recipe) end -_finish_canonical_status_recipe(f, ::OpenObjectFamilyCatalog, cache, recipe::_CanonicalStatusRecipe) = - _finish_status_recipe(f, cache, recipe) - -function _finish_canonical_status_recipe(f, catalog::ClosedObjectFamilyCatalog, cache, recipe::_CanonicalStatusRecipe) +function _finish_canonical_status_recipe(f::Callback, catalog::ClosedObjectFamilyCatalog, + cache, recipe::_CanonicalStatusRecipe, +) where {Callback} return _with_registered_status(catalog, recipe.original) do original recipe.changed || return f(original) _finish_admitted_status_recipe(f, catalog, original, recipe.edit_names, recipe.edit_references) @@ -6258,7 +6269,7 @@ end # Select and consume actual references in the exact branch. Result schema # alternatives never escape as a large union before registration/view creation. -@generated function _finish_admitted_status_recipe(f, ::ClosedObjectFamilyCatalog{F}, original::S, edit_names, edit_references) where {F,S} +@generated function _finish_admitted_status_recipe(f::Callback, ::ClosedObjectFamilyCatalog{F}, original::S, edit_names, edit_references) where {Callback,F,S} original_names = _status_schema_names(S) results = unique(family.parameters[2] for family in fieldtypes(F) if family.parameters[2] <: Status) branches = Expr[] @@ -6302,11 +6313,12 @@ function _model_object_status_for_preparation( end function _status_recipe_for_object!( - recipes::Dict{ObjectId,_CanonicalStatusRecipe}, - recipe_order::Vector{ObjectId}, + recipes::AbstractDict{I,_CanonicalStatusRecipe}, + recipe_order::AbstractVector{I}, model::CompositeModel, object_id::ObjectId, -) +) where {I<:ObjectId} + object_id = _index_object_id(recipes, object_id) return get!(recipes, object_id) do status = _model_object_status_for_preparation(model, object_id) push!(recipe_order, object_id) @@ -6315,11 +6327,12 @@ function _status_recipe_for_object!( end function _status_preparation_for_object!( - recipes::Dict{ObjectId,_CanonicalStatusRecipe}, - recipe_order::Vector{ObjectId}, + recipes::AbstractDict{I,_CanonicalStatusRecipe}, + recipe_order::AbstractVector{I}, model::CompositeModel, object_id::ObjectId, -) +) where {I<:ObjectId} + object_id = _index_object_id(recipes, object_id) recipe = get(recipes, object_id, nothing) isnothing(recipe) || return recipe status = _model_object_status_for_preparation(model, object_id) @@ -6331,10 +6344,10 @@ end function _apply_status_recipes!( model::CompositeModel, - recipes::Dict{ObjectId,_CanonicalStatusRecipe}, - recipe_order::Vector{ObjectId}; + recipes::AbstractDict{I,_CanonicalStatusRecipe}, + recipe_order::AbstractVector{I}; performance=nothing, -) +) where {I<:ObjectId} for object_id in recipe_order recipe = recipes[object_id] recipe.changed || continue @@ -6438,8 +6451,9 @@ function _prepare_model_output_statuses_batched!( applications; performance=nothing, ) - recipes = Dict{ObjectId,_CanonicalStatusRecipe}() - recipe_order = ObjectId[] + I = keytype(model.registry.objects) + recipes = Dict{I,_CanonicalStatusRecipe}() + recipe_order = I[] conversion_records = _no_status_conversion(model.status_conversion) ? model.status_conversion_records : Dict{Any,Any}() @@ -6560,8 +6574,9 @@ function _prepare_model_output_destination_statuses!( model::CompositeModel, resolved_destinations, ) - recipes = Dict{ObjectId,_CanonicalStatusRecipe}() - recipe_order = ObjectId[] + I = keytype(model.registry.objects) + recipes = Dict{I,_CanonicalStatusRecipe}() + recipe_order = I[] records_before = copy(model.status_conversion_records) try for resolved in resolved_destinations @@ -7243,15 +7258,15 @@ function _prepare_model_input_statuses_batched!( final_references=nothing, performance=nothing, ) - recipes = Dict{ObjectId,_CanonicalStatusRecipe}() - recipe_order = ObjectId[] + I = keytype(model.registry.objects) + recipes = Dict{I,_CanonicalStatusRecipe}() + recipe_order = I[] record_conversions = !_no_status_conversion(model.status_conversion) conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records - I = keytype(model.registry.objects) default_status_updates = Dict{Tuple{I,Symbol},Bool}() input_default_rewrites_avoided = 0 for partial in applications - input_default_rewrites_avoided += _with_model_application(applications_by_id, partial) do application + input_default_rewrites_avoided += Base.@inline _with_model_application(applications_by_id, partial) do application rewrites_avoided = 0 schema = _model_input_schema(application) defaults = _input_default_values(schema) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index b2bc0682c..7f1d77e5e 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1110,10 +1110,11 @@ function _replace_model_object_status!( ) object.status === status && return status store = model.registry.objects + object_id = object.id::keytype(store) return _with_registered_status(store.catalog, status) do admitted - _store_object_family_row!(store, object, object.id::keytype(store), admitted) + _store_object_family_row!(store, object, object_id, admitted) setfield!(object, :status, admitted) - _set_status_source_identity!(model, object.id, admitted) + _set_status_source_identity!(model, object_id, admitted) return admitted end end From a2b211294be3dee53490260ea926e8fdd34223b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 16:13:54 +0100 Subject: [PATCH 097/324] Preserve typed temporal views and stage growth before mutation --- src/composite_model/bound_many.jl | 15 -- src/composite_model/compilation.jl | 258 +++++++++++---------- test/test-model-temporal-initial-typing.jl | 47 ++++ 3 files changed, 179 insertions(+), 141 deletions(-) diff --git a/src/composite_model/bound_many.jl b/src/composite_model/bound_many.jl index 0ef02cb8a..834f4d581 100644 --- a/src/composite_model/bound_many.jl +++ b/src/composite_model/bound_many.jl @@ -119,18 +119,3 @@ end value, _bound_many_object_position(values, object_id), ) - -_rebind_compiled_bound_many_inputs(::NamedTuple{()}, ::Status) = NamedTuple() - -function _rebind_compiled_bound_many_inputs( - bound_inputs::NamedTuple, - status::Status, -) - names = propertynames(bound_inputs) - values = ntuple(length(names)) do index - name = names[index] - current = getproperty(bound_inputs, name) - _compiled_bound_many(current.ids.ids, getproperty(status, name)) - end - return NamedTuple{names}(values) -end diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 84b55d806..30fc2e831 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3487,74 +3487,63 @@ function _preserve_temporal_input_state!( ) end -function _preserve_model_status_view_temporal_state!( - current::CompiledModelStatusView, - previous::CompiledModelStatusView, - previous_temporal_sources, - key, -) - previous_by_input = Dict( - temporal_input.binding.input => temporal_input - for temporal_input in previous.temporal_inputs - ) - temporal_inputs = Tuple(begin - previous_input = get( - previous_by_input, - temporal_input.binding.input, - nothing, - ) - if isnothing(previous_input) - temporal_input +# Current and previous views have already crossed their application-family +# admission. Their names/positions are metadata; values still use one worker. +@generated function _preserve_model_status_view_temporal_state!( + current::CV, previous::PV, previous_temporal_sources, key, +) where {CV<:CompiledModelStatusView,PV<:CompiledModelStatusView} + CT, PT = fieldtype(CV, :temporal_inputs), fieldtype(PV, :temporal_inputs) + CP, PP = fieldtype(CV, :private_outputs), fieldtype(PV, :private_outputs) + input_name(TI) = fieldtype(fieldtype(fieldtype(TI, :binding), :plan), :route).parameters[1] + current_names = map(input_name, fieldtypes(CT)) + previous_names = map(input_name, fieldtypes(PT)) + temporal = Expr(:tuple) + for (index, name) in enumerate(current_names) + previous_index = findlast(isequal(name), previous_names) + current_input = :(getfield(current.temporal_inputs, $index)) + if isnothing(previous_index) + push!(temporal.args, current_input) else - previous_source_ids = get( - previous_temporal_sources, - (key..., temporal_input.binding.input), - previous_input.binding.source_ids, - ) - _preserve_temporal_input_state!( - temporal_input, - previous_input, - previous_source_ids, - ) - end - end for temporal_input in current.temporal_inputs) - temporal_by_name = Dict( - temporal_input.binding.input => temporal_input - for temporal_input in temporal_inputs - ) - private_output_names = propertynames(current.private_outputs) - private_output_references = ntuple( - index -> begin - name = private_output_names[index] - return hasproperty(previous.private_outputs, name) ? - getproperty(previous.private_outputs, name) : - getproperty(current.private_outputs, name) - end, - length(private_output_names), - ) - private_outputs = - NamedTuple{private_output_names}(private_output_references) - names = propertynames(current.status) - references = ntuple(length(names)) do index - name = names[index] - temporal_input = get(temporal_by_name, name, nothing) - isnothing(temporal_input) || return temporal_input.reference - hasproperty(private_outputs, name) && - return getproperty(private_outputs, name) - return refvalue(current.canonical_status, name) - end - status = Status(NamedTuple{names}(references)) - return CompiledModelStatusView( - previous.execution_stamp, - status, - current.canonical_status, - temporal_inputs, - private_outputs, - _rebind_compiled_bound_many_inputs( - current.bound_inputs, - status, - ), - ) + previous_input = :(getfield(previous.temporal_inputs, $previous_index)) + previous_ids = :(get(previous_temporal_sources, (key..., $(QuoteNode(name))), + getfield(getfield($previous_input, :binding), :source_ids))) + push!(temporal.args, :(_preserve_temporal_input_state!( + $current_input, $previous_input, $previous_ids))) + end + end + private_names = fieldnames(CP) + private_types = map(private_names) do name + fieldtype(name in fieldnames(PP) ? PP : CP, name) + end + private = Expr(:tuple, [name in fieldnames(PP) ? + :(getfield(previous.private_outputs, $(QuoteNode(name)))) : + :(getfield(current.private_outputs, $(QuoteNode(name)))) for name in private_names]...) + Private = NamedTuple{private_names,Tuple{private_types...}} + C = fieldtype(CV, :canonical_status) + edited_types = Tuple{private_types..., (fieldtype(TI, :reference) for TI in fieldtypes(CT))...} + edited_names = (private_names..., current_names...) + construction = StatusConstructionRecipe(_status_schema_names(C), edited_names) + selected = map(construction.actions) do action + _selected_status_reference_type(action, _status_schema_references(C), edited_types) + end + Result = Status{_status_schema_names(fieldtype(CV, :status)),Tuple{selected...}} + factory = ExactReferenceFactory(C, edited_types, Result, edited_names) + edited = Expr(:tuple, + [:(getfield(private_outputs, $index)) for index in eachindex(private_names)]..., + [:(getfield(getfield(temporal_inputs, $index), :reference)) for index in 1:fieldcount(CT)]...) + BI = fieldtype(CV, :bound_inputs) + bound_names = fieldnames(BI) + bound = Expr(:tuple, [:(_compiled_bound_many( + getfield(current.bound_inputs, $(QuoteNode(name))).ids.ids, + getproperty(status, $(QuoteNode(name))))) for name in bound_names]...) + return quote + temporal_inputs = $temporal + private_outputs = $Private($private) + status = _construct_status($(QuoteNode(factory)), current.canonical_status, $edited) + bound_inputs = NamedTuple{$(QuoteNode(bound_names))}($bound) + return CompiledModelStatusView(previous.execution_stamp, status, + current.canonical_status, temporal_inputs, private_outputs, bound_inputs) + end end function _preserve_model_status_view_with_previous!(previous, schema, application_id, @@ -3580,6 +3569,11 @@ function _record_previous_temporal_source!(input::CompiledTemporalInput, sources return nothing end +function _previous_temporal_source_storage(model::CompositeModel) + I = keytype(model.registry.objects) + return Dict{Tuple{Symbol,I,Symbol},Vector{I}}() +end + function _record_previous_temporal_sources!(view::CompiledModelStatusView, sources, key) for index in eachindex(view.temporal_inputs) Base.@inline _with_metadata_entry(_record_previous_temporal_source!, @@ -3592,7 +3586,7 @@ function _preserve_recompiled_model_status_views!( current::CompiledCompositeModel, previous::CompiledCompositeModel, ) - previous_temporal_sources = Dict{Tuple{Symbol,ObjectId,Symbol},Vector{ObjectId}}() + previous_temporal_sources = _previous_temporal_source_storage(current.model) for ((application_id, raw_id), current_view) in current.status_views_by_target object_id = _index_object_id(current.model.registry.objects, raw_id) key = (application_id, object_id) @@ -3675,48 +3669,53 @@ function _stage_temporal_many_extension( ) end -function _extend_temporal_many_inputs_in_place!( - view::CompiledModelStatusView, - model::CompositeModel, - key, - previous_temporal_sources, - applications_by_id, - application_positions, - distributed_outputs, +_stage_temporal_many_extensions(::Tuple{}, model, key, sources, applications, positions, distributed) = () + +function _stage_temporal_many_extensions(inputs::Tuple, model, key, sources, + applications, positions, distributed, ) - staged = Any[] - for temporal_input in view.temporal_inputs - previous_source_ids = get( - previous_temporal_sources, - (key..., temporal_input.binding.input), - nothing, - ) - isnothing(previous_source_ids) && continue + temporal_input = first(inputs) + previous_source_ids = get(sources, (key..., temporal_input.binding.input), nothing) + extension = if isnothing(previous_source_ids) + nothing + else extension = _stage_temporal_many_extension( - model, - temporal_input, - previous_source_ids, - applications_by_id, - application_positions, - distributed_outputs, + model, temporal_input, previous_source_ids, applications, positions, distributed, ) - isnothing(extension) && return false - push!(staged, extension) + isnothing(extension) && return nothing + extension end - isempty(staged) && return false - for ( - initial, - storage_references, - source_applications, - new_initial, - new_storage_references, - new_source_applications, - ) in staged - append!(initial, new_initial) - append!(storage_references, new_storage_references) - append!(source_applications, new_source_applications) + following = _stage_temporal_many_extensions(Base.tail(inputs), model, key, + sources, applications, positions, distributed) + isnothing(following) && return nothing + return (extension, following...) +end + +_apply_temporal_many_extensions!(::Tuple{}) = false +function _apply_temporal_many_extensions!(staged::Tuple) + extension = first(staged) + if !isnothing(extension) + initial, storage_references, source_applications, + new_initial, new_storage_references, new_source_applications = extension + # Staging has already checked compatibility; keep those types visible + # while appending without allocating another copy of the staged values. + T, R, A = eltype(initial), eltype(storage_references), eltype(source_applications) + append!(initial, (value::T for value in new_initial)) + append!(storage_references, (reference::R for reference in new_storage_references)) + append!(source_applications, (application::A for application in new_source_applications)) end - return true + following_applied = _apply_temporal_many_extensions!(Base.tail(staged)) + return !isnothing(extension) || following_applied +end + +function _extend_temporal_many_inputs_in_place!(view::CompiledModelStatusView, + model::CompositeModel, key, previous_temporal_sources, applications_by_id, + application_positions, distributed_outputs, +) + staged = _stage_temporal_many_extensions(view.temporal_inputs, model, key, + previous_temporal_sources, applications_by_id, application_positions, distributed_outputs) + isnothing(staged) && return false + return _apply_temporal_many_extensions!(staged) end function _extend_model_status_views( @@ -4006,10 +4005,7 @@ function _prepare_structural_compiled_delta( push!(input_bindings, binding) end forced_input_binding_keys = Set{Tuple{Symbol,ObjectId,Symbol}}() - previous_temporal_sources = Dict{ - Tuple{Symbol,ObjectId,Symbol}, - Vector{ObjectId}, - }() + previous_temporal_sources = _previous_temporal_source_storage(model) for binding in input_bindings _sorted_object_ids_intersect_set(binding.source_ids, dirty) || continue @@ -4470,10 +4466,7 @@ function _extend_compiled_scene( forced_input_binding_keys=Set{Tuple{Symbol,ObjectId,Symbol}}(), forced_call_target_keys=Set{Tuple{Symbol,ObjectId}}(), previous_views=compiled.status_views_by_target, - previous_temporal_sources_seed=Dict{ - Tuple{Symbol,ObjectId,Symbol}, - Vector{ObjectId}, - }(), + previous_temporal_sources_seed=_previous_temporal_source_storage(model), changed_application_ids_seed=Set{Symbol}(), changed_target_ids_seed=Set{Tuple{Symbol,ObjectId}}(), pure_addition::Bool=true, @@ -8777,19 +8770,32 @@ end @inline _with_metadata_entry(f, entries::AbstractVector, key::Integer, args::Vararg{Any,N}) where {N} = f(entries[key], args...) @inline _with_metadata_entry(f, entries::AbstractDict, key::Symbol, args::Vararg{Any,N}) where {N} = f(entries[key], args...) -# Partial target selections borrow their existing target vector. Admit them -# against their current metadata owner before reading model-specific fields. -function _call_admitted_model_application(current::A, partial, f::F, args::Vararg{Any,N}) where {A<:CompiledModelApplication,F,N} - partial isa A && getfield(partial, :plan) === getfield(current, :plan) || - throw(ArgumentError("The application is outside its compiled metadata owner.")) - return f(partial::A, args...) -end - -function _with_model_application(f::F, applications_by_id, partial, args::Vararg{Any,N}) where {F,N} - return Base.@inline _with_metadata_entry( - _call_admitted_model_application, applications_by_id, partial.id, - partial, f, args..., - ) +# Partial target selections borrow their existing target vector. Admit the +# actual application and its immutable plan in one typed metadata boundary. +@generated function _with_model_application(f::F, applications_by_id::CompiledMetadataTable{T}, + partial::CompiledModelApplication, args::Vararg{Any,N}, +) where {F,T,N} + branches = Expr[] + for (index, application_id) in enumerate(fieldnames(T)) + A = fieldtype(T, index) + A <: CompiledModelApplication || throw(ArgumentError( + "Application metadata requires compiled model applications.", + )) + push!(branches, quote + if application_id === $(QuoteNode(application_id)) + current = getfield(getfield(applications_by_id, :entries), $index) + partial isa $A && getfield(partial, :plan) === getfield(current, :plan) || + throw(ArgumentError("The application is outside its compiled metadata owner.")) + return f(partial::$A, args...) + end + end) + end + return quote + plan = getfield(partial, :plan)::CompiledApplicationPlan + application_id = getfield(plan, :id)::Symbol + $(branches...) + throw(KeyError(application_id)) + end end function _foreach_object_application(f::F, compiled::CompiledCompositeModel, object_id::ObjectId) where {F} diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 4f6ba590d..b4bde8147 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -180,6 +180,53 @@ end @test final_state(simulation, :scene).total === 3.75 end + +struct PairedSource <: AbstractTyped_Initial_SourceModel end +PSE.outputs_(::PairedSource) = (a=0f0, b=0f0) +function PSE.run!(::PairedSource, status, environment, constants, context) + status.a += one(status.a) + status.b += one(status.b) + return nothing +end +struct PairedConsumer <: AbstractTyped_Initial_ConsumerModel end +PSE.inputs_(::PairedConsumer) = (first_values=Required(AbstractVector), second_values=Required(AbstractVector)) +PSE.outputs_(::PairedConsumer) = (total=0.0,) +function PSE.run!(::PairedConsumer, status, environment, constants, context) + status.total = sum(status.first_values; init=zero(status.total)) + + sum(status.second_values; init=zero(status.total)) + return nothing +end + +@testset "all temporal extensions validate before any existing snapshot grows" begin + model = CompositeModel( + Object(:scene; scale=:Scene, + status=Status(first_values=Float32[], second_values=Float32[], total=0.0)), + Object(:a; scale=:Leaf, parent=:scene, status=Status(a=2f0, b=3f0)); + applications=( + ModelSpec(PairedSource(); name=:paired_source, on=Many(scale=:Leaf)), + ModelSpec(PairedConsumer(); name=:paired_consumer, on=One(id=:scene), inputs=( + PreviousTimeStep(:first_values) => Many(scale=:Leaf, within=SceneScope(), application=:paired_source, var=:a), + PreviousTimeStep(:second_values) => Many(scale=:Leaf, within=SceneScope(), application=:paired_source, var=:b), + )), + ), environment=(duration=Hour(1),)) + simulation = run!(model; steps=1, outputs=:all) + @test final_state(simulation, :scene).total === 5.0 + first_input = first(simulation.compiled.status_views_by_target[ + (:paired_consumer, ObjectId(:scene))].temporal_inputs) + initial, values = copy(first_input.initial), collect(first_input.reference[]) + reference = first(parent(first_input.reference[])) + # The first input can extend, while the second needs a mixed carrier rebuild. + register_object!(model, Object(:b; scale=:Leaf, parent=:scene, + status=Status(a=10f0, b=20.0))) + step!(simulation) + @test first_input.initial == initial + @test collect(first_input.reference[]) == values + @test only(parent(first_input.reference[])) === reference + @test final_state(simulation, :scene).total === 37.0 + @test outputs(simulation)[(:paired_consumer, ObjectId(:scene), :total)] == + [(1.0, 5.0), (2.0, 37.0)] +end + end module PreparedPublicationChecks From c6f1dbed1d0e66784ba63d5f3ae23f8217ce2747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 17:04:55 +0100 Subject: [PATCH 098/324] Index resolved call plans and unify output status preparation --- src/composite_model/compilation.jl | 206 +++++++++--------- .../execution_batch_schemas.jl | 40 ++-- src/composite_model/runtime_outputs.jl | 2 +- src/visualization/model_graph_view.jl | 3 +- test/test-model-authored-call-plans.jl | 21 ++ test/test-model-binding-index-identities.jl | 4 +- test/test-model-hard-calls.jl | 4 +- test/test-model-status-type-lifecycle.jl | 23 ++ test/test-selector-candidate-empty-scope.jl | 78 ++++++- test/test-unified-model-object-api.jl | 2 +- 10 files changed, 250 insertions(+), 133 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 30fc2e831..a6e28d688 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -374,25 +374,27 @@ struct SelectorCandidateIndex{W,S,K,SP,I,A,R,L,C} application_target_templates::C end -function _selector_candidate_index(; application_targets::Bool=false) +function _selector_candidate_index(model::CompositeModel; application_targets::Bool=false) + I = keytype(model.registry.objects) return SelectorCandidateIndex( Int[], Dict{Symbol,Vector{Int}}(), Dict{Symbol,Vector{Int}}(), Dict{Symbol,Vector{Int}}(), - Dict{ObjectId,Vector{Int}}(), + Dict{I,Vector{Int}}(), Dict{ - Union{ObjectId,Tuple{ObjectId,Symbol,Union{Symbol,ObjectId}}}, + Union{I,Tuple{I,Symbol,Union{Symbol,I}}}, Vector{Int}, }(), - Set{ObjectId}(), - Dict{Symbol,Set{Union{Symbol,ObjectId}}}(), + Set{I}(), + Dict{Symbol,Set{Union{Symbol,I}}}(), application_targets ? Dict{Any,Any}() : nothing, ) end function _freeze_selector_candidate_index(index::SelectorCandidateIndex) - freeze(groups) = Dict(key => Tuple(values) for (key, values) in groups) + freeze(groups::AbstractDict{K}) where {K} = + Dict{K,Tuple{Vararg{Int}}}(key => Tuple(values) for (key, values) in groups) return SelectorCandidateIndex( Tuple(index.wildcard), freeze(index.by_scale), @@ -482,7 +484,11 @@ function _selector_candidate_destination( default_scope=default_scope, ) if !isnothing(anchor) + I = keytype(index.by_id) anchor_id = ObjectId(anchor) + # An out-of-family anchor cannot acquire an object in this registry. + anchor_id isa I || return nothing + anchor_id = anchor_id::I for (label, value) in ( (:id, matcher.id), (:scale, matcher.scale), @@ -525,10 +531,12 @@ function _index_selector_candidate!( for label in (:scale, :kind, :species, :id) value = getproperty(matcher, label) isnothing(value) && continue - union!( - get!(index.template_label_values, label, Set{Union{Symbol,ObjectId}}()), - _selector_candidate_values(value), - ) + I = keytype(index.by_id) + labels = get!(index.template_label_values, label, Set{Union{Symbol,I}}()) + for candidate in _selector_candidate_values(value) + candidate isa eltype(labels) || continue + push!(labels, candidate) + end end end destination = _selector_candidate_destination( @@ -544,6 +552,9 @@ function _index_selector_candidate!( push!(index.wildcard, candidate_index) else for value in values + # Selectors may name future/missing IDs, including an ID family + # that this closed registry cannot ever register. Keep them empty. + value isa keytype(groups) || continue push!(get!(groups, value, Int[]), candidate_index) tracks_application_targets && groups === index.by_scope_anchor && push!( @@ -575,16 +586,17 @@ function _union_selector_candidates!( ) union!(candidates, index.wildcard) object = _model_object(model, object_id) - id, scale, kind, species = object.id, object.scale, object.kind, object.species + id = _index_object_id(model.registry.objects, object_id) + scale, kind, species = object.scale, object.kind, object.species _union_selector_bucket!(candidates, index.by_id, id) _union_selector_bucket!(candidates, index.by_scale, scale) _union_selector_bucket!(candidates, index.by_kind, kind) _union_selector_bucket!(candidates, index.by_species, species) # Ancestors cannot contribute without any scoped selector entries. isempty(index.by_scope_anchor) && return candidates - for anchor in _object_ancestor_ids(model.registry, object_id) + for raw_anchor in _object_ancestor_ids(model.registry, id) + anchor = _index_object_id(model.registry.objects, raw_anchor) _union_selector_bucket!(candidates, index.by_scope_anchor, anchor) - id, scale, kind, species = object.id, object.scale, object.kind, object.species _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :id, id) _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :scale, scale) _union_selector_bucket!(candidates, index.by_scope_anchor, anchor, :kind, kind) @@ -594,7 +606,7 @@ function _union_selector_candidates!( end function _application_target_candidate_index(model, application_plans) - index = _selector_candidate_index(; application_targets=true) + index = _selector_candidate_index(model; application_targets=true) for plan in application_plans _index_selector_candidate!( index, @@ -1534,7 +1546,7 @@ function _compiled_scenario_plan( input_plans_by_application, _compiled_application_input_recipes(input_plans_by_application), Tuple(call_plans), - _plans_by_application(applications, call_plans), + CompiledMetadataTable(_plans_by_application(applications, call_plans)), distributed_output_plans, call_owners, manual_application_ids, @@ -2108,7 +2120,7 @@ function _index_dynamic_input_bindings( bindings, many_binding_cache, ) - index = _selector_candidate_index() + index = _selector_candidate_index(model) for (binding_index, binding) in pairs(bindings) _index_dynamic_input_binding!( index, @@ -2145,7 +2157,7 @@ function _index_dynamic_call_binding!( end function _index_dynamic_call_bindings(model::CompositeModel, bindings) - index = _selector_candidate_index() + index = _selector_candidate_index(model) for (binding_index, binding) in pairs(bindings) _index_dynamic_call_binding!( index, @@ -2374,20 +2386,21 @@ function _index_model_input_bindings(bindings::AbstractVector{B}, ::Type{I}) whe return Dict{K,Tuple{Vararg{B}}}(key => Tuple(values) for (key, values) in grouped) end -# Hard-call cardinality is fixed by each application's authored call-plan tuple. -# Admit the application before materializing the per-target binding tuple. +# Cardinality and binding types come from the actual resolved runtime plans. +# Authored declarations remain unchanged when Scope/potential callees resolve. @generated function _index_model_call_bindings_for_application!( - application::CompiledModelApplication{P}, index, object_id::I, bindings, + plans::Plans, index, application_id::Symbol, object_id::I, bindings, ::Type{J}, -) where {P,I<:ObjectId,J<:ObjectId} - Plans = fieldtype(P, :call_plans) +) where {Plans<:Tuple,I<:ObjectId,J<:ObjectId} Types = [CompiledModelCallBinding{Plan,I,J} for Plan in fieldtypes(Plans)] names = [gensym(:binding) for _ in Types] admissions = [quote $(names[position]) = bindings[$position] - $(names[position]) isa $(Types[position]) || throw(ArgumentError( - "A hard-call binding is outside its prepared application declaration.", - )) + $(names[position]) isa $(Types[position]) && + getfield($(names[position]), :plan) === getfield(plans, $position) || + throw(ArgumentError( + "A hard-call binding is outside its prepared application declaration.", + )) end for position in eachindex(Types)] values = Expr(:tuple, [:( $(names[i])::$(Types[i]) ) for i in eachindex(Types)]...) return quote @@ -2395,22 +2408,22 @@ end "Hard-call binding count differs from its prepared application declaration.", )) $(admissions...) - index[(application.id, object_id)] = $values + index[(application_id, object_id)] = $values return index end end -function _index_model_call_bindings!(index, bindings, applications_by_id, ::Type{I}) where {I<:ObjectId} +function _index_model_call_bindings!(index, bindings, plans_by_application, ::Type{I}) where {I<:ObjectId} for ((application_id, object_id), values) in _group_model_bindings(bindings, I) Base.@inline _with_metadata_entry(_index_model_call_bindings_for_application!, - applications_by_id, application_id, index, object_id, values, I) + plans_by_application, application_id, index, application_id, object_id, values, I) end return index end -function _index_model_call_bindings(bindings, applications_by_id, ::Type{I}) where {I<:ObjectId} +function _index_model_call_bindings(bindings, plans_by_application, ::Type{I}) where {I<:ObjectId} index = Dict{Tuple{Symbol,I},Tuple{Vararg{CompiledModelCallBinding}}}() - return _index_model_call_bindings!(index, bindings, applications_by_id, I) + return _index_model_call_bindings!(index, bindings, plans_by_application, I) end """ @@ -2628,7 +2641,7 @@ function _compile_scene( input_bindings, keytype(model.registry.objects), ) call_bindings_by_target = _index_model_call_bindings( - call_bindings, applications_by_id, keytype(model.registry.objects), + call_bindings, scenario_plan.call_plans_by_application, keytype(model.registry.objects), ) call_owners = scenario_plan.call_owners application_children = scenario_plan.application_children @@ -2711,20 +2724,21 @@ function _application_target_template_key( object_id::ObjectId, ) object = _model_object(model, object_id) + id = _index_object_id(model.registry.objects, object_id) scope_roots = if isempty(index.scope_roots) () else - ancestors = _object_ancestor_ids(model.registry, object_id) + ancestors = _object_ancestor_ids(model.registry, id) Tuple( - ancestor_id for ancestor_id in ancestors - if ancestor_id in index.scope_roots + _index_object_id(model.registry.objects, ancestor_id) for ancestor_id in ancestors + if _index_object_id(model.registry.objects, ancestor_id) in index.scope_roots ) end return ( _application_target_template_label(index, :scale, object.scale), _application_target_template_label(index, :kind, object.kind), _application_target_template_label(index, :species, object.species), - _application_target_template_label(index, :id, object.id), + _application_target_template_label(index, :id, id), scope_roots, ) end @@ -4039,7 +4053,7 @@ function _prepare_structural_compiled_delta( ) end call_bindings_by_target = _index_model_call_bindings( - call_bindings, compiled.applications_by_id, keytype(model.registry.objects), + call_bindings, compiled.scenario_plan.call_plans_by_application, keytype(model.registry.objects), ) many_input_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -4228,7 +4242,8 @@ function _refresh_scene_call_bindings!( plans_by_application=compiled.scenario_plan.call_plans_by_application, ) replacement_call_bindings_by_target = _index_model_call_bindings( - replacement_call_bindings, applications_by_id, keytype(model.registry.objects), + replacement_call_bindings, compiled.scenario_plan.call_plans_by_application, + keytype(model.registry.objects), ) call_bindings = compiled.call_bindings for key in rebuilt_existing_call_targets @@ -4571,15 +4586,12 @@ function _extend_compiled_scene( added_ids, compiled.scenario_plan.manual_application_ids, ) - if pure_addition - _prepare_model_output_statuses_batched!( - model, - added_applications; - performance=performance, - ) - else - _prepare_model_output_statuses!(model, added_applications) - end + _prepare_model_output_statuses!( + model, + added_applications, + applications_by_id; + performance=performance, + ) _runtime_performance_finish!( performance, :call_binding_refresh, @@ -4782,7 +4794,7 @@ function _extend_compiled_scene( ) call_bindings_by_target = compiled.call_bindings_by_target isempty(new_call_bindings) || _index_model_call_bindings!( - call_bindings_by_target, new_call_bindings, applications_by_id, + call_bindings_by_target, new_call_bindings, compiled.scenario_plan.call_plans_by_application, keytype(model.registry.objects), ) call_owners = compiled.scenario_plan.call_owners @@ -6415,83 +6427,63 @@ function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId return Base.@inline _with_registered_status(identity, model.registry.objects.catalog, status) end -function _prepare_model_output_statuses!(model::CompositeModel, applications) - for application in applications - defaults = _local_output_schema(application.spec) - for object_id in application.target_ids - status = _ensure_model_object_status!(model, object_id) - for (variable, value) in pairs(defaults) - _publish_mode_for_output(application.spec, variable) == - :canonical || continue - status = _status_with_default( - model, - status, - object_id, - variable, - value; - application_id=application.id, - origin=:model_output_default, - ) - end - _replace_model_object_status!(model, object_id, status) - end - end - return model -end - -function _prepare_model_output_statuses_batched!( +function _prepare_model_output_statuses!( model::CompositeModel, - applications; + applications, + applications_by_id; performance=nothing, ) + isempty(applications) && return model I = keytype(model.registry.objects) recipes = Dict{I,_CanonicalStatusRecipe}() recipe_order = I[] - conversion_records = _no_status_conversion(model.status_conversion) ? - model.status_conversion_records : - Dict{Any,Any}() - for application in applications - defaults = _local_output_schema(application.spec) - for object_id in application.target_ids - preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - for (variable, value) in pairs(defaults) - _publish_mode_for_output(application.spec, variable) == - :canonical || continue - if preparation isa Status - variable in propertynames(preparation) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, + record_conversions = !_no_status_conversion(model.status_conversion) + conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records + for partial in applications + Base.@inline _with_model_application(applications_by_id, partial) do application + defaults = _local_output_schema(application.spec) + for object_id in application.target_ids + preparation = _status_preparation_for_object!( + recipes, + recipe_order, + model, + object_id, + ) + for (variable, value) in pairs(defaults) + _publish_mode_for_output(application.spec, variable) == + :canonical || continue + if preparation isa Status + variable in propertynames(preparation) && continue + preparation = _status_recipe_for_object!( + recipes, + recipe_order, + model, + object_id, + ) + end + _status_recipe_add_default!( model, + preparation, object_id, + variable, + value; + application_id=application.id, + origin=:model_output_default, + conversion_records=conversion_records, ) end - _status_recipe_add_default!( - model, - preparation, - object_id, - variable, - value; - application_id=application.id, - origin=:model_output_default, - conversion_records=conversion_records, - ) end end end + # Publish each final canonical Status and its conversion records after the + # ordered defaults have all been staged, in every lifecycle mode. result = _apply_status_recipes!( model, recipes, recipe_order; performance=performance, ) - conversion_records === model.status_conversion_records || - merge!(model.status_conversion_records, conversion_records) + record_conversions && merge!(model.status_conversion_records, conversion_records) return result end @@ -6730,7 +6722,7 @@ function _compile_model_distributed_outputs( _validate_model_writer_groups!( _model_writer_groups(applications, manual_application_ids), ) - _prepare_model_output_statuses_batched!(model, applications) + _prepare_model_output_statuses!(model, applications, applications_by_id) return NoCompiledDistributedOutputs() end @@ -6757,7 +6749,7 @@ function _compile_model_distributed_outputs( # destination state behind. _validate_model_output_destination_statuses!(model, resolved) _validate_required_model_output_destinations!(model, resolved) - _prepare_model_output_statuses_batched!(model, applications) + _prepare_model_output_statuses!(model, applications, applications_by_id) _prepare_model_output_destination_statuses!(model, resolved) bindings, by_execution_target = _compile_model_output_destination_bindings(model, resolved) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 4b8d5c113..87e2841f7 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -680,21 +680,33 @@ function _execution_batch_type_with_call_schemas(::Type{B}, schemas::NamedTuple) fieldtype(B,:environment_provider),fieldtype(B,:output_publication)} end -@generated function _current_call_binding_for_application(compiled, - application::CompiledModelApplication{P}, binding::B, -) where {P,B<:CompiledModelCallBinding} - plans = fieldtype(P,:call_plans) - Plan = fieldtype(B,:plan) - index = findfirst(==(Plan),collect(fieldtypes(plans))) - isnothing(index) && return :(throw(ArgumentError("A retained call no longer has its prepared declaration."))) - CallerId = fieldtype(B,:consumer_id) - CalleeId = eltype(fieldtype(B,:callee_object_ids)) - Bindings = Tuple{[CompiledModelCallBinding{T,CallerId,CalleeId} for T in fieldtypes(plans)]...} +@generated function _current_call_binding_for_application(compiled::CS, + application::CompiledModelApplication, binding::B, +) where {CS<:CompiledCompositeModel,B<:CompiledModelCallBinding} + Owner = fieldtype(fieldtype(CS, :scenario_plan), :call_plans_by_application) + Entries = fieldtype(Owner, :entries) + Plan = fieldtype(B, :plan) + CallerId = fieldtype(B, :consumer_id) + CalleeId = eltype(fieldtype(B, :callee_object_ids)) + branches = Expr[] + for (position, application_id) in enumerate(fieldnames(Entries)) + Plans = fieldtype(Entries, position) + index = findfirst(==(Plan), fieldtypes(Plans)) + isnothing(index) && continue + Bindings = Tuple{[CompiledModelCallBinding{T,CallerId,CalleeId} for T in fieldtypes(Plans)]...} + push!(branches, quote + if application_id === $(QuoteNode(application_id)) + bindings = get(compiled.call_bindings_by_target, + (application_id, binding.consumer_id), ()) + bindings isa $Bindings || _unprepared_runtime_configuration() + return getfield(bindings::$Bindings, $index)::$B + end + end) + end return quote - bindings = get(compiled.call_bindings_by_target, - (binding.application_id,binding.consumer_id),()) - bindings isa $Bindings || _unprepared_runtime_configuration() - return getfield(bindings::$Bindings,$index)::$B + application_id = getfield(getfield(application, :plan), :id)::Symbol + $(branches...) + throw(ArgumentError("A retained call no longer has its prepared declaration.")) end end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 63b5525c6..b4def88c9 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6014,7 +6014,7 @@ function _prepare_targeted_newborn_targets( output_applications = application_set.applications applications_by_object = application_set.applications_by_object if !application_set.outputs_prepared - _prepare_model_output_statuses_batched!(model, output_applications) + _prepare_model_output_statuses!(model, output_applications, compiled.applications_by_id) application_set.outputs_prepared = true end input_bindings = similar(compiled.input_bindings, 0) diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 9a40da82e..b593847bf 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -160,7 +160,6 @@ function _model_graph_compiled( isempty(diagnostics) || return nothing applications_by_id = _applications_by_id(applications) input_by_target = _index_model_input_bindings(input_bindings, keytype(model.registry.objects)) - call_by_target = _index_model_call_bindings(call_bindings, applications_by_id, keytype(model.registry.objects)) timeline = _model_timeline(model) scenario_plan = _compiled_scenario_plan( model, @@ -171,6 +170,8 @@ function _model_graph_compiled( distributed_output_plans, timeline, ) + call_by_target = _index_model_call_bindings(call_bindings, + scenario_plan.call_plans_by_application, keytype(model.registry.objects)) ordered_applications = Tuple( applications_by_id[application_id] for application_id in scenario_plan.application_order diff --git a/test/test-model-authored-call-plans.jl b/test/test-model-authored-call-plans.jl index f76e63c4c..b8d8986c5 100644 --- a/test/test-model-authored-call-plans.jl +++ b/test/test-model-authored-call-plans.jl @@ -78,6 +78,27 @@ end resolved = only(simulation.compiled.scenario_plan.call_plans) @test resolved.matcher.scope isa PSE.CompiledNamedScope @test resolved.matcher.scope.root_id === ObjectId(:future_root) + runtime_plans = simulation.compiled.scenario_plan.call_plans_by_application + @test only(runtime_plans[:driver]) === resolved + binding = only(simulation.compiled.call_bindings) + @test binding.plan === resolved + @test PSE._current_call_binding_for_application(simulation.compiled, + simulation.compiled.applications_by_id[:driver], binding) === binding + + # Same type, different resolved scope: only the actual runtime declaration + # may own a binding, even when the current target set happens to overlap. + with_field(value, name, replacement) = typeof(value)(ntuple( + index -> fieldnames(typeof(value))[index] === name ? replacement : getfield(value, index), + fieldcount(typeof(value)))...) + foreign_scope = with_field(resolved.matcher.scope, :root_id, ObjectId(:scene)) + foreign_matcher = with_field(resolved.matcher, :scope, foreign_scope) + foreign_plan = with_field(resolved, :matcher, foreign_matcher) + foreign_binding = PSE.CompiledModelCallBinding(foreign_plan, binding.consumer_id, + binding.callee_object_ids, binding.callee_application_ids) + @test typeof(foreign_binding) === typeof(binding) + @test_throws "outside its prepared application declaration" PSE._index_model_call_bindings( + [foreign_binding], runtime_plans, keytype(data.model.registry.objects)) + @test resolved.matcher.scope.root_id === ObjectId(:future_root) @test only(recipe.call_plans).matcher.scope isa Scope @test model_status(data.model, :leaf).value === 7f0 @test model_status(data.model, :leaf).calls == 2 diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 4130951ae..1c767a317 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -78,7 +78,7 @@ end rebuild_index(compiled, bindings::AbstractVector{<:PSE.CompiledModelInputBinding}, I) = PSE._index_model_input_bindings(bindings, I) rebuild_index(compiled, bindings::AbstractVector{<:PSE.CompiledModelCallBinding}, I) = - PSE._index_model_call_bindings(bindings, compiled.applications_by_id, I) + PSE._index_model_call_bindings(bindings, compiled.scenario_plan.call_plans_by_application, I) function check_index(model, compiled, bindings, index) I = keytype(model.registry.objects) @@ -121,7 +121,7 @@ end Tuple(bindings) repeated = [bindings; first(bindings)] @test_throws "Hard-call binding count differs from its prepared application declaration" PSE._index_model_call_bindings( - repeated, simulation.compiled.applications_by_id, I) + repeated, simulation.compiled.scenario_plan.call_plans_by_application, I) @test_throws TypeError PSE._model_binding_target_key(first(bindings), ObjectId{String}) one = call_targets(data.context, :one) many = call_targets(data.context, :many) diff --git a/test/test-model-hard-calls.jl b/test/test-model-hard-calls.jl index 755759479..6494a1ea6 100644 --- a/test/test-model-hard-calls.jl +++ b/test/test-model-hard-calls.jl @@ -417,12 +417,12 @@ end plan -> plan === only( candidate for candidate in - scenario_plan.call_plans_by_application.controller + scenario_plan.call_plans_by_application[:controller] if candidate.call == plan.call ), call_plans, ) - @test isempty(scenario_plan.call_plans_by_application.leaf_calls) + @test isempty(scenario_plan.call_plans_by_application[:leaf_calls]) one_binding = only( binding for binding in simulation.compiled.call_bindings if binding.call == :one diff --git a/test/test-model-status-type-lifecycle.jl b/test/test-model-status-type-lifecycle.jl index eda2cda6a..ce6523005 100644 --- a/test/test-model-status-type-lifecycle.jl +++ b/test/test-model-status-type-lifecycle.jl @@ -522,3 +522,26 @@ end @test all(value -> value isa Float32, last.(retained_consumer_stream)) @test length(retained_consumer_stream) == 3 end + +@testset "reparented output targets stage every default before publishing" begin + model = CompositeModel( + Object(:scene; scale=:Scene), + Object(:plant_a; scale=:Plant, parent=:scene), + Object(:plant_b; scale=:Plant, parent=:scene), + Object(:late_leaf; scale=:Leaf, parent=:plant_b); + applications=(ModelSpec(StatusTypeLifecycleOutputTransactionModel(); + name=:rewired_outputs, + on=Many(scale=:Leaf, within=Scope(ObjectId(:plant_a)))),), + environment=(duration=Hour(1),), + status_transform=StatusTypeLifecycleFailOn(:failing_output), + ) + simulation = run!(model; steps=0, outputs=:none) + records = copy(model.status_conversion_records) + @test model_object(model, :late_leaf).status === nothing + + reparent_object!(model, :late_leaf, :plant_a) + @test_throws "intentional conversion failure" continue!(simulation; steps=1) + @test model_object(model, :late_leaf).parent === ObjectId(:plant_a) + @test model_object(model, :late_leaf).status === nothing + @test model.status_conversion_records == records +end diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 4241ea299..8f78cec1d 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -17,7 +17,7 @@ using Test Object(:other_leaf; scale=:Leaf, parent=:other_plant), ) leaf_id = ObjectId(:leaf) - index = PlantSimEngine._selector_candidate_index() + index = PlantSimEngine._selector_candidate_index(model) push!(index.wildcard, 1) index.by_id[leaf_id] = [2] index.by_scale[:Leaf] = [3] @@ -38,7 +38,7 @@ using Test @test result === candidates @test candidates == Set([1, 2, 3, 4, 5, 99]) end - empty_index = PlantSimEngine._selector_candidate_index() + empty_index = PlantSimEngine._selector_candidate_index(model) candidates = Set([99]) @test PlantSimEngine._union_selector_candidates!( candidates, empty_index, model, leaf_id, @@ -72,7 +72,7 @@ using Test end @testset "Missing IDs are rejected before any label or scope lookup" begin - empty_scope_index = PlantSimEngine._selector_candidate_index() + empty_scope_index = PlantSimEngine._selector_candidate_index(model) push!(empty_scope_index.wildcard, 1) for candidate_index in ( empty_scope_index, @@ -92,8 +92,24 @@ using Test end end +# Close only the actual existing fixture families. No future family is invented. +function _closed_selector_candidate_fixture(model) + previous = model.registry + registry = PlantSimEngine.ObjectRegistry( + PlantSimEngine._closed_object_family_store(previous.objects), + previous.by_scale, previous.by_kind, previous.by_species, + previous.ancestor_ids_by_object) + fields = map(fieldnames(typeof(model))) do name + name === :registry && return registry + name in (:scenario_plan_cache, :binding_cache, :environment_binding_cache) && return nothing + name in (:bindings_dirty, :environment_bindings_dirty) && return true + getfield(model, name) + end + return CompositeModel(fields...) +end + @testset "Typed selector buckets preserve numeric and mixed identities" begin - for ids in ((10, 11, 12, 13), (0, :plant, "axis", 17)) + for ids in ((10, 11, 12, 13), (0, :plant, "axis", 17)), closed in (false, true) scene_id, plant_id, axis_id, leaf_id = ids for (kind, species) in ((:photosynthetic, :rauh), (nothing, nothing)) model = CompositeModel( @@ -102,7 +118,16 @@ end Object(axis_id; scale=:Axis, parent=plant_id), Object(leaf_id; scale=:Leaf, kind, species, parent=axis_id), ) - index = PlantSimEngine._selector_candidate_index() + closed && (model = _closed_selector_candidate_fixture(model)) + @test (model.registry.objects.catalog isa PlantSimEngine.ClosedObjectFamilyCatalog) === closed + I = keytype(model.registry.objects) + index = PlantSimEngine._selector_candidate_index(model) + frozen_empty = PlantSimEngine._freeze_selector_candidate_index(index) + @test keytype(index.by_id) === keytype(frozen_empty.by_id) === I + @test keytype(index.by_scope_anchor) === keytype(frozen_empty.by_scope_anchor) === + Union{I,Tuple{I,Symbol,Union{Symbol,I}}} + @test eltype(index.scope_roots) === eltype(frozen_empty.scope_roots) === I + @test isempty(frozen_empty.by_id) && isempty(frozen_empty.by_scope_anchor) selectors = ( Many(id=leaf_id), Many(scale=(:Leaf, :Fruit)), @@ -128,6 +153,49 @@ end ) === candidates @test candidates == union(expected, Set([99])) end + + # Both reverse indexes exist BEFORE the selected future object. + # Open accepts every identity family; Closed keeps its actual union. + for raw_future in (leaf_id + 1000, :future_leaf, 1.5) + future_id = ObjectId(raw_future) + @test !haskey(model.registry.objects, future_id) + future_index = PlantSimEngine._selector_candidate_index(model) + for (slot, selector) in pairs((Many(id=raw_future), + Many(id=raw_future, within=Subtree()))) + matcher = PlantSimEngine._compile_selector_matcher(model, selector) + @test PlantSimEngine._index_selector_candidate!(future_index, model, + matcher, slot; context=ObjectId(plant_id)) === future_index + end + frozen_future = PlantSimEngine._freeze_selector_candidate_index(future_index) + for candidate_index in (future_index, frozen_future) + @test isempty(PlantSimEngine._union_selector_candidates!(Set{Int}(), + candidate_index, model, ObjectId(leaf_id))) + end + if future_id isa I + @test haskey(future_index.by_id, future_id) + @test haskey(future_index.by_scope_anchor, + (ObjectId(plant_id), :id, future_id)) + register_object!(model, Object(raw_future; scale=:Leaf, + parent=axis_id, kind, species)) + for candidate_index in (future_index, frozen_future) + candidates = Set{Int}() + @test PlantSimEngine._union_selector_candidates!(candidates, + candidate_index, model, future_id) === candidates + @test candidates == Set([1, 2]) + end + else + # This type can never be registered in the closed store. + # Its otherwise valid selector must stay an empty match. + @test closed + @test isempty(future_index.by_id) + @test isempty(future_index.by_scope_anchor) + @test isempty(future_index.wildcard) + for candidate_index in (future_index, frozen_future) + @test isempty(PlantSimEngine._union_selector_candidates!(Set{Int}(), + candidate_index, model, ObjectId(leaf_id))) + end + end + end end end end diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index a56ebb69f..3a1ba8a35 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -4303,7 +4303,7 @@ end @test initializing_growth_plan.manual_application_ids == (:dynamic_initializer,) @test only( - initializing_growth_plan.call_plans_by_application.initializing_growth, + initializing_growth_plan.call_plans_by_application[:initializing_growth], ).potential_callee_application_ids == (:dynamic_initializer,) initializing_schedule = Dict( row.application_id => row From f8f0d3a47bf4ff9fa315f85a6ffc034b78710bd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 17:31:39 +0100 Subject: [PATCH 099/324] Keep lifecycle target removal inside prepared identity families --- src/composite_model/compilation.jl | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index a6e28d688..1c538bf9f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3989,20 +3989,25 @@ function _prepare_structural_compiled_delta( performance=nothing, ) started_at = _runtime_performance_start(performance) - dirty = Set{ObjectId}(dirty_object_ids) + I = keytype(model.registry.objects) + dirty = Set{I}() + for object_id in dirty_object_ids + push!(dirty, _index_object_id(model.registry.objects, object_id)) + end removed_target_keys = Set{Tuple{Symbol,ObjectId}}() changed_application_ids = Set{Symbol}() applications_by_object = compiled.applications_by_object for object_id in dirty - for application in get(applications_by_object, object_id, ()) + _foreach_object_application(compiled, object_id) do application found, position = _sorted_object_id_position( application.target_ids, object_id, ) - found || continue + found || return nothing push!(removed_target_keys, (application.id, object_id)) push!(changed_application_ids, application.id) deleteat!(application.target_ids, position) + return nothing end end @@ -4013,7 +4018,8 @@ function _prepare_structural_compiled_delta( input_bindings = similar(compiled.input_bindings, 0) sizehint!(input_bindings, length(compiled.input_bindings)) for binding in compiled.input_bindings - if binding.consumer_id in dirty + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + if consumer_id in dirty continue end push!(input_bindings, binding) @@ -4036,8 +4042,8 @@ function _prepare_structural_compiled_delta( call_bindings = CompiledModelCallBinding[] sizehint!(call_bindings, length(compiled.call_bindings)) for binding in compiled.call_bindings - key = (binding.application_id, binding.consumer_id) - if binding.consumer_id in dirty + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + if consumer_id in dirty continue end push!(call_bindings, binding) From c66c6c6f459c5b5bbb5bdf5cd4132285936fa47b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 17:41:54 +0100 Subject: [PATCH 100/324] Derive hard-call storage from resolved plan and identity types --- src/composite_model/compilation.jl | 31 +++++++++++++++++---- test/test-model-binding-index-identities.jl | 23 ++++++++------- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1c538bf9f..49faae842 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1754,6 +1754,23 @@ function CompiledModelCallBinding( ) end +# Resolved plan types and the registry identity family determine every call +# binding, including future targets. Empty real plan tuples need no bindings. +@generated function _model_call_binding_storage( + ::P, ::Type{I}, +) where {P<:Union{NamedTuple,CompiledMetadataTable},I<:ObjectId} + T = P <: CompiledMetadataTable ? fieldtype(P, :entries) : P + families = Any[] + for Plans in fieldtypes(T), Plan in fieldtypes(Plans), CallerI in Base.uniontypes(I) + B = isconcretetype(CallerI) ? + CompiledModelCallBinding{Plan,CallerI,I} : + (CompiledModelCallBinding{Plan,C,I} where {C<:CallerI}) + push!(families, B) + end + B = isempty(families) ? Union{} : Union{families...} + return :(Vector{$B}()) +end + @inline function Base.getproperty( binding::CompiledModelCallBinding, name::Symbol, @@ -2421,8 +2438,8 @@ function _index_model_call_bindings!(index, bindings, plans_by_application, ::Ty return index end -function _index_model_call_bindings(bindings, plans_by_application, ::Type{I}) where {I<:ObjectId} - index = Dict{Tuple{Symbol,I},Tuple{Vararg{CompiledModelCallBinding}}}() +function _index_model_call_bindings(bindings::AbstractVector{B}, plans_by_application, ::Type{I}) where {B,I<:ObjectId} + index = Dict{Tuple{Symbol,I},Tuple{Vararg{B}}}() return _index_model_call_bindings!(index, bindings, plans_by_application, I) end @@ -4039,7 +4056,7 @@ function _prepare_structural_compiled_delta( input_bindings, keytype(model.registry.objects), ) - call_bindings = CompiledModelCallBinding[] + call_bindings = similar(compiled.call_bindings, 0) sizehint!(call_bindings, length(compiled.call_bindings)) for binding in compiled.call_bindings consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) @@ -4211,7 +4228,7 @@ function _refresh_scene_call_bindings!( ; by_object=applications_by_object, plans_by_application=compiled.scenario_plan.call_plans_by_application, - ) : CompiledModelCallBinding[] + ) : similar(compiled.call_bindings, 0) affected_call_applications = CompiledModelApplication[] if !isempty(rebuilt_existing_call_targets) target_ids_by_application = Dict{Symbol,Vector{ObjectId}}() @@ -4239,7 +4256,7 @@ function _refresh_scene_call_bindings!( end end replacement_call_bindings = isempty(affected_call_applications) ? - CompiledModelCallBinding[] : + similar(compiled.call_bindings, 0) : _compile_model_call_bindings( model, affected_call_applications, @@ -8925,7 +8942,9 @@ function _compile_model_call_bindings( _compile_model_call_plans(model, applications), ) end - bindings = CompiledModelCallBinding[] + bindings = _model_call_binding_storage( + plans_by_application, keytype(model.registry.objects), + ) for application in applications for consumer_id in application.target_ids for plan in _application_plans( diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 1c767a317..cc6b66063 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -75,16 +75,11 @@ function call_fixture(closed) return (; model, simulation, capture, context=target.context) end -rebuild_index(compiled, bindings::AbstractVector{<:PSE.CompiledModelInputBinding}, I) = - PSE._index_model_input_bindings(bindings, I) -rebuild_index(compiled, bindings::AbstractVector{<:PSE.CompiledModelCallBinding}, I) = - PSE._index_model_call_bindings(bindings, compiled.scenario_plan.call_plans_by_application, I) - -function check_index(model, compiled, bindings, index) +function check_index(model, compiled, bindings, index, rebuild_index) I = keytype(model.registry.objects) @test keytype(index) === Tuple{Symbol,I} @test valtype(index) === Tuple{Vararg{eltype(bindings)}} - rebuilt = rebuild_index(compiled, bindings, I) + rebuilt = rebuild_index(bindings, I) @test keytype(rebuilt) === Tuple{Symbol,I} @test valtype(rebuilt) === Tuple{Vararg{eltype(bindings)}} @test Set(keys(rebuilt)) == Set(keys(index)) @@ -95,7 +90,7 @@ function check_index(model, compiled, bindings, index) @test index[key] === expected @test all(PSE._model_binding_target_key(binding, I) === key for binding in values) end - empty_index = rebuild_index(compiled, empty(bindings), I) + empty_index = rebuild_index(empty(bindings), I) @test isempty(empty_index) @test keytype(empty_index) === Tuple{Symbol,I} @test valtype(empty_index) === Tuple{Vararg{eltype(bindings)}} @@ -104,8 +99,15 @@ end function check_indexes(model, simulation) compiled = simulation.compiled - check_index(model, compiled, compiled.input_bindings, compiled.input_bindings_by_target) - check_index(model, compiled, compiled.call_bindings, compiled.call_bindings_by_target) + check_index(model, compiled, compiled.input_bindings, compiled.input_bindings_by_target, + PSE._index_model_input_bindings) + check_index(model, compiled, compiled.call_bindings, compiled.call_bindings_by_target, + (bindings, I) -> PSE._index_model_call_bindings( + bindings, compiled.scenario_plan.call_plans_by_application, I)) + if all(isempty, values(compiled.scenario_plan.call_plans_by_application.entries)) + @test eltype(compiled.call_bindings) === Union{} + @test valtype(compiled.call_bindings_by_target) === Tuple{} + end end @testset "binding indexes keep registry identities for cold and observed calls" begin @@ -116,6 +118,7 @@ end @test I === (closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId) check_indexes(model, simulation) bindings = simulation.compiled.call_bindings + closed && @test all(isconcretetype, Base.uniontypes(eltype(bindings))) @test Tuple(binding.call for binding in bindings) == (:one, :many) @test simulation.compiled.call_bindings_by_target[(:capture, ObjectId(:root))] === Tuple(bindings) From 93eb368cb3f628269c615ba7a36b0d86a0e16c31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 17:54:24 +0100 Subject: [PATCH 101/324] Validate writer ownership through prepared application metadata --- src/composite_model/compilation.jl | 164 ++++++++++++++--------------- 1 file changed, 77 insertions(+), 87 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 49faae842..be5801086 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4603,12 +4603,7 @@ function _extend_compiled_scene( ) call_bindings = compiled.call_bindings dynamic_call_binding_indices = compiled.dynamic_call_binding_indices - _validate_model_writers_for_objects!( - applications, - applications_by_object, - added_ids, - compiled.scenario_plan.manual_application_ids, - ) + _validate_model_writers_for_objects!(compiled, added_ids) _prepare_model_output_statuses!( model, added_applications, @@ -5468,14 +5463,20 @@ function _model_environment_output_schema(application::CompiledModelApplication) return environment_outputs_(application.spec) end -function _model_writer_groups(applications, skipped_application_ids=Set{Symbol}()) - groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() - for (index, application) in pairs(applications) - application.id in skipped_application_ids && continue - for object_id in application.target_ids - for variable in _model_canonical_output_names(application) - push!(get!(groups, (object_id, variable), Tuple{Int,Any}[]), (index, application)) +function _model_writer_groups( + applications, applications_by_id, ::Type{I}, skipped_application_ids=(), +) where {I<:ObjectId} + groups = Dict{Tuple{I,Symbol},Vector{Tuple{Int,Symbol}}}() + for application in applications + Base.@inline _with_model_application(applications_by_id, application) do current + current.id in skipped_application_ids && return nothing + for object_id in current.target_ids + for variable in _model_canonical_output_names(current) + push!(get!(groups, (object_id, variable), Tuple{Int,Symbol}[]), + (current.slot, current.id)) + end end + return nothing end end return groups @@ -5511,16 +5512,13 @@ function _update_after_labels(spec, variable::Symbol) return labels end -function _updates_after_previous_writer(spec, variable::Symbol, previous_applications) +function _updates_after_previous_writer(spec, variable::Symbol, previous_application_ids) matching = _matching_updates(spec, variable) isempty(matching) && return false for update in matching after = _update_after(update) isempty(after) && continue - any( - label -> any(application -> _update_matches_application(label, application), previous_applications), - after, - ) && return true + any(label -> label in previous_application_ids, after) && return true end return false end @@ -5543,44 +5541,48 @@ function _manual_call_application_ids(call_bindings) return ids end -function _validate_model_writer_groups!(writer_groups) +function _validate_model_writer_groups!(writer_groups, applications_by_id) for ((object_id, variable), indexed_writers) in writer_groups length(indexed_writers) <= 1 && continue sort!(indexed_writers; by=first) - previous = CompiledModelApplication[] - for (_, application) in indexed_writers - if _declares_update_without_previous_writer(application.spec, variable, previous) - error( - "Application `$(application.id)` declares `Updates($(variable))` for object ", - "`$(object_id.value)`, but no previous writer for `$(variable)` exists. ", - "Move it after the producer named in `after=...`." - ) - end - if !isempty(previous) && isempty(_matching_updates(application.spec, variable)) - previous_labels = sort!(collect(reduce(union!, (_application_match_labels(app) for app in previous); init=Set{Symbol}()))) - error( - "Ambiguous canonical writers for variable `$(variable)` on object ", - "`$(object_id.value)`. ", - "applications. Application `$(application.id)` must declare ", - "`Updates(:$(variable); after=...)` matching one of the previous writers ", - "`$(previous_labels)`." - ) - end - if !isempty(previous) && - !_updates_after_previous_writer( - application.spec, - variable, - CompiledModelApplication[last(previous)], - ) - previous_writer = last(previous) - error( - "Application `$(application.id)` updates `$(variable)` on object ", - "`$(object_id.value)` without an ordering relation to the immediately ", - "previous writer `$(previous_writer.id)`. Add that application identifier ", - "to `Updates(:$(variable); after=...)`." - ) + previous = Symbol[] + for (_, application_id) in indexed_writers + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + if _declares_update_without_previous_writer(application.spec, variable, previous) + error( + "Application `$(application.id)` declares `Updates($(variable))` for object ", + "`$(object_id.value)`, but no previous writer for `$(variable)` exists. ", + "Move it after the producer named in `after=...`." + ) + end + if !isempty(previous) && isempty(_matching_updates(application.spec, variable)) + labels = Set{Symbol}() + for previous_id in previous + union!(labels, Base.@inline _with_metadata_entry( + _application_match_labels, applications_by_id, previous_id)) + end + previous_labels = sort!(collect(labels)) + error( + "Ambiguous canonical writers for variable `$(variable)` on object ", + "`$(object_id.value)`. ", + "applications. Application `$(application.id)` must declare ", + "`Updates(:$(variable); after=...)` matching one of the previous writers ", + "`$(previous_labels)`." + ) + end + if !isempty(previous) && + !_updates_after_previous_writer(application.spec, variable, (last(previous),)) + previous_writer = last(previous) + error( + "Application `$(application.id)` updates `$(variable)` on object ", + "`$(object_id.value)` without an ordering relation to the immediately ", + "previous writer `$(previous_writer)`. Add that application identifier ", + "to `Updates(:$(variable); after=...)`." + ) + end + push!(previous, application.id) + return nothing end - push!(previous, application) end end return nothing @@ -5657,7 +5659,7 @@ function _push_compiled_writer_owner!( end function _validate_compiled_writer_ownership!(ownership, applications_by_id) - groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() + groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Symbol}}}() for ((object_id, variable), owners) in ownership sort!(owners; by=owner -> owner.application_slot) seen_application_slots = Set{Int}() @@ -5674,16 +5676,16 @@ function _validate_compiled_writer_ownership!(ownership, applications_by_id) get!( groups, (object_id, variable), - Tuple{Int,Any}[], + Tuple{Int,Symbol}[], ), ( owner.application_slot, - applications_by_id[owner.application_id], + owner.application_id, ), ) end end - _validate_model_writer_groups!(groups) + _validate_model_writer_groups!(groups, applications_by_id) return ownership end @@ -5756,41 +5758,26 @@ function _validate_manual_model_output_destination_plans!( return nothing end -function _validate_model_writers!(applications, call_bindings=()) - manual_application_ids = _manual_call_application_ids(call_bindings) - return _validate_model_writer_groups!( - _model_writer_groups(applications, manual_application_ids), - ) -end - function _validate_model_writers_for_objects!( - applications, - applications_by_object, - object_ids, - manual_application_ids=(), + compiled::CompiledCompositeModel, object_ids, ) isempty(object_ids) && return nothing - positions = Dict( - application.id => index - for (index, application) in pairs(applications) - ) - groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() - for object_id in object_ids - for application in get(applications_by_object, object_id, ()) - application.id in manual_application_ids && continue + objects = compiled.model.registry.objects + I = keytype(objects) + groups = Dict{Tuple{I,Symbol},Vector{Tuple{Int,Symbol}}}() + manual_application_ids = compiled.scenario_plan.manual_application_ids + for raw_id in object_ids + object_id = _index_object_id(objects, raw_id) + _foreach_object_application(compiled, object_id) do application + application.id in manual_application_ids && return nothing for variable in _model_canonical_output_names(application) - push!( - get!( - groups, - (object_id, variable), - Tuple{Int,Any}[], - ), - (positions[application.id], application), - ) + push!(get!(groups, (object_id, variable), Tuple{Int,Symbol}[]), + (application.slot, application.id)) end + return nothing end end - return _validate_model_writer_groups!(groups) + return _validate_model_writer_groups!(groups, compiled.applications_by_id) end function _model_application_hint_scale(model::CompositeModel, target_ids::AbstractVector{<:ObjectId}) @@ -6743,7 +6730,9 @@ function _compile_model_distributed_outputs( ::NoCompiledDistributedOutputPlans, ) _validate_model_writer_groups!( - _model_writer_groups(applications, manual_application_ids), + _model_writer_groups(applications, applications_by_id, + keytype(model.registry.objects), manual_application_ids), + applications_by_id, ) _prepare_model_output_statuses!(model, applications, applications_by_id) return NoCompiledDistributedOutputs() @@ -9339,11 +9328,12 @@ function _explain_writers( compiled::CompiledCompositeModel, ::NoCompiledDistributedOutputs, ) - groups = _model_writer_groups(compiled.applications, _manual_call_application_ids(compiled)) + groups = _model_writer_groups(compiled.applications, compiled.applications_by_id, + keytype(compiled.model.registry.objects), _manual_call_application_ids(compiled)) rows = NamedTuple[] for ((object_id, variable), indexed_writers) in groups sort!(indexed_writers; by=first) - applications = [application for (_, application) in indexed_writers] + applications = [compiled.applications_by_id[id] for (_, id) in indexed_writers] push!( rows, ( From dec817344ee83d1e438fdd9385d6cb24d3063c28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 17:54:29 +0100 Subject: [PATCH 102/324] Retain exact declared port types during CompositeModel preparation --- src/composite_model/authored_ports.jl | 36 +++++++++++++++++----- test/test-model-authored-port-inventory.jl | 35 ++++++++++++++++++++- 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl index 5e530ae88..f5f157ef0 100644 --- a/src/composite_model/authored_ports.jl +++ b/src/composite_model/authored_ports.jl @@ -43,10 +43,12 @@ end Base.propertynames(::AuthoredOutputPorts) = (:all_names, :local_names, :distributed_names, :canonical_names) # One stable owner is shared by the authored recipe and compiled application. -# Name carriers preserve static schemas without retaining initialization values. -mutable struct AuthoredPortInventory{I,O,EI,EO,C} +# Name and type carriers preserve declarations without retaining initialization values. +mutable struct AuthoredPortInventory{I,O,IT,OT,EI,EO,C} const inputs::I const outputs::O + const input_types::IT + const output_types::OT const environment_inputs::EI const environment_outputs::EO const contracts::C @@ -72,8 +74,7 @@ function _capture_authored_metadata(operation, phase::Symbol, application_id::Un end end -function _authored_output_ports(spec::ModelSpec) - schema = _output_schema(spec) +function _authored_output_ports(spec::ModelSpec, schema::NamedTuple) all_names = Tuple(Symbol(name) for name in keys(schema)) local_names = Tuple(Symbol(name) for name in keys(schema) if !(schema[name] isa Distributed)) distributed_names = Tuple(Symbol(name) for name in keys(schema) if schema[name] isa Distributed) @@ -82,13 +83,31 @@ function _authored_output_ports(spec::ModelSpec) return AuthoredOutputPorts(all_names, local_names, distributed_names, canonical_names) end +# Preparation retains the exact declaration types in the existing inventory. +# Explicit Type{T} fields prevent NamedTuple construction from widening them to +# DataType/UnionAll; later factories can read the witnesses from the owner type. +function _authored_port_types(type_for, schema::NamedTuple{Names}) where {Names} + types = map(type_for, values(schema)) + fields = Tuple{map(T -> Type{T}, types)...} + return NamedTuple{Names,fields}(types) +end + function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) # This is the constructor's existing output read. A failed output hook # retains its existing top-level authoring failure and application recovery. - output_ports = _authored_output_ports(spec) + output_schema = _output_schema(spec) + output_ports = _authored_output_ports(spec, output_schema) + output_types = _authored_port_types(_output_value_type, output_schema) model = model_(spec) - inputs = _capture_authored_metadata(:input_ports, application_id) do - AuthoredPortNames(Tuple(Symbol(name) for name in keys(_input_schema(model)))) + input_metadata = _capture_authored_metadata(:input_ports, application_id) do + schema = _input_schema(model) + (AuthoredPortNames(Tuple(Symbol(name) for name in keys(schema))), + _authored_port_types(_input_expected_type, schema)) + end + inputs, input_types = if input_metadata isa ScenarioPreparationFailure + input_metadata, input_metadata + else + input_metadata end environment_inputs = _capture_authored_metadata(:environment_input_ports, application_id) do AuthoredPortNames(Tuple(Symbol(name) for name in keys(environment_inputs_(model)))) @@ -115,5 +134,6 @@ function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) _validate_variable_contract_names(spec, declared_contracts, declared) end end - return AuthoredPortInventory(inputs, output_ports, environment_inputs, environment_outputs, contracts) + return AuthoredPortInventory(inputs, output_ports, input_types, output_types, + environment_inputs, environment_outputs, contracts) end diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index 2c78f0a71..ef501961a 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -54,7 +54,7 @@ spec(model::Probe) = ModelSpec(model; name=model.key, on=Many(kind=model.key, sc outputs_to=(OutputTo(One(Self())),)) function inventory_is_value_free(value) - value isa Union{Nothing,Symbol,VariableContract} && return true + value isa Union{Nothing,Symbol,VariableContract,Type} && return true value isa Tuple && return all(inventory_is_value_free, value) value isa NamedTuple && return all(inventory_is_value_free, values(value)) value isa Union{Default,Required,Distributed,AbstractArray,Ref,AbstractModel} && return false @@ -80,6 +80,11 @@ end ports = recipe.ports @test (@inferred PSE._authored_port_names(ports.inputs)) === (input_name(process_model),) @test ports.input_names === (input_name(process_model),) + @test getproperty(ports.input_types, input_name(process_model)) === Vector{Float32} + @test fieldtype(typeof(ports.input_types), 1) === Type{Vector{Float32}} + @test getproperty(ports.output_types, output_name(process_model)) === Float32 + @test getproperty(ports.output_types, distributed_name(process_model)) === Vector{Float32} + @test fieldtypes(typeof(ports.output_types)) === (Type{Float32}, Type{Vector{Float32}}) @test ports.outputs.all_names === (output_name(process_model), distributed_name(process_model)) @test ports.outputs.local_names === (output_name(process_model),) @test ports.outputs.distributed_names === (distributed_name(process_model),) @@ -226,6 +231,34 @@ function PSE.variable_contracts_(model::Ordered) end PSE.run!(::Ordered, status, environment, constants, context) = nothing +@testset "constructor retains future application types before targets exist" begin + calls = Ref(0) + model = CompositeModel(Object(:scene; scale=:Scene); applications=( + ModelSpec(Ordered(calls); name=:future_reader, on=Many(scale=:FutureLeaf)), + )) + ports = only(model.scenario_plan_cache.authored).ports + @test values(ports.input_types) === (Float32, Float32) + @test fieldtypes(typeof(ports.input_types)) === (Type{Float32}, Type{Float32}) + @test values(ports.output_types) === (Float32,) + @test fieldtypes(typeof(ports.output_types)) === (Type{Float32},) + @test calls[] == 1 + @test isnothing(model_status(model, :scene)) + @test inventory_is_value_free(ports) + for seed in (1f0, 1.0) + future = Probe(:future, Ref(hook_zero), Ref(seed)) + future_model = CompositeModel(Object(:scene; scale=:Scene); + applications=(spec(future),)) + future_ports = only(future_model.scenario_plan_cache.authored).ports + T = typeof(seed) + @test future_ports.input_types.buffer_future === Vector{T} + @test fieldtypes(typeof(future_ports.input_types)) === (Type{Vector{T}},) + @test values(future_ports.output_types) === (Float32, Vector{T}) + @test fieldtypes(typeof(future_ports.output_types)) === (Type{Float32}, Type{Vector{T}}) + @test future.counter[] == map(_ -> 1, hook_zero) + @test inventory_is_value_free(future_ports) + end +end + @testset "earlier live route scope still wins over a later pure contract error" begin calls = Ref(0) model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( From 08acb2048de8422c87d4845a1eb6da7669459b0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 20:09:30 +0100 Subject: [PATCH 103/324] Format writer identities without generic array display --- src/composite_model/compilation.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index be5801086..ea0eec7e6 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5561,7 +5561,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) union!(labels, Base.@inline _with_metadata_entry( _application_match_labels, applications_by_id, previous_id)) end - previous_labels = sort!(collect(labels)) + previous_labels = join(sort!([String(label) for label in labels]), ", ") error( "Ambiguous canonical writers for variable `$(variable)` on object ", "`$(object_id.value)`. ", From 2cb8dd6e9feb67c06b54dd596d52d1ae1a7a400b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 20:17:48 +0100 Subject: [PATCH 104/324] Inline canonical default staging at the typed application boundary --- src/composite_model/compilation.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index ea0eec7e6..b625319d3 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6471,7 +6471,7 @@ function _prepare_model_output_statuses!( object_id, ) end - _status_recipe_add_default!( + Base.@inline _status_recipe_add_default!( model, preparation, object_id, From 793ed731aecb5b628986b718940390b771db3a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 21:00:50 +0100 Subject: [PATCH 105/324] Retain typed application ownership while refreshing hard calls --- src/composite_model/compilation.jl | 186 ++++++++++++++------------ src/visualization/model_graph_view.jl | 1 + 2 files changed, 104 insertions(+), 83 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b625319d3..6de8d092d 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2610,10 +2610,12 @@ function _compile_scene( status_view_schema=nothing, ) timeline = scenario_plan.timeline + applications_by_id = _applications_by_id(applications) started_at = _runtime_performance_start(performance) call_bindings = _compile_model_call_bindings( model, applications; + applications_by_id=applications_by_id, plans_by_application=scenario_plan.call_plans_by_application, ) _runtime_performance_finish!( @@ -2621,7 +2623,6 @@ function _compile_scene( :call_binding_compile, started_at, ) - applications_by_id = _applications_by_id(applications) distributed_outputs = _compile_model_distributed_outputs( model, applications, @@ -4164,10 +4165,15 @@ function _refresh_scene_call_bindings!( applications_by_id = compiled.applications_by_id applications_by_object = compiled.applications_by_object has_calls = !isempty(compiled.scenario_plan.call_plans) - rebuilt_existing_call_targets = - Set{Tuple{Symbol,ObjectId}}(forced_call_target_keys) - changed_call_target_keys = - Set{Tuple{Symbol,ObjectId}}(forced_call_target_keys) + I = keytype(model.registry.objects) + K = Tuple{Symbol,I} + rebuilt_existing_call_targets = Set{K}() + changed_call_target_keys = Set{K}() + for (application_id, raw_id) in forced_call_target_keys + key = (application_id, _index_object_id(model.registry.objects, raw_id)) + push!(rebuilt_existing_call_targets, key) + push!(changed_call_target_keys, key) + end observed_manual_call_binding_indices_by_callee_target = compiled.observed_manual_call_binding_indices_by_callee_target if has_calls @@ -4195,7 +4201,8 @@ function _refresh_scene_call_bindings!( default_to_context=true, default_scope=_default_dependency_scope(model, binding.consumer_id), ) || continue - key = (binding.application_id, binding.consumer_id) + key = (binding.application_id, + _index_object_id(model.registry.objects, binding.consumer_id)) push!(changed_call_target_keys, key) extension = key in forced_call_target_keys ? nothing : @@ -4227,32 +4234,35 @@ function _refresh_scene_call_bindings!( applications, ; by_object=applications_by_object, + applications_by_id=applications_by_id, plans_by_application=compiled.scenario_plan.call_plans_by_application, ) : similar(compiled.call_bindings, 0) - affected_call_applications = CompiledModelApplication[] + affected_call_applications = similar(applications, 0) if !isempty(rebuilt_existing_call_targets) - target_ids_by_application = Dict{Symbol,Vector{ObjectId}}() + target_ids_by_application = Dict{Symbol,Vector{I}}() for (application_id, object_id) in rebuilt_existing_call_targets push!( get!( target_ids_by_application, application_id, - ObjectId[], + I[], ), object_id, ) end for application_id in sort!( collect(keys(target_ids_by_application)); - by=id -> applications_by_id[id].slot, + by=id -> begin + Base.@inline _with_metadata_entry( + application -> application.slot, applications_by_id, id) + end, ) - application = applications_by_id[application_id] target_ids = target_ids_by_application[application_id] _sort_object_ids!(target_ids) - push!( - affected_call_applications, - _partial_model_application(application, target_ids), - ) + Base.@inline _with_metadata_entry(applications_by_id, application_id, target_ids) do application, ids + push!(affected_call_applications, _partial_model_application(application, ids)) + return nothing + end end end replacement_call_bindings = isempty(affected_call_applications) ? @@ -4262,6 +4272,7 @@ function _refresh_scene_call_bindings!( affected_call_applications, applications; by_object=applications_by_object, + applications_by_id=applications_by_id, plans_by_application=compiled.scenario_plan.call_plans_by_application, ) replacement_call_bindings_by_target = _index_model_call_bindings( @@ -8923,6 +8934,7 @@ function _compile_model_call_bindings( lookup_applications=applications, ; by_object=nothing, + applications_by_id, plans_by_application=nothing, ) if isnothing(plans_by_application) @@ -8934,79 +8946,87 @@ function _compile_model_call_bindings( bindings = _model_call_binding_storage( plans_by_application, keytype(model.registry.objects), ) - for application in applications - for consumer_id in application.target_ids - for plan in _application_plans( - plans_by_application, - application.id, - ) - call_sym = plan.call - selector = plan.selector - proc = plan.process - app_name = plan.application - mode = _compiled_call_mode(plan) - callee_object_ids, callee_application_ids = if mode === :initializer - # Initializers never cache or track pre-existing target objects. - # Their one scheduled application is statically validated, and - # run_initializer! resolves only its explicit newborn identity. - ( - ObjectId[], - Symbol[plan.potential_callee_application_ids...], - ) - else - isnothing(by_object) && - (by_object = _applications_by_object(lookup_applications, model.registry.objects)) - object_ids = _dependency_object_ids( - model, - selector, - plan.matcher, - consumer_id, - ) - application_ids = Symbol[] - for object_id in object_ids - append!( - application_ids, - _matching_callee_applications( - by_object, - object_id, - proc, - app_name, - ), + for partial_application in applications + by_object = Base.@inline _with_model_application( + applications_by_id, partial_application, by_object, plans_by_application, + ) do application, application_objects, application_plans + for consumer_id in application.target_ids + for plan in _application_plans( + application_plans, + application.id, + ) + call_sym = plan.call + selector = plan.selector + proc = plan.process + app_name = plan.application + mode = _compiled_call_mode(plan) + callee_object_ids, callee_application_ids = if mode === :initializer + # Initializers never cache or track pre-existing target objects. + # Their one scheduled application is statically validated, and + # run_initializer! resolves only its explicit newborn identity. + ( + ObjectId[], + Symbol[plan.potential_callee_application_ids...], + ) + else + isnothing(application_objects) && + (application_objects = _applications_by_object(lookup_applications, model.registry.objects)) + object_ids = _dependency_object_ids( + model, + selector, + plan.matcher, + consumer_id, ) + application_ids = Symbol[] + for object_id in object_ids + append!( + application_ids, + _matching_callee_applications( + application_objects, + object_id, + proc, + app_name, + ), + ) + end + unique!(application_ids) + (object_ids, application_ids) end - unique!(application_ids) - (object_ids, application_ids) - end - if mode === :manual && - isempty(callee_application_ids) && selector isa One - error( - "Call `$(call_sym)` on application `$(application.id)` matched objects ", - "$([id.value for id in callee_object_ids]) but no model application", - isnothing(proc) ? "." : " with process `$(proc)`.", - ) - end - if mode === :manual && selector isa One && - length(callee_application_ids) != 1 - error( - "Call `$(call_sym)` on application `$(application.id)` expected one callee application, ", - "got `$(callee_application_ids)`. Add `application=:name` to disambiguate." - ) - elseif selector isa OptionalOne && length(callee_application_ids) > 1 - error( - "Call `$(call_sym)` on application `$(application.id)` expected zero or one callee application, ", - "got `$(callee_application_ids)`. Add `application=:name` to disambiguate." + if mode === :manual && + isempty(callee_application_ids) && selector isa One + matched_objects = join([string(id.value) for id in callee_object_ids], ", ") + error( + "Call `$(call_sym)` on application `$(application.id)` matched objects ", + "[$(matched_objects)] but no model application", + isnothing(proc) ? "." : " with process `$(proc)`.", + ) + end + if mode === :manual && selector isa One && + length(callee_application_ids) != 1 + callee_applications = join([String(id) for id in callee_application_ids], ", ") + error( + "Call `$(call_sym)` on application `$(application.id)` expected one callee application, ", + "got `[$(callee_applications)]`. Add `application=:name` to disambiguate." + ) + elseif selector isa OptionalOne && length(callee_application_ids) > 1 + callee_applications = join([String(id) for id in callee_application_ids], ", ") + error( + "Call `$(call_sym)` on application `$(application.id)` expected zero or one callee application, ", + "got `[$(callee_applications)]`. Add `application=:name` to disambiguate." + ) + end + push!( + bindings, + CompiledModelCallBinding( + plan, + consumer_id, + _application_target_ids(model, callee_object_ids), + callee_application_ids, + ), ) end - push!( - bindings, - CompiledModelCallBinding( - plan, - consumer_id, - _application_target_ids(model, callee_object_ids), - callee_application_ids, - ), - ) end + return application_objects end end return bindings diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index b593847bf..757b3bacf 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -392,6 +392,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) _compile_model_call_bindings( model, applications; + applications_by_id=_applications_by_id(applications), plans_by_application=_plans_by_application( applications, call_plans, From 30df1abcf5abacfcc03aa23f2b1e160efb4dd74d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 21:35:05 +0100 Subject: [PATCH 106/324] Prepare concrete target caches and typed output defaults --- src/composite_model/compilation.jl | 138 +++++++++++++++++---------- test/test-model-api-stabilization.jl | 4 +- 2 files changed, 88 insertions(+), 54 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6de8d092d..d3337111f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -361,6 +361,19 @@ mutable struct CompiledApplicationSchedule{E,A,P,G} const generic_entry_indices::G end +# Membership lengths vary across object classes; they are runtime data rather +# than type parameters of the shared application-target cache. +struct _ApplicationTargetTemplate + candidate_slots::Vector{Int} + matched_slots::Vector{Int} +end + +function _application_target_template_cache(::Type{I}) where {I<:ObjectId} + K = Tuple{Union{Nothing,Symbol},Union{Nothing,Symbol},Union{Nothing,Symbol}, + Union{Nothing,I},Tuple{Vararg{I}}} + return Dict{K,_ApplicationTargetTemplate}() +end + """Reverse candidate index for compiled selector matchers.""" struct SelectorCandidateIndex{W,S,K,SP,I,A,R,L,C} wildcard::W @@ -388,7 +401,7 @@ function _selector_candidate_index(model::CompositeModel; application_targets::B }(), Set{I}(), Dict{Symbol,Set{Union{Symbol,I}}}(), - application_targets ? Dict{Any,Any}() : nothing, + application_targets ? _application_target_template_cache(I) : nothing, ) end @@ -407,7 +420,7 @@ function _freeze_selector_candidate_index(index::SelectorCandidateIndex) label => Set(values) for (label, values) in index.template_label_values ), - Dict{Any,Any}(), + _application_target_template_cache(keytype(index.by_id)), ) end @@ -2721,11 +2734,6 @@ function _compile_scene( ) end -struct _ApplicationTargetTemplate{C,M} - candidate_slots::C - matched_slots::M -end - function _application_target_template_label( index::SelectorCandidateIndex, label::Symbol, @@ -2784,14 +2792,14 @@ function _application_target_template( model, object_id, ) - sorted_candidates = Tuple(sort!(collect(candidate_slots))) - matched_slots = Tuple( - slot for slot in sorted_candidates if _selector_matches_object_id( - model, - compiled.applications[slot].target_matcher, - object_id, - ) - ) + sorted_candidates = sort!(collect(candidate_slots)) + matched_slots = Int[] + for slot in sorted_candidates + matches = Base.@inline _with_metadata_entry(compiled.applications_by_id, slot) do application + _selector_matches_object_id(model, application.target_matcher, object_id) + end + matches && push!(matched_slots, slot) + end template = _ApplicationTargetTemplate( sorted_candidates, matched_slots, @@ -2811,8 +2819,10 @@ function _new_application_targets( performance=nothing, ) candidate_slots = Set{Int}() - targets = Dict{Symbol,Vector{ObjectId}}() - for object_id in added_ids + I = keytype(model.registry.objects) + targets = Dict{Symbol,Vector{I}}() + for raw_id in added_ids + object_id = _index_object_id(model.registry.objects, raw_id) template = _application_target_template( model, compiled, @@ -2821,9 +2831,10 @@ function _new_application_targets( ) union!(candidate_slots, template.candidate_slots) for slot in template.matched_slots - application = compiled.applications[slot] - application_targets = get!(targets, application.id) do - ObjectId[] + application_id = Base.@inline _with_metadata_entry( + application -> application.id, compiled.applications_by_id, slot) + application_targets = get!(targets, application_id) do + I[] end push!(application_targets, object_id) end @@ -2834,14 +2845,16 @@ function _new_application_targets( length(candidate_slots), ) for (application_id, matched) in targets - application = compiled.applications_by_id[application_id] - new_count = length(application.target_ids) + length(matched) - if (application.applies_to isa One && new_count != 1) || - (application.applies_to isa OptionalOne && new_count > 1) - # Reuse canonical selector diagnostics without replaying authored - # model declarations or preparing any new status/default values. - _resolve_object_ids(model, application.applies_to, application.target_matcher) - error("Inconsistent lifecycle target cardinality for application `$(application.id)`.") + Base.@inline _with_metadata_entry(compiled.applications_by_id, application_id) do application + new_count = length(application.target_ids) + length(matched) + if (application.applies_to isa One && new_count != 1) || + (application.applies_to isa OptionalOne && new_count > 1) + # Reuse canonical selector diagnostics without replaying authored + # model declarations or preparing any new status/default values. + _resolve_object_ids(model, application.applies_to, application.target_matcher) + error("Inconsistent lifecycle target cardinality for application `$(application.id)`.") + end + return nothing end end return targets @@ -4522,7 +4535,9 @@ function _extend_compiled_scene( structural_dirty_ids=ObjectId[], performance=nothing, ) - added_ids = ObjectId[id for id in added_objects if haskey(model.registry.objects, id)] + I = keytype(model.registry.objects) + added_ids = I[_index_object_id(model.registry.objects, id) + for id in added_objects if haskey(model.registry.objects, id)] started_at = _runtime_performance_start(performance) new_targets = _new_application_targets( model, @@ -6448,6 +6463,43 @@ function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId return Base.@inline _with_registered_status(identity, model.registry.objects.catalog, status) end +_stage_model_output_defaults!(::Tuple{}, ::Tuple{}, preparation, context) = nothing + +function _stage_model_output_defaults!( + variables::Tuple{Symbol,Vararg{Symbol}}, + defaults::Tuple{V,Vararg}, + preparation, + context, +) where {V} + variable = first(variables) + value = first(defaults) + if _publish_mode_for_output(context.application.spec, variable) == :canonical + if !(preparation isa Status && variable in propertynames(preparation)) + if preparation isa Status + preparation = _status_recipe_for_object!( + context.recipes, + context.recipe_order, + context.model, + context.object_id, + ) + end + Base.@inline _status_recipe_add_default!( + context.model, + preparation, + context.object_id, + variable, + value; + application_id=context.application.id, + origin=:model_output_default, + conversion_records=context.conversion_records, + ) + end + end + return _stage_model_output_defaults!( + Base.tail(variables), Base.tail(defaults), preparation, context, + ) +end + function _prepare_model_output_statuses!( model::CompositeModel, applications, @@ -6470,29 +6522,11 @@ function _prepare_model_output_statuses!( model, object_id, ) - for (variable, value) in pairs(defaults) - _publish_mode_for_output(application.spec, variable) == - :canonical || continue - if preparation isa Status - variable in propertynames(preparation) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - end - Base.@inline _status_recipe_add_default!( - model, - preparation, - object_id, - variable, - value; - application_id=application.id, - origin=:model_output_default, - conversion_records=conversion_records, - ) - end + context = (; model, application, object_id, recipes, + recipe_order, conversion_records) + _stage_model_output_defaults!( + keys(defaults), values(defaults), preparation, context, + ) end end end diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 5b329a463..539323541 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -1521,12 +1521,12 @@ end @test key_1a != key_2 @test index.template_label_values == Dict(:scale => Set([:Leaf])) - target_template_1 = PlantSimEngine._application_target_template( + target_template_1 = @inferred PlantSimEngine._application_target_template( model, compiled, ObjectId(:template_leaf_1a), ) - target_template_2 = PlantSimEngine._application_target_template( + target_template_2 = @inferred PlantSimEngine._application_target_template( model, compiled, ObjectId(:template_leaf_2), From 35273e5ad1f723352e11829db72d57e6762b5621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 21:47:11 +0100 Subject: [PATCH 107/324] Keep the registry identity type immutable during growth refresh --- src/composite_model/compilation.jl | 1 - 1 file changed, 1 deletion(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index d3337111f..1d854c7a2 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4774,7 +4774,6 @@ function _extend_compiled_scene( added_applications else rewired_applications = copy(added_applications) - I = keytype(model.registry.objects) targets_by_application = Dict{Symbol,Vector{I}}() for raw_id in rewired_consumer_ids object_id = _index_object_id(model.registry.objects, raw_id) From 97a64a013b30363041d053368e96f467fb48c430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 22:09:53 +0100 Subject: [PATCH 108/324] Preserve concrete selector keys and canonical status recipes --- src/composite_model/compilation.jl | 114 ++++++++++++++++++++++------- src/composite_model/selectors.jl | 2 +- test/test-status-construction.jl | 13 ++++ 3 files changed, 100 insertions(+), 29 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1d854c7a2..124097097 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -368,10 +368,46 @@ struct _ApplicationTargetTemplate matched_slots::Vector{Int} end +struct _ApplicationTargetTemplateKey{I<:ObjectId} + scale::Union{Nothing,Symbol} + kind::Union{Nothing,Symbol} + species::Union{Nothing,Symbol} + id::Union{Nothing,I} + scope_roots::Union{Nothing,Vector{I}} +end + +function Base.hash(key::_ApplicationTargetTemplateKey, seed::UInt) + result = hash(key.scale, seed) + result = hash(key.kind, result) + result = hash(key.species, result) + result = hash(key.id, result) + roots = key.scope_roots + result = hash(isnothing(roots) ? 0 : length(roots), result) + if !isnothing(roots) + for root in roots + result = hash(root, result) + end + end + return result +end + +function Base.isequal(left::_ApplicationTargetTemplateKey, right::_ApplicationTargetTemplateKey) + isequal(left.scale, right.scale) && isequal(left.kind, right.kind) && + isequal(left.species, right.species) && isequal(left.id, right.id) || return false + a, b = left.scope_roots, right.scope_roots + isnothing(a) && return isnothing(b) + isnothing(b) && return false + length(a) == length(b) || return false + for index in eachindex(a) + isequal(a[index], b[index]) || return false + end + return true +end +Base.:(==)(left::_ApplicationTargetTemplateKey, right::_ApplicationTargetTemplateKey) = + isequal(left, right) + function _application_target_template_cache(::Type{I}) where {I<:ObjectId} - K = Tuple{Union{Nothing,Symbol},Union{Nothing,Symbol},Union{Nothing,Symbol}, - Union{Nothing,I},Tuple{Vararg{I}}} - return Dict{K,_ApplicationTargetTemplate}() + return Dict{_ApplicationTargetTemplateKey{I},_ApplicationTargetTemplate}() end """Reverse candidate index for compiled selector matchers.""" @@ -407,9 +443,9 @@ end function _freeze_selector_candidate_index(index::SelectorCandidateIndex) freeze(groups::AbstractDict{K}) where {K} = - Dict{K,Tuple{Vararg{Int}}}(key => Tuple(values) for (key, values) in groups) + Dict{K,Vector{Int}}(key => copy(values) for (key, values) in groups) return SelectorCandidateIndex( - Tuple(index.wildcard), + copy(index.wildcard), freeze(index.by_scale), freeze(index.by_kind), freeze(index.by_species), @@ -2751,16 +2787,22 @@ function _application_target_template_key( ) object = _model_object(model, object_id) id = _index_object_id(model.registry.objects, object_id) - scope_roots = if isempty(index.scope_roots) - () - else + I = keytype(model.registry.objects) + scope_roots = nothing + if !isempty(index.scope_roots) ancestors = _object_ancestor_ids(model.registry, id) - Tuple( - _index_object_id(model.registry.objects, ancestor_id) for ancestor_id in ancestors - if _index_object_id(model.registry.objects, ancestor_id) in index.scope_roots - ) + for raw_ancestor in ancestors + ancestor = _index_object_id(model.registry.objects, raw_ancestor) + ancestor in index.scope_roots || continue + if isnothing(scope_roots) + scope_roots = I[ancestor] + else + push!(scope_roots, ancestor) + end + end end - return ( + # This vector is owned by the immutable key and is never changed afterwards. + return _ApplicationTargetTemplateKey{I}( _application_target_template_label(index, :scale, object.scale), _application_target_template_label(index, :kind, object.kind), _application_target_template_label(index, :species, object.species), @@ -6174,16 +6216,16 @@ Sparse reference edits staged before committing one canonical object status. Unchanged fields remain in the original status. A model-owned construction recipe supplies their order when the staged edits are committed. """ -mutable struct _CanonicalStatusRecipe - original::Union{Nothing,Status} +mutable struct _CanonicalStatusRecipe{S<:Union{Nothing,Status}} + original::S edit_names::Vector{Symbol} edit_references::Vector{Ref} changed::Bool field_changes::Int end -function _CanonicalStatusRecipe(status::Union{Nothing,Status}) - return _CanonicalStatusRecipe( +function _CanonicalStatusRecipe(status::S) where {S<:Union{Nothing,Status}} + return _CanonicalStatusRecipe{S}( status, Symbol[], Ref[], @@ -6192,6 +6234,20 @@ function _CanonicalStatusRecipe(status::Union{Nothing,Status}) ) end +# The finite catalog witnesses every original status type before sparse edits. +# Open preparation keeps the same recipe algorithm behind its ordinary JIT barrier. +_canonical_status_recipe_storage(::OpenObjectFamilyCatalog, ::Type{I}) where {I<:ObjectId} = + Dict{I,_CanonicalStatusRecipe}() + +@generated function _canonical_status_recipe_storage(::ClosedObjectFamilyCatalog{F}, + ::Type{I}, +) where {F,I<:ObjectId} + schemas = unique([Nothing; [family.parameters[2] for family in fieldtypes(F) + if family.parameters[2] <: Status]]) + R = Union{map(S -> _CanonicalStatusRecipe{S}, schemas)...} + return :(Dict{$I,$R}()) +end + @inline function _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) variable in recipe.edit_names && return true return !isnothing(recipe.original) && variable in propertynames(recipe.original) @@ -6353,25 +6409,27 @@ function _model_object_status_for_preparation( end function _status_recipe_for_object!( - recipes::AbstractDict{I,_CanonicalStatusRecipe}, + recipes::AbstractDict{I,R}, recipe_order::AbstractVector{I}, model::CompositeModel, object_id::ObjectId, -) where {I<:ObjectId} +) where {I<:ObjectId,R<:_CanonicalStatusRecipe} object_id = _index_object_id(recipes, object_id) return get!(recipes, object_id) do status = _model_object_status_for_preparation(model, object_id) - push!(recipe_order, object_id) - _CanonicalStatusRecipe(status) + Base.@inline _with_registered_status(model.registry.objects.catalog, status) do original + push!(recipe_order, object_id) + _CanonicalStatusRecipe(original) + end end end function _status_preparation_for_object!( - recipes::AbstractDict{I,_CanonicalStatusRecipe}, + recipes::AbstractDict{I,R}, recipe_order::AbstractVector{I}, model::CompositeModel, object_id::ObjectId, -) where {I<:ObjectId} +) where {I<:ObjectId,R<:_CanonicalStatusRecipe} object_id = _index_object_id(recipes, object_id) recipe = get(recipes, object_id, nothing) isnothing(recipe) || return recipe @@ -6384,10 +6442,10 @@ end function _apply_status_recipes!( model::CompositeModel, - recipes::AbstractDict{I,_CanonicalStatusRecipe}, + recipes::AbstractDict{I,R}, recipe_order::AbstractVector{I}; performance=nothing, -) where {I<:ObjectId} +) where {I<:ObjectId,R<:_CanonicalStatusRecipe} for object_id in recipe_order recipe = recipes[object_id] recipe.changed || continue @@ -6507,7 +6565,7 @@ function _prepare_model_output_statuses!( ) isempty(applications) && return model I = keytype(model.registry.objects) - recipes = Dict{I,_CanonicalStatusRecipe}() + recipes = _canonical_status_recipe_storage(model.registry.objects.catalog, I) recipe_order = I[] record_conversions = !_no_status_conversion(model.status_conversion) conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records @@ -6614,7 +6672,7 @@ function _prepare_model_output_destination_statuses!( resolved_destinations, ) I = keytype(model.registry.objects) - recipes = Dict{I,_CanonicalStatusRecipe}() + recipes = _canonical_status_recipe_storage(model.registry.objects.catalog, I) recipe_order = I[] records_before = copy(model.status_conversion_records) try @@ -7300,7 +7358,7 @@ function _prepare_model_input_statuses_batched!( performance=nothing, ) I = keytype(model.registry.objects) - recipes = Dict{I,_CanonicalStatusRecipe}() + recipes = _canonical_status_recipe_storage(model.registry.objects.catalog, I) recipe_order = I[] record_conversions = !_no_status_conversion(model.status_conversion) conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index fbcf88319..fdfaac277 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -738,7 +738,7 @@ _compile_selector_matcher(model::CompositeModel, selector::AbstractObjectMultipl function _scope_object_ids(model::CompositeModel, scope, context) if isnothing(scope) || scope isa SceneScope - return ObjectId[keys(model.registry.objects)...] + return collect(keys(model.registry.objects)) end current_id = _object_id_from_context(context) diff --git a/test/test-status-construction.jl b/test/test-status-construction.jl index 80a333f7c..f8a860e22 100644 --- a/test/test-status-construction.jl +++ b/test/test-status-construction.jl @@ -13,6 +13,8 @@ const PSE = PlantSimEngine replacement = Ref(3.0f0) tail = Ref([4.0]) edits = PSE._CanonicalStatusRecipe(original) + @test fieldtype(typeof(edits), :original) === typeof(original) + @test (@inferred PSE._status_recipe_has_variable(edits, :keep)) @test isempty(edits.edit_names) @test isempty(edits.edit_references) @test !PSE._status_recipe_set_reference!(edits, :keep, keep) @@ -60,6 +62,17 @@ const PSE = PlantSimEngine projected = PSE._closed_object_family_store(model.registry.objects) @test projected.layout_cache == cache @test projected.layout_cache !== cache + recipes = @inferred PSE._canonical_status_recipe_storage(projected.catalog, keytype(projected)) + Original = typeof(model_status(model, :object)) + @test valtype(typeof(recipes)) === Union{PSE._CanonicalStatusRecipe{Nothing}, + PSE._CanonicalStatusRecipe{Original}} + @test isempty(recipes) + order = keytype(projected)[] + staged = PSE._status_recipe_for_object!(recipes, order, model, ObjectId(:object)) + @test staged.original === model_status(model, :object) + @test typeof(staged) === PSE._CanonicalStatusRecipe{Original} + @test PSE._status_recipe_for_object!(recipes, order, model, ObjectId(:object)) === staged + @test order == [ObjectId(:object)] @test isempty(CompositeModel(Object(:other)).registry.objects.layout_cache) discarded = PSE.ObjectFamilyStore() merge!(discarded.layout_cache, cache) From c06d4bfaff0b46d22812a608f5d891328cc94311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 23:03:10 +0100 Subject: [PATCH 109/324] Keep selector cache components and lifecycle identities concrete --- src/composite_model/compilation.jl | 19 ++++++++++++------- test/test-model-lifecycle-empty-targets.jl | 10 ++++++++++ test/test-selector-candidate-empty-scope.jl | 14 +++++++++----- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 124097097..6b2edeb43 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -423,7 +423,7 @@ struct SelectorCandidateIndex{W,S,K,SP,I,A,R,L,C} application_target_templates::C end -function _selector_candidate_index(model::CompositeModel; application_targets::Bool=false) +function _selector_candidate_index(model::CompositeModel, application_target_templates) I = keytype(model.registry.objects) return SelectorCandidateIndex( Int[], @@ -437,7 +437,7 @@ function _selector_candidate_index(model::CompositeModel; application_targets::B }(), Set{I}(), Dict{Symbol,Set{Union{Symbol,I}}}(), - application_targets ? _application_target_template_cache(I) : nothing, + application_target_templates, ) end @@ -655,7 +655,8 @@ function _union_selector_candidates!( end function _application_target_candidate_index(model, application_plans) - index = _selector_candidate_index(model; application_targets=true) + index = _selector_candidate_index(model, + _application_target_template_cache(keytype(model.registry.objects))) for plan in application_plans _index_selector_candidate!( index, @@ -2186,7 +2187,7 @@ function _index_dynamic_input_bindings( bindings, many_binding_cache, ) - index = _selector_candidate_index(model) + index = _selector_candidate_index(model, nothing) for (binding_index, binding) in pairs(bindings) _index_dynamic_input_binding!( index, @@ -2223,7 +2224,7 @@ function _index_dynamic_call_binding!( end function _index_dynamic_call_bindings(model::CompositeModel, bindings) - index = _selector_candidate_index(model) + index = _selector_candidate_index(model, nothing) for (binding_index, binding) in pairs(bindings) _index_dynamic_call_binding!( index, @@ -4578,8 +4579,12 @@ function _extend_compiled_scene( performance=nothing, ) I = keytype(model.registry.objects) - added_ids = I[_index_object_id(model.registry.objects, id) - for id in added_objects if haskey(model.registry.objects, id)] + added_ids = I[] + for raw_id in added_objects + object_id = _index_object_id(model.registry.objects, raw_id) + haskey(model.registry.objects, object_id) || continue + push!(added_ids, object_id) + end started_at = _runtime_performance_start(performance) new_targets = _new_application_targets( model, diff --git a/test/test-model-lifecycle-empty-targets.jl b/test/test-model-lifecycle-empty-targets.jl index 475823213..5f366f198 100644 --- a/test/test-model-lifecycle-empty-targets.jl +++ b/test/test-model-lifecycle-empty-targets.jl @@ -85,4 +85,14 @@ end @test isempty(simulation.environment_bindings.by_target) @test isempty(simulation.environment_bindings.positions_by_target) @test isempty(simulation.environment_bindings.targets_by_object) + + # One structural delta can contain an ID removed before its first refresh. + register_object!(model, Object(:discarded; scale=:Leaf, parent=:plant_b)) + remove_object!(model, :discarded) + register_object!(model, Object(:replacement; scale=:Leaf, parent=:plant_b)) + @test ObjectId(:discarded) in PlantSimEngine.lifecycle_delta(model).structural_dirty_ids + continue!(simulation; steps=1) + @test !haskey(model.registry.objects, ObjectId(:discarded)) + @test simulation.compiled.applications_by_id[:b].target_ids == [ObjectId(:replacement)] + @test model_object(model, :replacement).status.seen == 23.0 end diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 8f78cec1d..5552e5934 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -17,7 +17,11 @@ using Test Object(:other_leaf; scale=:Leaf, parent=:other_plant), ) leaf_id = ObjectId(:leaf) - index = PlantSimEngine._selector_candidate_index(model) + index = @inferred PlantSimEngine._selector_candidate_index(model, nothing) + @test isnothing(index.application_target_templates) + cache = PlantSimEngine._application_target_template_cache(keytype(model.registry.objects)) + cached = @inferred PlantSimEngine._selector_candidate_index(model, cache) + @test cached.application_target_templates === cache push!(index.wildcard, 1) index.by_id[leaf_id] = [2] index.by_scale[:Leaf] = [3] @@ -38,7 +42,7 @@ using Test @test result === candidates @test candidates == Set([1, 2, 3, 4, 5, 99]) end - empty_index = PlantSimEngine._selector_candidate_index(model) + empty_index = PlantSimEngine._selector_candidate_index(model, nothing) candidates = Set([99]) @test PlantSimEngine._union_selector_candidates!( candidates, empty_index, model, leaf_id, @@ -72,7 +76,7 @@ using Test end @testset "Missing IDs are rejected before any label or scope lookup" begin - empty_scope_index = PlantSimEngine._selector_candidate_index(model) + empty_scope_index = PlantSimEngine._selector_candidate_index(model, nothing) push!(empty_scope_index.wildcard, 1) for candidate_index in ( empty_scope_index, @@ -121,7 +125,7 @@ end closed && (model = _closed_selector_candidate_fixture(model)) @test (model.registry.objects.catalog isa PlantSimEngine.ClosedObjectFamilyCatalog) === closed I = keytype(model.registry.objects) - index = PlantSimEngine._selector_candidate_index(model) + index = PlantSimEngine._selector_candidate_index(model, nothing) frozen_empty = PlantSimEngine._freeze_selector_candidate_index(index) @test keytype(index.by_id) === keytype(frozen_empty.by_id) === I @test keytype(index.by_scope_anchor) === keytype(frozen_empty.by_scope_anchor) === @@ -159,7 +163,7 @@ end for raw_future in (leaf_id + 1000, :future_leaf, 1.5) future_id = ObjectId(raw_future) @test !haskey(model.registry.objects, future_id) - future_index = PlantSimEngine._selector_candidate_index(model) + future_index = PlantSimEngine._selector_candidate_index(model, nothing) for (slot, selector) in pairs((Many(id=raw_future), Many(id=raw_future, within=Subtree()))) matcher = PlantSimEngine._compile_selector_matcher(model, selector) From 4d15a3191b838d1570fa3420b16b46d1375830cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 23:03:16 +0100 Subject: [PATCH 110/324] Prepare source reference families and honor effective model defaults --- src/authoring.jl | 4 +- src/composite_model/authored_ports.jl | 29 +- src/composite_model/compilation.jl | 641 +++++++++++------- src/composite_model/display.jl | 4 +- src/composite_model/registry_topology.jl | 56 +- src/composite_model/selectors.jl | 63 +- src/composite_model/source_compilation.jl | 6 +- src/composite_model/status_conversion.jl | 61 +- .../status_view_construction.jl | 4 +- src/output_schema.jl | 5 +- src/scenario_source.jl | 4 +- src/visualization/model_graph_view.jl | 6 +- test/test-model-api-stabilization.jl | 16 +- test/test-model-authored-port-inventory.jl | 23 + test/test-model-binding-index-identities.jl | 26 +- test/test-model-scenario-authoring.jl | 5 +- test/test-resolved-input-materialization.jl | 590 +++++++++++++++- 17 files changed, 1225 insertions(+), 318 deletions(-) diff --git a/src/authoring.jl b/src/authoring.jl index af5ee1b30..c29df4dbf 100644 --- a/src/authoring.jl +++ b/src/authoring.jl @@ -1073,8 +1073,8 @@ function _scenario_model_groups(compilation) for application in compilation.applications model = _application_default_model(application) push!(get!(groups, model, Symbol[]), application.id) - isnothing(application.model_overrides) && continue - for replacement in values(application.model_overrides) + isnothing(_application_model_overrides(application)) && continue + for replacement in values(_application_model_overrides(application)) application_ids = get!(groups, replacement, Symbol[]) application.id in application_ids || push!(application_ids, application.id) end diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl index f5f157ef0..5ddd2855b 100644 --- a/src/composite_model/authored_ports.jl +++ b/src/composite_model/authored_ports.jl @@ -44,11 +44,12 @@ Base.propertynames(::AuthoredOutputPorts) = (:all_names, :local_names, :distribu # One stable owner is shared by the authored recipe and compiled application. # Name and type carriers preserve declarations without retaining initialization values. -mutable struct AuthoredPortInventory{I,O,IT,OT,EI,EO,C} +mutable struct AuthoredPortInventory{I,O,IT,OT,OET,EI,EO,C} const inputs::I const outputs::O const input_types::IT const output_types::OT + const output_element_types::OET const environment_inputs::EI const environment_outputs::EO const contracts::C @@ -92,12 +93,36 @@ function _authored_port_types(type_for, schema::NamedTuple{Names}) where {Names} return NamedTuple{Names,fields}(types) end +# Only real numeric-array defaults have element evidence. Missing fields mean +# no initializer value (e.g. Required), whereas Tuple{} means a real empty array. +_output_element_types(value) = nothing +_output_element_types(value::Distributed) = _output_element_types(value.declaration) +_output_element_types(value::Default) = _output_element_types(value.value) +function _output_element_types(value::Array{T}) where {T<:Number} + isempty(value) && return Tuple{} + isconcretetype(T) && return Tuple{T} + types = DataType[] + for element in value + element_type = typeof(element) + element_type in types || push!(types, element_type) + end + return Tuple{types...} +end + +function _authored_output_element_types(schema::NamedTuple{Names}) where {Names} + types = map(_output_element_types, values(schema)) + names = Tuple(Names[index] for index in eachindex(Names) if !isnothing(types[index])) + selected = NamedTuple{names}(Tuple(T for T in types if !isnothing(T))) + return _authored_port_types(identity, selected) +end + function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) # This is the constructor's existing output read. A failed output hook # retains its existing top-level authoring failure and application recovery. output_schema = _output_schema(spec) output_ports = _authored_output_ports(spec, output_schema) output_types = _authored_port_types(_output_value_type, output_schema) + output_element_types = _authored_output_element_types(output_schema) model = model_(spec) input_metadata = _capture_authored_metadata(:input_ports, application_id) do schema = _input_schema(model) @@ -135,5 +160,5 @@ function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) end end return AuthoredPortInventory(inputs, output_ports, input_types, output_types, - environment_inputs, environment_outputs, contracts) + output_element_types, environment_inputs, environment_outputs, contracts) end diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6b2edeb43..b8c75de22 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2,7 +2,7 @@ Immutable scenario-level metadata for one model application. Runtime object membership is stored separately in [`CompiledModelApplication`](@ref). """ -struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,P,CP} +struct CompiledApplicationPlan{S,AT,TM,TS,CL,P,CP} slot::Int id::Symbol spec::S @@ -12,7 +12,6 @@ struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO,P,CP} target_matcher::TM timestep::TS clock::CL - model_overrides::MO ports::P call_plans::CP end @@ -55,7 +54,6 @@ end name === :target_matcher && return getfield(plan, :target_matcher) name === :timestep && return getfield(plan, :timestep) name === :clock && return getfield(plan, :clock) - name === :model_overrides && return getfield(plan, :model_overrides) return getproperty(plan, name) end @@ -69,7 +67,7 @@ _input_route_source(::InputRouteTag{INPUT,SOURCE}) where {INPUT,SOURCE} = Val(SO _input_route_from_status(::InputRouteTag{INPUT,SOURCE,FROM_STATUS}) where {INPUT,SOURCE,FROM_STATUS} = FROM_STATUS """Immutable authored input declaration and reference-access recipe.""" -struct CompiledModelInputPlan{TAG,SEL,M,OA,PSA,W} +struct CompiledModelInputPlan{TAG,SEL,M,OA,PSA,W,RT<:Tuple} route::TAG slot::Int application_slot::Int @@ -86,6 +84,7 @@ struct CompiledModelInputPlan{TAG,SEL,M,OA,PSA,W} potential_source_application_ids::PSA breaks_same_step_cycle::Bool window::W + reference_types::Type{RT} end """Fixed metadata schema whose scalar lookups stay inside its typed owner.""" @@ -906,7 +905,7 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs) authored_records = Tuple(authored) recipes = Tuple(record for record in authored_records if record isa AuthoredApplicationRecipe) - program = _prepare_authored_scenario_program(recipes) + program = _prepare_authored_scenario_program(model, recipes) return ScenarioPreparation(model, source_specs, authored_records, failure, program, nothing) end @@ -1503,11 +1502,11 @@ function _prepare_authored_scenario_graph(application_records, input_records, ca frozen_children, order, failures) end -function _prepare_authored_scenario_program(recipes) +function _prepare_authored_scenario_program(model, recipes) applications = _graph_record_vector(AuthoredApplicationRecipe, recipes) output_records = _prepare_authored_output_records(applications) destinations = _authored_distributed_output_plans(applications, output_records) - input_records = _prepare_authored_input_records(applications, destinations) + input_records = _prepare_authored_input_records(model, applications, destinations) inputs = Tuple(record for record in input_records if record isa CompiledModelInputPlan) calls = Tuple(plan for application in applications for plan in application.call_plans) graph = _prepare_authored_scenario_graph(applications, inputs, calls, destinations) @@ -1521,6 +1520,7 @@ function _authored_input_graph_matches(records::Tuple, plans) authored.application_id === resolved.application_id && authored.input === resolved.input && authored.selector === resolved.selector && authored.origin === resolved.origin && + authored.reference_types === resolved.reference_types && authored.potential_source_application_ids === resolved.potential_source_application_ids && authored.order_after_application_ids === resolved.order_after_application_ids end @@ -2701,10 +2701,6 @@ function _compile_scene( :input_binding_compile, started_at, ) - # Lifecycle refresh may replace an initially empty `Many(...)` carrier - # with a concrete carrier type. Keep the per-target index type-stable - # across that replacement so an updated compiled scene can be stored in - # an existing `Simulation`. input_bindings_by_target = _index_model_input_bindings( input_bindings, keytype(model.registry.objects), ) @@ -3289,7 +3285,7 @@ end function _can_append_stable_many_sources(binding::CompiledModelInputBinding) binding.multiplicity == :many || return false binding.carrier_hint === :ref_vector || return false - binding.carrier isa RefVector || return false + binding.carrier isa Union{RefVector,ObjectRefVector} || return false potential_application_ids = binding.potential_source_application_ids source_application_ids = binding.source_application_ids length(source_application_ids) == length(potential_application_ids) || @@ -3398,7 +3394,7 @@ function _append_added_many_sources!( performance, ) && return true - new_carrier = _input_carrier(model, binding.selector, new_source_ids, _input_route_source(binding.plan.route)) + new_carrier = _input_carrier(model, binding.selector, new_source_ids, _input_route_source(binding.plan.route), binding.plan.reference_types) isnothing(new_carrier) && return false existing_refs = parent(binding.carrier) new_refs = parent(new_carrier) @@ -4702,11 +4698,6 @@ function _extend_compiled_scene( input_bindings, length(compiled.input_bindings) + added_input_binding_capacity, ) - # A `Many(...)` binding that starts empty is compiled with an untyped - # `RefVector{Any}` carrier. Once matching objects are registered, the - # refreshed carrier becomes concrete (for example `RefVector{Float64}`). - # Keep this incremental index value-widened so that lifecycle refresh can - # replace an initially empty binding without rebuilding the whole scene. input_bindings_by_target = compiled.input_bindings_by_target many_binding_cache = compiled.many_input_binding_cache changed_bindings = similar(input_bindings, 0) @@ -5408,13 +5399,13 @@ function _resolve_application_recipes( recipe.environment_hint, recipe.ports.environment_inputs; on_error=on_environment_error, ) - model_overrides = _compiled_object_model_overrides(spec, target_ids, recipe.id) + _validate_compiled_object_overrides!(spec, target_ids, recipe.id) push!(applications, CompiledModelApplication( CompiledApplicationPlan( recipe.slot, recipe.id, spec, recipe.process, recipe.name, selector, target_matcher, timestep(spec), _model_application_clock(model, spec, target_ids, timeline), - model_overrides, recipe.ports, recipe.call_plans, + recipe.ports, recipe.call_plans, ), target_ids, )) @@ -5486,30 +5477,95 @@ function _model_environment_bindings_with_environment_sources( return (; resolved...) end -function _compiled_object_model_overrides(spec, target_ids, application_id::Symbol) +function _validate_compiled_object_overrides!(spec, target_ids, application_id::Symbol) model = model_(spec) model isa ObjectModelOverrides || return nothing target_set = Set(target_ids) - unmatched = ObjectId[id for id in keys(model.overrides) if !(id in target_set)] + unmatched = ObjectId[id for id in keys(model.variants) if !(id in target_set)] isempty(unmatched) || error( "Object override(s) `$([id.value for id in unmatched])` for application ", "`$(application_id)` do not match its `on=...` target set." ) - return model.overrides + return nothing end -_application_default_model(application::CompiledModelApplication) = - model_(application.spec) isa ObjectModelOverrides ? - model_(application.spec).base : - model_(application.spec) +_application_model_overrides(application) = + model_(application.spec) isa ObjectModelOverrides ? model_(application.spec).variants : nothing -function _application_model(application::CompiledModelApplication, object_id::ObjectId) - isnothing(application.model_overrides) && return _application_default_model(application) - return get( - application.model_overrides, - object_id, - _application_default_model(application), - ) +function _application_default_model(application) + model = model_(application.spec) + return model isa ObjectModelOverrides ? _object_override_base(model) : model +end + +function _application_model(application, object_id::ObjectId) + return _with_application_variant((model, ports) -> model, application, object_id) +end + +@inline function _with_application_variant(f::F, application, object_id::ObjectId, + args::Vararg{Any,N}, +) where {F,N} + model = model_(application.spec) + if model isa ObjectModelOverrides + owner = model.variants + slot = get(owner.object_slots, object_id, 1) + return Base.@inline _with_metadata_entry(_call_application_variant, + owner.entries, slot, f, args...) + end + return f(model, _application_ports(application), args...) +end + +@inline _call_application_variant(entry, f::F, args::Vararg{Any,N}) where {F,N} = + f(entry.model, entry.ports, args...) + +@inline function _foreach_application_variant(f::F, application, + args::Vararg{Any,N}, +) where {F,N} + model = model_(application.spec) + if model isa ObjectModelOverrides + return _foreach_configured_variant(f, model.variants.entries, args...) + end + f(model, _application_ports(application), args...) + return nothing +end +_foreach_configured_variant(f, ::Tuple{}, args::Vararg{Any,N}) where {N} = nothing +function _foreach_configured_variant(f::F, entries::Tuple, args::Vararg{Any,N}) where {F,N} + entry = first(entries) + f(entry.model, entry.ports, args...) + return _foreach_configured_variant(f, Base.tail(entries), args...) +end + +_read_application_defaults(model, ::Val{:outputs}) = _local_output_schema(model) +_read_application_defaults(model, ::Val{:inputs}) = _input_default_values(_input_schema(model)) +_variant_defaults_type(ports, ::Val{:outputs}) = ports.defaults_types.outputs +_variant_defaults_type(ports, ::Val{:inputs}) = ports.defaults_types.inputs + +function _application_default_schemas(application, kind) + model = model_(application.spec) + return model isa ObjectModelOverrides ? IdDict{AbstractModel,NamedTuple}() : + _read_application_defaults(model, kind) +end +@inline _with_application_defaults(f::F, application, object_id, defaults::NamedTuple, + kind, args::Vararg{Any,N}) where {F,N} = f(defaults, args...) +@inline function _with_application_defaults(f::F, application, object_id, + cache::IdDict{AbstractModel,NamedTuple}, kind, args::Vararg{Any,N}, +) where {F,N} + return Base.@inline _with_application_variant(_call_configured_defaults, + application, object_id, f, cache, kind, args...) +end +@inline function _call_configured_defaults(model, ports, f::F, cache, kind, + args::Vararg{Any,N}, +) where {F,N} + return _with_configured_defaults(f, model, cache, kind, + _variant_defaults_type(ports, kind), args...) +end +@inline function _with_configured_defaults(f::F, model, cache, kind, ::Type{S}, + args::Vararg{Any,N}, +) where {F,S<:NamedTuple,N} + schema = get!(cache, model) do + _read_application_defaults(model, kind) + end + schema isa S || throw(ArgumentError("A model default schema changed after preparation.")) + return f(schema::S, args...) end _application_ports(application::CompiledModelApplication) = getfield(application, :plan).ports @@ -6064,83 +6120,43 @@ end end function _input_reference_carrier( - ::Union{One,OptionalOne}, source_ids, reference_for, + ::Union{One,OptionalOne}, source_ids, reference_for, ::Type{<:Tuple}, ) isempty(source_ids) && return nothing return _checked_input_reference(reference_for(only(source_ids))) end -function _input_reference_carrier(::Many, source_ids, reference_for) - first_source = iterate(source_ids) - isnothing(first_source) && return RefVector{Any}() - source_id, iteration_state = first_source - reference = _checked_input_reference(reference_for(source_id)) - isnothing(reference) && return nothing - return _many_input_reference_carrier( - source_ids, reference_for, reference, typeof(reference[]), iteration_state, - ) -end - -function _many_input_reference_carrier( - source_ids, reference_for, first_reference::Base.RefValue{T}, ::Type{T}, - iteration_state, -) where {T} - references = Base.RefValue{T}[] - sizehint!(references, length(source_ids) + 1) - push!(references, first_reference) - while true - next_source = iterate(source_ids, iteration_state) - isnothing(next_source) && break - source_id, iteration_state = next_source - reference = _checked_input_reference(reference_for(source_id)) - isnothing(reference) && return nothing - if reference isa Base.RefValue{T} - push!(references, reference) - else - heterogeneous = Base.RefValue[references...] - push!(heterogeneous, reference) - return _heterogeneous_input_reference_carrier( - source_ids, reference_for, heterogeneous, iteration_state, - ) +@generated function _input_reference_carrier( + ::Many, source_ids, reference_for::F, ::Type{RT}, +) where {F,RT<:Tuple} + types = fieldtypes(RT) + isempty(types) && return :(throw(ArgumentError("A Many input requires a prepared reference family."))) + all(R -> R <: Base.RefValue && isconcretetype(R), types) || + return :(throw(ArgumentError("A Many input requires exact prepared reference types."))) + R = Union{types...} + homogeneous = length(types) == 1 && isconcretetype(eltype(only(types))) + result = homogeneous ? :(RefVector(references)) : :(ObjectRefVector(references)) + return quote + references = $R[] + sizehint!(references, length(source_ids) + 1) + for source_id in source_ids + reference = _checked_input_reference(reference_for(source_id)) + isnothing(reference) && return nothing + reference isa $R || throw(ArgumentError( + "An input source reference is outside its prepared Many family.")) + push!(references, reference::$R) end + return $result end - return RefVector(references) -end - -# An abstract Ref payload must retain the previous ObjectRefVector contract, -# even when its current value happens to have the same type as another source. -function _many_input_reference_carrier( - source_ids, reference_for, first_reference::Base.RefValue, ::Type, - iteration_state, -) - references = Base.RefValue[first_reference] - sizehint!(references, length(source_ids) + 1) - return _heterogeneous_input_reference_carrier( - source_ids, reference_for, references, iteration_state, - ) -end - -function _heterogeneous_input_reference_carrier( - source_ids, reference_for, references, iteration_state, -) - while true - next_source = iterate(source_ids, iteration_state) - isnothing(next_source) && break - source_id, iteration_state = next_source - reference = _checked_input_reference(reference_for(source_id)) - isnothing(reference) && return nothing - push!(references, reference) - end - return ObjectRefVector(references) end function _input_carrier( model::CompositeModel, selector::AbstractObjectMultiplicity, - source_ids::AbstractVector{<:ObjectId}, source_var, + source_ids::AbstractVector{<:ObjectId}, source_var, reference_types::Type{<:Tuple}, ) reference_for = source_id -> _status_ref_or_nothing(model_status(model, source_id), source_var) - return _input_reference_carrier(selector, source_ids, reference_for) + return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end function _has_stream_only_input_source( @@ -6171,17 +6187,19 @@ function _stream_only_initial_reference( application = only(matching_applications) if _publish_mode_for_output(application.spec, source_var) == :stream_only - initial, _, _ = _materialize_status_value( - model, - source_var, - getproperty(_local_output_schema(application.spec), source_var); - object_id=source_id, - application_id=application.id, - origin=:stream_only_source_default, - private_copy=true, - reuse=true, - ) - return Ref(initial) + return Base.@inline _with_application_variant(application, source_id) do effective_model, ports + initial, _, _ = _materialize_status_value( + model, + source_var, + getproperty(_local_output_schema(effective_model), source_var); + object_id=source_id, + application_id=application.id, + origin=:stream_only_source_default, + private_copy=true, + reuse=true, + ) + return Ref(initial) + end end end return _status_ref_or_nothing( @@ -6197,11 +6215,12 @@ function _stream_only_initial_carrier( source_application_ids, source_var::Symbol, applications_by_id, + reference_types::Type{<:Tuple}, ) reference_for = source_id -> _stream_only_initial_reference( model, source_id, source_application_ids, source_var, applications_by_id, ) - return _input_reference_carrier(selector, source_ids, reference_for) + return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end function _ref_vector_carrier(refs) @@ -6576,19 +6595,21 @@ function _prepare_model_output_statuses!( conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records for partial in applications Base.@inline _with_model_application(applications_by_id, partial) do application - defaults = _local_output_schema(application.spec) + schemas = _application_default_schemas(application, Val(:outputs)) for object_id in application.target_ids - preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - context = (; model, application, object_id, recipes, - recipe_order, conversion_records) - _stage_model_output_defaults!( - keys(defaults), values(defaults), preparation, context, - ) + Base.@inline _with_application_defaults(application, object_id, schemas, Val(:outputs)) do defaults + preparation = _status_preparation_for_object!( + recipes, + recipe_order, + model, + object_id, + ) + context = (; model, application, object_id, recipes, + recipe_order, conversion_records) + _stage_model_output_defaults!( + keys(defaults), values(defaults), preparation, context, + ) + end end end end @@ -7234,64 +7255,67 @@ function _prepare_model_input_defaults!( ) for partial in applications _with_model_application(applications_by_id, partial) do application - schema = _model_input_schema(application) - defaults = _input_default_values(schema) + _model_input_names(application) + schemas = _application_default_schemas(application, Val(:inputs)) for object_id in application.target_ids - status = _ensure_model_object_status!(model, object_id) - for (variable, value) in pairs(defaults) - variable = Symbol(variable) - variable in propertynames(status) && continue - reference = isnothing(final_references) ? - nothing : - get( - final_references, - (application.id, object_id, variable), - nothing, - ) - if !isnothing(reference) - # Preserve conversion callbacks, validation, and diagnostic - # records while avoiding a default Status that the resolved - # carrier would replace immediately below. - _no_status_conversion(model.status_conversion) || - _materialize_status_value( - model, + Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults + status = _ensure_model_object_status!(model, object_id) + for (variable, value) in pairs(defaults) + variable = Symbol(variable) + variable in propertynames(status) && continue + reference = isnothing(final_references) ? + nothing : + get( + final_references, + (application.id, object_id, variable), + nothing, + ) + if !isnothing(reference) + # Preserve conversion callbacks, validation, and diagnostic + # records while avoiding a default Status that the resolved + # carrier would replace immediately below. + _no_status_conversion(model.status_conversion) || + _materialize_status_value( + model, + variable, + value; + object_id=object_id, + application_id=application.id, + origin=:model_input_default, + private_copy=true, + ) + status = _status_with_reference( + status, variable, - value; - object_id=object_id, - application_id=application.id, - origin=:model_input_default, - private_copy=true, + reference, ) - status = _status_with_reference( + _runtime_performance_count!( + performance, + :input_default_status_rewrites_avoided, + ) + continue + end + status = _status_with_default( + model, status, + object_id, variable, - reference, + value; + application_id=application.id, + origin=:model_input_default, ) - _runtime_performance_count!( - performance, - :input_default_status_rewrites_avoided, + push!( + get!( + model.input_default_status_variables, + object_id, + Set{Symbol}(), + ), + variable, ) - continue end - status = _status_with_default( - model, - status, - object_id, - variable, - value; - application_id=application.id, - origin=:model_input_default, - ) - push!( - get!( - model.input_default_status_variables, - object_id, - Set{Symbol}(), - ), - variable, - ) + _replace_model_object_status!(model, object_id, status) + return nothing end - _replace_model_object_status!(model, object_id, status) end return nothing end @@ -7372,68 +7396,72 @@ function _prepare_model_input_statuses_batched!( for partial in applications input_default_rewrites_avoided += Base.@inline _with_model_application(applications_by_id, partial) do application rewrites_avoided = 0 - schema = _model_input_schema(application) - defaults = _input_default_values(schema) + _model_input_names(application) + schemas = _application_default_schemas(application, Val(:inputs)) for object_id in application.target_ids - preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - for (variable_, value) in pairs(defaults) - variable = Symbol(variable_) - if preparation isa Status - variable in propertynames(preparation) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - else - _status_recipe_has_variable(preparation, variable) && continue - end - reference = isnothing(final_references) ? - nothing : - get( - final_references, - (application.id, object_id, variable), - nothing, + rewrites_avoided += Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults + object_rewrites_avoided = 0 + preparation = _status_preparation_for_object!( + recipes, + recipe_order, + model, + object_id, ) - if !isnothing(reference) - # Preserve conversion callbacks, validation, and diagnostic - # records even though the resolved carrier owns storage. - _no_status_conversion(model.status_conversion) || - _materialize_status_value( + for (variable_, value) in pairs(defaults) + variable = Symbol(variable_) + if preparation isa Status + variable in propertynames(preparation) && continue + preparation = _status_recipe_for_object!( + recipes, + recipe_order, model, + object_id, + ) + else + _status_recipe_has_variable(preparation, variable) && continue + end + reference = isnothing(final_references) ? + nothing : + get( + final_references, + (application.id, object_id, variable), + nothing, + ) + if !isnothing(reference) + # Preserve conversion callbacks, validation, and diagnostic + # records even though the resolved carrier owns storage. + _no_status_conversion(model.status_conversion) || + _materialize_status_value( + model, + variable, + value; + object_id=object_id, + application_id=application.id, + origin=:model_input_default, + private_copy=true, + conversion_records=conversion_records, + ) + _status_recipe_set_reference!( + preparation, variable, - value; - object_id=object_id, - application_id=application.id, - origin=:model_input_default, - private_copy=true, - conversion_records=conversion_records, + reference, ) - _status_recipe_set_reference!( + object_rewrites_avoided += 1 + continue + end + _status_recipe_add_default!( + model, preparation, + object_id, variable, - reference, + value; + application_id=application.id, + origin=:model_input_default, + conversion_records=conversion_records, ) - rewrites_avoided += 1 - continue + default_status_updates[(object_id, variable)] = true end - _status_recipe_add_default!( - model, - preparation, - object_id, - variable, - value; - application_id=application.id, - origin=:model_input_default, - conversion_records=conversion_records, - ) - default_status_updates[(object_id, variable)] = true + return object_rewrites_avoided end end return rewrites_avoided @@ -7959,7 +7987,139 @@ Base.@nospecializeinfer function _input_plan_variable_contracts!( return schema end +# The family is fixed by preparation, not by the first matching organ. Existing +# configured reference storage takes precedence over declared numeric defaults. + +function _many_scope_is_current(model, matcher) + scope = matcher.scope + scope isa Scope && return haskey(model.registry.objects, + first(_named_scope_root_candidate(model, scope))) + scope isa CompiledNamedScope && return haskey(model.registry.objects, scope.root_id) + return true +end + +function _many_current_application_targets(model, application) + matcher = application.target_matcher + _many_scope_is_current(model, matcher) || return ObjectId[] + # Metadata needs membership, not the application's multiplicity check. + many = _selector_as_many(applies_to(application.spec)) + return _resolve_object_ids(model, many, _resolve_selector_matcher(model, matcher)) +end + +function _many_current_source_ids(model, consumer, producer, variant, selector, + source_selectors, distributed) + current = Set{ObjectId}() + if isnothing(producer) + matcher = _authored_selector_matcher(selector) + _many_scope_is_current(model, matcher) || return current + matcher = _resolve_selector_matcher(model, matcher) + for consumer_id in _many_current_application_targets(model, consumer) + union!(current, _dependency_object_ids(model, selector, matcher, consumer_id)) + end + else + isempty(source_selectors) && return current + for execution_id in _many_current_application_targets(model, producer) + _application_model(producer, execution_id) === variant || continue + if distributed + for destination in source_selectors + matcher = _authored_selector_matcher(destination) + _many_scope_is_current(model, matcher) || continue + union!(current, _dependency_object_ids(model, _selector_as_many(destination), + _resolve_selector_matcher(model, matcher), execution_id)) + end + else + push!(current, execution_id) + end + end + end + return current +end + +function _many_model_variant_types(producer) + model = model_(producer.spec) + if model isa ObjectModelOverrides + return map(model.variants.entries) do entry + (entry.model, entry.ports.output_types, entry.ports.output_element_types) + end + end + ports = _application_ports(producer) + return ((model, ports.output_types, ports.output_element_types),) +end + +function _prepare_many_reference_types(model, consumer, input, selector, + source_var, producer_ids, applications_by_id, distributed_output_plans) + references = Any[] + add(R) = R in references || push!(references, R) + declared_input = getproperty(_application_ports(consumer).input_types, input) + fallback = declared_input <: AbstractVector ? eltype(declared_input) : Union{} + isconcretetype(fallback) || (fallback = Union{}) + producers = isempty(producer_ids) ? (nothing,) : producer_ids + for producer_id in producers + producer = isnothing(producer_id) ? nothing : applications_by_id[producer_id] + distributed = !isnothing(producer) && + source_var in _model_distributed_output_names(producer) + source_selectors = if isnothing(producer) + (selector,) + elseif distributed + _application_output_selectors(producer, source_var, distributed_output_plans) + elseif _publish_mode_for_output(producer.spec, source_var) === :stream_only + () + else + (applies_to(producer.spec),) + end + variants = isnothing(producer) ? ((nothing, nothing, nothing),) : _many_model_variant_types(producer) + for (variant, output_types, element_types) in variants + current = _many_current_source_ids(model, consumer, producer, variant, + selector, source_selectors, distributed) + missing_current = copy(current) + observed_any = false + for source_selector in source_selectors + matcher = _authored_selector_matcher(source_selector) + for object in values(model.registry.objects) + _matches_object_criteria(object; scale=matcher.scale, kind=matcher.kind, + species=matcher.species, id=matcher.id) || continue + status = object.status + status isa Status && source_var in propertynames(status) || continue + reference = refvalue(status, source_var) + reference isa Base.RefValue || continue + add(typeof(reference)) + observed_any = true + delete!(missing_current, object.id) + end + end + # Current references replace this variant's default only when every + # current source already owns one. Missing fields still materialize + # the declared default. Other families remain eligible for reparenting. + !isempty(current) && isempty(missing_current) && continue + T = if isnothing(producer) || !isnothing(model.status_conversion.transform) + fallback + else + _configured_status_value_type(model.status_conversion, + getproperty(output_types, source_var), get(element_types, source_var, nothing)) + end + candidates = isnothing(T) ? () : Base.uniontypes(T) + if isempty(candidates) || !all(isconcretetype, candidates) + isnothing(producer) && observed_any && continue + candidates = fallback === Union{} ? () : (fallback,) + end + isempty(candidates) && throw(ArgumentError( + "Many input `$(input)` on application `$(consumer.id)` has no concrete " * + "configured source type for `$(source_var)`. Declare a concrete producer " * + "or input element type, or provide its configured initial state.")) + for T in candidates + T === Union{} && throw(ArgumentError( + "Many input `$(input)` has no configured source element type.")) + add(Base.RefValue{T}) + end + end + end + isempty(references) && throw(ArgumentError("A Many input has no prepared reference family.")) + # Julia canonicalizes the union; its members give deterministic witness order. + return Tuple{Base.uniontypes(Union{references...})...} +end + Base.@nospecializeinfer function _compiled_model_input_plan( + model::CompositeModel, slot::Int, writer_applications, application, @@ -8035,10 +8195,13 @@ Base.@nospecializeinfer function _compiled_model_input_plan( potential_source_application_ids, breaks_same_step_cycle, _selector_window(selector), + selector isa Many ? _prepare_many_reference_types(model, application, + input, selector, source_var, potential_source_application_ids, + applications_by_id, distributed_output_plans) : Tuple{}, ) end -function _prepare_authored_input_records(applications, distributed_output_plans) +function _prepare_authored_input_records(model, applications, distributed_output_plans) plans = CompiledModelInputPlan[] records = Any[] applications_by_id = Dict(application.id => application for application in applications) @@ -8066,7 +8229,7 @@ function _prepare_authored_input_records(applications, distributed_output_plans) _validate_declared_model_input_name!(application, input) selector isa AbstractObjectMultiplicity || error( "Input binding `$(input)` on application `$(application.id)` must use an object selector.") - _compiled_model_input_plan(length(plans) + 1, writer_applications, + _compiled_model_input_plan(model, length(plans) + 1, writer_applications, application, input, selector, get(input_origins(application.spec), input, :model_spec), applications_by_id, distributed_output_plans, local_output_names, @@ -8087,7 +8250,7 @@ function _prepare_authored_input_records(applications, distributed_output_plans) selector = One(within=Self(), process=producer.process, application=producer.id, var=input) record = _capture_authored_metadata(:input_plans, application.id) do - _compiled_model_input_plan(length(plans) + 1, writer_applications, + _compiled_model_input_plan(model, length(plans) + 1, writer_applications, application, input, selector, :inferred_same_object, applications_by_id, distributed_output_plans, local_output_names, variable_contracts_by_application) @@ -8107,7 +8270,7 @@ function _resolve_model_input_plan(model, plan::CompiledModelInputPlan, slot::In plan.application_id, plan.input, plan.selector, matcher, plan.origin, plan.order_after_application_ids, plan.source_var, plan.process, plan.application, plan.multiplicity, plan.potential_source_application_ids, - plan.breaks_same_step_cycle, plan.window) + plan.breaks_same_step_cycle, plan.window, plan.reference_types) end function _resolve_model_input_plans(model, preparation::ScenarioPreparation, @@ -8118,7 +8281,7 @@ function _resolve_model_input_plans(model, preparation::ScenarioPreparation, else # A partial report is a different declaration set. Project the real # recipes through the SAME pure factory, without replaying a hook. - _prepare_authored_input_records(_project_authored_applications(preparation, applications), + _prepare_authored_input_records(model, _project_authored_applications(preparation, applications), distributed_output_plans) end plans = CompiledModelInputPlan[] @@ -8233,8 +8396,8 @@ function _resolve_model_output_destination_plans(model::CompositeModel, # override validation and Scope resolution, retaining phase order. authored = _authored_metadata_value(preparation.program.output_records[application.id]) distributed_names = _model_distributed_output_names(application) - if !isnothing(application.model_overrides) - for replacement in values(application.model_overrides) + if !isnothing(_application_model_overrides(application)) + for replacement in values(_application_model_overrides(application)) replacement_names = _distributed_output_names(replacement) _output_destination_layout(application.spec, replacement_names, replacement) Set(replacement_names) == Set(distributed_names) || error( @@ -8530,9 +8693,10 @@ function _materialize_input_route( source_application_ids, source_var, applications_by_id, + plan.reference_types, ) else - _input_carrier(model, selector, source_ids, source_var_tag) + _input_carrier(model, selector, source_ids, source_var_tag, plan.reference_types) end carrier_hint = if isempty(source_ids) && selector isa OptionalOne :optional_default @@ -9222,9 +9386,9 @@ function explain_applications(compiled::CompiledCompositeModel) timestep=application.timestep, clock=application.clock, model_type=typeof(_application_default_model(application)), - model_storage=isnothing(application.model_overrides) ? :shared_application : :per_object_override, + model_storage=isnothing(_application_model_overrides(application)) ? :shared_application : :per_object_override, model_dispatch=_application_model_dispatch(application), - object_overrides=isnothing(application.model_overrides) ? + object_overrides=isnothing(_application_model_overrides(application)) ? NamedTuple[] : [ ( @@ -9232,7 +9396,7 @@ function explain_applications(compiled::CompiledCompositeModel) model_type=typeof(model), ) for (object_id, model) in sort!( - collect(application.model_overrides); + collect(_application_model_overrides(application)); by=pair -> string(first(pair).value), ) ], @@ -9245,12 +9409,11 @@ explain_applications(model::CompositeModel) = explain_applications(_diagnostic_bindings(model)) function _application_model_dispatch(application::CompiledModelApplication) - isnothing(application.model_overrides) && return :concrete_shared - override_type = valtype(typeof(application.model_overrides)) + owner = _application_model_overrides(application) + isnothing(owner) && return :concrete_shared default_type = typeof(_application_default_model(application)) - return isconcretetype(override_type) && default_type == override_type ? - :concrete_per_object : - :heterogeneous_per_object + return all(entry -> typeof(entry.model) === default_type, owner.entries) ? + :concrete_per_object : :heterogeneous_per_object end function explain_schedule(compiled::CompiledCompositeModel) diff --git a/src/composite_model/display.jl b/src/composite_model/display.jl index 03102e1de..b41c6d8bc 100644 --- a/src/composite_model/display.jl +++ b/src/composite_model/display.jl @@ -49,13 +49,13 @@ end function _model_display_application(application) spec = application isa ModelSpec ? application : nothing model = isnothing(spec) ? application : spec.model - base_model = model isa ObjectModelOverrides ? model.base : model + base_model = model isa ObjectModelOverrides ? _object_override_base(model) : model label = string(nameof(typeof(base_model))) if !isnothing(spec) && !isnothing(spec.name) label = string(_model_display_label(spec.name), ": ", label) end if model isa ObjectModelOverrides - count = length(model.overrides) + count = length(model.variants) label *= string(" (", count, " object override", count == 1 ? "" : "s", ")") end if !isnothing(spec) && !isnothing(spec.timestep) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 7f1d77e5e..ed73b1682 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -171,22 +171,46 @@ function ObjectInstance( ) end -struct ObjectModelOverrides{M,O} <: AbstractModel - base::M - overrides::O -end - -process(model::ObjectModelOverrides) = process(model.base) -inputs_(model::ObjectModelOverrides) = inputs_(model.base) -outputs_(model::ObjectModelOverrides) = outputs_(model.base) -dep(model::ObjectModelOverrides) = dep(model.base) -timespec(model::ObjectModelOverrides) = timespec(model.base) -output_policy(model::ObjectModelOverrides) = output_policy(model.base) -timestep_hint(model::ObjectModelOverrides) = timestep_hint(model.base) -environment_hint(model::ObjectModelOverrides) = environment_hint(model.base) -environment_inputs_(model::ObjectModelOverrides) = environment_inputs_(model.base) -environment_outputs_(model::ObjectModelOverrides) = environment_outputs_(model.base) -variable_contracts_(model::ObjectModelOverrides) = variable_contracts_(model.base) +# Configured variants and their value-free port metadata have one typed owner. +# The ID map stores only slots; numerical state remains in the actual models. +struct ConfiguredModelVariants{V,I<:ObjectId} <: AbstractDict{I,AbstractModel} + entries::V + object_slots::Dict{I,Int} +end +Base.length(owner::ConfiguredModelVariants) = length(owner.object_slots) +Base.keys(owner::ConfiguredModelVariants) = keys(owner.object_slots) +Base.haskey(owner::ConfiguredModelVariants, id) = haskey(owner.object_slots, id) +function Base.getindex(owner::ConfiguredModelVariants, id) + return _with_metadata_entry(entry -> entry.model, owner.entries, owner.object_slots[id]) +end +function Base.get(owner::ConfiguredModelVariants, id, default) + slot = get(owner.object_slots, id, 0) + return iszero(slot) ? default : + _with_metadata_entry(entry -> entry.model, owner.entries, slot) +end +function Base.iterate(owner::ConfiguredModelVariants, state=nothing) + item = isnothing(state) ? iterate(owner.object_slots) : iterate(owner.object_slots, state) + isnothing(item) && return nothing + (id, _), next = item + return id => owner[id], next +end + +struct ObjectModelOverrides{V} <: AbstractModel + variants::V +end +_object_override_base(model::ObjectModelOverrides) = first(model.variants.entries).model + +process(model::ObjectModelOverrides) = process(_object_override_base(model)) +inputs_(model::ObjectModelOverrides) = inputs_(_object_override_base(model)) +outputs_(model::ObjectModelOverrides) = outputs_(_object_override_base(model)) +dep(model::ObjectModelOverrides) = dep(_object_override_base(model)) +timespec(model::ObjectModelOverrides) = timespec(_object_override_base(model)) +output_policy(model::ObjectModelOverrides) = output_policy(_object_override_base(model)) +timestep_hint(model::ObjectModelOverrides) = timestep_hint(_object_override_base(model)) +environment_hint(model::ObjectModelOverrides) = environment_hint(_object_override_base(model)) +environment_inputs_(model::ObjectModelOverrides) = environment_inputs_(_object_override_base(model)) +environment_outputs_(model::ObjectModelOverrides) = environment_outputs_(_object_override_base(model)) +variable_contracts_(model::ObjectModelOverrides) = variable_contracts_(_object_override_base(model)) function Object( id; diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index fdfaac277..aba1dae68 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -320,7 +320,7 @@ end function _validate_model_override_contract!(base, replacement; description) base_contract = model_interface(base) replacement_contract = model_interface(replacement) - isequal(base_contract, replacement_contract) && return nothing + isequal(base_contract, replacement_contract) && return (; base=base_contract, replacement=replacement_contract) error( "$(description) has an incompatible model contract. Expected ", "`$(base_contract)`, got `$(replacement_contract)`. Object and instance ", @@ -329,6 +329,38 @@ function _validate_model_override_contract!(base, replacement; description) ) end +function _configured_variant_ports(contract) + input_defaults = _input_default_values(contract.inputs) + output_defaults = _local_output_declarations(contract.outputs) + return ( + input_types=_authored_port_types(_input_expected_type, contract.inputs), + output_types=_authored_port_types(_output_value_type, contract.outputs), + output_element_types=_authored_output_element_types(contract.outputs), + input_names=keys(contract.inputs), output_names=keys(contract.outputs), + input_default_names=keys(input_defaults), output_default_names=keys(output_defaults), + defaults_types=_authored_port_types(identity, + (inputs=typeof(input_defaults), outputs=typeof(output_defaults))), + ) +end + +function _prepare_object_model_overrides(base, object_models; description) + isempty(object_models) && throw(ArgumentError("Object overrides must not be empty.")) + entries = Any[] + I = Union{map(typeof, collect(keys(object_models)))...} + slots = Dict{I,Int}() + for (object_id, replacement) in pairs(object_models) + contracts = _validate_model_override_contract!(base, replacement; description) + isempty(entries) && push!(entries, (model=base, ports=_configured_variant_ports(contracts.base))) + slot = findfirst(entry -> entry.model === replacement, entries) + if isnothing(slot) + push!(entries, (model=replacement, ports=_configured_variant_ports(contracts.replacement))) + slot = length(entries) + end + slots[object_id] = slot + end + return ObjectModelOverrides(ConfiguredModelVariants(Tuple(entries), slots)) +end + function _object_override_models(instance::ObjectInstance, specs, instance_ids) entries = Dict{Int,Vector{Pair{ObjectId,AbstractModel}}}() valid_ids = Set(instance_ids) @@ -441,14 +473,8 @@ function _mount_object_instance_applications(instance::ObjectInstance, instance_ mounted_model = get(instance_overrides, index, model_(spec)) if haskey(object_overrides, index) object_models = object_overrides[index] - for replacement in values(object_models) - _validate_model_override_contract!( - mounted_model, - replacement; - description="Object override for template application `$(base_name)`", - ) - end - mounted_model = ObjectModelOverrides(mounted_model, object_models) + mounted_model = _prepare_object_model_overrides(mounted_model, object_models; + description="Object override for template application `$(base_name)`") end push!( mounted, @@ -668,19 +694,24 @@ function _criteria_scope(criteria) return isnothing(keyword) ? positional : keyword end -function _named_scope_root_id(model::CompositeModel, scope::Scope) +# Resolve the authored root identity independently from current membership. +# Preparation can retain a future scope without caching a missing-root failure. +function _named_scope_root_candidate(model::CompositeModel, scope::Scope) if scope.root isa Symbol for instance in model.instances instance.name == scope.root || continue - root_id = _instance_root_id(instance) - haskey(model.registry.objects, root_id) || error( - "Object instance `$(instance.name)` has no current root object `$(root_id.value)`.", - ) - return root_id + return _instance_root_id(instance), instance.name end end - root_id = ObjectId(scope.root) + return ObjectId(scope.root), nothing +end + +function _named_scope_root_id(model::CompositeModel, scope::Scope) + root_id, instance_name = _named_scope_root_candidate(model, scope) haskey(model.registry.objects, root_id) && return root_id + isnothing(instance_name) || error( + "Object instance `$(instance_name)` has no current root object `$(root_id.value)`.", + ) available_ids = [id.value for id in object_ids(model)] available_instances = sort!(Symbol[instance.name for instance in model.instances]; by=string) symbolic_ids = Symbol[id for id in available_ids if id isa Symbol] diff --git a/src/composite_model/source_compilation.jl b/src/composite_model/source_compilation.jl index 4a654e034..de09e7507 100644 --- a/src/composite_model/source_compilation.jl +++ b/src/composite_model/source_compilation.jl @@ -208,9 +208,9 @@ end function _compiled_source_application_models(application::CompiledModelApplication) models = Any[_application_default_model(application)] - if !isnothing(application.model_overrides) - for object_id in sort!(collect(keys(application.model_overrides)); by=id -> string(id.value)) - push!(models, application.model_overrides[object_id]) + if !isnothing(_application_model_overrides(application)) + for object_id in sort!(collect(keys(_application_model_overrides(application))); by=id -> string(id.value)) + push!(models, _application_model_overrides(application)[object_id]) end end unique_models = Any[] diff --git a/src/composite_model/status_conversion.jl b/src/composite_model/status_conversion.jl index 2d30bae39..3dd93d4e2 100644 --- a/src/composite_model/status_conversion.jl +++ b/src/composite_model/status_conversion.jl @@ -123,6 +123,64 @@ end _matching_status_type_rule(rules, value) = _matching_status_type_rule_for_type(rules, typeof(value)) +# The value materializer and the type-only preparation use the same join. +_status_array_element_type(types) = foldl(typejoin, types) + +# No conversion function or initializer is called here. A concrete target fixes +# the converted scalar type. An abstract target cannot be predicted in general. +function _configured_status_value_type(policy::StatusConversionPolicy, T, elements) + T === Union{} && return nothing + if T isa Union + results = map(Base.uniontypes(T)) do member + _configured_status_value_type(policy, member, nothing) + end + any(isnothing, results) && return nothing + return Union{results...} + end + rule = _matching_status_type_rule_for_type(policy.rules, T) + if !isnothing(rule) + return isconcretetype(last(rule)) ? last(rule) : nothing + end + T <: Array{<:Number} || return T + isempty(policy.rules) && return T + declared_element = eltype(T) + if isnothing(elements) + # A required homogeneous array has the same result type whether empty + # or not. An abstract element declaration needs real initializer types. + isconcretetype(declared_element) || return nothing + elements = Tuple{declared_element} + end + types = fieldtypes(elements) + if isempty(types) + rule = _matching_status_type_rule_for_type(policy.rules, declared_element) + isnothing(rule) && return T + target = last(rule) + return isconcretetype(target) ? Array{target,ndims(T)} : nothing + end + converted = Any[] + type_changed = false + same_type_conversion = false + for source in types + rule = _matching_status_type_rule_for_type(policy.rules, source) + if isnothing(rule) + push!(converted, source) + else + target = last(rule) + isconcretetype(target) || return nothing + push!(converted, target) + type_changed |= target !== source + same_type_conversion |= target === source + end + end + converted_array = Array{_status_array_element_type(converted),ndims(T)} + type_changed && return converted_array + # A user conversion may return a different value of the same scalar type. + # If that could change an abstract array's storage, types alone do not prove + # which branch of the value materializer will run. Diagnose, never guess. + same_type_conversion && converted_array !== T && return nothing + return T +end + function _convert_numeric_array_elements(rules, value::Array{<:Number}; context) if isempty(value) rule = _matching_status_type_rule_for_type(rules, eltype(value)) @@ -150,8 +208,7 @@ function _convert_numeric_array_elements(rules, value::Array{<:Number}; context) end changed || return value, false, nothing - effective_eltype = foldl( - typejoin, + effective_eltype = _status_array_element_type( (typeof(element) for element in converted_values), ) converted_array = similar(value, effective_eltype) diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index 00aa0bd2a..cd0b3f72b 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -206,7 +206,9 @@ function _assemble_model_status_view(model, application, object_id, output_defaults = if isempty(temporal_bindings) && isempty(output_routing(application.spec)) NamedTuple() else - defaults = _local_output_schema(application.spec) + defaults = Base.@inline _with_application_variant(application, object_id) do effective_model, ports + _local_output_schema(effective_model) + end for variable in keys(defaults) _publish_mode_for_output(application.spec, variable) == :stream_only && push!(private_names, Symbol(variable)) diff --git a/src/output_schema.jl b/src/output_schema.jl index 8e3f7ab5d..710adf0b5 100644 --- a/src/output_schema.jl +++ b/src/output_schema.jl @@ -36,8 +36,9 @@ function _output_schema(model) return schema end -function _local_output_schema(model) - schema = _output_schema(model) +_local_output_schema(model) = _local_output_declarations(_output_schema(model)) + +function _local_output_declarations(schema::NamedTuple) any(value -> value isa Distributed, values(schema)) || return schema names = Tuple(name for name in keys(schema) if !(schema[name] isa Distributed)) return NamedTuple{names}(map(name -> schema[name], names)) diff --git a/src/scenario_source.jl b/src/scenario_source.jl index bdd1f3220..f05ae8df6 100644 --- a/src/scenario_source.jl +++ b/src/scenario_source.jl @@ -207,8 +207,8 @@ function _scenario_source_models(model) add_application = function (application) process_model = model_(as_model_spec(application)) if process_model isa ObjectModelOverrides - push!(models, process_model.base) - append!(models, values(process_model.overrides)) + push!(models, _object_override_base(process_model)) + append!(models, values(process_model.variants)) else push!(models, process_model) end diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 757b3bacf..5090e2fa6 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -930,14 +930,14 @@ function _model_graph_application_dict( ) for update in updates(spec) ], - "modelStorage" => isnothing(application.model_overrides) ? "shared_application" : "per_object_override", - "objectOverrides" => isnothing(application.model_overrides) ? Any[] : [ + "modelStorage" => isnothing(_application_model_overrides(application)) ? "shared_application" : "per_object_override", + "objectOverrides" => isnothing(_application_model_overrides(application)) ? Any[] : [ Dict( "objectId" => _model_graph_object_id_value(object_id.value), "modelType" => string(typeof(override)), "parameters" => _model_graph_model_parameters(override), ) - for (object_id, override) in application.model_overrides + for (object_id, override) in _application_model_overrides(application) ], ) end diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 539323541..bfc775b51 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -2507,6 +2507,10 @@ end parent=:plant, status=Status(signal=2), ), + # Configure a Rational family outside this plant before growth uses it. + Object(:other_plant; scale=:Plant), + Object(:configured_rational; scale=:Leaf, parent=:other_plant, + status=Status(signal=1 // 1)), ] append!( objects, @@ -2544,6 +2548,8 @@ end ] carrier = first(bindings).carrier @test carrier isa PlantSimEngine.ObjectRefVector + @test eltype(parent(carrier)) === + Union{Base.RefValue{Float64},Base.RefValue{Int},Base.RefValue{Rational{Int}}} @test all(binding -> binding.carrier === carrier, bindings) register_object!( @@ -2795,12 +2801,10 @@ end end @testset "execution plan extends only the affected concrete runs" begin - context_models = PlantSimEngine.ObjectModelOverrides( - StabilizationContextModel(), - Dict( - ObjectId(:leaf_z) => StabilizationAlternativeContextModel(), - ), - ) + replacement = StabilizationAlternativeContextModel() + context_models = PlantSimEngine._prepare_object_model_overrides( + StabilizationContextModel(), Dict(ObjectId(:leaf_z) => replacement); + description="Test object override") model = CompositeModel( Object(:scene; scale=:Scene), Object(:leaf_a; scale=:Leaf, parent=:scene), diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index ef501961a..1db99a14b 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -62,6 +62,26 @@ function inventory_is_value_free(value) return all(name -> inventory_is_value_free(getfield(value, name)), fieldnames(typeof(value))) end +@testset "array element evidence stores types without initializer values" begin + value = Real[1.0, 2.0] + schema = (scalar=0f0, direct=value, distributed=Distributed(Default(value)), + empty=Real[], required=Distributed(Required(Vector{Real}))) + elements = PSE._authored_output_element_types(schema) + @test keys(elements) === (:direct, :distributed, :empty) + @test values(elements) === (Tuple{Float64}, Tuple{Float64}, Tuple{}) + @test fieldtypes(typeof(elements)) === + (Type{Tuple{Float64}}, Type{Tuple{Float64}}, Type{Tuple{}}) + @test !hasproperty(elements, :scalar) && !hasproperty(elements, :required) + @test inventory_is_value_free(elements) + push!(value, 3) + @test elements.direct === Tuple{Float64} + current = PSE._authored_output_element_types(schema) + @test current.direct === current.distributed === Tuple{Float64,Int} + @test value == Real[1.0, 2.0, 3] + @test PSE._output_element_types(Float32[1, 2]) === Tuple{Float32} + @test PSE._output_element_types(Float32[]) === Tuple{} +end + @testset "constructor owns one instance-specific value-free port inventory" begin a = Probe(:a, Ref(hook_zero), Ref(1f0)) b = Probe(:b, Ref(hook_zero), Ref(2f0)) @@ -85,6 +105,9 @@ end @test getproperty(ports.output_types, output_name(process_model)) === Float32 @test getproperty(ports.output_types, distributed_name(process_model)) === Vector{Float32} @test fieldtypes(typeof(ports.output_types)) === (Type{Float32}, Type{Vector{Float32}}) + @test keys(ports.output_element_types) === (distributed_name(process_model),) + @test getproperty(ports.output_element_types, distributed_name(process_model)) === Tuple{Float32} + @test fieldtypes(typeof(ports.output_element_types)) === (Type{Tuple{Float32}},) @test ports.outputs.all_names === (output_name(process_model), distributed_name(process_model)) @test ports.outputs.local_names === (output_name(process_model),) @test ports.outputs.distributed_names === (distributed_name(process_model),) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index cc6b66063..bd8cdd05e 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -176,11 +176,14 @@ end end end -@testset "input binding tuple schemas may change without widening registry keys" begin +@testset "prepared input binding tuple families retain registry keys after birth" begin first_status = Status(x=3f0) model = CompositeModel(Object(:root; scale=:Plant), Object(:other; scale=:Plant), Object(1; scale=:Leaf, parent=:root, status=first_status), - Object(:leaf; scale=:Leaf, parent=:root, status=Status(x=5f0)); + Object(:leaf; scale=:Leaf, parent=:root, status=Status(x=5f0)), + # A real configured source outside the current subtree prepares the + # Float64 family before a compatible newborn enters that subtree. + Object(:other_family; scale=:Leaf, parent=:other, status=Status(x=0.0)); applications=(ModelSpec(Reader(); name=:reader, on=One(id=:root), inputs=( single=One(id=1, within=Subtree(), var=:x, from_status=true), values=Many(scale=:Leaf, within=Subtree(), var=:x, from_status=true))),)) @@ -194,6 +197,8 @@ end @test single.carrier === first_ref @test model_status(model, :root).total === 11.0 many = last(before).carrier + @test many isa PSE.ObjectRefVector + @test eltype(parent(many)) === Union{Base.RefValue{Float32},Base.RefValue{Float64}} @test all(reference === PSE.refvalue(model_status(model, id), :x) for (id, reference) in zip(last(before).source_ids, parent(many))) @test_throws TypeError PSE._model_binding_target_key(single, ObjectId{String}) @@ -202,7 +207,15 @@ end register_object!(model, Object(2; scale=:Leaf, parent=:root, status=new_status)) step!(simulation) after = simulation.compiled.input_bindings_by_target[key] - @test typeof(after) !== typeof(before) + @test typeof(after) === typeof(before) + # The mixed-ID order inserts 2 before :leaf. A rebuilt column keeps the + # prepared representation and the original live references. + @test typeof(last(after).carrier) === typeof(many) + @test last(after).source_ids == [ObjectId(1), ObjectId(2), ObjectId(:leaf)] + @test parent(last(after).carrier)[1] === first_ref + @test parent(last(after).carrier)[2] === PSE.refvalue(new_status, :x) + @test parent(last(after).carrier)[3] === + PSE.refvalue(model_status(model, :leaf), :x) @test last(after).carrier isa PSE.ObjectRefVector @test first(after).carrier === first_ref @test model_status(model, :root).total === 20.0 @@ -222,13 +235,15 @@ end check_indexes(model, simulation) end -@testset "initially empty Many changes its real carrier schema after birth" begin +@testset "initially empty Many keeps its prepared carrier schema after birth" begin model = CompositeModel(Object(:root; scale=:Plant); applications=(ModelSpec(ManyReader(); name=:reader, on=One(id=:root), inputs=( values=Many(scale=:Leaf, within=Subtree(), var=:x, from_status=true),)),)) simulation = run!(model; steps=1, outputs=:all) key = (:reader, ObjectId(:root)) previous = simulation.compiled.input_bindings_by_target[key] + prepared_carrier = only(previous).carrier + @test prepared_carrier isa PSE.RefVector{Float64} @test isempty(only(previous).source_ids) @test isempty(only(previous).carrier) @test model_status(model, :root).total === 0.0 @@ -238,7 +253,8 @@ end register_object!(model, Object(1; scale=:Leaf, parent=:root, status)) step!(simulation) current = simulation.compiled.input_bindings_by_target[key] - @test typeof(current) !== typeof(previous) + @test typeof(current) === typeof(previous) + @test only(current).carrier === prepared_carrier @test only(current).source_ids == [ObjectId(1)] @test only(parent(only(current).carrier)) === reference @test model_status(model, :root).total === 7.0 diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl index fed0887a3..fdfa8fff8 100644 --- a/test/test-model-scenario-authoring.jl +++ b/test/test-model-scenario-authoring.jl @@ -134,8 +134,9 @@ end end @testset "future scopes, targets and overrides resolve only against the first run" begin - models = PSE.ObjectModelOverrides(ConstantProbe(1.0), - Dict(ObjectId(:future_leaf) => ConstantProbe(7.0))) + replacement = ConstantProbe(7.0) + models = PSE._prepare_object_model_overrides(ConstantProbe(1.0), + Dict(ObjectId(:future_leaf) => replacement); description="Test object override") model = CompositeModel(Object(:root; scale=:Plant); applications=( ModelSpec(models; name=:probe, on=One(scale=:Leaf, within=Scope(ObjectId(:future_root))), every=Hour(2)),), diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index 2d1f21624..c68335277 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -36,6 +36,31 @@ function PSE.run!(model::Distributor, status, environment, constants, context) return nothing end +struct RequiredDistributor <: AbstractResolved_Endpoint_DistributorModel end +PSE.outputs_(::RequiredDistributor) = (x=Distributed(Required(Real)),) +PSE.run!(::RequiredDistributor, status, environment, constants, context) = nothing + +struct ArraySource{A,C} <: AbstractResolved_Endpoint_SourceModel + value::A + declarations::C +end +function PSE.outputs_(model::ArraySource) + model.declarations[] += 1 + return (x=model.value,) +end +PSE.run!(::ArraySource, status, environment, constants, context) = nothing + +struct ArrayManyReader{T} <: AbstractResolved_Endpoint_ReaderModel + initial::T +end +PSE.inputs_(::ArrayManyReader) = (x=Required(AbstractVector),) +PSE.outputs_(model::ArrayManyReader) = (seen=model.initial,) +function PSE.run!(model::ArrayManyReader, status, environment, constants, context) + initial = zero(model.initial) + status.seen = sum(array -> sum(array; init=initial), status.x; init=initial) + return nothing +end + function point_scene(::Type{T}; policy=nothing, stream_only=false) where {T} return CompositeModel(Object(:source; scale=:Leaf), Object(:reader; scale=:Reader); applications=( @@ -76,6 +101,541 @@ end end end +# Keep scalar outputs generic while testing vector-valued source carriers. +struct ManyReader{V,T} <: AbstractResolved_Endpoint_ReaderModel + initial::T +end +PSE.inputs_(::ManyReader{V}) where {V} = (x=Required(V),) +PSE.outputs_(model::ManyReader) = (seen=model.initial,) +PSE.run!(model::ManyReader, status, environment, constants, context) = + (status.seen=sum(status.x; init=zero(model.initial)); nothing) + +@testset "absent declared producers have their Many family before first growth" begin + for T in (Float32, Float64) + model = CompositeModel(Object(:reader; scale=:Reader); applications=( + ModelSpec(Source(T(2)); name=:source, on=Many(scale=:Leaf)), + ModelSpec(ManyReader{AbstractVector,T}(zero(T)); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) + plan = only(model.scenario_plan_cache.program.input_records) + @test plan.reference_types === Tuple{Base.RefValue{T}} + @test fieldtype(typeof(plan), :reference_types) === Type{Tuple{Base.RefValue{T}}} + simulation = run!(model; steps=0, outputs=:all) + binding = only(simulation.compiled.input_bindings) + carrier = binding.carrier + status_type = typeof(model_status(model, :reader)) + binding_type = typeof(binding) + @test carrier isa PSE.RefVector{T} + @test isempty(carrier) + register_object!(model, Object(:new_leaf; scale=:Leaf)) + continue!(simulation; steps=1) + current = only(simulation.compiled.input_bindings) + @test typeof(current) === binding_type + @test current.carrier === carrier + @test typeof(model_status(model, :reader)) === status_type + @test model_status(model, :reader).seen === T(2) + @test only(parent(carrier)) === PSE.refvalue(model_status(model, :new_leaf), :x) + @test current.source_ids == [ObjectId(:new_leaf)] + end +end + +function array_scene(values, policy; existing) + source = ArraySource(values, Ref(0)) + objects = existing ? (Object(:leaf; scale=:Leaf), Object(:reader; scale=:Reader)) : + (Object(:reader; scale=:Reader),) + model = CompositeModel(objects...; applications=( + ModelSpec(source; name=:source, on=Many(scale=:Leaf)), + ModelSpec(ArrayManyReader(0f0); name=:reader, on=One(id=:reader), + inputs=(x=Many(SceneScope(); scale=:Leaf, application=:source, var=:x),)), + ), environment=(duration=Hour(1),), type_promotion=policy) + return model, source +end + +@testset "array-default type witnesses agree with real source materialization" begin + cases = ( + (Real[1.0, 2.0], Dict(Float64 => Float32), Vector{Float32}), + (Real[1, 2.0], Dict(Float64 => Float32), Vector{Real}), + (Real[1.0 2.0; 3.0 4.0], Dict(Float64 => Float32), Matrix{Float32}), + (Real[], Dict(Real => Float32), Vector{Float32}), + (Real[], Dict(Float64 => Float32), Vector{Real}), + (Real[1.0, 2.0], nothing, Vector{Real}), + ) + for (values, policy, Value) in cases + model, source = array_scene(copy(values), policy; existing=false) + @test source.declarations[] == 1 + plan = only(model.scenario_plan_cache.program.input_records) + @test plan.reference_types === Tuple{Base.RefValue{Value}} + simulation = run!(model; steps=0, outputs=:all) + carrier = only(simulation.compiled.input_bindings).carrier + @test carrier isa PSE.RefVector{Value} + @test isempty(carrier) + register_object!(model, Object(:leaf; scale=:Leaf)) + continue!(simulation; steps=1) + + # Compare to the existing ordinary initialization/conversion path, + # rather than reproducing its join or conversion logic in this test. + baseline_model, baseline_source = array_scene(copy(values), policy; existing=true) + @test baseline_source.declarations[] == 1 + baseline = run!(baseline_model; steps=1, outputs=:all) + actual = model_status(model, :leaf).x + expected = model_status(baseline_model, :leaf).x + @test typeof(actual) === Value + @test typeof(expected) === Value + @test isequal(actual, expected) + @test actual !== source.value + @test only(parent(only(simulation.compiled.input_bindings).carrier)) === + PSE.refvalue(model_status(model, :leaf), :x) + @test only(simulation.compiled.input_bindings).carrier === carrier + @test model_status(model, :reader).seen === model_status(baseline_model, :reader).seen + for key in ((:source, ObjectId(:leaf), :x), (:reader, ObjectId(:reader), :seen)) + @test outputs(simulation)[key] == outputs(baseline)[key] + end + end + + # Equal interface values may still contain different actual element types. + # Preserve separate constructor witnesses for the configured replacement. + base_source = ArraySource(Real[1.0, 2.0], Ref(0)) + replacement = ArraySource(Real[1f0, 2f0], Ref(0)) + template = CompositeModelTemplate(( + ModelSpec(base_source; name=:source, on=Many(scale=:Leaf)), + )) + instance = ObjectInstance(:stand, template; root=Object(:plant; scale=:Plant), + objects=(Object(:base_leaf; scale=:Leaf, parent=:plant), + Object(:override_leaf; scale=:Leaf, parent=:plant)), + object_overrides=(Override(object=:override_leaf, application=:source, model=replacement),)) + overridden = CompositeModel(instance, Object(:reader; scale=:Reader); applications=( + ModelSpec(ArrayManyReader(0f0); name=:reader, on=One(id=:reader), + inputs=(x=Many(SceneScope(); scale=:Leaf, application=:stand__source, var=:x),)), + ), environment=(duration=Hour(1),), type_promotion=Dict(Float64 => Float32)) + override_simulation = run!(overridden; steps=1, outputs=:all) + override_binding = only(override_simulation.compiled.input_bindings) + @test eltype(parent(override_binding.carrier)) === + Union{Base.RefValue{Vector{Float32}},Base.RefValue{Vector{Real}}} + @test model_status(overridden, :base_leaf).x isa Vector{Float32} + @test model_status(overridden, :override_leaf).x isa Vector{Real} + @test model_status(overridden, :reader).seen === 6f0 + @test override_binding.source_ids == [ObjectId(:base_leaf), ObjectId(:override_leaf)] + @test parent(override_binding.carrier)[1] === PSE.refvalue(model_status(overridden, :base_leaf), :x) + @test parent(override_binding.carrier)[2] === PSE.refvalue(model_status(overridden, :override_leaf), :x) + + # Length/value changes within the configured numeric representation remain + # runtime data, not additional reference-layout families. + model, source = array_scene(Real[1.0, 2.0], Dict(Float64 => Float32); existing=false) + @test source.declarations[] == 1 + push!(source.value, 4.0) + simulation = run!(model; steps=0, outputs=:none) + register_object!(model, Object(:leaf; scale=:Leaf)) + continue!(simulation; steps=1) + @test model_status(model, :leaf).x == Float32[1, 2, 4] + @test model_status(model, :leaf).x isa Vector{Float32} + @test model_status(model, :reader).seen === 7f0 +end + +@testset "configured Float32 refs take precedence over Float64 producer defaults" begin + source = Status(x=1f0) + model = CompositeModel(Object(:source; scale=:Leaf, status=source), + Object(:reader; scale=:Reader); applications=( + ModelSpec(Source(2.0); name=:source, on=Many(scale=:Leaf)), + ModelSpec(ManyReader{AbstractVector,Float32}(0f0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) + @test only(model.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float32}} + simulation = run!(model; steps=1, outputs=:all) + carrier = only(simulation.compiled.input_bindings).carrier + @test carrier isa PSE.RefVector{Float32} + @test model_status(model, :reader).seen === 2f0 + @test only(parent(carrier)) === PSE.refvalue(source, :x) + register_object!(model, Object(:z_leaf; scale=:Leaf, status=Status(x=3f0))) + continue!(simulation; steps=1) + @test only(simulation.compiled.input_bindings).carrier === carrier + @test carrier isa PSE.RefVector{Float32} + @test model_status(model, :reader).seen === 8f0 + @test parent(carrier)[1] === PSE.refvalue(model_status(model, :source), :x) + @test parent(carrier)[2] === PSE.refvalue(model_status(model, :z_leaf), :x) +end + +@testset "partial current source state also admits the missing default family" begin + supplied = Status(x=1f0) + model = CompositeModel(Object(:a_leaf; scale=:Leaf, status=supplied), + Object(:b_leaf; scale=:Leaf), Object(:reader; scale=:Reader); + applications=( + ModelSpec(Source(2.0); name=:source, on=Many(scale=:Leaf)), + ModelSpec(ManyReader{AbstractVector,Float64}(0.0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) + plan = only(model.scenario_plan_cache.program.input_records) + @test Set(fieldtypes(plan.reference_types)) == + Set((Base.RefValue{Float32}, Base.RefValue{Float64})) + simulation = run!(model; steps=0, outputs=:all) + carrier = only(simulation.compiled.input_bindings).carrier + @test carrier isa PSE.ObjectRefVector + @test model_status(model, :a_leaf).x === 1f0 + @test model_status(model, :b_leaf).x === 0.0 + @test parent(carrier)[1] === PSE.refvalue(supplied, :x) + @test parent(carrier)[2] === PSE.refvalue(model_status(model, :b_leaf), :x) + continue!(simulation; steps=1) + @test model_status(model, :reader).seen === 4.0 + @test model_status(model, :a_leaf).x === 2f0 + @test model_status(model, :b_leaf).x === 2.0 + @test only(simulation.compiled.input_bindings).carrier === carrier +end + +@testset "declared heterogeneous Many stays finite from empty to two producers" begin + model = CompositeModel(Object(:reader; scale=:Reader); applications=( + ModelSpec(Source(2f0); name=:first, on=Many(kind=:first, scale=:Leaf)), + ModelSpec(Source(3.0); name=:second, on=Many(kind=:second, scale=:Leaf)), + ModelSpec(ManyReader{AbstractVector,Float64}(0.0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, var=:x),)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; steps=0, outputs=:all) + binding = only(simulation.compiled.input_bindings) + carrier = binding.carrier + B = typeof(binding) + @test carrier isa PSE.ObjectRefVector + @test eltype(parent(carrier)) === Union{Base.RefValue{Float32},Base.RefValue{Float64}} + @test isempty(carrier) + register_object!(model, Object(:first_leaf; scale=:Leaf, kind=:first)) + continue!(simulation; steps=1) + @test only(simulation.compiled.input_bindings).carrier === carrier + @test typeof(only(simulation.compiled.input_bindings)) === B + @test model_status(model, :reader).seen === 2.0 + register_object!(model, Object(:second_leaf; scale=:Leaf, kind=:second)) + continue!(simulation; steps=1) + @test only(simulation.compiled.input_bindings).carrier === carrier + @test typeof(only(simulation.compiled.input_bindings)) === B + @test model_status(model, :reader).seen === 10.0 + @test map(typeof, collect(carrier)) == [Float32, Float64] + @test parent(carrier)[1] === PSE.refvalue(model_status(model, :first_leaf), :x) + @test parent(carrier)[2] === PSE.refvalue(model_status(model, :second_leaf), :x) +end + +@testset "empty scoped producer keeps its default and other reparentable families" begin + outside = Status(x=1f0) + model = CompositeModel(Object(:a_root; scale=:Plant), Object(:b_root; scale=:Plant), + Object(:b_leaf; scale=:Leaf, parent=:b_root, status=outside), + Object(:reader; scale=:Reader, parent=:a_root); applications=( + ModelSpec(Source(2.0); name=:source, + on=Many(Scope(ObjectId(:a_root)); scale=:Leaf)), + ModelSpec(ManyReader{AbstractVector,Float64}(0.0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; steps=0, outputs=:all) + binding = only(simulation.compiled.input_bindings) + B = typeof(binding) + C = typeof(binding.carrier) + @test eltype(parent(binding.carrier)) === Union{Base.RefValue{Float32},Base.RefValue{Float64}} + @test isempty(binding.carrier) + register_object!(model, Object(:a_leaf; scale=:Leaf, parent=:a_root)) + continue!(simulation; steps=1) + current = only(simulation.compiled.input_bindings) + @test typeof(current) === B + @test typeof(current.carrier) === C + @test model_status(model, :reader).seen === 2.0 + @test current.source_ids == [ObjectId(:a_leaf)] + reparent_object!(model, :b_leaf, :a_root) + continue!(simulation; steps=1) + current = only(simulation.compiled.input_bindings) + @test typeof(current) === B + @test typeof(current.carrier) === C + @test current.source_ids == [ObjectId(:a_leaf), ObjectId(:b_leaf)] + @test parent(current.carrier)[2] === PSE.refvalue(outside, :x) + @test model_status(model, :reader).seen === 8.0 +end + +@testset "numeric override witnesses do not erase an unobserved base family" begin + for base_configured in (false, true) + original = Status(x=1f0) + objects = base_configured ? + (Object(:base_leaf; scale=:Leaf, parent=:plant, status=original), + Object(:override_leaf; scale=:Leaf, parent=:plant)) : + (Object(:override_leaf; scale=:Leaf, parent=:plant, status=original),) + template = CompositeModelTemplate(( + ModelSpec(Source(2.0); name=:source, on=Many(scale=:Leaf)), + )) + instance = ObjectInstance(:stand, template; root=Object(:plant; scale=:Plant), + objects, object_overrides=(Override(object=:override_leaf, + application=:source, model=Source(3f0)),)) + model = CompositeModel(instance, Object(:reader; scale=:Reader); applications=( + ModelSpec(ManyReader{AbstractVector,Float64}(0.0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:stand__source, var=:x),)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; steps=0, outputs=:all) + binding = only(simulation.compiled.input_bindings) + B = typeof(binding) + if base_configured + @test binding.carrier isa PSE.RefVector{Float32} + continue!(simulation; steps=1) + @test model_status(model, :reader).seen === 5.0 + else + @test eltype(parent(binding.carrier)) === + Union{Base.RefValue{Float32},Base.RefValue{Float64}} + register_object!(model, Object(:z_base_leaf; scale=:Leaf, parent=:plant)) + continue!(simulation; steps=1) + current = only(simulation.compiled.input_bindings) + @test typeof(current) === B + @test typeof(current.carrier) === typeof(binding.carrier) + @test model_status(model, :reader).seen === 5.0 + @test parent(current.carrier)[1] === PSE.refvalue(original, :x) + @test parent(current.carrier)[2] === + PSE.refvalue(model_status(model, :z_base_leaf), :x) + end + end +end + +@testset "distributed Many observes destination refs rather than execution objects" begin + status = Status(x=1f0) + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:leaf; scale=:Leaf, status), Object(:reader; scale=:Reader); applications=( + ModelSpec(Distributor(4.0); name=:writer, on=Many(scale=:Scene), + outputs_to=(OutputTo(Many(SceneScope(); scale=:Leaf)),)), + ModelSpec(ManyReader{AbstractVector,Float32}(0f0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:writer, var=:x),)), + ), environment=(duration=Hour(1),)) + @test only(model.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float32}} + simulation = run!(model; steps=1, outputs=:all) + carrier = only(simulation.compiled.input_bindings).carrier + @test carrier isa PSE.RefVector{Float32} + @test model_status(model, :reader).seen === 4f0 + @test only(parent(carrier)) === PSE.refvalue(status, :x) +end + +@testset "a future One destination does not freeze a false Many preparation failure" begin + model = CompositeModel(Object(:scene; scale=:Scene), Object(:reader; scale=:Reader); + applications=( + ModelSpec(Distributor(4f0); name=:writer, on=Many(scale=:Scene), + outputs_to=(OutputTo(One(SceneScope(); id=:future_leaf, scale=:Leaf)),)), + ModelSpec(ManyReader{AbstractVector,Float32}(0f0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:writer, var=:x),)), + ), environment=(duration=Hour(1),)) + @test only(model.scenario_plan_cache.program.input_records) isa PSE.CompiledModelInputPlan + @test only(model.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float32}} + register_object!(model, Object(:future_leaf; scale=:Leaf)) + simulation = run!(model; steps=1, outputs=:all) + @test only(simulation.compiled.input_bindings).carrier isa PSE.RefVector{Float32} + @test model_status(model, :reader).seen === 4f0 + @test only(parent(only(simulation.compiled.input_bindings).carrier)) === + PSE.refvalue(model_status(model, :future_leaf), :x) +end + +@testset "stream-only Many uses its private type instead of canonical refs" begin + status = Status(x=1f0) + model = CompositeModel(Object(:leaf; scale=:Leaf, status), + Object(:reader; scale=:Reader); applications=( + ModelSpec(Source(2.0); name=:source, on=Many(scale=:Leaf), + output_routing=(x=:stream_only,)), + ModelSpec(ManyReader{AbstractVector,Float64}(0.0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) + @test only(model.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float64}} + simulation = run!(model; steps=0, outputs=:all) + carrier = only(simulation.compiled.input_bindings).carrier + @test carrier isa PSE.RefVector{Float64} + @test only(parent(carrier)) !== PSE.refvalue(status, :x) + continue!(simulation; steps=1) + @test model_status(model, :reader).seen === 2.0 + @test status.x === 1f0 + @test outputs(simulation)[(:source, ObjectId(:leaf), :x)] == [(1.0, 2.0)] +end + +@testset "an absent Required(Real) producer needs a configured element type" begin + function required_scene(::Type{V}) where {V} + CompositeModel(Object(:scene; scale=:Scene), Object(:reader; scale=:Reader); + applications=( + ModelSpec(RequiredDistributor(); name=:writer, on=Many(scale=:Scene), + outputs_to=(OutputTo(Many(SceneScope(); scale=:Leaf)),)), + ModelSpec(ManyReader{V,Float32}(0f0); name=:reader, on=One(id=:reader), + inputs=(x=Many(SceneScope(); scale=:Leaf, application=:writer, var=:x),)), + ), environment=(duration=Hour(1),)) + end + typed = required_scene(Vector{Float32}) + @test only(typed.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float32}} + @test only(run!(typed; steps=0, outputs=:none).compiled.input_bindings).carrier isa + PSE.RefVector{Float32} + ambiguous = required_scene(AbstractVector) + @test only(ambiguous.scenario_plan_cache.program.input_records) isa PSE.ScenarioPreparationFailure + @test_throws "no concrete configured source type" run!(ambiguous; steps=0, outputs=:none) + + # A known Ref in another scope is eligible after reparenting, but cannot + # determine a new producer configuration whose Required(Real) is unresolved. + scoped = CompositeModel(Object(:scene; scale=:Scene), Object(:a_root; scale=:Plant), + Object(:b_root; scale=:Plant), Object(:b_leaf; scale=:Leaf, parent=:b_root, + status=Status(x=1f0)), Object(:reader; scale=:Reader); applications=( + ModelSpec(RequiredDistributor(); name=:writer, on=Many(scale=:Scene), + outputs_to=(OutputTo(Many(Scope(ObjectId(:a_root)); scale=:Leaf)),)), + ModelSpec(ManyReader{AbstractVector,Float32}(0f0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:writer, var=:x),)), + ), environment=(duration=Hour(1),)) + @test only(scoped.scenario_plan_cache.program.input_records) isa PSE.ScenarioPreparationFailure + @test_throws "no concrete configured source type" run!(scoped; steps=0, outputs=:none) +end + +@testset "status-only empty Many requires a concrete configured element type" begin + function status_only(::Type{V}) where {V} + CompositeModel(Object(:reader; scale=:Reader); applications=( + ModelSpec(ManyReader{V,Float32}(0f0); name=:reader, on=One(id=:reader), + inputs=(x=Many(SceneScope(); scale=:Leaf, var=:x, from_status=true),)), + ), environment=(duration=Hour(1),)) + end + typed = status_only(Vector{Float32}) + @test only(typed.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float32}} + simulation = run!(typed; steps=0, outputs=:none) + @test only(simulation.compiled.input_bindings).carrier isa PSE.RefVector{Float32} + ambiguous = status_only(AbstractVector) + @test only(ambiguous.scenario_plan_cache.program.input_records) isa PSE.ScenarioPreparationFailure + @test_throws "no concrete configured source type" run!(ambiguous; steps=0, outputs=:none) +end + +struct VariantInputDefaults{T} <: AbstractResolved_Endpoint_ReaderModel + seed::Base.RefValue{Float64} + input_reads::Base.RefValue{Int} + output_reads::Base.RefValue{Int} +end +function PSE.inputs_(model::VariantInputDefaults) + model.input_reads[] += 1 + return (offset=Default(model.seed[]),) +end +function PSE.outputs_(model::VariantInputDefaults{T}) where {T} + model.output_reads[] += 1 + return (seen=zero(T),) +end +PSE.run!(::VariantInputDefaults{T}, status, environment, constants, context) where {T} = + (status.seen = T(status.offset + context.time); nothing) + +struct VariantPrivateDefaults{T} <: AbstractResolved_Endpoint_SourceModel + output_reads::Base.RefValue{Int} +end +PSE.inputs_(::VariantPrivateDefaults) = NamedTuple() +function PSE.outputs_(model::VariantPrivateDefaults{T}) where {T} + model.output_reads[] += 1 + return (live=zero(T), private=zero(T)) +end +function PSE.run!(::VariantPrivateDefaults{T}, status, environment, constants, context) where {T} + status.private = T(context.time) + status.live = 2 * status.private + return nothing +end + +function variant_defaults_scene(base, replacement; private=false) + template = CompositeModelTemplate((ModelSpec(base; name=:variant, on=Many(scale=:Leaf), + output_routing=private ? (private=:stream_only,) : NamedTuple()),)) + leaves = Tuple(Object(id; scale=:Leaf, parent=:plant, + status=private ? Status(private=99.0) : nothing) + for id in (:a_base, :b_override, :c_base, :d_override)) + instance = ObjectInstance(:stand, template; root=Object(:plant; scale=:Plant), + objects=leaves, object_overrides=( + Override(object=:b_override, application=:variant, model=replacement), + Override(object=:d_override, application=:variant, model=replacement))) + applications = private ? (ModelSpec(ManyReader{AbstractVector,Float64}(0.0); + name=:reader, on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:stand__variant, var=:private),)),) : () + return CompositeModel(instance, Object(:reader; scale=:Reader); + applications, environment=(duration=Hour(1),)) +end + +@testset "effective input defaults stay fresh and are read once per used variant" begin + base = VariantInputDefaults{Float64}(Ref(1.0), Ref(0), Ref(0)) + replacement = VariantInputDefaults{Float32}(Ref(1.0), Ref(0), Ref(0)) + model = variant_defaults_scene(base, replacement) + # Both input declarations are compatible at preparation. Their values may + # subsequently change without changing the prepared variable or numeric type. + base.seed[], replacement.seed[] = 3.0, 7.0 + simulation = run!(model; steps=0, outputs=:all) + compiled = simulation.compiled + application = compiled.applications_by_id[:stand__variant] + @test PSE._application_model(application, ObjectId(:b_override)) === replacement + references = Dict(id => PSE.refvalue(model_status(model, id), :offset) + for id in (:a_base, :b_override, :c_base, :d_override)) + @test model_status(model, :a_base).offset === model_status(model, :c_base).offset === 3.0 + @test model_status(model, :b_override).offset === model_status(model, :d_override).offset === 7.0 + @test model_status(model, :a_base).seen === 0.0 + @test model_status(model, :b_override).seen === 0f0 + for batched in (false, true) + base.input_reads[] = replacement.input_reads[] = 0 + if batched + PSE._prepare_model_input_statuses_batched!(model, (application,), + compiled.applications_by_id, compiled.input_bindings) + else + PSE._prepare_model_input_defaults!(model, (application,), compiled.applications_by_id) + end + @test (base.input_reads[], replacement.input_reads[]) == (1, 1) + @test all(PSE.refvalue(model_status(model, id), :offset) === reference + for (id, reference) in references) + end + step!(simulation) + @test model_status(model, :a_base).seen === 4.0 + @test model_status(model, :b_override).seen === 8f0 + @test outputs(simulation)[(:stand__variant, ObjectId(:a_base), :seen)] == [(1.0, 4.0)] + @test outputs(simulation)[(:stand__variant, ObjectId(:b_override), :seen)] == [(1.0, 8f0)] + base.seed[] = 11.0 + register_object!(model, Object(:e_base; scale=:Leaf, parent=:plant)) + step!(simulation) + @test model_status(model, :e_base).offset === 11.0 + @test model_status(model, :e_base).seen === 13.0 + @test all(PSE.refvalue(model_status(model, id), :offset) === reference + for (id, reference) in references) +end + +@testset "effective stream-only defaults retain private numeric refs and histories" begin + base = VariantPrivateDefaults{Float64}(Ref(0)) + replacement = VariantPrivateDefaults{Float32}(Ref(0)) + model = variant_defaults_scene(base, replacement; private=true) + simulation = run!(model; steps=0, outputs=:all) + compiled = simulation.compiled + application = compiled.applications_by_id[:stand__variant] + base_view = compiled.status_views_by_target[(:stand__variant, ObjectId(:a_base))] + override_view = compiled.status_views_by_target[(:stand__variant, ObjectId(:b_override))] + @test base_view.private_outputs.private isa Base.RefValue{Float64} + @test override_view.private_outputs.private isa Base.RefValue{Float32} + @test PSE.refvalue(base_view.status, :private) === base_view.private_outputs.private + @test PSE.refvalue(override_view.status, :private) === override_view.private_outputs.private + @test override_view.private_outputs.private !== PSE.refvalue(model_status(model, :b_override), :private) + base.output_reads[] = replacement.output_reads[] = 0 + PSE._prepare_model_output_statuses!(model, (application,), compiled.applications_by_id) + @test (base.output_reads[], replacement.output_reads[]) == (1, 1) + + # Isolate each cold reader from declaration/diagnostic reads elsewhere. + base.output_reads[] = replacement.output_reads[] = 0 + initial = PSE._stream_only_initial_reference(model, ObjectId(:b_override), + [:stand__variant], :private, compiled.applications_by_id) + @test initial isa Base.RefValue{Float32} + @test initial[] === 0f0 + @test (base.output_reads[], replacement.output_reads[]) == (0, 1) + base.output_reads[] = replacement.output_reads[] = 0 + positions = Dict(id => index for (index, id) in pairs(compiled.application_order)) + ephemeral = PSE._compile_model_status_view(model, application, ObjectId(:b_override), (), + compiled.applications_by_id, positions, compiled.distributed_outputs; + execution_stamp=override_view.execution_stamp, status_view_schema=compiled.status_view_schema, + input_binding_storage=compiled.input_bindings) + @test (base.output_reads[], replacement.output_reads[]) == (0, 1) + @test ephemeral.private_outputs.private isa Base.RefValue{Float32} + @test ephemeral.canonical_status === override_view.canonical_status + @test compiled.status_views_by_target[(:stand__variant, ObjectId(:b_override))] === override_view + continue!(simulation; steps=2) + @test model_status(model, :reader).seen === 8.0 + @test model_status(model, :a_base).private === model_status(model, :b_override).private === 99.0 + @test model_status(model, :a_base).live === 4.0 + @test model_status(model, :b_override).live === 4f0 + @test outputs(simulation)[(:stand__variant, ObjectId(:a_base), :private)] == [(1.0, 1.0), (2.0, 2.0)] + @test outputs(simulation)[(:stand__variant, ObjectId(:b_override), :private)] == [(1.0, 1f0), (2.0, 2f0)] + @test override_view.private_outputs.private === + compiled.status_views_by_target[(:stand__variant, ObjectId(:b_override))].private_outputs.private +end + struct CountWriterChecks count::Base.RefValue{Int} end @@ -111,12 +671,12 @@ end cells = [Ref(1.0), Ref(2.0), Ref(3.0)] visited = Int[] reference_for(id) = (push!(visited, id.value); cells[id.value]) - @test PSE._input_reference_carrier(One(), ids[1:1], reference_for) === cells[1] + @test PSE._input_reference_carrier(One(), ids[1:1], reference_for, Tuple{}) === cells[1] @test visited == [1] empty!(visited) - @test isnothing(PSE._input_reference_carrier(OptionalOne(), ObjectId{Int}[], reference_for)) + @test isnothing(PSE._input_reference_carrier(OptionalOne(), ObjectId{Int}[], reference_for, Tuple{})) @test isempty(visited) - homogeneous = PSE._input_reference_carrier(Many(), ids, reference_for) + homogeneous = PSE._input_reference_carrier(Many(), ids, reference_for, Tuple{Base.RefValue{Float64}}) @test homogeneous isa PSE.RefVector{Float64} @test visited == [1, 2, 3] @test all(parent(homogeneous)[index] === cells[index] for index in eachindex(cells)) @@ -126,7 +686,7 @@ end mixed = Base.RefValue[Ref(1f0), Ref(2.0), Ref(3)] empty!(visited) mixed_for(id) = (push!(visited, id.value); mixed[id.value]) - heterogeneous = PSE._input_reference_carrier(Many(), ids, mixed_for) + heterogeneous = PSE._input_reference_carrier(Many(), ids, mixed_for, Tuple{Base.RefValue{Float32},Base.RefValue{Float64},Base.RefValue{Int}}) @test heterogeneous isa PSE.ObjectRefVector @test visited == [1, 2, 3] @test all(parent(heterogeneous)[index] === mixed[index] for index in eachindex(mixed)) @@ -135,16 +695,16 @@ end @test heterogeneous[1] === 7f0 abstract = Ref{Real}(1.0) - @test PSE._input_reference_carrier(Many(), ids[1:1], _ -> abstract) isa PSE.ObjectRefVector - @test PSE._input_reference_carrier(Many(), ObjectId{Int}[], reference_for) isa PSE.RefVector{Any} - @test isnothing(PSE._input_reference_carrier(One(), ids[1:1], _ -> nothing)) + @test PSE._input_reference_carrier(Many(), ids[1:1], _ -> abstract, Tuple{Base.RefValue{Real}}) isa PSE.ObjectRefVector + @test PSE._input_reference_carrier(Many(), ObjectId{Int}[], reference_for, Tuple{Base.RefValue{Float64}}) isa PSE.RefVector{Float64} + @test isnothing(PSE._input_reference_carrier(One(), ids[1:1], _ -> nothing, Tuple{})) empty!(visited) missing_for(id) = (push!(visited, id.value); id.value == 2 ? nothing : cells[id.value]) - @test isnothing(PSE._input_reference_carrier(Many(), ids, missing_for)) + @test isnothing(PSE._input_reference_carrier(Many(), ids, missing_for, Tuple{Base.RefValue{Float64}})) @test visited == [1, 2] external = Ref([4.0], 1) - @test_throws ArgumentError PSE._input_reference_carrier(One(), ids[1:1], _ -> external) - @test_throws ArgumentError PSE._input_reference_carrier(Many(), ids[1:1], _ -> external) + @test_throws ArgumentError PSE._input_reference_carrier(One(), ids[1:1], _ -> external, Tuple{}) + @test_throws ArgumentError PSE._input_reference_carrier(Many(), ids[1:1], _ -> external, Tuple{Base.RefValue{Float64}}) end struct OffsetSourceIds{T} <: AbstractVector{T} @@ -178,7 +738,7 @@ end ids = OffsetSourceIds(ObjectId.(1:4), -3) visited = Int[] getter(id) = (push!(visited, id.value); cells[id.value]) - carrier = PSE._input_reference_carrier(Many(), ids, getter) + carrier = PSE._input_reference_carrier(Many(), ids, getter, Tuple{unique(typeof.(cells))...}) @test ids.reads == [-3, -2, -1, 0] @test visited == [1, 2, 3, 4] @test all(parent(carrier)[index] === cells[index] for index in eachindex(cells)) @@ -190,12 +750,12 @@ end end end empty_ids = OffsetSourceIds(ObjectId{Int}[], 9) - @test PSE._input_reference_carrier(Many(), empty_ids, _ -> error("empty source visited")) isa PSE.RefVector{Any} + @test PSE._input_reference_carrier(Many(), empty_ids, _ -> error("empty source visited"), Tuple{Base.RefValue{Float32}}) isa PSE.RefVector{Float32} @test isempty(empty_ids.reads) for selector in (One(), OptionalOne()) ids = OffsetSourceIds([ObjectId(1)], 7) cell = Ref(5.0) - @test PSE._input_reference_carrier(selector, ids, _ -> cell) === cell + @test PSE._input_reference_carrier(selector, ids, _ -> cell, Tuple{}) === cell @test ids.reads == [7] end end @@ -203,14 +763,14 @@ end @noinline function repeat_point_carrier(model, selector, ids, expected, repetitions) same = true for _ in 1:repetitions - same &= PSE._input_carrier(model, selector, ids, Val(:x)) === expected + same &= PSE._input_carrier(model, selector, ids, Val(:x), Tuple{}) === expected end return same end @noinline point_allocations(model, selector, ids, expected, repetitions) = @allocated repeat_point_carrier(model, selector, ids, expected, repetitions) @noinline many_allocations(ids, getter) = - @allocated PSE._input_reference_carrier(Many(), ids, getter) + @allocated PSE._input_reference_carrier(Many(), ids, getter, Tuple{Base.RefValue{Float64}}) @testset "point materialization has no allocation per source and Many builds one vector" begin status = Status(x=1.0) From 2d32f5e1023bab5d1824d02cf1ee6e2e9fd944eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 13 Nov 2026 23:47:10 +0100 Subject: [PATCH 111/324] Unify input default staging and carrier wiring --- src/composite_model/compilation.jl | 199 +------------------- src/visualization/model_graph_view.jl | 4 +- test/test-resolved-input-materialization.jl | 18 +- 3 files changed, 17 insertions(+), 204 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b8c75de22..8a768edc6 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4840,28 +4840,15 @@ function _extend_compiled_scene( end rewired_applications end - if pure_addition - final_input_references = _model_input_status_references(changed_bindings) - _prepare_model_input_statuses_batched!( - model, - affected_input_applications, - applications_by_id, - changed_bindings; - final_references=final_input_references, - performance=performance, - ) - else - _prepare_model_input_defaults!( - model, - affected_input_applications, - applications_by_id; - performance=performance, - ) - _wire_model_input_carriers!( - model, - changed_bindings, - ) - end + final_input_references = _model_input_status_references(changed_bindings) + _prepare_model_input_statuses_batched!( + model, + affected_input_applications, + applications_by_id, + changed_bindings; + final_references=final_input_references, + performance=performance, + ) _validate_model_required_inputs!( model, affected_input_applications, @@ -6497,42 +6484,6 @@ function _apply_status_recipes!( return model end -function _status_with_reference(status::Status, variable::Symbol, reference::Base.RefValue) - names = propertynames(status) - if variable in names - references = ntuple( - index -> names[index] == variable ? reference : refvalue(status, names[index]), - length(names), - ) - return Status(NamedTuple{names}(references)) - end - extended_names = (names..., variable) - references = (ntuple(index -> refvalue(status, names[index]), length(names))..., reference) - return Status(NamedTuple{extended_names}(references)) -end - -function _status_with_default( - model::CompositeModel, - status::Status, - object_id::ObjectId, - variable::Symbol, - value; - application_id=nothing, - origin=:model_default, -) - variable in propertynames(status) && return status - initial, _, _ = _materialize_status_value( - model, - variable, - value; - object_id=object_id, - application_id=application_id, - origin=origin, - private_copy=true, - ) - return _status_with_reference(status, variable, Ref(initial)) -end - function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId) object = _model_object(model, object_id) status = object.status @@ -7246,138 +7197,6 @@ function _model_input_status_references(bindings) return references end -function _prepare_model_input_defaults!( - model::CompositeModel, - applications, - applications_by_id; - final_references=nothing, - performance=nothing, -) - for partial in applications - _with_model_application(applications_by_id, partial) do application - _model_input_names(application) - schemas = _application_default_schemas(application, Val(:inputs)) - for object_id in application.target_ids - Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults - status = _ensure_model_object_status!(model, object_id) - for (variable, value) in pairs(defaults) - variable = Symbol(variable) - variable in propertynames(status) && continue - reference = isnothing(final_references) ? - nothing : - get( - final_references, - (application.id, object_id, variable), - nothing, - ) - if !isnothing(reference) - # Preserve conversion callbacks, validation, and diagnostic - # records while avoiding a default Status that the resolved - # carrier would replace immediately below. - _no_status_conversion(model.status_conversion) || - _materialize_status_value( - model, - variable, - value; - object_id=object_id, - application_id=application.id, - origin=:model_input_default, - private_copy=true, - ) - status = _status_with_reference( - status, - variable, - reference, - ) - _runtime_performance_count!( - performance, - :input_default_status_rewrites_avoided, - ) - continue - end - status = _status_with_default( - model, - status, - object_id, - variable, - value; - application_id=application.id, - origin=:model_input_default, - ) - push!( - get!( - model.input_default_status_variables, - object_id, - Set{Symbol}(), - ), - variable, - ) - end - _replace_model_object_status!(model, object_id, status) - return nothing - end - end - return nothing - end - end - return model -end - -function _wire_model_input_carriers!( - model::CompositeModel, - bindings; - final_references=nothing, -) - for binding in bindings - binding.carrier_hint == :temporal_stream && continue - isnothing(binding.carrier) && continue - object = _model_object(model, binding.consumer_id) - status = object.status - status isa Status || continue - reference = if isnothing(final_references) - _model_input_status_reference(binding) - else - get( - final_references, - ( - binding.application_id, - binding.consumer_id, - binding.input, - ), - nothing, - ) - end - isnothing(reference) && - (reference = _model_input_status_reference(binding)) - if binding.input in propertynames(status) && - refvalue(status, binding.input) === reference - delete!( - get!( - model.input_default_status_variables, - binding.consumer_id, - Set{Symbol}(), - ), - binding.input, - ) - continue - end - _replace_model_object_status!( - model, - object, - _status_with_reference(status, binding.input, reference), - ) - delete!( - get!( - model.input_default_status_variables, - binding.consumer_id, - Set{Symbol}(), - ), - binding.input, - ) - end - return model -end - function _prepare_model_input_statuses_batched!( model::CompositeModel, applications, diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index 5090e2fa6..f7c64f360 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -432,8 +432,8 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) ) end _model_graph_phase!(diagnostics, :input_status, nothing) do - _prepare_model_input_defaults!(model, applications, _applications_by_id(applications)) - _wire_model_input_carriers!(model, input_bindings) + _prepare_model_input_statuses_batched!( + model, applications, _applications_by_id(applications), input_bindings) end children = Dict{Symbol,Set{Symbol}}( diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index c68335277..127ee613d 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -564,18 +564,12 @@ end @test model_status(model, :b_override).offset === model_status(model, :d_override).offset === 7.0 @test model_status(model, :a_base).seen === 0.0 @test model_status(model, :b_override).seen === 0f0 - for batched in (false, true) - base.input_reads[] = replacement.input_reads[] = 0 - if batched - PSE._prepare_model_input_statuses_batched!(model, (application,), - compiled.applications_by_id, compiled.input_bindings) - else - PSE._prepare_model_input_defaults!(model, (application,), compiled.applications_by_id) - end - @test (base.input_reads[], replacement.input_reads[]) == (1, 1) - @test all(PSE.refvalue(model_status(model, id), :offset) === reference - for (id, reference) in references) - end + base.input_reads[] = replacement.input_reads[] = 0 + PSE._prepare_model_input_statuses_batched!(model, (application,), + compiled.applications_by_id, compiled.input_bindings) + @test (base.input_reads[], replacement.input_reads[]) == (1, 1) + @test all(PSE.refvalue(model_status(model, id), :offset) === reference + for (id, reference) in references) step!(simulation) @test model_status(model, :a_base).seen === 4.0 @test model_status(model, :b_override).seen === 8f0 From bb40cfccbcc91842dca11809b434a51ab6139392 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 00:52:01 +0100 Subject: [PATCH 112/324] Prepare typed output retention from execution schemas --- src/composite_model/compilation.jl | 16 +- .../execution_batch_schemas.jl | 4 +- src/composite_model/execution_dispatch.jl | 2 - src/composite_model/runtime_outputs.jl | 613 +++++++++++------- src/time/runtime/output_export.jl | 6 +- test/test-model-empty-output-requests.jl | 52 +- test/test-model-output-boundaries.jl | 4 +- test/test-model-public-refresh-owners.jl | 2 +- 8 files changed, 436 insertions(+), 263 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 8a768edc6..c1400f880 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -373,6 +373,16 @@ struct _ApplicationTargetTemplateKey{I<:ObjectId} species::Union{Nothing,Symbol} id::Union{Nothing,I} scope_roots::Union{Nothing,Vector{I}} + + # The registry always supplies I. There is no inferred constructor: both + # identity-bearing fields can be nothing, which cannot determine I. + function _ApplicationTargetTemplateKey{I}( + scale::Union{Nothing,Symbol}, kind::Union{Nothing,Symbol}, + species::Union{Nothing,Symbol}, id::Union{Nothing,I}, + scope_roots::Union{Nothing,Vector{I}}, + ) where {I<:ObjectId} + return new{I}(scale, kind, species, id, scope_roots) + end end function Base.hash(key::_ApplicationTargetTemplateKey, seed::UInt) @@ -7869,8 +7879,10 @@ function _prepare_many_reference_types(model, consumer, input, selector, source_var, producer_ids, applications_by_id, distributed_output_plans) references = Any[] add(R) = R in references || push!(references, R) - declared_input = getproperty(_application_ports(consumer).input_types, input) - fallback = declared_input <: AbstractVector ? eltype(declared_input) : Union{} + declared_input = _configured_status_value_type(model.status_conversion, + getproperty(_application_ports(consumer).input_types, input), nothing) + fallback = !isnothing(declared_input) && declared_input <: AbstractVector ? + eltype(declared_input) : Union{} isconcretetype(fallback) || (fallback = Union{}) producers = isempty(producer_ids) ? (nothing,) : producer_ids for producer_id in producers diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 87e2841f7..749b016c7 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -606,8 +606,8 @@ function _prepare_execution_batch_schemas(simulation::Simulation, schemas::Named plan.batches,closed_slots,plan.schedule,plan.model_revision,plan.environment_revision) return Simulation(simulation.model,simulation.compiled,simulation.environment_bindings, closed,simulation.output_retention,storage,simulation.output_datetimes, - simulation.output_requests,simulation.output_request_matchers, - simulation.output_request_targets,simulation.output_request_model_revision, + _prepare_output_request_schemas(simulation.output_requests, schemas), + simulation.output_request_model_revision, simulation.runtime_revision,simulation.current_step,simulation.constants, simulation.performance) end diff --git a/src/composite_model/execution_dispatch.jl b/src/composite_model/execution_dispatch.jl index d802152dd..e40221c89 100644 --- a/src/composite_model/execution_dispatch.jl +++ b/src/composite_model/execution_dispatch.jl @@ -56,8 +56,6 @@ function _simulation_with_execution_plan(simulation::Simulation, plan::CompiledE simulation.temporal_streams, simulation.output_datetimes, simulation.output_requests, - simulation.output_request_matchers, - simulation.output_request_targets, simulation.output_request_model_revision, simulation.runtime_revision, simulation.current_step, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index b4def88c9..dd2b763e1 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -28,6 +28,21 @@ mutable struct OutputRequestMembership{T} initial::T end +struct OutputRequestTarget{T} + scale::Union{Nothing,Symbol} + memberships::Vector{OutputRequestMembership{T}} +end + +struct CompiledOutputRequest{R,M,D,RF,VF,SF} + request::R + matcher::M + application_id::Symbol + targets::D + reference_types::Type{RF} + value_types::Type{VF} + stream_types::Type{SF} +end + """ TemporalDependencyBuffer{T} <: AbstractVector{Tuple{Float64,T}} @@ -1437,7 +1452,7 @@ end Result of running a [`CompositeModel`](@ref). Use `outputs`, `collect_outputs`, [`final_state`](@ref), and `PlantSimEngine.Diagnostics` to inspect it. """ -mutable struct Simulation{S,CS,EB,EP,OR,TS,DT,R,RM,RT,C,P} +mutable struct Simulation{S,CS,EB,EP,OR,TS,DT,R,C,P} model::S compiled::CS environment_bindings::EB @@ -1446,8 +1461,6 @@ mutable struct Simulation{S,CS,EB,EP,OR,TS,DT,R,RM,RT,C,P} temporal_streams::TS output_datetimes::DT output_requests::R - output_request_matchers::RM - output_request_targets::RT output_request_model_revision::Int runtime_revision::Int current_step::Int @@ -1831,32 +1844,31 @@ _model_output_object_ids(compiled, application, variable::Symbol) = compiled.distributed_outputs, ) -function _model_output_reference( - compiled, - application, - object_id::ObjectId, - variable::Symbol, -) +@inline function _output_reference_from_view(view, operation::F, variable, args::Vararg{Any,N}) where {F,N} + return operation(refvalue(view.status, variable), args...) +end + +function _with_model_output_reference(operation::F, compiled, application, + object_id::ObjectId, variable::Symbol, args::Vararg{Any,N}, +) where {F,N} + id = _index_object_id(compiled.model.registry.objects, object_id) if _model_output_names(application) !== _model_canonical_output_names(application) && variable in _model_output_names(application) && !(variable in _model_canonical_output_names(application)) && - haskey( - compiled.status_views_by_target, - (application.id, object_id), - ) - status = _model_status_view_for_application( - compiled, - application, - object_id, - ).status - return refvalue(status, variable) + haskey(compiled.status_views_by_target, (application.id, id)) + return Base.@inline _with_model_status_view(_output_reference_from_view, + compiled.status_view_schema, application.id, + compiled.status_views_by_target[(application.id, id)], operation, variable, args...) + end + return Base.@inline _with_registered_status(compiled.model.registry.objects.catalog, + model_status(compiled.model, id)) do status + operation(refvalue(status, variable), args...) end - return refvalue( - model_status(compiled.model, object_id), - variable, - ) end +_model_output_reference(compiled, application, object_id::ObjectId, variable::Symbol) = + _with_model_output_reference(identity, compiled, application, object_id, variable) + function _initialize_model_output_stream!( streams, compiled::CompiledCompositeModel, @@ -4857,7 +4869,7 @@ function compile_model_output_retention( requested_outputs = Set{Tuple{Symbol,Symbol}}() names = Set{Symbol}() - for request in output_requests + _foreach_output_request(output_requests) do request request.name in names && error( "Duplicate output request name `$(request.name)`. Request names must be unique." ) @@ -7651,223 +7663,345 @@ function _continue_scene!(simulation::Simulation, steps::Integer) return simulation end -function _output_request_target( - model, - compiled, - application, - object_id, +# Lower the existing current/future output witness, without reading any value. +function _prepared_request_container_members(::Type{C}) where {C} + C <: AbstractVector && return Tuple(Base.uniontypes(eltype(C))) + C <: Tuple && return fieldtypes(C) + throw(ArgumentError("A prepared output container must be a finite tuple or vector family.")) +end + +function _prepared_request_reference_family(::Type{R}) where {R} + references = if R <: Ref + (R,) + elseif R <: RefVector + _prepared_request_container_members(fieldtype(R, :v)) + elseif R <: ObjectRefVector + _prepared_request_container_members(fieldtype(R, :refs)) + else + throw(ArgumentError("An output request has no prepared reference witness.")) + end + !isempty(references) && all(T -> T <: Ref && isconcretetype(T), references) || + throw(ArgumentError("An output request needs exact finite reference types.")) + return references +end + +function _prepared_request_add_value_types!(types, ::Type{T}) where {T} + for Value in Base.uniontypes(T) + isconcretetype(Value) || throw(ArgumentError( + "An output-request value has no finite prepared type family.")) + Value in types || push!(types, Value) + end + return nothing +end + +function _prepared_request_output_families(::Type{Targets}) where {Targets<:Tuple} + families = Dict{Symbol,NamedTuple{(:references,:values,:streams),Tuple{Vector{Any},Vector{Any},Vector{Any}}}}() + for Target in fieldtypes(Targets) + Outputs = fieldtype(Target, :output_bindings) + Outputs <: Tuple && isconcretetype(Outputs) || throw(ArgumentError( + "Prepared output bindings need a concrete tuple schema.")) + for Output in fieldtypes(Outputs) + variable = Output.parameters[1] + streams, Reference = if Output <: RuntimeOutputStream + ((fieldtype(Output, :stream),), fieldtype(Output, :reference)) + elseif Output <: RuntimeDistributedOutputStream + (_prepared_request_container_members(fieldtype(Output, :streams)), + fieldtype(Output, :references)) + else + throw(ArgumentError("Invalid prepared runtime output witness.")) + end + family = get!(families, variable) do + (references=Any[], values=Any[], streams=Any[]) + end + for RefType in _prepared_request_reference_family(Reference) + RefType in family.references || push!(family.references, RefType) + # Membership initial values come from this fresh reference, + # and may be wider than the append-only stream's value type. + _prepared_request_add_value_types!(family.values, eltype(RefType)) + end + for Stream in streams + Stream in family.streams || push!(family.streams, Stream) + Stream <: AbstractVector && isconcretetype(Stream) || throw(ArgumentError( + "A retained stream needs a concrete prepared vector schema.")) + Sample = eltype(Stream) + Sample <: Tuple && fieldcount(Sample) == 2 && + fieldtype(Sample, 1) === Float64 || throw(ArgumentError( + "A retained stream must contain (Float64, value) samples.")) + _prepared_request_add_value_types!(family.values, fieldtype(Sample, 2)) + end + end + end + return families +end + +@generated function _prepared_output_request_types( + ::ClosedExecutionCohortSchema{Targets}, variable::Symbol, +) where {Targets} + branches = Expr[] + for (name, family) in _prepared_request_output_families(Targets) + Refs, Values, Streams = Tuple{family.references...}, Tuple{family.values...}, Tuple{family.streams...} + Witness = NamedTuple{(:references,:values,:streams),Tuple{Type{Refs},Type{Values},Type{Streams}}} + push!(branches, :(variable === $(QuoteNode(name)) && + return $Witness(($Refs, $Values, $Streams)))) + end + return quote + $(branches...) + throw(ArgumentError("The requested variable has no prepared retained-output witness.")) + end +end + +@inline _prepared_output_request_types(schema::PreparedExecutionBatchSchema, variable::Symbol, - start_time, -) - initial = _model_output_reference( - compiled, - application, - object_id, - variable, - )[] - return ( - scale=_model_object(model, object_id).scale, - memberships=[ - OutputRequestMembership( - float(start_time), - nothing, - deepcopy(initial), - ), - ], - ) +) = _prepared_output_request_types(_execution_cohort_schema(schema), variable) + +@inline _visit_output_request(request, operation::F) where {F} = operation(request) +@inline _visit_output_request(record::CompiledOutputRequest, operation::F) where {F} = operation(record.request) + +function _foreach_output_request(operation::F, requests) where {F} + for slot in 1:length(requests) + Base.@inline _with_metadata_entry(_visit_output_request, requests, slot, operation) + end + return nothing +end + +@generated function _with_output_request_reference(f::F, record::CompiledOutputRequest{R,M,D,RF}, + reference, args::Vararg{Any,N}, +) where {F,R,M,D,RF,N} + branches = [:(reference isa $RefType && return f(reference::$RefType, args...)) + for RefType in fieldtypes(RF)] + return quote + $(branches...) + throw(ArgumentError("The output-request reference is outside its prepared family.")) + end +end + +@generated function _with_output_request_value(f::F, record::CompiledOutputRequest{R,M,D,RF,VF,SF}, + value, args::Vararg{Any,N}, +) where {F,R,M,D,RF,VF,SF,N} + branches = [:(value isa $T && return f(value::$T, args...)) for T in fieldtypes(VF)] + return quote + $(branches...) + throw(ArgumentError("The output-request value is outside its prepared family.")) + end +end + +@generated function _with_output_request_target(f::F, record::CompiledOutputRequest{R,M,D,RF,VF,SF}, + target, args::Vararg{Any,N}, +) where {F,R,M,D,RF,VF,SF,N} + fieldtypes(VF) === (Any,) && return :(f(target, args...)) + branches = [:(target isa OutputRequestTarget{$T} && + return f(target::OutputRequestTarget{$T}, args...)) for T in fieldtypes(VF)] + return quote + $(branches...) + throw(ArgumentError("The output-request target is outside its prepared family.")) + end +end + +function _new_output_request_target(initial::T, scale, start_time) where {T} + return OutputRequestTarget(scale, + OutputRequestMembership{T}[OutputRequestMembership(float(start_time), nothing, deepcopy(initial))]) +end + +function _output_request_reference_value(reference::R, record, operation::F, + args::Vararg{Any,N}, +) where {R,F,N} + return Base.@inline _with_output_request_value(operation, record, reference[], args...) +end + +function _output_request_from_reference(reference, record, operation::F, + args::Vararg{Any,N}, +) where {F,N} + return Base.@inline _with_output_request_reference(_output_request_reference_value, + record, reference, record, operation, args...) +end + +function _with_output_request_initial(operation::F, record, compiled, application, + object_id, args::Vararg{Any,N}, +) where {F,N} + return Base.@inline _with_model_output_reference(_output_request_from_reference, + compiled, application, object_id, record.request.var, record, operation, args...) +end + +function _compile_output_request(model, compiled, request) + matcher = _compile_selector_matcher(model, request.selector) + application = _model_request_application(model, compiled, request) + I = keytype(typeof(model.registry.objects)) + targets = Dict{I,Any}() + record = CompiledOutputRequest(request, matcher, application.id, targets, Tuple{Any}, Tuple{Any}, Tuple{Any}) + owned_ids = Set{I}(_index_object_id(model.registry.objects, id) + for id in _model_output_object_ids(compiled, application, request.var)) + for raw_id in _resolve_object_ids(model, request.selector, matcher; context=request.context) + object_id = _index_object_id(model.registry.objects, raw_id) + object_id in owned_ids || continue + targets[object_id] = _with_output_request_initial(_new_output_request_target, + record, compiled, application, object_id, _model_object(model, object_id).scale, 0.0) + end + return record +end + +function _compile_output_requests(model, compiled, requests::Tuple) + names = map(request -> request.name, requests) + entries = map(request -> _compile_output_request(model, compiled, request), requests) + return CompiledMetadataTable(NamedTuple{names}(entries)) +end + +# Host lowering reuses all existing membership objects and snapshot values. +# The schema also contains admitted future targets when a group is empty. +function _prepare_output_request_record(record, schemas) + schema = getproperty(schemas, record.application_id) + types = _prepared_output_request_types(schema, record.request.var) + Target = Union{(OutputRequestTarget{T} for T in fieldtypes(types.values))...} + I = keytype(typeof(record.targets)) + targets = Dict{I,Target}() + prepared = CompiledOutputRequest(record.request, record.matcher, record.application_id, + targets, types.references, types.values, types.streams) + for (id, target) in record.targets + targets[id] = _with_output_request_target(identity, prepared, target) + end + return prepared +end + +function _prepare_output_request_schemas(owner::CompiledMetadataTable, schemas) + return CompiledMetadataTable(map(record -> _prepare_output_request_record(record, schemas), + owner.entries)) end _output_request_target_is_active(target) = - !isempty(target.memberships) && - isnothing(last(target.memberships).end_time) + !isempty(target.memberships) && isnothing(last(target.memberships).end_time) + +@generated function _output_request_stream_published_at(record::CompiledOutputRequest{R,M,D,RF,VF,SF}, + samples, time::Float64, +) where {R,M,D,RF,VF,SF} + branches = [:(samples isa $S && return !isempty(samples::$S) && first(last(samples::$S)) == time) + for S in fieldtypes(SF)] + return quote + $(branches...) + throw(ArgumentError("The output-request stream is outside its prepared family.")) + end +end -function _output_request_published_at(simulation, application_id, object_id, variable, time) +function _output_request_published_at(record, simulation, application_id, object_id, variable, time) samples = get(simulation.temporal_streams, (application_id, object_id, variable), nothing) - return !isnothing(samples) && !isempty(samples) && first(last(samples)) == time + isnothing(samples) && return false + return Base.@inline _output_request_stream_published_at(record, samples, time) end -function _initial_output_request_targets( - model, - compiled, - output_requests, - output_request_matchers, +function _close_output_request_target!(target, end_time) + last(target.memberships).end_time = end_time + return nothing +end + +function _reopen_output_request_target!(initial, target::OutputRequestTarget{T}, start_time) where {T} + push!(target.memberships, OutputRequestMembership(start_time, nothing, deepcopy(initial))) + return nothing +end + +function _refresh_output_request_target!(target, record, simulation, application, object_id, start_time) + _output_request_target_is_active(target) && return nothing + return _with_output_request_initial(_reopen_output_request_target!, record, + simulation.compiled, application, object_id, target, start_time) +end + +function _refresh_output_request_for_application!(application, record, simulation, + added_object_ids, completed_applications, ) - targets = Dict{Symbol,Tuple{Symbol,Dict{ObjectId,Any}}}() - for request in output_requests - application = _model_request_application(model, compiled, request) - object_ids = _resolve_object_ids( - model, - request.selector, - output_request_matchers[request.name]; - context=request.context, - ) - owned_ids = Set( - _model_output_object_ids( - compiled, - application, - request.var, - ), - ) - filter!(id -> id in owned_ids, object_ids) - targets[request.name] = ( - application.id, - Dict( - id => _output_request_target( - model, - compiled, - application, - id, - request.var, - 0.0, - ) - for id in object_ids - ), - ) + request = record.request + object_targets = record.targets + application_id = record.application_id + objects = simulation.model.registry.objects + I = keytype(typeof(objects)) + matched_ids = I[] + if isnothing(added_object_ids) + _runtime_performance_count!(simulation.performance, :output_request_selector_resolutions) + for raw_id in _resolve_object_ids(simulation.model, _selector_as_many(request.selector), + record.matcher; context=request.context) + push!(matched_ids, _index_object_id(objects, raw_id)) + end + else + _runtime_performance_count!(simulation.performance, + :output_request_incremental_object_checks, length(added_object_ids)) + for raw_id in added_object_ids + object_id = _index_object_id(objects, raw_id) + _selector_matches_object_id(simulation.model, record.matcher, object_id; + context=request.context) && push!(matched_ids, object_id) + end end - return targets + owned_ids = Set{I}() + for raw_id in _model_output_object_ids(simulation.compiled, application, request.var) + push!(owned_ids, _index_object_id(objects, raw_id)) + end + filter!(id -> id in owned_ids, matched_ids) + active_ids = Set{I}() + for (object_id, raw_target) in object_targets + Base.@inline _with_output_request_target(_output_request_target_is_active, + record, raw_target) && push!(active_ids, object_id) + end + matched_id_set = Set{I}(matched_ids) + current_ids = isnothing(added_object_ids) ? matched_id_set : union(active_ids, matched_id_set) + if request.selector isa Union{One,OptionalOne} && length(current_ids) > 1 + error("Output request `$(request.name)` expected at most one current object for selector ", + "`$(request.selector)`, got $([id.value for id in current_ids]).") + end + publication_time = float(simulation.current_step + 1) + manual_application = application_id in simulation.compiled.scenario_plan.manual_application_ids + application_completed = + (!isnothing(completed_applications) && application_id in completed_applications) || + get(simulation.output_retention.accepted_call_times, application_id, -Inf) == publication_time + membership_end_time = application_completed ? + float(simulation.current_step + 1) : float(simulation.current_step) + if isnothing(added_object_ids) + for object_id in active_ids + object_id in matched_id_set && continue + target_end_time = manual_application ? + (_output_request_published_at(record, simulation, application_id, object_id, + request.var, publication_time) ? publication_time : + float(simulation.current_step)) : membership_end_time + Base.@inline _with_output_request_target(_close_output_request_target!, record, + object_targets[object_id], target_end_time) + end + end + start_time = application_completed ? float(simulation.current_step + 2) : float(simulation.current_step + 1) + for object_id in matched_ids + # An accepted same-step publication wins over a completed/empty call. + target_start_time = manual_application && + _output_request_published_at(record, simulation, application_id, object_id, + request.var, publication_time) ? publication_time : start_time + if haskey(object_targets, object_id) + Base.@inline _with_output_request_target(_refresh_output_request_target!, record, + object_targets[object_id], record, simulation, application, object_id, target_start_time) + else + object_targets[object_id] = _with_output_request_initial(_new_output_request_target, + record, simulation.compiled, application, object_id, + _model_object(simulation.model, object_id).scale, target_start_time) + end + end + return nothing end -function _refresh_output_request_targets!( - simulation::Simulation, - lifecycle=nothing, +function _refresh_output_request_record!(record, simulation, added_object_ids, completed_applications) + return Base.@inline _with_metadata_entry(_refresh_output_request_for_application!, + simulation.compiled.applications_by_id, record.application_id, + record, simulation, added_object_ids, completed_applications) +end + +function _refresh_output_request_targets!(simulation::Simulation, lifecycle=nothing, completed_applications=nothing, ) current_revision = model_revision(simulation.model) - simulation.output_request_model_revision == current_revision && - return simulation + simulation.output_request_model_revision == current_revision && return simulation if isempty(simulation.output_requests) simulation.output_request_model_revision = current_revision return simulation end started_at = _runtime_performance_start(simulation.performance) - _runtime_performance_count!( - simulation.performance, - :output_request_target_refreshes, - ) - added_object_ids = simulation.output_request_model_revision == -1 ? - nothing : _incremental_output_request_object_ids(lifecycle) - for request in simulation.output_requests - matcher = simulation.output_request_matchers[request.name] - application_id, object_targets = - simulation.output_request_targets[request.name] - matched_ids = if isnothing(added_object_ids) - _runtime_performance_count!( - simulation.performance, - :output_request_selector_resolutions, - ) - _resolve_object_ids( - simulation.model, - _selector_as_many(request.selector), - matcher; - context=request.context, - ) - else - _runtime_performance_count!( - simulation.performance, - :output_request_incremental_object_checks, - length(added_object_ids), - ) - ObjectId[ - object_id for object_id in added_object_ids - if _selector_matches_object_id( - simulation.model, - matcher, - object_id; - context=request.context, - ) - ] - end - application = _compiled_application_by_id( - simulation.compiled, - application_id, - ) - owned_ids = Set( - _model_output_object_ids( - simulation.compiled, - application, - request.var, - ), - ) - filter!(id -> id in owned_ids, matched_ids) - active_ids = Set( - object_id for (object_id, target) in object_targets - if _output_request_target_is_active(target) - ) - matched_id_set = Set(matched_ids) - current_ids = isnothing(added_object_ids) ? - matched_id_set : - union(active_ids, matched_id_set) - if request.selector isa Union{One,OptionalOne} && length(current_ids) > 1 - error( - "Output request `$(request.name)` expected at most one current object for selector ", - "`$(request.selector)`, got $([id.value for id in current_ids]).", - ) - end - publication_time = float(simulation.current_step + 1) - manual_application = application_id in simulation.compiled.scenario_plan.manual_application_ids - application_completed = - (!isnothing(completed_applications) && application_id in completed_applications) || - get(simulation.output_retention.accepted_call_times, application_id, -Inf) == publication_time - membership_end_time = application_completed ? - float(simulation.current_step + 1) : - float(simulation.current_step) - if isnothing(added_object_ids) - for object_id in setdiff(active_ids, matched_id_set) - # A manual call may publish before removing an object, or may - # run only after removal. Preserve the last accepted sample in - # the former case without inventing a held sample in the latter. - target_end_time = manual_application ? - (_output_request_published_at(simulation, application_id, object_id, - request.var, publication_time) ? publication_time : - float(simulation.current_step)) : membership_end_time - last(object_targets[object_id].memberships).end_time = - target_end_time - end - end - start_time = application_completed ? - float(simulation.current_step + 2) : - float(simulation.current_step + 1) - for object_id in matched_ids - # Same-step accepted newborn publications take precedence over an - # already completed call. Newborns created after an accepted empty - # call instead join the following publication interval. - target_start_time = manual_application && - _output_request_published_at(simulation, application_id, object_id, - request.var, publication_time) ? publication_time : start_time - if haskey(object_targets, object_id) - target = object_targets[object_id] - _output_request_target_is_active(target) && continue - initial = _model_output_reference( - simulation.compiled, - application, - object_id, - request.var, - )[] - push!( - target.memberships, - OutputRequestMembership( - target_start_time, - nothing, - deepcopy(initial), - ), - ) - continue - end - object_targets[object_id] = _output_request_target( - simulation.model, - simulation.compiled, - application, - object_id, - request.var, - target_start_time, - ) - end - end - _runtime_performance_finish!( - simulation.performance, - :output_request_target_refresh, - started_at, - ) + _runtime_performance_count!(simulation.performance, :output_request_target_refreshes) + added_object_ids = simulation.output_request_model_revision == -1 ? nothing : + _incremental_output_request_object_ids(lifecycle) + for slot in 1:length(simulation.output_requests) + Base.@inline _with_metadata_entry(_refresh_output_request_record!, simulation.output_requests, + slot, simulation, added_object_ids, completed_applications) + end + _runtime_performance_finish!(simulation.performance, :output_request_target_refresh, started_at) simulation.output_request_model_revision = current_revision return simulation end @@ -8034,16 +8168,7 @@ function _prepare_simulation!( length(execution_plan.batches), ) started_at = _runtime_performance_start(performance_counters) - output_request_matchers = Dict( - request.name => _compile_selector_matcher(model, request.selector) - for request in output_requests - ) - output_request_targets = _initial_output_request_targets( - model, - compiled, - output_requests, - output_request_matchers, - ) + compiled_output_requests = _compile_output_requests(model, compiled, output_requests) _runtime_performance_finish!( performance_counters, :initial_output_target_compile, @@ -8062,9 +8187,7 @@ function _prepare_simulation!( output_retention, temporal_streams, _model_output_datetimes(environment_backend(model.environment), env_bindings), - output_requests, - output_request_matchers, - output_request_targets, + compiled_output_requests, model_revision(model), model.runtime_revision, 0, @@ -8318,9 +8441,10 @@ end function _model_requested_output_rows( sim::Simulation, - request, + record::CompiledOutputRequest, ) - application_id, requested_objects = sim.output_request_targets[request.name] + request = record.request + application_id, requested_objects = record.application_id, record.targets application = _compiled_application_by_id(sim.compiled, application_id) declared_scale = _selector_declared_scale(request.selector) timeline = _model_timeline(sim.model) @@ -8402,12 +8526,13 @@ end function _collect_model_requested_outputs(sim::Simulation, sink) outputs = Dict{Symbol,Any}() - for request in sim.output_requests + for record in sim.output_requests + request = record.request haskey(outputs, request.name) && error( "Duplicate output request name `$(request.name)`. Request names must be unique." ) outputs[request.name] = _materialize_model_output_rows( - _model_requested_output_rows(sim, request), + _model_requested_output_rows(sim, record), sink, ) end @@ -8452,17 +8577,13 @@ end function collect_outputs(sim::Simulation, name::Symbol; sink=DataFrames.DataFrame) started_at = _runtime_performance_start(sim.performance) - matches = [request for request in sim.output_requests if request.name == name] - isempty(matches) && error( + haskey(sim.output_requests, name) || error( "No model output request named `$(name)`. Available request names are ", - isempty(sim.output_requests) ? "none." : join((request.name for request in sim.output_requests), ", "), - ) - length(matches) == 1 || error( - "Duplicate model output request name `$(name)`. Request names must be unique." + isempty(sim.output_requests) ? "none." : join(keys(sim.output_requests), ", "), ) - request = only(matches) + record = sim.output_requests[name] collected = _materialize_model_output_rows( - _model_requested_output_rows(sim, request), + _model_requested_output_rows(sim, record), sink, ) _runtime_performance_finish!( diff --git a/src/time/runtime/output_export.jl b/src/time/runtime/output_export.jl index a079f692d..8cd675dd7 100644 --- a/src/time/runtime/output_export.jl +++ b/src/time/runtime/output_export.jl @@ -46,10 +46,10 @@ function _export_clock(request::OutputRequest, timeline::TimelineContext) end function _normalize_output_requests(requests) - isnothing(requests) && return OutputRequest[] - requests isa OutputRequest && return OutputRequest[requests] + isnothing(requests) && return () + requests isa OutputRequest && return (requests,) requests isa AbstractVector{<:OutputRequest} || error( "`outputs` must be `:all`, `:none`, an `OutputRequest`, or a vector of `OutputRequest`." ) - return collect(requests) + return Tuple(requests) end diff --git a/test/test-model-empty-output-requests.jl b/test/test-model-empty-output-requests.jl index be7b1be01..ea8876cbc 100644 --- a/test/test-model-empty-output-requests.jl +++ b/test/test-model-empty-output-requests.jl @@ -11,9 +11,8 @@ PSE.run!(::Counter, status, environment, constants, context) = (status.counter + model = CompositeModel(Object(:first; scale=:Leaf); applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),)) simulation = run!(model; steps=1, outputs=selection) - @test simulation.output_requests === () - @test isempty(simulation.output_request_matchers) - @test isempty(simulation.output_request_targets) + @test isempty(simulation.output_requests) + @test simulation.output_requests isa PSE.CompiledMetadataTable{NamedTuple{(),Tuple{}}} register_object!(model, Object(:second; scale=:Leaf)) continue!(simulation) @test current_step(simulation) == 2 @@ -34,9 +33,54 @@ end model = CompositeModel(Object(:first; scale=:Leaf); applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),)) simulation = run!(model; steps=2, outputs=request) - @test only(simulation.output_requests) === request + @test only(simulation.output_requests).request === request @test outputs(simulation)[(:counter, ObjectId(:first), :counter)] == [(1.0, 1), (2.0, 2)] @test length(collect_outputs(simulation, :counter; sink=nothing)) == 2 @test_throws ErrorException PSE._model_output_selection(:unsupported) end + +@testset "typed requests share one owner through output membership changes" begin + model = CompositeModel( + Object(1; scale=:Plant), + Object(2; scale=:Leaf, parent=1), + Object(3; scale=:Leaf, parent=1); + applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),), + ) + first_request = OutputRequest(OptionalOne(id=2, scale=:Leaf), :counter; name=:first) + plant_request = OutputRequest(Many(Subtree(), scale=:Leaf), :counter; + name=:plant, context=ObjectId(1)) + simulation = run!(model; steps=0, outputs=OutputRequest[first_request, plant_request]) + @test Tuple(entry.request for entry in simulation.output_requests) === + (first_request, plant_request) + record = simulation.output_requests[:plant] + original_target = record.targets[ObjectId(2)] + original_memberships = original_target.memberships + batch = only(simulation.execution_plan.batches) + schema = PSE.PreparedExecutionBatchSchema{Vector{typeof(batch)}}() + simulation = PSE._prepare_execution_batch_schemas(simulation, (counter=schema,)) + record = simulation.output_requests[:plant] + @test keytype(typeof(record.targets)) === keytype(typeof(model.registry.objects)) + @test all(id -> id.value isa Int, keys(record.targets)) + @test valtype(typeof(record.targets)) === PSE.OutputRequestTarget{Int} + @test record.targets[ObjectId(2)] === original_target + @test record.targets[ObjectId(2)].memberships === original_memberships + @test_throws ArgumentError PSE._with_output_request_reference(identity, record, Ref(1f0)) + @test_throws ArgumentError PSE._with_output_request_value(identity, record, 1f0) + step!(simulation) + register_object!(model, Object(4; scale=:Leaf, parent=1)) + step!(simulation) + remove_object!(model, 2) + step!(simulation) + rows = collect_outputs(simulation, :plant; sink=nothing) + @test [(row.object_id, row.timestep, row.value) for row in rows] == [ + (2, 1, 1), (3, 1, 1), + (2, 2, 2), (3, 2, 2), (4, 2, 1), + (3, 3, 3), (4, 3, 2), + ] + @test [(row.object_id, row.timestep, row.value) + for row in collect_outputs(simulation, :first; sink=nothing)] == [(2, 1, 1), (2, 2, 2)] + @test record.targets[ObjectId(2)].memberships === original_memberships + @test only(original_memberships).end_time === 2.0 + @test outputs(simulation)[(:counter, ObjectId(2), :counter)] == [(1.0, 1), (2.0, 2)] +end end diff --git a/test/test-model-output-boundaries.jl b/test/test-model-output-boundaries.jl index 5a6a863a1..853d0dbef 100644 --- a/test/test-model-output-boundaries.jl +++ b/test/test-model-output-boundaries.jl @@ -423,9 +423,7 @@ end @test getproperty.(rows, :timestep) == [1, 2, 5, 6] @test getproperty.(rows, :value) == [1, 2, 5, 6] @test all(row -> row.object_id == :leaf, rows) - target = simulation.output_request_targets[ - :plant_1_leaves - ][2][ObjectId(:leaf)] + target = simulation.output_requests[:plant_1_leaves].targets[ObjectId(:leaf)] @test [ (membership.start_time, membership.end_time) for membership in target.memberships diff --git a/test/test-model-public-refresh-owners.jl b/test/test-model-public-refresh-owners.jl index 6935c5faf..a4e89447e 100644 --- a/test/test-model-public-refresh-owners.jl +++ b/test/test-model-public-refresh-owners.jl @@ -183,7 +183,7 @@ function check_memberships(simulation) scientific_rows = [(row.object_id, row.timestep, row.value) for row in rows] @info "selective force authority" scientific_rows @test scientific_rows == [(:leaf1, 1, 1), (:leaf2, 2, 1)] - targets = simulation.output_request_targets[:chosen][2] + targets = simulation.output_requests[:chosen].targets @test [(membership.start_time, membership.end_time) for membership in targets[ObjectId(:leaf1)].memberships] == [(0.0, 1.0)] @test haskey(targets, ObjectId(:leaf2)) From b632c2b08c14c97dfd04588740ecdb1d0a43c326 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 00:52:03 +0100 Subject: [PATCH 113/324] Publish registration conversions only after successful admission --- src/composite_model/registry_topology.jl | 7 +++++-- src/composite_model/status_conversion.jl | 3 ++- test/test-model-status-type-lifecycle.jl | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index ed73b1682..1fad4bb28 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1394,10 +1394,13 @@ function _register_object_status!(model, object, parent_id, source_status, statu _register_converted_object!(model, object, parent_id, status, status) end end - status = _convert_registered_status(model, object.id, source_status) - return _with_registered_status(catalog, status) do converted + conversion_records = Dict{Any,Any}() + status = _convert_registered_status(model, object.id, source_status; conversion_records) + registered = _with_registered_status(catalog, status) do converted _register_converted_object!(model, object, parent_id, source_status, converted) end + merge!(model.status_conversion_records, conversion_records) + return registered end function _register_converted_object!(model, object, parent_id, source_status, status) diff --git a/src/composite_model/status_conversion.jl b/src/composite_model/status_conversion.jl index 3dd93d4e2..fe9f30559 100644 --- a/src/composite_model/status_conversion.jl +++ b/src/composite_model/status_conversion.jl @@ -374,7 +374,7 @@ function _materialize_status_value( return effective, details.storage_changed, details.mapping_rule end -function _convert_registered_status(model, object_id, status) +function _convert_registered_status(model, object_id, status; conversion_records) status isa Status || return status _no_status_conversion(model.status_conversion) && return status names = propertynames(status) @@ -388,6 +388,7 @@ function _convert_registered_status(model, object_id, status) reference[]; object_id=object_id, origin=:supplied_status, + conversion_records=conversion_records, ) changed |= variable_changed return variable_changed ? Ref(converted) : reference diff --git a/test/test-model-status-type-lifecycle.jl b/test/test-model-status-type-lifecycle.jl index ce6523005..5f1eafb89 100644 --- a/test/test-model-status-type-lifecycle.jl +++ b/test/test-model-status-type-lifecycle.jl @@ -545,3 +545,21 @@ end @test model_object(model, :late_leaf).status === nothing @test model.status_conversion_records == records end + +@testset "rejected supplied status leaves registration receipts unpublished" begin + model = CompositeModel(Object(:parent; scale=:Plant); + status_transform=StatusTypeLifecycleFailOn(:failing_output), + type_promotion=Dict(Float64 => Float32)) + source = Status(first_output=1.0, failing_output=2.0) + object = Object(:rejected; scale=:Leaf, parent=:parent, status=source) + records = copy(model.status_conversion_records) + children = copy(model_object(model, :parent).children) + @test_throws "intentional conversion failure" register_object!(model, object) + @test ObjectId(:rejected) ∉ object_ids(model) + @test model.status_conversion_records == records + @test model_object(model, :parent).children == children + @test object.status === source + @test source.first_output === 1.0 + @test source.failing_output === 2.0 + @test !haskey(model.status_source_identities, ObjectId(:rejected)) +end From 09af511474cd998afda3dc3b90c9c11bfbd8032f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 01:13:15 +0100 Subject: [PATCH 114/324] Keep output request refresh inside admitted type boundaries --- src/composite_model/runtime_outputs.jl | 28 +++++++++++++++--------- test/test-model-empty-output-requests.jl | 27 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index dd2b763e1..a4b318e21 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7797,18 +7797,19 @@ end end end -function _new_output_request_target(initial::T, scale, start_time) where {T} - return OutputRequestTarget(scale, +function _insert_output_request_target!(initial::T, targets, object_id, scale, start_time) where {T} + targets[object_id] = OutputRequestTarget(scale, OutputRequestMembership{T}[OutputRequestMembership(float(start_time), nothing, deepcopy(initial))]) + return nothing end -function _output_request_reference_value(reference::R, record, operation::F, +@inline function _output_request_reference_value(reference::R, record, operation::F, args::Vararg{Any,N}, ) where {R,F,N} return Base.@inline _with_output_request_value(operation, record, reference[], args...) end -function _output_request_from_reference(reference, record, operation::F, +@inline function _output_request_from_reference(reference, record, operation::F, args::Vararg{Any,N}, ) where {F,N} return Base.@inline _with_output_request_reference(_output_request_reference_value, @@ -7833,8 +7834,9 @@ function _compile_output_request(model, compiled, request) for raw_id in _resolve_object_ids(model, request.selector, matcher; context=request.context) object_id = _index_object_id(model.registry.objects, raw_id) object_id in owned_ids || continue - targets[object_id] = _with_output_request_initial(_new_output_request_target, - record, compiled, application, object_id, _model_object(model, object_id).scale, 0.0) + _with_output_request_initial(_insert_output_request_target!, + record, compiled, application, object_id, targets, object_id, + _model_object(model, object_id).scale, 0.0) end return record end @@ -7939,8 +7941,14 @@ function _refresh_output_request_for_application!(application, record, simulatio matched_id_set = Set{I}(matched_ids) current_ids = isnothing(added_object_ids) ? matched_id_set : union(active_ids, matched_id_set) if request.selector isa Union{One,OptionalOne} && length(current_ids) > 1 - error("Output request `$(request.name)` expected at most one current object for selector ", - "`$(request.selector)`, got $([id.value for id in current_ids]).") + io = IOBuffer() + ancestors = Any[] + print(io, "Output request `", String(request.name), "` expected at most one current object for selector `") + _print_selector_diagnostic(io, request.selector, ancestors) + print(io, "`, got ") + _print_selector_diagnostic(io, [id.value for id in current_ids], ancestors) + print(io, '.') + error(String(take!(io))) end publication_time = float(simulation.current_step + 1) manual_application = application_id in simulation.compiled.scenario_plan.manual_application_ids @@ -7970,8 +7978,8 @@ function _refresh_output_request_for_application!(application, record, simulatio Base.@inline _with_output_request_target(_refresh_output_request_target!, record, object_targets[object_id], record, simulation, application, object_id, target_start_time) else - object_targets[object_id] = _with_output_request_initial(_new_output_request_target, - record, simulation.compiled, application, object_id, + _with_output_request_initial(_insert_output_request_target!, + record, simulation.compiled, application, object_id, object_targets, object_id, _model_object(simulation.model, object_id).scale, target_start_time) end end diff --git a/test/test-model-empty-output-requests.jl b/test/test-model-empty-output-requests.jl index ea8876cbc..bde957c00 100644 --- a/test/test-model-empty-output-requests.jl +++ b/test/test-model-empty-output-requests.jl @@ -83,4 +83,31 @@ end @test only(original_memberships).end_time === 2.0 @test outputs(simulation)[(:counter, ObjectId(2), :counter)] == [(1.0, 1), (2.0, 2)] end + +@testset "output request cardinality diagnostics survive lifecycle growth" begin + model = CompositeModel(Object(:first_leaf; scale=:Leaf); + applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),)) + request = OutputRequest(OptionalOne(scale=:Leaf), :counter; + name=:chosen_leaf, application=:counter) + simulation = run!(model; steps=0, outputs=request) + original_target = simulation.output_requests[:chosen_leaf].targets[ObjectId(:first_leaf)] + register_object!(model, Object(:second_leaf; scale=:Leaf)) + failure = try + continue!(simulation; steps=0) + nothing + catch exception + exception + end + @test failure isa ErrorException + if failure isa ErrorException + message = sprint(showerror, failure) + @test occursin("Output request `chosen_leaf` expected at most one current object", message) + @test occursin("OptionalOne", message) + @test occursin("first_leaf", message) + @test occursin("second_leaf", message) + end + @test current_step(simulation) == 0 + @test length(simulation.output_requests[:chosen_leaf].targets) == 1 + @test simulation.output_requests[:chosen_leaf].targets[ObjectId(:first_leaf)] === original_target +end end From da364b130064e292632fee787fca2ee95508a073 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 01:48:31 +0100 Subject: [PATCH 115/324] Resolve output references through prepared variable names --- src/composite_model/runtime_outputs.jl | 181 +++++++++++++---------- test/test-model-empty-output-requests.jl | 22 +++ 2 files changed, 122 insertions(+), 81 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index a4b318e21..4fc8d1858 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1844,30 +1844,61 @@ _model_output_object_ids(compiled, application, variable::Symbol) = compiled.distributed_outputs, ) -@inline function _output_reference_from_view(view, operation::F, variable, args::Vararg{Any,N}) where {F,N} - return operation(refvalue(view.status, variable), args...) +# Admit the authored variable name before reading a dynamically selected Ref. +# The application already owns ALL; no Status-wide field switch or new name +# catalogue is needed for local, private or distributed outputs. +@generated function _with_model_output_variable(operation::F, + ::AuthoredOutputPorts{ALL}, variable::Symbol, args::Vararg{Any,N}, +) where {F,ALL,N} + branches = [:(variable === $(QuoteNode(name)) && + return operation(Val{$(QuoteNode(name))}(), args...)) for name in ALL] + return quote + $(branches...) + throw(ArgumentError("The output variable is outside its prepared application declaration.")) + end end -function _with_model_output_reference(operation::F, compiled, application, +@inline function _output_reference_from_view(view, operation::F, + ::Val{VARIABLE}, args::Vararg{Any,N}, +) where {F,VARIABLE,N} + return operation(refvalue(view.status, VARIABLE), args...) +end + +@inline function _with_model_output_reference(operation::F, compiled, application, object_id::ObjectId, variable::Symbol, args::Vararg{Any,N}, ) where {F,N} + return Base.@inline _with_model_output_variable(_with_model_output_reference, + _application_ports(application).outputs, variable, + operation, compiled, application, object_id, args...) +end + +function _with_model_output_reference(::Val{VARIABLE}, operation::F, compiled, + application, object_id::ObjectId, args::Vararg{Any,N}, +) where {VARIABLE,F,N} id = _index_object_id(compiled.model.registry.objects, object_id) if _model_output_names(application) !== _model_canonical_output_names(application) && - variable in _model_output_names(application) && - !(variable in _model_canonical_output_names(application)) && + VARIABLE in _model_output_names(application) && + !(VARIABLE in _model_canonical_output_names(application)) && haskey(compiled.status_views_by_target, (application.id, id)) return Base.@inline _with_model_status_view(_output_reference_from_view, compiled.status_view_schema, application.id, - compiled.status_views_by_target[(application.id, id)], operation, variable, args...) + compiled.status_views_by_target[(application.id, id)], operation, + Val{VARIABLE}(), args...) end return Base.@inline _with_registered_status(compiled.model.registry.objects.catalog, model_status(compiled.model, id)) do status - operation(refvalue(status, variable), args...) + operation(refvalue(status, VARIABLE), args...) end end -_model_output_reference(compiled, application, object_id::ObjectId, variable::Symbol) = - _with_model_output_reference(identity, compiled, application, object_id, variable) +function _initialize_model_output_stream_from_reference!(reference::R, streams, + retention, application_id::Symbol, key, variable::Symbol, + sizehint_steps::Integer, clock_dt, +) where {R<:Ref} + streams[key] = _model_new_output_stream(reference[], retention, + application_id, variable, sizehint_steps, clock_dt) + return streams +end function _initialize_model_output_stream!( streams, @@ -1880,27 +1911,10 @@ function _initialize_model_output_stream!( ) key = _model_stream_key(application.id, object_id, variable) haskey(streams, key) && return streams - reference = _model_output_reference( - compiled, - application, - object_id, - variable, - ) - isnothing(reference) && error( - "Application `$(application.id)` declares retained output ", - "`$(variable)`, but object `$(object_id.value)` status has no ", - "such variable.", - ) - stream = _model_new_output_stream( - reference[], - retention, - application.id, - variable, - sizehint_steps, - application.clock.dt, - ) - streams[key] = stream - return streams + return Base.@inline _with_model_output_reference( + _initialize_model_output_stream_from_reference!, compiled, application, + object_id, variable, streams, retention, application.id, key, variable, + sizehint_steps, application.clock.dt) end function _initialize_changed_model_output_streams!( @@ -4874,14 +4888,14 @@ function compile_model_output_retention( "Duplicate output request name `$(request.name)`. Request names must be unique." ) push!(names, request.name) - application = _model_request_application( + application_id = _model_request_application_id( compiled.model, compiled, request, ) - push!(requested_outputs, (application.id, request.var)) - if application.id in compiled.scenario_plan.manual_application_ids - get!(accepted_call_times, application.id, -Inf) + push!(requested_outputs, (application_id, request.var)) + if application_id in compiled.scenario_plan.manual_application_ids + get!(accepted_call_times, application_id, -Inf) end end retained_outputs_by_application = Dict{Symbol,Vector{Symbol}}() @@ -7825,7 +7839,13 @@ end function _compile_output_request(model, compiled, request) matcher = _compile_selector_matcher(model, request.selector) - application = _model_request_application(model, compiled, request) + application_id = _model_request_application_id(model, compiled, request) + return _compiled_application_by_id(compiled, application_id) do application + _compile_output_request_targets(model, compiled, request, matcher, application) + end +end + +function _compile_output_request_targets(model, compiled, request, matcher, application) I = keytype(typeof(model.registry.objects)) targets = Dict{I,Any}() record = CompiledOutputRequest(request, matcher, application.id, targets, Tuple{Any}, Tuple{Any}, Tuple{Any}) @@ -8292,60 +8312,63 @@ function _materialize_model_output_rows(rows, sink) return sink(rows) end -function _model_request_application(model::CompositeModel, compiled::CompiledCompositeModel, request) - requested_ids = Set(resolve_object_ids( - model, - request.selector; - context=request.context, - )) +function _model_request_application_id(model::CompositeModel, compiled::CompiledCompositeModel, request) + I = keytype(typeof(model.registry.objects)) + requested_ids = Set{I}() + for id in resolve_object_ids(model, request.selector; context=request.context) + push!(requested_ids, _index_object_id(model.registry.objects, id)) + end declared_scale = _selector_declared_scale(request.selector) - candidates = CompiledModelApplication[] - for application in compiled.applications - isnothing(request.application) || - application.id == request.application || - application.name == request.application || - continue - local_output = request.var in _model_output_names(application) - local_match = local_output && ( - any(id -> id in requested_ids, application.target_ids) || - (!isnothing(declared_scale) && - _model_application_matches_scale(model, application, declared_scale)) - ) - distributed_match = _model_request_matches_distributed_output( - compiled, - application, - request, - requested_ids, - ) - (local_match || distributed_match) || continue - if isnothing(request.application) && - !distributed_match && - _publish_mode_for_output(application.spec, request.var) == :stream_only - continue + candidates = Symbol[] + for application_id in keys(compiled.applications_by_id) + matches = _compiled_application_by_id(compiled, application_id) do application + isnothing(request.application) || + application.id == request.application || + application.name == request.application || + return false + local_output = request.var in _model_output_names(application) + local_match = local_output && ( + any(id -> id in requested_ids, application.target_ids) || + (!isnothing(declared_scale) && + _model_application_matches_scale(model, application, declared_scale)) + ) + distributed_match = _model_request_matches_distributed_output( + compiled, application, request, requested_ids, + ) + (local_match || distributed_match) || return false + return !(isnothing(request.application) && !distributed_match && + _publish_mode_for_output(application.spec, request.var) == :stream_only) end - push!(candidates, application) + matches && push!(candidates, application_id) end if isempty(candidates) - error( - "No model output publisher found for selector `$(request.selector)` and variable `$(request.var)`", - isnothing(request.application) ? - "." : - " from application `$(request.application)`.", - ) + io = IOBuffer() + print(io, "No model output publisher found for selector `") + _print_selector_diagnostic(io, request.selector, Any[]) + print(io, "` and variable `", String(request.var), '`') + isnothing(request.application) || + print(io, " from application `", String(request.application), '`') + print(io, '.') + error(String(take!(io))) elseif length(candidates) > 1 if isnothing(request.application) manual_application_ids = _manual_call_application_ids(compiled) root_candidates = filter( - application -> !(application.id in manual_application_ids), + id -> !(id in manual_application_ids), candidates, ) length(root_candidates) == 1 && return only(root_candidates) end - error( - "Ambiguous model output publishers for selector `$(request.selector)` and variable `$(request.var)`: ", - join((application.id for application in candidates), ", "), - ". Provide `application=` or make one publisher canonical.", - ) + io = IOBuffer() + print(io, "Ambiguous model output publishers for selector `") + _print_selector_diagnostic(io, request.selector, Any[]) + print(io, "` and variable `", String(request.var), "`: ") + for (index, id) in pairs(candidates) + index == 1 || print(io, ", ") + print(io, String(id)) + end + print(io, ". Provide `application=` or make one publisher canonical.") + error(String(take!(io))) end return only(candidates) end @@ -8394,10 +8417,6 @@ _model_request_matches_distributed_output( compiled.distributed_outputs, ) -function _model_request_application(sim::Simulation, request) - return _model_request_application(sim.model, sim.compiled, request) -end - function _selector_declared_scale(selector::AbstractObjectMultiplicity) selector_criteria = criteria(selector) return _criteria_get(selector_criteria, :scale, nothing) diff --git a/test/test-model-empty-output-requests.jl b/test/test-model-empty-output-requests.jl index bde957c00..2be73a6e0 100644 --- a/test/test-model-empty-output-requests.jl +++ b/test/test-model-empty-output-requests.jl @@ -110,4 +110,26 @@ end @test length(simulation.output_requests[:chosen_leaf].targets) == 1 @test simulation.output_requests[:chosen_leaf].targets[ObjectId(:first_leaf)] === original_target end + +function request_publishers_model() + return CompositeModel(Object(:first; scale=:Leaf), Object(:second; scale=:Leaf); + applications=( + ModelSpec(Counter(); name=:first_counter, on=One(id=:first)), + ModelSpec(Counter(); name=:second_counter, on=One(id=:second)), + )) +end + +@testset "retained requests select a unique publisher by application identity" begin + @test_throws "No model output publisher found" run!(request_publishers_model(); + steps=0, outputs=OutputRequest(Many(scale=:Leaf), :missing)) + @test_throws "Ambiguous model output publishers" run!(request_publishers_model(); + steps=0, outputs=OutputRequest(Many(scale=:Leaf), :counter)) + simulation = run!(request_publishers_model(); steps=1, + outputs=OutputRequest(Many(scale=:Leaf), :counter; + name=:selected, application=:second_counter)) + record = simulation.output_requests[:selected] + @test record.application_id === :second_counter + @test Set(keys(record.targets)) == Set((ObjectId(:second),)) + @test outputs(simulation)[(:second_counter, ObjectId(:second), :counter)] == [(1.0, 1)] +end end From a57fcac28747ce1ac578f0f93872c2e05a702e5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 02:08:02 +0100 Subject: [PATCH 116/324] Read output references through named status callbacks --- src/composite_model/object_families.jl | 10 +++++++--- src/composite_model/runtime_outputs.jl | 22 +++++++++++++++------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index c84a80ab0..7621380c0 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -34,11 +34,15 @@ end # Open registration crosses the ordinary JIT function barrier. Closed # registration keeps the operation inside the exact admitted Status branch, # rather than first returning a large union from the Object's Any-valued field. -@inline _with_registered_status(f, ::OpenObjectFamilyCatalog, status) = f(status) +@inline _with_registered_status(f::OP, ::OpenObjectFamilyCatalog, status, + args::Vararg{Any,N}, +) where {OP,N} = f(status, args...) -@generated function _with_registered_status(f, ::ClosedObjectFamilyCatalog{F}, status) where {F} +@generated function _with_registered_status(f::OP, ::ClosedObjectFamilyCatalog{F}, + status, args::Vararg{Any,N}, +) where {OP,F,N} schemas = unique(family.parameters[2] for family in fieldtypes(F)) - branches = [:(status isa $S && return f(status::$S)) for S in schemas] + branches = [:(status isa $S && return f(status::$S, args...)) for S in schemas] return quote $(branches...) throw(ArgumentError("The status schema is outside the prepared object family catalog.")) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 4fc8d1858..611ff9506 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1858,10 +1858,19 @@ _model_output_object_ids(compiled, application, variable::Symbol) = end end -@inline function _output_reference_from_view(view, operation::F, +@inline function _output_reference_from_status(status::S, operation::F, ::Val{VARIABLE}, args::Vararg{Any,N}, -) where {F,VARIABLE,N} - return operation(refvalue(view.status, VARIABLE), args...) +) where {S,F,VARIABLE,N} + status isa Status && VARIABLE in propertynames(status) || throw(ArgumentError( + "The requested output is absent from the selected status.", + )) + return operation(refvalue(status, VARIABLE), args...) +end + +@inline function _output_reference_from_view(view, operation::F, + variable::Val, args::Vararg{Any,N}, +) where {F,N} + return _output_reference_from_status(view.status, operation, variable, args...) end @inline function _with_model_output_reference(operation::F, compiled, application, @@ -1885,10 +1894,9 @@ function _with_model_output_reference(::Val{VARIABLE}, operation::F, compiled, compiled.status_views_by_target[(application.id, id)], operation, Val{VARIABLE}(), args...) end - return Base.@inline _with_registered_status(compiled.model.registry.objects.catalog, - model_status(compiled.model, id)) do status - operation(refvalue(status, VARIABLE), args...) - end + return Base.@inline _with_registered_status(_output_reference_from_status, + compiled.model.registry.objects.catalog, model_status(compiled.model, id), + operation, Val{VARIABLE}(), args...) end function _initialize_model_output_stream_from_reference!(reference::R, streams, From 7476fbbcc6a09723fac5a439b9952f4378bc86b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 02:28:11 +0100 Subject: [PATCH 117/324] Preserve output request action specialization across metadata gates --- src/composite_model/runtime_outputs.jl | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 611ff9506..fe93c1825 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7838,11 +7838,22 @@ end record, reference, record, operation, args...) end +# The action crosses several metadata gates without being called there. Keep +# its concrete callable type when forwarding it alongside the scientific data. +struct _OutputRequestAction{F} + operation::F +end + +function (action::_OutputRequestAction{F})(args::Vararg{Any,N}) where {F,N} + return action.operation(args...) +end + function _with_output_request_initial(operation::F, record, compiled, application, object_id, args::Vararg{Any,N}, ) where {F,N} + action = _OutputRequestAction(operation) return Base.@inline _with_model_output_reference(_output_request_from_reference, - compiled, application, object_id, record.request.var, record, operation, args...) + compiled, application, object_id, record.request.var, record, action, args...) end function _compile_output_request(model, compiled, request) From c9dbf4b3955e61def3916adc5a869cf3fff9da57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 03:09:25 +0100 Subject: [PATCH 118/324] Keep growth and temporal retention inside prepared metadata owners --- src/composite_model/compilation.jl | 94 +++++++++++++++----------- src/composite_model/runtime_outputs.jl | 24 +++++-- src/composite_model/selectors.jl | 52 +++++++++++--- test/test-selector-query-scope-root.jl | 25 +++++++ 4 files changed, 140 insertions(+), 55 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index c1400f880..e2b41c831 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4602,43 +4602,51 @@ function _extend_compiled_scene( applications_by_id = compiled.applications_by_id new_target_application_ids = sort!( collect(keys(new_targets)); - by=application_id -> applications_by_id[application_id].slot, - ) - new_target_applications = Tuple( - applications_by_id[application_id] - for application_id in new_target_application_ids + by=application_id -> begin + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + application.slot + end + end, ) - for application in new_target_applications - _insert_sorted_object_ids!( - application.target_ids, - new_targets[application.id], - ) + for application_id in new_target_application_ids + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + _insert_sorted_object_ids!( + application.target_ids, + new_targets[application.id], + ) + return nothing + end end changed_application_ids = union( Set(new_target_application_ids), changed_application_ids_seed, ) for application_id in changed_application_ids - application = applications_by_id[application_id] - if application.id in changed_application_ids_seed - target_count = length(application.target_ids) - if application.applies_to isa One && target_count != 1 - error( - "Lifecycle refresh left application `$(application.id)` with ", - "$(target_count) targets for a `One` selector.", - ) - elseif application.applies_to isa OptionalOne && target_count > 1 - error( - "Lifecycle refresh left application `$(application.id)` with ", - "$(target_count) targets for an `OptionalOne` selector.", - ) + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + if application.id in changed_application_ids_seed + target_count = length(application.target_ids) + if application.applies_to isa One && target_count != 1 + error( + "Lifecycle refresh left application `$(application.id)` with ", + "$(target_count) targets for a `One` selector.", + ) + elseif application.applies_to isa OptionalOne && target_count > 1 + error( + "Lifecycle refresh left application `$(application.id)` with ", + "$(target_count) targets for an `OptionalOne` selector.", + ) + end end + return nothing end end applications_by_object = compiled.applications_by_object - for application in new_target_applications - for object_id in new_targets[application.id] - push!(get!(applications_by_object, object_id, Any[]), application) + for application_id in new_target_application_ids + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + for object_id in new_targets[application.id] + push!(get!(applications_by_object, object_id, Any[]), application) + end + return nothing end end manual_application_ids = compiled.scenario_plan.manual_application_ids @@ -4666,10 +4674,14 @@ function _extend_compiled_scene( ) started_at = _runtime_performance_start(performance) - added_applications = CompiledModelApplication[ - _partial_model_application(application, new_targets[application.id]) - for application in new_target_applications - ] + added_applications = CompiledModelApplication[] + for application_id in new_target_application_ids + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + push!(added_applications, + _partial_model_application(application, new_targets[application.id])) + return nothing + end + end new_call_bindings, changed_call_target_keys, observed_manual_call_binding_indices_by_callee_target = _refresh_scene_call_bindings!( model, @@ -4838,15 +4850,21 @@ function _extend_compiled_scene( end for application_id in sort!( collect(keys(targets_by_application)); - by=id -> applications_by_id[id].slot, + by=id -> begin + Base.@inline _with_metadata_entry(applications_by_id, id) do application + application.slot + end + end, ) - application = applications_by_id[application_id] - target_ids = targets_by_application[application_id] - _sort_object_ids!(target_ids) - push!( - rewired_applications, - _partial_model_application(application, target_ids), - ) + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + target_ids = targets_by_application[application_id] + _sort_object_ids!(target_ids) + push!( + rewired_applications, + _partial_model_application(application, target_ids), + ) + return nothing + end end rewired_applications end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index fe93c1825..44766179b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4779,6 +4779,18 @@ function _model_output_retention_covers_binding( end end +_model_output_retention_covers_inputs(::Tuple{}, plan, compiled) = true + +function _model_output_retention_covers_inputs(inputs::Tuple, plan, compiled) + _model_output_retention_covers_binding(plan, compiled, first(inputs).binding) || + return false + return _model_output_retention_covers_inputs(Base.tail(inputs), plan, compiled) +end + +function _model_output_retention_covers_view(view, plan, compiled) + return _model_output_retention_covers_inputs(view.temporal_inputs, plan, compiled) +end + function _model_output_retention_covers_addition( plan::OutputRetentionPlan, compiled::CompiledCompositeModel, @@ -4787,13 +4799,11 @@ function _model_output_retention_covers_addition( id = _index_object_id(compiled.model.registry.objects, object_id) view = get(compiled.status_views_by_target, (application_id, id), nothing) isnothing(view) && continue - view isa CompiledModelStatusView || throw(ArgumentError("Invalid compiled status view for temporal retention.")) - temporal_inputs = getfield(view, :temporal_inputs)::Tuple - for temporal_input in temporal_inputs - temporal_input isa CompiledTemporalInput || throw(ArgumentError("Invalid temporal retention input.")) - binding = getfield(temporal_input, :binding)::CompiledModelInputBinding - _model_output_retention_covers_binding(plan, compiled, binding) || return false - end + covers = Base.@inline _with_model_status_view( + _model_output_retention_covers_view, compiled.status_view_schema, + application_id, view, plan, compiled, + ) + covers || return false end return true end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index aba1dae68..e96203a2a 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -220,12 +220,25 @@ function _validate_selector_context( context::Symbol, ) allowed = _selector_context_fields(context) - invalid = Symbol[field for field in _selector_semantic_fields(selector) if !(field in allowed)] - isempty(invalid) || error( - "Selector field(s) `$(Tuple(invalid))` are not valid in ", - "$(_selector_context_description(context)) selectors. ", - "Allowed fields are `$(allowed)`." - ) + invalid = Symbol[] + for field in _selector_semantic_fields(selector) + field in allowed || push!(invalid, field) + end + if !isempty(invalid) + allowed_fields = Symbol[] + for field in allowed + push!(allowed_fields, field) + end + io = IOBuffer() + ancestors = Any[] + print(io, "Selector field(s) `") + _print_selector_diagnostic(io, invalid, ancestors) + print(io, "` are not valid in ", _selector_context_description(context), + " selectors. Allowed fields are `") + _print_selector_diagnostic(io, allowed_fields, ancestors) + print(io, "`.") + error(String(take!(io))) + end if context == :application_target scope = _criteria_scope(criteria(selector)) scope isa Union{Nothing,SceneScope,Scope} || error( @@ -667,17 +680,36 @@ function _selector_scope_from_positional(selectors) end function _selector_value_from_positional(selectors, ::Type{Relation}) - values = [selector.relation for selector in selectors if selector isa Relation] + values = Symbol[] + for selector in selectors + selector isa Relation && push!(values, selector.relation) + end isempty(values) && return nothing - length(unique(values)) == 1 || error("Conflicting `Relation(...)` selector values: $(values).") - return only(unique(values)) + first_value = first(values) + for value in values + if value != first_value + io = IOBuffer() + print(io, "Conflicting `Relation(...)` selector values: ") + _print_selector_diagnostic(io, values, Any[]) + print(io, '.') + error(String(take!(io))) + end + end + return first_value end function _criteria_value(criteria, key::Symbol, selector_type) positional = _selector_value_from_positional(criteria.selectors, selector_type) keyword = haskey(criteria, key) ? getproperty(criteria, key) : nothing if !isnothing(positional) && !isnothing(keyword) && positional != keyword - error("Conflicting selector values for `$(key)`: `$(positional)` and `$(keyword)`.") + io = IOBuffer() + ancestors = Any[] + print(io, "Conflicting selector values for `", String(key), "`: `") + _print_selector_diagnostic(io, positional, ancestors) + print(io, "` and `") + _print_selector_diagnostic(io, keyword, ancestors) + print(io, "`.") + error(String(take!(io))) end return isnothing(keyword) ? positional : keyword end diff --git a/test/test-selector-query-scope-root.jl b/test/test-selector-query-scope-root.jl index 4352dc7d8..08027445c 100644 --- a/test/test-selector-query-scope-root.jl +++ b/test/test-selector-query-scope-root.jl @@ -165,4 +165,29 @@ end end end + +@testset "selector context and relation conflicts retain their rules and diagnostics" begin + model = scope_scene() + children = sorted_ids(:axis_a, Symbol("2")) + @test resolve_object_ids(model, + Many(Relation(:children), Relation(:children)); context=:plant_a) == children + @test resolve_object_ids(model, + Many(Relation(:children); relation=:children); context=:plant_a) == children + + error = query_error(model, + Many(Relation(:children), Relation(:children), Relation(:parent)); + context=:plant_a) + @test occursin("Conflicting `Relation(...)` selector values", error) + @test occursin(r"children.*children.*parent", error) + + error = query_error(model, + Many(Relation(:children); relation=:parent); context=:plant_a) + @test occursin("Conflicting selector values for `relation`", error) + @test occursin("children", error) && occursin("parent", error) + + error = query_error(model, Many(scale=:Leaf, application=:reader)) + @test occursin("not valid in object-query selectors", error) + @test occursin("application", error) + @test occursin("Allowed fields", error) && occursin("scale", error) +end end From 0a48bb4833681b9de67302fe14009ef888938b38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 03:59:39 +0100 Subject: [PATCH 119/324] Prepare prospective Many types without converting existing source cells --- src/composite_model/compilation.jl | 17 +++-- src/composite_model/selectors.jl | 22 ++++-- test/test-model-input-binding-storage.jl | 8 ++- test/test-model-input-recipes.jl | 3 +- test/test-model-temporal-initial-typing.jl | 75 ++++++++++++++++---- test/test-resolved-input-materialization.jl | 53 +++++++++++--- test/test-selector-construction-inference.jl | 9 +++ 7 files changed, 146 insertions(+), 41 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index e2b41c831..b4e0fddd7 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -7834,8 +7834,8 @@ Base.@nospecializeinfer function _input_plan_variable_contracts!( return schema end -# The family is fixed by preparation, not by the first matching organ. Existing -# configured reference storage takes precedence over declared numeric defaults. +# Preparation keeps real cells unchanged and retains every concrete prospective +# configured type. A current Ref32 does not change a future Default64 into Ref32. function _many_scope_is_current(model, matcher) scope = matcher.scope @@ -7936,10 +7936,9 @@ function _prepare_many_reference_types(model, consumer, input, selector, delete!(missing_current, object.id) end end - # Current references replace this variant's default only when every - # current source already owns one. Missing fields still materialize - # the declared default. Other families remain eligible for reparenting. - !isempty(current) && isempty(missing_current) && continue + # Real current cells need no conversion. A concrete declared future + # family is still admissible even when every current source has a cell. + current_complete = !isempty(current) && isempty(missing_current) T = if isnothing(producer) || !isnothing(model.status_conversion.transform) fallback else @@ -7948,9 +7947,13 @@ function _prepare_many_reference_types(model, consumer, input, selector, end candidates = isnothing(T) ? () : Base.uniontypes(T) if isempty(candidates) || !all(isconcretetype, candidates) - isnothing(producer) && observed_any && continue candidates = fallback === Union{} ? () : (fallback,) end + # A transform or abstract Required may leave the prospective type + # unknown. Existing complete references remain valid evidence. + if isempty(candidates) + (current_complete || (isnothing(producer) && observed_any)) && continue + end isempty(candidates) && throw(ArgumentError( "Many input `$(input)` on application `$(consumer.id)` has no concrete " * "configured source type for `$(source_var)`. Declare a concrete producer " * diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index e96203a2a..64576d2e3 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -679,15 +679,23 @@ function _selector_scope_from_positional(selectors) return only(scopes) end +_first_positional_relation(::Tuple{}) = nothing +function _first_positional_relation(selectors::Tuple) + selector = first(selectors) + selector isa Relation && return selector + return _first_positional_relation(Base.tail(selectors)) +end + function _selector_value_from_positional(selectors, ::Type{Relation}) - values = Symbol[] + relation = _first_positional_relation(selectors) + isnothing(relation) && return nothing + first_value = relation.relation for selector in selectors - selector isa Relation && push!(values, selector.relation) - end - isempty(values) && return nothing - first_value = first(values) - for value in values - if value != first_value + if selector isa Relation && selector.relation != first_value + values = Symbol[] + for candidate in selectors + candidate isa Relation && push!(values, candidate.relation) + end io = IOBuffer() print(io, "Conflicting `Relation(...)` selector values: ") _print_selector_diagnostic(io, values, Any[]) diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index cac4832c9..9efebd970 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -94,13 +94,15 @@ function ordinary_control(; called=false) families = observe_families!(DataType[], simulation) initial_families = copy(families) @test eltype(simulation.compiled.input_bindings) === PSE.CompiledModelInputBinding - @test isempty(check_carriers(data, simulation).carrier) + initial_many = check_carriers(data, simulation) + @test isempty(initial_many.carrier) totals = [advance!(data, simulation)] birth!(data.model, :leaf_1, 7.0) push!(totals, advance!(data, simulation)) observe_families!(families, simulation) future = binding(simulation, :a, :values) - @test !(typeof(future) in initial_families) + @test typeof(future) in initial_families + @test future.carrier === initial_many.carrier first = check_carriers(data, simulation) carrier, source_ids = first.carrier, first.source_ids birth!(data.model, :leaf_2, 11.0) @@ -143,7 +145,7 @@ end simulation.compiled.input_bindings) @test isempty(prototype) - incomplete = storage_prototype(control.initial_families) + incomplete = storage_prototype(filter(B -> B !== typeof(control.future), control.families)) @test_throws "outside its prepared storage family" PSE._with_model_input_binding( identity, incomplete, control.future) end diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 91bc7864a..4198c1ace 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -161,6 +161,7 @@ end binding = only(simulation.compiled.input_bindings) carrier = input_carrier(binding) @test carrier isa PSE.ObjectRefVector + @test carrier === old_carrier @test Set(binding.source_ids) == Set((ObjectId(1), ObjectId(:new_leaf))) @test isempty(binding.source_application_ids) for (id, reference) in zip(binding.source_ids, parent(carrier)) @@ -170,7 +171,7 @@ end @test PSE.refvalue(second, :x)[] isa Float64 first_ref[] = 7f0 @test first.x === 7f0 - @test only(old_carrier) === 7f0 + @test old_carrier[findfirst(isequal(ObjectId(1)), binding.source_ids)] === 7f0 continue!(simulation) @test model_status(model, :plant).total === 16.0 @test outputs(simulation)[(:aggregate, ObjectId(:plant), :total)] == diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index b4bde8147..7658704e7 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -171,7 +171,7 @@ end )) prototype = Vector{Union{unique(typeof(binding) for binding in compiled.input_bindings)...}}() before = model.binding_cache - @test_throws "temporal snapshot payload is outside its prepared input family" PSE._prepare_simulation!( + @test_throws "mixed private ObjectRefVector storage requires source-reference family evidence" PSE._prepare_simulation!( model; steps=0, outputs=:none, constants=PSE.Constants(), status_view_schema=schema, input_binding_storage=prototype) @test model.binding_cache === before @@ -197,36 +197,83 @@ function PSE.run!(::PairedConsumer, status, environment, constants, context) return nothing end -@testset "all temporal extensions validate before any existing snapshot grows" begin - model = CompositeModel( +function paired_temporal_scene() + return CompositeModel( Object(:scene; scale=:Scene, status=Status(first_values=Float32[], second_values=Float32[], total=0.0)), - Object(:a; scale=:Leaf, parent=:scene, status=Status(a=2f0, b=3f0)); + Object(:a; scale=:Leaf, parent=:scene, status=Status(a=2f0, b=3f0)), + Object(:other; scale=:Scene), + # A real configured source family exists before preparation, outside the + # consumer's Subtree. It contributes type evidence, never consumer values. + Object(:outside; scale=:Leaf, parent=:other, status=Status(a=0f0, b=0.0)); applications=( ModelSpec(PairedSource(); name=:paired_source, on=Many(scale=:Leaf)), ModelSpec(PairedConsumer(); name=:paired_consumer, on=One(id=:scene), inputs=( - PreviousTimeStep(:first_values) => Many(scale=:Leaf, within=SceneScope(), application=:paired_source, var=:a), - PreviousTimeStep(:second_values) => Many(scale=:Leaf, within=SceneScope(), application=:paired_source, var=:b), + PreviousTimeStep(:first_values) => Many(scale=:Leaf, within=Subtree(), application=:paired_source, var=:a), + PreviousTimeStep(:second_values) => Many(scale=:Leaf, within=Subtree(), application=:paired_source, var=:b), )), ), environment=(duration=Hour(1),)) +end + +@testset "configured temporal growth preserves snapshots and complete values" begin + model = paired_temporal_scene() simulation = run!(model; steps=1, outputs=:all) @test final_state(simulation, :scene).total === 5.0 - first_input = first(simulation.compiled.status_views_by_target[ - (:paired_consumer, ObjectId(:scene))].temporal_inputs) - initial, values = copy(first_input.initial), collect(first_input.reference[]) - reference = first(parent(first_input.reference[])) - # The first input can extend, while the second needs a mixed carrier rebuild. + old_inputs = simulation.compiled.status_views_by_target[ + (:paired_consumer, ObjectId(:scene))].temporal_inputs + first_private, second_private = map(old_inputs) do temporal + only(parent(temporal.reference[])) + end + @test second_private isa Base.RefValue{Float32} + @test first_private !== PSE.refvalue(model_status(model, :a), :a) + @test second_private !== PSE.refvalue(model_status(model, :a), :b) + register_object!(model, Object(:b; scale=:Leaf, parent=:scene, status=Status(a=10f0, b=20.0))) step!(simulation) - @test first_input.initial == initial - @test collect(first_input.reference[]) == values - @test only(parent(first_input.reference[])) === reference + current = simulation.compiled.status_views_by_target[ + (:paired_consumer, ObjectId(:scene))].temporal_inputs + # Mixed snapshot storage rebuilds the private views. Existing values survive + # without mutating a saved view or sharing live canonical source cells. + @test first(current[1].reference[]) === 3f0 + @test first(current[2].reference[]) === 4f0 + @test first_private[] === 2f0 + @test second_private[] === 3f0 + @test first(parent(current[1].reference[])) !== PSE.refvalue(model_status(model, :a), :a) + @test first(parent(current[2].reference[])) !== PSE.refvalue(model_status(model, :a), :b) + @test last(parent(current[2].reference[])) isa Base.RefValue{Float64} + @test last(parent(current[2].reference[])) !== PSE.refvalue(model_status(model, :b), :b) + @test current[1].binding.source_ids == [ObjectId(:a), ObjectId(:b)] + @test current[2].binding.source_ids == [ObjectId(:a), ObjectId(:b)] @test final_state(simulation, :scene).total === 37.0 @test outputs(simulation)[(:paired_consumer, ObjectId(:scene), :total)] == [(1.0, 5.0), (2.0, 37.0)] end +@testset "an unprepared temporal family cannot partly extend private snapshots" begin + model = paired_temporal_scene() + simulation = run!(model; steps=1, outputs=:all) + temporal_inputs = simulation.compiled.status_views_by_target[ + (:paired_consumer, ObjectId(:scene))].temporal_inputs + before = map(temporal_inputs) do temporal + (initial=copy(temporal.initial), values=collect(temporal.reference[]), + references=Tuple(parent(temporal.reference[])), owner=temporal.reference) + end + history = copy(outputs(simulation)[(:paired_consumer, ObjectId(:scene), :total)]) + # The first input's Ref32 is admitted. The second has neither the configured + # Ref32 nor Ref64 type, so no existing private snapshot may be extended. + register_object!(model, Object(:b; scale=:Leaf, parent=:scene, + status=Status(a=10f0, b=big"20.0"))) + @test_throws "outside its prepared Many family" step!(simulation) + for (temporal, saved) in zip(temporal_inputs, before) + @test temporal.initial == saved.initial + @test collect(temporal.reference[]) == saved.values + @test Tuple(parent(temporal.reference[])) === saved.references + @test temporal.reference === saved.owner + end + @test outputs(simulation)[(:paired_consumer, ObjectId(:scene), :total)] == history +end + end module PreparedPublicationChecks diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index 127ee613d..9c38b4469 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -232,7 +232,7 @@ end @test model_status(model, :reader).seen === 7f0 end -@testset "configured Float32 refs take precedence over Float64 producer defaults" begin +@testset "configured Float32 refs coexist with prospective Float64 producer defaults" begin source = Status(x=1f0) model = CompositeModel(Object(:source; scale=:Leaf, status=source), Object(:reader; scale=:Reader); applications=( @@ -241,20 +241,28 @@ end on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, application=:source, var=:x),)), ), environment=(duration=Hour(1),)) - @test only(model.scenario_plan_cache.program.input_records).reference_types === - Tuple{Base.RefValue{Float32}} + @test Set(fieldtypes(only(model.scenario_plan_cache.program.input_records).reference_types)) == + Set((Base.RefValue{Float32}, Base.RefValue{Float64})) simulation = run!(model; steps=1, outputs=:all) carrier = only(simulation.compiled.input_bindings).carrier - @test carrier isa PSE.RefVector{Float32} + @test carrier isa PSE.ObjectRefVector @test model_status(model, :reader).seen === 2f0 @test only(parent(carrier)) === PSE.refvalue(source, :x) register_object!(model, Object(:z_leaf; scale=:Leaf, status=Status(x=3f0))) continue!(simulation; steps=1) @test only(simulation.compiled.input_bindings).carrier === carrier - @test carrier isa PSE.RefVector{Float32} + @test carrier isa PSE.ObjectRefVector @test model_status(model, :reader).seen === 8f0 @test parent(carrier)[1] === PSE.refvalue(model_status(model, :source), :x) @test parent(carrier)[2] === PSE.refvalue(model_status(model, :z_leaf), :x) + register_object!(model, Object(:zz_default; scale=:Leaf)) + continue!(simulation; steps=1) + @test only(simulation.compiled.input_bindings).carrier === carrier + @test model_status(model, :zz_default).x === 6.0 + @test PSE.refvalue(model_status(model, :zz_default), :x) isa Base.RefValue{Float64} + @test parent(carrier)[1] === PSE.refvalue(source, :x) + @test source.x === 6f0 + @test model_status(model, :reader).seen === 18f0 end @testset "partial current source state also admits the missing default family" begin @@ -369,7 +377,8 @@ end binding = only(simulation.compiled.input_bindings) B = typeof(binding) if base_configured - @test binding.carrier isa PSE.RefVector{Float32} + @test eltype(parent(binding.carrier)) === + Union{Base.RefValue{Float32},Base.RefValue{Float64}} continue!(simulation; steps=1) @test model_status(model, :reader).seen === 5.0 else @@ -398,13 +407,21 @@ end on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, application=:writer, var=:x),)), ), environment=(duration=Hour(1),)) - @test only(model.scenario_plan_cache.program.input_records).reference_types === - Tuple{Base.RefValue{Float32}} + @test Set(fieldtypes(only(model.scenario_plan_cache.program.input_records).reference_types)) == + Set((Base.RefValue{Float32}, Base.RefValue{Float64})) simulation = run!(model; steps=1, outputs=:all) carrier = only(simulation.compiled.input_bindings).carrier - @test carrier isa PSE.RefVector{Float32} + @test carrier isa PSE.ObjectRefVector @test model_status(model, :reader).seen === 4f0 @test only(parent(carrier)) === PSE.refvalue(status, :x) + register_object!(model, Object(:z_leaf; scale=:Leaf)) + continue!(simulation; steps=1) + @test only(simulation.compiled.input_bindings).carrier === carrier + @test parent(carrier)[1] === PSE.refvalue(status, :x) + @test status.x === 4f0 + @test model_status(model, :z_leaf).x === 4.0 + @test PSE.refvalue(model_status(model, :z_leaf), :x) isa Base.RefValue{Float64} + @test model_status(model, :reader).seen === 8f0 end @testset "a future One destination does not freeze a false Many preparation failure" begin @@ -483,6 +500,24 @@ end @test_throws "no concrete configured source type" run!(scoped; steps=0, outputs=:none) end +@testset "complete real refs remain sufficient for an abstract Required producer" begin + supplied = Status(x=1f0) + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:leaf; scale=:Leaf, status=supplied), Object(:reader; scale=:Reader); + applications=( + ModelSpec(RequiredDistributor(); name=:writer, on=Many(scale=:Scene), + outputs_to=(OutputTo(Many(SceneScope(); scale=:Leaf)),)), + ModelSpec(ManyReader{AbstractVector,Float32}(0f0); name=:reader, + on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, + application=:writer, var=:x),)), + ), environment=(duration=Hour(1),)) + @test only(model.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Float32}} + simulation = run!(model; steps=0, outputs=:none) + @test only(parent(only(simulation.compiled.input_bindings).carrier)) === + PSE.refvalue(supplied, :x) +end + @testset "status-only empty Many requires a concrete configured element type" begin function status_only(::Type{V}) where {V} CompositeModel(Object(:reader; scale=:Reader); applications=( diff --git a/test/test-selector-construction-inference.jl b/test/test-selector-construction-inference.jl index c17ed6144..a03e45a67 100644 --- a/test/test-selector-construction-inference.jl +++ b/test/test-selector-construction-inference.jl @@ -15,3 +15,12 @@ using Test @test object_address(One(kind="leaf")).kind === :leaf @test_throws ErrorException One(unsupported=:value) end + +@testset "selectors without a Relation keep a concrete absent relation" begin + model = CompositeModel(Object(:leaf; scale=:Leaf)) + direct = @inferred PlantSimEngine._compile_selector_matcher(model, One(id=:leaf)) + scoped = @inferred PlantSimEngine._compile_selector_matcher(model, Many(Subtree(); scale=:Leaf)) + @test direct.relation === nothing + @test scoped.relation === nothing + @test resolve_object_ids(model, One(id=:leaf)) == [ObjectId(:leaf)] +end From a2930bfa722b26122051cda63a1fdde7e985ad8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 04:10:42 +0100 Subject: [PATCH 120/324] Keep growth views and private snapshots inside prepared type admissions --- src/composite_model/compilation.jl | 55 ++++++++++++++----- src/composite_model/selectors.jl | 9 ++- .../status_view_construction.jl | 50 ++++++++++------- test/test-model-input-binding-storage.jl | 21 +++++++ test/test-model-output-retention-owners.jl | 12 +++- 5 files changed, 109 insertions(+), 38 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b4e0fddd7..5b881fd4e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3640,7 +3640,7 @@ end end end -function _preserve_model_status_view_with_previous!(previous, schema, application_id, +@inline function _preserve_model_status_view_with_previous!(previous, schema, application_id, current, previous_temporal_sources, key, ) return Base.@inline _with_model_status_view(_preserve_model_status_view_temporal_state!, @@ -3704,6 +3704,8 @@ function _stage_temporal_many_extension( applications_by_id, application_positions, distributed_outputs, + status_view_schema, + canonical_status, ) binding = temporal_input.binding binding.multiplicity == :many || return nothing @@ -3728,8 +3730,20 @@ function _stage_temporal_many_extension( source_values isa AbstractVector || return nothing length(source_values) == length(source_ids) || return nothing new_indices = (previous_count + 1):length(source_ids) + return Base.@inline _with_temporal_copy_payloads(_stage_temporal_many_extension_payloads, + status_view_schema, binding, canonical_status, initial, storage, + source_applications, source_values, new_indices, applications_by_id, + application_positions, distributed_outputs) +end + +_private_temporal_reference(value) = Ref(_private_temporal_value(value)) + +function _stage_temporal_many_extension_payloads(payloads, binding, canonical_status, + initial, storage, source_applications, source_values, new_indices, + applications_by_id, application_positions, distributed_outputs, +) new_initial = Any[ - _private_temporal_value(source_values[index]) + (Base.@inline _copy_temporal_status_value(payloads, source_values[index], _private_temporal_value)) for index in new_indices ] # A newly selected schema may require rebuilding the private carrier. Do @@ -3738,7 +3752,7 @@ function _stage_temporal_many_extension( new_source_applications = Union{Nothing,Symbol}[ _temporal_source_application( binding, - source_ids[index], + binding.source_ids[index], applications_by_id, application_positions, distributed_outputs, @@ -3747,7 +3761,8 @@ function _stage_temporal_many_extension( ] storage_references = parent(storage) new_storage_references = Base.RefValue[ - Ref(_private_temporal_value(value)) for value in new_initial + (Base.@inline _copy_temporal_status_value(payloads, value, _private_temporal_reference)) + for value in new_initial ] all(reference -> reference isa eltype(storage_references), new_storage_references) || return nothing @@ -3763,10 +3778,10 @@ function _stage_temporal_many_extension( ) end -_stage_temporal_many_extensions(::Tuple{}, model, key, sources, applications, positions, distributed) = () +_stage_temporal_many_extensions(::Tuple{}, model, key, sources, applications, positions, distributed, schema, canonical_status) = () function _stage_temporal_many_extensions(inputs::Tuple, model, key, sources, - applications, positions, distributed, + applications, positions, distributed, schema, canonical_status, ) temporal_input = first(inputs) previous_source_ids = get(sources, (key..., temporal_input.binding.input), nothing) @@ -3775,12 +3790,13 @@ function _stage_temporal_many_extensions(inputs::Tuple, model, key, sources, else extension = _stage_temporal_many_extension( model, temporal_input, previous_source_ids, applications, positions, distributed, + schema, canonical_status, ) isnothing(extension) && return nothing extension end following = _stage_temporal_many_extensions(Base.tail(inputs), model, key, - sources, applications, positions, distributed) + sources, applications, positions, distributed, schema, canonical_status) isnothing(following) && return nothing return (extension, following...) end @@ -3804,10 +3820,11 @@ end function _extend_temporal_many_inputs_in_place!(view::CompiledModelStatusView, model::CompositeModel, key, previous_temporal_sources, applications_by_id, - application_positions, distributed_outputs, + application_positions, distributed_outputs, status_view_schema, ) staged = _stage_temporal_many_extensions(view.temporal_inputs, model, key, - previous_temporal_sources, applications_by_id, application_positions, distributed_outputs) + previous_temporal_sources, applications_by_id, application_positions, + distributed_outputs, status_view_schema, view.canonical_status) isnothing(staged) && return false return _apply_temporal_many_extensions!(staged) end @@ -3858,7 +3875,8 @@ function _extend_model_status_views( isnothing(view) && continue extended = Base.@inline _with_model_status_view(_extend_temporal_many_inputs_in_place!, compiled.status_view_schema, application_id, view, model, key, - previous_temporal_sources, applications_by_id, positions, distributed_outputs) + previous_temporal_sources, applications_by_id, positions, distributed_outputs, + compiled.status_view_schema) if extended delete!(affected_keys, key) end @@ -4792,9 +4810,18 @@ function _extend_compiled_scene( recorder = _AddedConsumerInputBindings( model, many_binding_cache, changed_bindings, input_bindings_by_target, ) - for partial in added_applications - isempty(partial.target_ids) && continue - _with_model_application(applications_by_id, partial) do application + # Both vectors were filled in the same application-slot order above. + # Read the original partial only after selecting its exact owner. + for position in eachindex(added_applications) + Base.@inline _with_metadata_entry( + applications_by_id, new_target_application_ids[position], + added_applications, position, + ) do current, partials, partial_position + partial = partials[partial_position] + partial isa typeof(current) && partial.plan === current.plan || + throw(ArgumentError("The application is outside its compiled metadata owner.")) + application = partial::typeof(current) + isempty(application.target_ids) && return nothing _with_metadata_entry( compiled.scenario_plan.input_recipes_by_application, application.id, ) do recipe @@ -7478,7 +7505,7 @@ function _distributed_temporal_source_application( end _status_view_execution_stamp(previous::CompiledModelStatusView, model, key) = previous.execution_stamp -function _status_view_execution_stamp(model, key, previous, schema) +@inline function _status_view_execution_stamp(model, key, previous, schema) isnothing(previous) && return _targeted_call_execution_stamp(model, key) return Base.@inline _with_model_status_view(_status_view_execution_stamp, schema, first(key), previous, model, key) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 64576d2e3..28b2ae025 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -222,7 +222,14 @@ function _validate_selector_context( allowed = _selector_context_fields(context) invalid = Symbol[] for field in _selector_semantic_fields(selector) - field in allowed || push!(invalid, field) + accepted = false + for allowed_field in allowed + if field === allowed_field + accepted = true + break + end + end + accepted || push!(invalid, field) end if !isempty(invalid) allowed_fields = Symbol[] diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index cd0b3f72b..90cad3c06 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -66,9 +66,13 @@ end schema, binding.application_id, f, binding, status, args...) end -@inline _copy_temporal_status_value(::Nothing, value) = _private_temporal_value(value) -@generated function _copy_temporal_status_value(::Val{Payloads}, value) where {Payloads} - branches = [:(typeof(value) === $T && return _private_temporal_value(value::$T)) +# Copy/construction stays inside the exact payload branch, before returning a +# value to an Any-valued transient staging collection. +@inline _copy_temporal_status_value(::Nothing, value, operation::F) where {F} = operation(value) +@generated function _copy_temporal_status_value(::Val{Payloads}, value, + operation::F, +) where {Payloads,F} + branches = [:(typeof(value) === $T && return operation(value::$T)) for T in fieldtypes(Payloads)] return quote $(branches...) @@ -87,14 +91,14 @@ function _gather_temporal_initial(binding::CompiledModelInputBinding, status::St ) initial = status[binding.input] end - binding.multiplicity == :many || return _copy_temporal_status_value(payloads, initial) + binding.multiplicity == :many || return (Base.@inline _copy_temporal_status_value(payloads, initial, _private_temporal_value)) initial isa AbstractVector || error( "Temporal `Many` input `$(binding.input)` on application ", "`$(binding.application_id)` requires a vector-like initialized value; got ", "`$(typeof(initial))`.", ) if length(initial) == length(binding.source_ids) - return Any[_copy_temporal_status_value(payloads, value) for value in initial] + return Any[(Base.@inline _copy_temporal_status_value(payloads, value, _private_temporal_value)) for value in initial] end binding.policy isa PreviousTimeStep && error( "Temporal `Many` input `$(binding.input)` on application ", @@ -107,7 +111,7 @@ function _gather_temporal_initial(binding::CompiledModelInputBinding, status::St "`$(binding.application_id)` needs an initialized element to preallocate ", "$(length(binding.source_ids)) temporal values.", ) - return Any[_copy_temporal_status_value(payloads, first(initial)) for _ in binding.source_ids] + return Any[(Base.@inline _copy_temporal_status_value(payloads, first(initial), _private_temporal_value)) for _ in binding.source_ids] end function _collect_status_view_binding!(binding::CompiledModelInputBinding, @@ -157,35 +161,41 @@ function _gather_admitted_status_view_temporal!(payloads, binding::CompiledModel )) end many = binding.multiplicity == :many - storage = many ? Any[_copy_temporal_status_value(payloads, value) for value in initial] : - _copy_temporal_status_value(payloads, initial) + storage = many ? Any[(Base.@inline _copy_temporal_status_value(payloads, value, _private_temporal_value)) for value in initial] : + (Base.@inline _copy_temporal_status_value(payloads, initial, _private_temporal_value)) push!(recipes, _TemporalStatusViewRecipe(binding.input, binding, source_applications, initial, storage, many)) return nothing end -function _compile_model_status_view(model::CompositeModel, +@inline function _compile_model_status_view(model::CompositeModel, application::CompiledModelApplication, object_id::ObjectId, input_bindings::Tuple, applications_by_id, application_positions, distributed_outputs=NoCompiledDistributedOutputs(); execution_stamp::Base.RefValue{UInt64}, status_view_schema, input_binding_storage, ) - return _with_model_application(applications_by_id, application) do admitted_application - raw_status = _ensure_model_object_status!(model, object_id) - return _with_registered_status(model.registry.objects.catalog, raw_status) do canonical_status - _assemble_model_status_view(model, admitted_application, object_id, - input_bindings, canonical_status, applications_by_id, - application_positions, distributed_outputs, execution_stamp, - status_view_schema, input_binding_storage) - end - end + return Base.@inline _with_model_application(_compile_model_status_view_for_application, + applications_by_id, application, model, object_id, input_bindings, + applications_by_id, application_positions, distributed_outputs, + execution_stamp, status_view_schema, input_binding_storage) +end + +function _compile_model_status_view_for_application(application, model, object_id, + input_bindings, applications_by_id, application_positions, distributed_outputs, + execution_stamp, status_view_schema, input_binding_storage, +) + raw_status = _ensure_model_object_status!(model, object_id) + return Base.@inline _with_registered_status(_assemble_model_status_view, + model.registry.objects.catalog, raw_status, model, application, object_id, + input_bindings, applications_by_id, application_positions, + distributed_outputs, execution_stamp, status_view_schema, input_binding_storage) end # All modes gather the same values, in the original conversion/snapshot order. # Selection below concerns exact component construction, never scientific logic. -function _assemble_model_status_view(model, application, object_id, - input_bindings, canonical_status, applications_by_id, application_positions, +function _assemble_model_status_view(canonical_status, model, application, object_id, + input_bindings, applications_by_id, application_positions, distributed_outputs, execution_stamp, status_view_schema, input_binding_storage, ) temporal_bindings = similar(input_binding_storage, 0) diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 9efebd970..4b07dd86c 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -247,6 +247,27 @@ end check_carriers(closed, simulation) end +@testset "new consumers compile only their original partial target selection" begin + data = fixture() + simulation = prepare(data.model) + old_bindings = copy(simulation.compiled.input_bindings) + shared = check_carriers(data, simulation) + register_object!(data.model, Object(:c; scale=:Reader, parent=:scene, + status=Status(total=0.0))) + continue!(simulation; steps=0) + + @test length(simulation.compiled.input_bindings) == length(old_bindings) + 2 + @test all(actual === previous for (actual, previous) in + zip(simulation.compiled.input_bindings, old_bindings)) + @test binding(simulation, :c, :single).carrier === + PSE.refvalue(model_status(data.model, :anchor), :x) + @test binding(simulation, :c, :values).carrier === shared.carrier + @test binding(simulation, :c, :values).source_ids === shared.source_ids + step!(simulation) + @test model_status(data.model, :c).total == 3.0 + check_carriers(data, simulation) +end + @testset "partial applications retain their exact target selection and metadata owner" begin data = fixture() simulation = prepare(data.model) diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl index 91626f381..ac7724a42 100644 --- a/test/test-model-output-retention-owners.jl +++ b/test/test-model-output-retention-owners.jl @@ -148,11 +148,17 @@ end model_status(simulation.model, 0)) do payloads, binding, status # Each value is deliberately read through Any, as between the copies. values = Any[2f0] - first_copy = @inferred PSE._copy_temporal_status_value(payloads, values[1]) + first_copy = @inferred PSE._copy_temporal_status_value(payloads, values[1], PSE._private_temporal_value) second_values = Any[first_copy] - second_copy = @inferred PSE._copy_temporal_status_value(payloads, second_values[1]) + second_copy = @inferred PSE._copy_temporal_status_value(payloads, second_values[1], PSE._private_temporal_value) @test first_copy === second_copy === 2f0 - @test_throws "outside its prepared input family" PSE._copy_temporal_status_value(payloads, 2.0) + # Ref construction also occurs after payload admission, not after an Any join. + storage_reference = @inferred PSE._copy_temporal_status_value( + payloads, second_values[1], PSE._private_temporal_reference) + @test storage_reference isa Base.RefValue{Float32} + @test storage_reference[] === 2f0 + @test_throws "outside its prepared input family" PSE._copy_temporal_status_value( + payloads, 2.0, PSE._private_temporal_value) end previous_owner = simulation.model.binding_cache key = (:writer, ObjectId(3)) From 8fcd45213b0ab2fd8f2819edfc5a9d0b28b34fdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 04:26:34 +0100 Subject: [PATCH 121/324] Reuse one inline application gate and typed Many preservation branch --- src/composite_model/compilation.jl | 29 +++++++------------ src/composite_model/runtime_outputs.jl | 6 ++-- .../status_view_construction.jl | 2 +- test/test-model-output-retention-owners.jl | 10 +++---- test/test-model-temporal-initial-typing.jl | 2 +- test/test-resolved-input-materialization.jl | 6 ++-- 6 files changed, 22 insertions(+), 33 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 5b881fd4e..169666a5e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3539,8 +3539,7 @@ function _preserve_temporal_input_state!( previous::CompiledTemporalInput, previous_source_ids, ) - if current.binding.multiplicity != :many || - previous.binding.multiplicity != :many + if !(current.binding.selector isa Many && previous.binding.selector isa Many) current.reference[] = _private_temporal_value(previous.reference[]) return CompiledTemporalInput( current.binding, @@ -3897,10 +3896,10 @@ function _extend_model_status_views( get(input_bindings_by_target, key, ()), applications_by_id, positions, - distributed_outputs; - execution_stamp=_status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema), - status_view_schema=compiled.status_view_schema, - input_binding_storage=compiled.input_bindings, + distributed_outputs, + _status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema), + compiled.status_view_schema, + compiled.input_bindings, ) views[key] = isnothing(previous_view) ? current_view : @@ -4810,17 +4809,8 @@ function _extend_compiled_scene( recorder = _AddedConsumerInputBindings( model, many_binding_cache, changed_bindings, input_bindings_by_target, ) - # Both vectors were filled in the same application-slot order above. - # Read the original partial only after selecting its exact owner. - for position in eachindex(added_applications) - Base.@inline _with_metadata_entry( - applications_by_id, new_target_application_ids[position], - added_applications, position, - ) do current, partials, partial_position - partial = partials[partial_position] - partial isa typeof(current) && partial.plan === current.plan || - throw(ArgumentError("The application is outside its compiled metadata owner.")) - application = partial::typeof(current) + for partial in added_applications + _with_model_application(applications_by_id, partial) do application isempty(application.target_ids) && return nothing _with_metadata_entry( compiled.scenario_plan.input_recipes_by_application, application.id, @@ -7538,8 +7528,8 @@ function _compile_model_status_views( get(input_bindings_by_target, key, ()), applications_by_id, positions, - distributed_outputs; - execution_stamp=_status_view_execution_stamp(model, key, + distributed_outputs, + _status_view_execution_stamp(model, key, isnothing(previous_views) ? nothing : get(previous_views, key, nothing), status_view_schema), status_view_schema, input_binding_storage, ) @@ -8945,6 +8935,7 @@ end end) end return quote + $(Expr(:meta, :inline)) plan = getfield(partial, :plan)::CompiledApplicationPlan application_id = getfield(plan, :id)::Symbol $(branches...) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 44766179b..84015f2b2 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6157,9 +6157,9 @@ function _append_targeted_newborn_targets!( (getfield(cache,:execution_stamp)::Base.RefValue{UInt64}) status_view = _compile_model_status_view(runtime_model(context),partial_application, object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, - targeted_runtime.application_positions,compiled.distributed_outputs; - execution_stamp=stamp, status_view_schema=compiled.status_view_schema, - input_binding_storage=compiled.input_bindings)::CompiledModelStatusView + targeted_runtime.application_positions,compiled.distributed_outputs, + stamp, compiled.status_view_schema, + compiled.input_bindings)::CompiledModelStatusView output_groups = _runtime_model_output_groups(compiled,application,object_id) environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) call_bindings = () # targeted admission has rejected nested callees diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index 90cad3c06..0f745043d 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -171,7 +171,7 @@ end @inline function _compile_model_status_view(model::CompositeModel, application::CompiledModelApplication, object_id::ObjectId, input_bindings::Tuple, applications_by_id, application_positions, - distributed_outputs=NoCompiledDistributedOutputs(); + distributed_outputs, execution_stamp::Base.RefValue{UInt64}, status_view_schema, input_binding_storage, ) diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl index ac7724a42..fb689e1ce 100644 --- a/test/test-model-output-retention-owners.jl +++ b/test/test-model-output-retention-owners.jl @@ -113,9 +113,8 @@ function construction_trace(; schema=ViewConstructionTrace(), prototype=nothing) stamp = Ref(UInt64(0)) prior_view_count = schema isa ViewConstructionTrace ? length(schema.views) : 0 ephemeral = PSE._compile_model_status_view(model, partial, ObjectId(3), (), - compiled.applications_by_id, positions, compiled.distributed_outputs; - execution_stamp=stamp, status_view_schema=schema, - input_binding_storage=compiled.input_bindings) + compiled.applications_by_id, positions, compiled.distributed_outputs, + stamp, schema, compiled.input_bindings) @test ephemeral.execution_stamp === stamp @test ephemeral.canonical_status === previous.canonical_status @test PSE.refvalue(ephemeral.status, :live) === PSE.refvalue(previous.status, :live) @@ -167,9 +166,8 @@ end positions = Dict(id => index for (index, id) in pairs(compiled.application_order)) @test_throws "outside supported prepared application view families" PSE._compile_model_status_view( simulation.model, compiled.applications_by_id[:writer], ObjectId(3), (), - compiled.applications_by_id, positions, compiled.distributed_outputs; - execution_stamp=before.execution_stamp, status_view_schema=invalid, - input_binding_storage=compiled.input_bindings) + compiled.applications_by_id, positions, compiled.distributed_outputs, + before.execution_stamp, invalid, compiled.input_bindings) @test simulation.model.binding_cache === previous_owner @test compiled.status_views_by_target[key] === before end diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 7658704e7..83a7e3106 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -93,7 +93,7 @@ end end function rebuild_input(ids, initial) - binding = (multiplicity=:many, source_ids=ObjectId.(ids)) + binding = (selector=Many(), source_ids=ObjectId.(ids)) storage = PSE.RefVector(Base.RefValue{Any}[ Ref{Any}(deepcopy(value)) for value in initial ]) diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index 9c38b4469..ed0a2da03 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -647,9 +647,9 @@ end base.output_reads[] = replacement.output_reads[] = 0 positions = Dict(id => index for (index, id) in pairs(compiled.application_order)) ephemeral = PSE._compile_model_status_view(model, application, ObjectId(:b_override), (), - compiled.applications_by_id, positions, compiled.distributed_outputs; - execution_stamp=override_view.execution_stamp, status_view_schema=compiled.status_view_schema, - input_binding_storage=compiled.input_bindings) + compiled.applications_by_id, positions, compiled.distributed_outputs, + override_view.execution_stamp, compiled.status_view_schema, + compiled.input_bindings) @test (base.output_reads[], replacement.output_reads[]) == (0, 1) @test ephemeral.private_outputs.private isa Base.RefValue{Float32} @test ephemeral.canonical_status === override_view.canonical_status From 2183cdda82654de2932a3854bc4b0ac98b4c6473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 04:34:39 +0100 Subject: [PATCH 122/324] Admit input status recipes and references through their prepared owners --- src/composite_model/compilation.jl | 294 ++++++++++++++++++----------- 1 file changed, 188 insertions(+), 106 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 169666a5e..423d3357f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6304,6 +6304,35 @@ _canonical_status_recipe_storage(::OpenObjectFamilyCatalog, ::Type{I}) where {I< return :(Dict{$I,$R}()) end +# The existing recipe dictionary is the witness for its actual CSR instances. +@inline function _with_canonical_status_recipe(f::F, + ::AbstractDict{I,_CanonicalStatusRecipe}, recipe, args::Vararg{Any,N}, +) where {F,I,N} + return f(recipe::_CanonicalStatusRecipe, args...) +end +@generated function _with_canonical_status_recipe(f::F, ::AbstractDict{I,R}, + recipe, args::Vararg{Any,N}, +) where {F,I,R,N} + families = Base.uniontypes(R) + all(T -> isconcretetype(T) && T <: _CanonicalStatusRecipe, families) || + throw(ArgumentError("Canonical recipe storage requires concrete recipe families.")) + branches = [:(recipe isa $T && return f(recipe::$T, args...)) for T in families] + return quote + $(Expr(:meta, :inline)) + $(branches...) + throw(ArgumentError("The canonical status recipe is outside its storage family.")) + end +end + +@inline function _with_canonical_status_preparation(f::F, recipes, catalog, + preparation, args::Vararg{Any,N}, +) where {F,N} + if preparation isa _CanonicalStatusRecipe + return _with_canonical_status_recipe(f, recipes, preparation, args...) + end + return Base.@inline _with_registered_status(f, catalog, preparation, args...) +end + @inline function _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) variable in recipe.edit_names && return true return !isnothing(recipe.original) && variable in propertynames(recipe.original) @@ -7242,6 +7271,156 @@ function _model_input_status_references(bindings) return references end +# Projection uses existing raw binding families; no references or values are made. +function _model_input_status_reference_types(B) + references = Any[] + for Binding in _model_input_binding_family_types(B) + Carrier = fieldtype(Binding, :carrier) + # Both the final-reference table and its consumers skip absent carriers. + Carrier === Nothing && continue + isconcretetype(Carrier) || throw(ArgumentError( + "An input status reference requires an exact prepared carrier type.")) + Reference = Carrier <: Base.RefValue ? Carrier : Base.RefValue{Carrier} + isconcretetype(Reference) || throw(ArgumentError( + "An input status reference requires an exact prepared reference type.")) + Reference in references || push!(references, Reference) + end + return Tuple(references) +end + +@inline function _with_model_input_status_reference(f::F, + ::AbstractVector{CompiledModelInputBinding}, reference, args::Vararg{Any,N}, +) where {F,N} + reference isa Ref || throw(ArgumentError("An input status reference must be a Ref.")) + return f(reference, args...) +end + +@generated function _with_model_input_status_reference(f::F, + ::AbstractVector{B}, reference, args::Vararg{Any,N}, +) where {F,B,N} + references = _model_input_status_reference_types(B) + branches = [:(reference isa $R && return f(reference::$R, args...)) for R in references] + return quote + $(branches...) + throw(ArgumentError("The input status reference is outside its prepared binding family.")) + end +end + +# The per-record worker already owns a concrete real B after existing IB admission. +# Use the same projection when no all-bindings union is needed. +@generated function _with_model_input_status_reference(f::F, + binding::B, reference, args::Vararg{Any,N}, +) where {F,B<:CompiledModelInputBinding,N} + references = _model_input_status_reference_types(B) + branches = [:(reference isa $R && return f(reference::$R, args...)) for R in references] + return quote + $(branches...) + throw(ArgumentError("The input status reference is outside its prepared binding family.")) + end +end + +_stage_model_input_defaults!(preparation, ::Tuple{}, ::Tuple{}, context) = 0 +function _stage_model_input_defaults!(preparation, variables::Tuple, + defaults::Tuple{V,Vararg}, context, +) where {V} + variable, value = first(variables), first(defaults) + if preparation isa Status + if !(variable in propertynames(preparation)) + recipe = _status_recipe_for_object!(context.recipes, + context.recipe_order, context.model, context.object_id) + return _with_canonical_status_recipe(_stage_model_input_defaults!, + context.recipes, recipe, variables, defaults, context) + end + return _stage_model_input_defaults!(preparation, + Base.tail(variables), Base.tail(defaults), context) + end + avoided = 0 + if !_status_recipe_has_variable(preparation, variable) + reference = isnothing(context.final_references) ? nothing : + get(context.final_references, + (context.application.id, context.object_id, variable), nothing) + if isnothing(reference) + Base.@inline _status_recipe_add_default!(context.model, preparation, + context.object_id, variable, value; + application_id=context.application.id, origin=:model_input_default, + conversion_records=context.conversion_records) + context.default_status_updates[(context.object_id, variable)] = true + else + avoided = Base.@inline _with_model_input_status_reference( + _stage_model_input_default_reference!, context.bindings, reference, + preparation, variable, value, context) + end + end + return avoided + _stage_model_input_defaults!(preparation, + Base.tail(variables), Base.tail(defaults), context) +end + +function _stage_model_input_default_reference!(reference, preparation, variable, + value, context, +) + # Keep the existing conversion/validation even when the carrier owns storage. + _no_status_conversion(context.model.status_conversion) || + _materialize_status_value(context.model, variable, value; + object_id=context.object_id, application_id=context.application.id, + origin=:model_input_default, private_copy=true, + conversion_records=context.conversion_records) + _status_recipe_set_reference!(preparation, variable, reference) + return 1 +end + +function _stage_model_bound_input_reference!(binding, context) + binding.carrier_hint == :temporal_stream && return nothing + isnothing(binding.carrier) && return nothing + preparation = get(context.recipes, binding.consumer_id, nothing) + if isnothing(preparation) + preparation = _model_object(context.model, binding.consumer_id).status + preparation isa Status || return nothing + end + reference = isnothing(context.final_references) ? + _model_input_status_reference(binding) : + get(context.final_references, + (binding.application_id, binding.consumer_id, binding.input), nothing) + isnothing(reference) && (reference = _model_input_status_reference(binding)) + return Base.@inline _with_model_input_status_reference( + _stage_model_bound_input_reference_with_reference!, binding, + reference, preparation, binding, context) +end + +function _stage_model_bound_input_reference_with_reference!(reference, + preparation, binding, context, +) + return _with_canonical_status_preparation(_stage_admitted_model_input_reference!, + context.recipes, context.model.registry.objects.catalog, preparation, + reference, binding, context) +end + +function _stage_admitted_model_input_reference!(preparation, reference, binding, + context, +) + if preparation isa Status + if binding.input in propertynames(preparation) && + refvalue(preparation, binding.input) === reference + context.default_status_updates[(binding.consumer_id, binding.input)] = false + return nothing + end + recipe = _status_recipe_for_object!(context.recipes, context.recipe_order, + context.model, binding.consumer_id) + return _with_canonical_status_recipe(_set_model_input_status_reference!, + context.recipes, recipe, reference, binding, context) + elseif _status_recipe_has_variable(preparation, binding.input) && + _status_recipe_reference(preparation, binding.input) === reference + context.default_status_updates[(binding.consumer_id, binding.input)] = false + return nothing + end + return _set_model_input_status_reference!(preparation, reference, binding, context) +end + +function _set_model_input_status_reference!(preparation, reference, binding, context) + _status_recipe_set_reference!(preparation, binding.input, reference) + context.default_status_updates[(binding.consumer_id, binding.input)] = false + return nothing +end + function _prepare_model_input_statuses_batched!( model::CompositeModel, applications, @@ -7257,6 +7436,8 @@ function _prepare_model_input_statuses_batched!( conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records default_status_updates = Dict{Tuple{I,Symbol},Bool}() input_default_rewrites_avoided = 0 + context = (; model, recipes, recipe_order, bindings, final_references, + conversion_records, default_status_updates) for partial in applications input_default_rewrites_avoided += Base.@inline _with_model_application(applications_by_id, partial) do application rewrites_avoided = 0 @@ -7264,68 +7445,12 @@ function _prepare_model_input_statuses_batched!( schemas = _application_default_schemas(application, Val(:inputs)) for object_id in application.target_ids rewrites_avoided += Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults - object_rewrites_avoided = 0 preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - for (variable_, value) in pairs(defaults) - variable = Symbol(variable_) - if preparation isa Status - variable in propertynames(preparation) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, - model, - object_id, - ) - else - _status_recipe_has_variable(preparation, variable) && continue - end - reference = isnothing(final_references) ? - nothing : - get( - final_references, - (application.id, object_id, variable), - nothing, - ) - if !isnothing(reference) - # Preserve conversion callbacks, validation, and diagnostic - # records even though the resolved carrier owns storage. - _no_status_conversion(model.status_conversion) || - _materialize_status_value( - model, - variable, - value; - object_id=object_id, - application_id=application.id, - origin=:model_input_default, - private_copy=true, - conversion_records=conversion_records, - ) - _status_recipe_set_reference!( - preparation, - variable, - reference, - ) - object_rewrites_avoided += 1 - continue - end - _status_recipe_add_default!( - model, - preparation, - object_id, - variable, - value; - application_id=application.id, - origin=:model_input_default, - conversion_records=conversion_records, - ) - default_status_updates[(object_id, variable)] = true - end - return object_rewrites_avoided + recipes, recipe_order, model, object_id) + selected = (; context..., application, object_id) + _with_canonical_status_preparation(_stage_model_input_defaults!, + recipes, model.registry.objects.catalog, preparation, + keys(defaults), values(defaults), selected) end end return rewrites_avoided @@ -7333,51 +7458,8 @@ function _prepare_model_input_statuses_batched!( end for binding in bindings - binding.carrier_hint == :temporal_stream && continue - isnothing(binding.carrier) && continue - recipe = get(recipes, binding.consumer_id, nothing) - if isnothing(recipe) - status = _model_object(model, binding.consumer_id).status - status isa Status || continue - end - reference = if isnothing(final_references) - _model_input_status_reference(binding) - else - get( - final_references, - ( - binding.application_id, - binding.consumer_id, - binding.input, - ), - nothing, - ) - end - isnothing(reference) && - (reference = _model_input_status_reference(binding)) - if isnothing(recipe) - if binding.input in propertynames(status) && - refvalue(status, binding.input) === reference - default_status_updates[(binding.consumer_id, binding.input)] = false - continue - end - recipe = _status_recipe_for_object!( - recipes, - recipe_order, - model, - binding.consumer_id, - ) - elseif _status_recipe_has_variable(recipe, binding.input) && - _status_recipe_reference(recipe, binding.input) === reference - default_status_updates[(binding.consumer_id, binding.input)] = false - continue - end - _status_recipe_set_reference!( - recipe, - binding.input, - reference, - ) - default_status_updates[(binding.consumer_id, binding.input)] = false + Base.@inline _with_model_input_binding(_stage_model_bound_input_reference!, + bindings, binding, context) end result = _apply_status_recipes!( From 3c254de8e243791c0622645f5e2e6655fbe4bfc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 04:54:16 +0100 Subject: [PATCH 123/324] Keep dynamic input memberships in vectors and derive selector traits --- src/composite_model/compilation.jl | 90 +++++++++++-------- .../status_view_construction.jl | 3 +- src/input_schema.jl | 6 ++ test/test-model-binding-index-identities.jl | 21 +++-- test/test-model-input-binding-storage.jl | 3 +- test/test-model-status-type-conversion.jl | 47 ++++++++++ test/test-selector-candidate-empty-scope.jl | 4 +- 7 files changed, 123 insertions(+), 51 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 423d3357f..aae0b1dac 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -80,13 +80,20 @@ struct CompiledModelInputPlan{TAG,SEL,M,OA,PSA,W,RT<:Tuple} source_var::Symbol process::Union{Nothing,Symbol} application::Union{Nothing,Symbol} - multiplicity::Symbol potential_source_application_ids::PSA breaks_same_step_cycle::Bool window::W reference_types::Type{RT} end +@inline function Base.getproperty(plan::CompiledModelInputPlan, name::Symbol) + name === :multiplicity && return multiplicity(getfield(plan, :selector)) + return getfield(plan, name) +end + +Base.propertynames(plan::CompiledModelInputPlan) = + (fieldnames(typeof(plan))..., :multiplicity) + """Fixed metadata schema whose scalar lookups stay inside its typed owner.""" mutable struct CompiledMetadataTable{T<:NamedTuple} const entries::T @@ -473,9 +480,9 @@ _selector_candidate_values(value) = value isa Tuple ? value : (value,) function _selector_scope_anchor( model::CompositeModel, - matcher::CompiledSelectorMatcher; - context=nothing, - default_scope=nothing, + matcher::CompiledSelectorMatcher, + context, + default_scope, ) scope = if !isnothing(matcher.scope) matcher.scope @@ -517,9 +524,9 @@ end function _selector_candidate_destination( index::SelectorCandidateIndex, model::CompositeModel, - matcher::CompiledSelectorMatcher; - context=nothing, - default_scope=nothing, + matcher::CompiledSelectorMatcher, + context, + default_scope, ) scope = isnothing(matcher.scope) ? default_scope : matcher.scope if scope isa Self && isnothing(matcher.relation) @@ -537,9 +544,9 @@ function _selector_candidate_destination( end anchor = _selector_scope_anchor( model, - matcher; - context=context, - default_scope=default_scope, + matcher, + context, + default_scope, ) if !isnothing(anchor) I = keytype(index.by_id) @@ -579,9 +586,9 @@ function _index_selector_candidate!( index::SelectorCandidateIndex, model::CompositeModel, matcher::CompiledSelectorMatcher, - candidate_index::Int; - context=nothing, - default_scope=nothing, + candidate_index::Int, + context, + default_scope, ) tracks_application_targets = !isnothing(index.application_target_templates) @@ -600,9 +607,9 @@ function _index_selector_candidate!( destination = _selector_candidate_destination( index, model, - matcher; - context=context, - default_scope=default_scope, + matcher, + context, + default_scope, ) isnothing(destination) && return index groups, values = destination @@ -672,6 +679,8 @@ function _application_target_candidate_index(model, application_plans) model, plan.target_matcher, plan.slot, + nothing, + nothing, ) end return _freeze_selector_candidate_index(index) @@ -1656,7 +1665,7 @@ end name === :source_var && return getfield(plan, :source_var) name === :process && return getfield(plan, :process) name === :application && return getfield(plan, :application) - name === :multiplicity && return getfield(plan, :multiplicity) + name === :multiplicity && return multiplicity(getfield(plan, :selector)) name === :potential_source_application_ids && return getfield(plan, :potential_source_application_ids) name === :breaks_same_step_cycle && @@ -2182,9 +2191,9 @@ function _index_dynamic_input_binding!( index, model, binding.matcher, - binding_index; - context=binding.consumer_id, - default_scope=_default_dependency_scope( + binding_index, + binding.consumer_id, + _default_dependency_scope( model, binding.consumer_id, ), @@ -2223,9 +2232,9 @@ function _index_dynamic_call_binding!( index, model, binding.matcher, - binding_index; - context=binding.consumer_id, - default_scope=_default_dependency_scope( + binding_index, + binding.consumer_id, + _default_dependency_scope( model, binding.consumer_id, ), @@ -2457,10 +2466,8 @@ function _group_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B, end function _index_model_input_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B<:CompiledModelInputBinding,I<:ObjectId} - K = Tuple{Symbol,I} - grouped = _group_model_bindings(bindings, I) - # Input membership remains dynamic over its canonical current/future family. - return Dict{K,Tuple{Vararg{B}}}(key => Tuple(values) for (key, values) in grouped) + # Membership length is runtime data; the existing input family supplies B. + return _group_model_bindings(bindings, I) end # Cardinality and binding types come from the actual resolved runtime plans. @@ -2988,18 +2995,21 @@ struct _AddedConsumerInputBindings{M,C,B,I} end function _record_consumer_input_bindings!( - recorder::_AddedConsumerInputBindings, bindings, application, consumer_id, + recorder::_AddedConsumerInputBindings, bindings::AbstractVector{B}, application, consumer_id, first_new_binding, last_new_binding, -) +) where {B} first_new_binding <= last_new_binding || return nothing + new_bindings = B[] + sizehint!(new_bindings, last_new_binding - first_new_binding + 1) for binding_index in first_new_binding:last_new_binding - bindings[binding_index] = _share_many_input_binding!( + binding = _share_many_input_binding!( recorder.many_binding_cache, recorder.model, bindings[binding_index], ) + bindings[binding_index] = binding + push!(new_bindings, binding) end - new_bindings = bindings[first_new_binding:last_new_binding] append!(recorder.changed_bindings, new_bindings) - recorder.input_bindings_by_target[(application.id, consumer_id)] = Tuple(new_bindings) + recorder.input_bindings_by_target[(application.id, consumer_id)] = new_bindings return nothing end @@ -4580,10 +4590,13 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S )] = previous_source_ids end target = (binding.application_id, consumer_id) - input_bindings_by_target[target] = Tuple( - existing === binding ? replacement_binding : existing - for existing in get(input_bindings_by_target, target, ()) - ) + # Replace the membership container so shallow diagnostic snapshots retain + # the previous bindings, while all unmodified binding/carrier objects stay shared. + members = valtype(typeof(input_bindings_by_target))() + for existing in get(input_bindings_by_target, target, ()) + push!(members, existing === binding ? replacement_binding : existing) + end + input_bindings_by_target[target] = members return true end @@ -7491,7 +7504,7 @@ function _prepare_model_input_statuses_batched!( end function _private_temporal_value(value) - return deepcopy(value) + return _private_initial_value(value) end function _temporal_source_application( @@ -8142,7 +8155,6 @@ Base.@nospecializeinfer function _compiled_model_input_plan( source_var, process_filter, application_filter, - multiplicity(selector), potential_source_application_ids, breaks_same_step_cycle, _selector_window(selector), @@ -8220,7 +8232,7 @@ function _resolve_model_input_plan(model, plan::CompiledModelInputPlan, slot::In return CompiledModelInputPlan(plan.route, slot, plan.application_slot, plan.application_id, plan.input, plan.selector, matcher, plan.origin, plan.order_after_application_ids, plan.source_var, plan.process, - plan.application, plan.multiplicity, plan.potential_source_application_ids, + plan.application, plan.potential_source_application_ids, plan.breaks_same_step_cycle, plan.window, plan.reference_types) end diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index 0f745043d..c5d244243 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -170,7 +170,8 @@ end @inline function _compile_model_status_view(model::CompositeModel, application::CompiledModelApplication, object_id::ObjectId, - input_bindings::Tuple, applications_by_id, application_positions, + input_bindings::Union{AbstractVector{<:CompiledModelInputBinding},Tuple{}}, + applications_by_id, application_positions, distributed_outputs, execution_stamp::Base.RefValue{UInt64}, status_view_schema, input_binding_storage, diff --git a/src/input_schema.jl b/src/input_schema.jl index 155e3be5c..288f02c19 100644 --- a/src/input_schema.jl +++ b/src/input_schema.jl @@ -41,6 +41,12 @@ end _private_initial_value(value) = deepcopy(value) +function _private_initial_value(value::Array{T}) where {T} + # Isbits elements contain no mutable identities; a fresh dense copy has the + # same private-value semantics without entering Base's erased Memory helper. + return isbitstype(T) ? copy(value) : deepcopy(value) +end + @noinline function _invalid_input_schema_error(model, schema) context = "`inputs_($(typeof(model)))`" schema isa NamedTuple || error( diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index bd8cdd05e..126b7d03d 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -75,35 +75,37 @@ function call_fixture(closed) return (; model, simulation, capture, context=target.context) end -function check_index(model, compiled, bindings, index, rebuild_index) +function check_index(model, compiled, bindings, index, rebuild_index, value_type) I = keytype(model.registry.objects) @test keytype(index) === Tuple{Symbol,I} - @test valtype(index) === Tuple{Vararg{eltype(bindings)}} + @test valtype(index) === value_type rebuilt = rebuild_index(bindings, I) @test keytype(rebuilt) === Tuple{Symbol,I} - @test valtype(rebuilt) === Tuple{Vararg{eltype(bindings)}} + @test valtype(rebuilt) === value_type @test Set(keys(rebuilt)) == Set(keys(index)) for (key, values) in rebuilt expected = Tuple(binding for binding in bindings if (binding.application_id, binding.consumer_id) == key) - @test values === expected - @test index[key] === expected + @test Tuple(values) === expected + @test Tuple(index[key]) === expected @test all(PSE._model_binding_target_key(binding, I) === key for binding in values) end empty_index = rebuild_index(empty(bindings), I) @test isempty(empty_index) @test keytype(empty_index) === Tuple{Symbol,I} - @test valtype(empty_index) === Tuple{Vararg{eltype(bindings)}} + @test valtype(empty_index) === value_type return nothing end function check_indexes(model, simulation) compiled = simulation.compiled check_index(model, compiled, compiled.input_bindings, compiled.input_bindings_by_target, - PSE._index_model_input_bindings) + PSE._index_model_input_bindings, Vector{eltype(compiled.input_bindings)}) + @test isconcretetype(valtype(compiled.input_bindings_by_target)) check_index(model, compiled, compiled.call_bindings, compiled.call_bindings_by_target, (bindings, I) -> PSE._index_model_call_bindings( - bindings, compiled.scenario_plan.call_plans_by_application, I)) + bindings, compiled.scenario_plan.call_plans_by_application, I), + Tuple{Vararg{eltype(compiled.call_bindings)}}) if all(isempty, values(compiled.scenario_plan.call_plans_by_application.entries)) @test eltype(compiled.call_bindings) === Union{} @test valtype(compiled.call_bindings_by_target) === Tuple{} @@ -208,6 +210,9 @@ end step!(simulation) after = simulation.compiled.input_bindings_by_target[key] @test typeof(after) === typeof(before) + @test after !== before + @test first(after) === first(before) + @test Tuple(binding.input for binding in before) == (:single, :values) # The mixed-ID order inserts 2 before :leaf. A rebuilt column keeps the # prepared representation and the original live references. @test typeof(last(after).carrier) === typeof(many) diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 4b07dd86c..133eeb95c 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -121,7 +121,8 @@ end data = fixture() simulation = prepare(data.model, prototype) input_cache = simulation.compiled.input_bindings_by_target - @test valtype(input_cache) === Tuple{Vararg{eltype(prototype)}} + @test valtype(input_cache) === Vector{eltype(prototype)} + @test isconcretetype(valtype(input_cache)) @test simulation.compiled.input_bindings !== prototype @test eltype(simulation.compiled.input_bindings) === eltype(prototype) @test isempty(check_carriers(data, simulation).carrier) diff --git a/test/test-model-status-type-conversion.jl b/test/test-model-status-type-conversion.jl index 39a745db5..f466f71b0 100644 --- a/test/test-model-status-type-conversion.jl +++ b/test/test-model-status-type-conversion.jl @@ -30,6 +30,53 @@ function PlantSimEngine.run!( return nothing end +# The same default object is deliberately reused by two real application targets. +struct OwnedArrayDefaultModel{V} <: AbstractStatus_Type_ConversionModel + default::V +end +PlantSimEngine.inputs_(model::OwnedArrayDefaultModel) = (payload=Default(model.default),) +PlantSimEngine.outputs_(::OwnedArrayDefaultModel) = NamedTuple() +PlantSimEngine.run!(::OwnedArrayDefaultModel, status, environment, constants, context) = nothing + +@testset "private array defaults retain bits and independent mutable graphs" begin + function prepared_defaults(value) + model = CompositeModel( + Object(:first; scale=:Scene), Object(:second; scale=:Scene); + applications=(ModelSpec(OwnedArrayDefaultModel(value); + name=:defaults, on=Many(scale=:Scene)),), + environment=(duration=Hour(1),)) + run!(model; steps=0, outputs=:none) + return model_status(model, :first).payload, model_status(model, :second).payload + end + + source = Float32[reinterpret(Float32, UInt32(0x7fc00001)), -0f0, 3f0] + left, right = prepared_defaults(source) + @test left isa Vector{Float32} && right isa Vector{Float32} + @test left !== source && right !== source && left !== right + @test reinterpret(UInt32, left) == reinterpret(UInt32, source) + @test reinterpret(UInt32, right) == reinterpret(UInt32, source) + left[3] = 9f0 + @test right[3] === source[3] === 3f0 + + shared = Float32[1, 2] + nested = [shared, shared] + first_graph, second_graph = prepared_defaults(nested) + @test first_graph !== nested && second_graph !== nested && first_graph !== second_graph + @test first_graph[1] === first_graph[2] + @test second_graph[1] === second_graph[2] + @test first_graph[1] !== shared && second_graph[1] !== shared + @test first_graph[1] !== second_graph[1] + first_graph[1][1] = 9f0 + @test first_graph[2][1] === 9f0 + @test second_graph[1][1] === shared[1] === 1f0 + + cycle = Any[] + push!(cycle, cycle) + copied_cycle = PlantSimEngine._private_initial_value(cycle) + @test copied_cycle !== cycle + @test copied_cycle[1] === copied_cycle +end + struct StatusTransformParticle{T} value::T spread::T diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 5552e5934..3961dcee7 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -144,7 +144,7 @@ end for (position, selector) in pairs(selectors) matcher = PlantSimEngine._compile_selector_matcher(model, selector) PlantSimEngine._index_selector_candidate!( - index, model, matcher, position; context=ObjectId(plant_id), + index, model, matcher, position, ObjectId(plant_id), nothing, ) end expected = Set([1, 2, 5, 6]) @@ -168,7 +168,7 @@ end Many(id=raw_future, within=Subtree()))) matcher = PlantSimEngine._compile_selector_matcher(model, selector) @test PlantSimEngine._index_selector_candidate!(future_index, model, - matcher, slot; context=ObjectId(plant_id)) === future_index + matcher, slot, ObjectId(plant_id), nothing) === future_index end frozen_future = PlantSimEngine._freeze_selector_candidate_index(future_index) for candidate_index in (future_index, frozen_future) From ebcacfe69e643a040532542a1c7654156f3ef8e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 05:20:09 +0100 Subject: [PATCH 124/324] Share Many inputs through one cache with typed query and plan indexes --- src/composite_model/compilation.jl | 268 ++++++++++++++--------- test/test-model-input-binding-storage.jl | 54 +++++ 2 files changed, 223 insertions(+), 99 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index aae0b1dac..98b7f54ce 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3108,6 +3108,81 @@ function _final_inferred_output_plans( return isempty(final_matches) ? matches : final_matches end +# Runtime scope identity has one layout; membership and IDs remain ordinary data. +struct _ManyBindingScopeAnchor{I<:ObjectId} + kind::Symbol + id::Union{Nothing,I} + + _ManyBindingScopeAnchor{I}(kind::Symbol, id::Union{Nothing,I}) where {I<:ObjectId} = + new{I}(kind, id) +end +Base.isequal(left::_ManyBindingScopeAnchor, right::_ManyBindingScopeAnchor) = + left.kind === right.kind && isequal(left.id, right.id) +Base.hash(anchor::_ManyBindingScopeAnchor, seed::UInt) = anchor.kind === :scene ? + hash((anchor.kind,), seed) : hash((anchor.kind, anchor.id), seed) + +struct _ManyBindingQueryKey{S,I<:ObjectId} + selector::S + anchor::_ManyBindingScopeAnchor{I} + source_var::Symbol + process::Union{Nothing,Symbol} + application::Union{Nothing,Symbol} + carrier_hint::Symbol + carrier_type::DataType +end +_many_binding_query_components(key::_ManyBindingQueryKey) = + (key.selector, key.anchor, key.source_var, key.process, key.application, + key.carrier_hint, key.carrier_type) +Base.isequal(left::_ManyBindingQueryKey, right::_ManyBindingQueryKey) = + isequal(_many_binding_query_components(left), _many_binding_query_components(right)) +Base.hash(key::_ManyBindingQueryKey, seed::UInt) = + hash(_many_binding_query_components(key), seed) + +struct _ManyBindingPlanKey{I<:ObjectId} + slot::Int + anchor::_ManyBindingScopeAnchor{I} +end +Base.isequal(left::_ManyBindingPlanKey, right::_ManyBindingPlanKey) = + left.slot == right.slot && isequal(left.anchor, right.anchor) +Base.hash(key::_ManyBindingPlanKey, seed::UInt) = + hash((:compiled_many_input_plan, key.slot, key.anchor), seed) + +# Both indexes use exactly the family of the existing global input storage. +# The binding vector is an alias used by its existing admission gate, not a copy. +struct _ManyInputBindingCache{I<:ObjectId,S,B,IB<:AbstractVector{B}} + by_query::Dict{_ManyBindingQueryKey{S,I},B} + by_plan::Dict{_ManyBindingPlanKey{I},B} + bindings::IB +end + +@generated function _empty_many_input_binding_cache(::Type{I}, bindings::AbstractVector{B}, +) where {I<:ObjectId,B} + IB = bindings + selectors = Any[] + if B === CompiledModelInputBinding + S = Many + else + for Binding in _model_input_binding_family_types(B) + Selector = fieldtype(fieldtype(Binding, :plan), :selector) + Selector <: Many || continue + isconcretetype(Selector) || throw(ArgumentError( + "Many sharing requires exact prepared selector types.")) + Selector in selectors || push!(selectors, Selector) + end + S = Union{selectors...} + end + Cache = _ManyInputBindingCache{I,S,B,IB} + Query = _ManyBindingQueryKey{S,I} + Plan = _ManyBindingPlanKey{I} + return :($Cache(Dict{$Query,$B}(), Dict{$Plan,$B}(), bindings)) +end + +function _many_scope_anchor(model, kind::Symbol, raw_id) + I = keytype(model.registry.objects) + id = isnothing(raw_id) ? nothing : _index_object_id(model.registry.objects, raw_id) + return _ManyBindingScopeAnchor{I}(kind, id) +end + function _many_binding_scope_anchor( model::CompositeModel, selector, @@ -3115,136 +3190,119 @@ function _many_binding_scope_anchor( ) selector_criteria = criteria(selector) !isnothing(_criteria_value(selector_criteria, :relation, Relation)) && - return (:consumer, consumer_id) + return _many_scope_anchor(model, :consumer, consumer_id) explicit_scope = _criteria_scope(selector_criteria) scope = isnothing(explicit_scope) ? _default_dependency_scope(model, consumer_id) : explicit_scope if isnothing(scope) || scope isa SceneScope - return (:scene,) + return _many_scope_anchor(model, :scene, nothing) elseif scope isa SelfPlant - return (:plant, _ancestor_id(model, consumer_id; scale=:Plant)) + return _many_scope_anchor(model, :plant, + _ancestor_id(model, consumer_id; scale=:Plant)) elseif scope isa Scope - return (:scope, _named_scope_root_id(model, scope)) + return _many_scope_anchor(model, :scope, _named_scope_root_id(model, scope)) elseif scope isa Ancestor - return ( - :ancestor, - _ancestor_id( - model, - consumer_id; - scale=scope.scale, - include_self=false, - ), - ) + return _many_scope_anchor(model, :ancestor, + _ancestor_id(model, consumer_id; scale=scope.scale, include_self=false)) end - return (:consumer, consumer_id) + return _many_scope_anchor(model, :consumer, consumer_id) end -_many_binding_scope_anchor( - model::CompositeModel, - binding::CompiledModelInputBinding, -) = _many_binding_scope_anchor(model, binding.selector, binding.consumer_id) +_many_binding_scope_anchor(model::CompositeModel, binding::CompiledModelInputBinding) = + _many_binding_scope_anchor(model, binding.selector, binding.consumer_id) -function _many_binding_plan_share_key( - model::CompositeModel, - plan::CompiledModelInputPlan, - consumer_id::ObjectId, +function _many_binding_plan_share_key(model::CompositeModel, + plan::CompiledModelInputPlan, consumer_id::ObjectId, ) plan.multiplicity == :many || return nothing anchor = _many_binding_scope_anchor(model, plan.selector, consumer_id) - first(anchor) === :consumer && return nothing - any(isnothing, anchor) && return nothing - return (:compiled_many_input_plan, plan.slot, anchor) + anchor.kind === :consumer && return nothing + anchor.kind !== :scene && isnothing(anchor.id) && return nothing + return _ManyBindingPlanKey(plan.slot, anchor) end -function _many_binding_plan_share_key( - model::CompositeModel, - binding::CompiledModelInputBinding, -) - return _many_binding_plan_share_key( - model, - binding.plan, - binding.consumer_id, - ) -end +_many_binding_plan_share_key(model::CompositeModel, binding::CompiledModelInputBinding) = + _many_binding_plan_share_key(model, binding.plan, binding.consumer_id) -function _many_binding_share_key(model::CompositeModel, binding::CompiledModelInputBinding) +function _many_binding_share_key(cache::_ManyInputBindingCache{I,S}, + model::CompositeModel, binding::CompiledModelInputBinding, +) where {I,S} binding.multiplicity == :many || return nothing isnothing(binding.carrier) && return nothing - return ( - binding.selector, - _many_binding_scope_anchor(model, binding), - binding.source_var, - binding.process, - binding.application, - binding.carrier_hint, - typeof(binding.carrier), - ) + return _ManyBindingQueryKey{S,I}(binding.selector, + _many_binding_scope_anchor(model, binding), binding.source_var, + binding.process, binding.application, binding.carrier_hint, typeof(binding.carrier)) end function _binding_with_shared_many_sources( - binding::CompiledModelInputBinding, - canonical::CompiledModelInputBinding, + binding::CompiledModelInputBinding, canonical::CompiledModelInputBinding, ) - return CompiledModelInputBinding( - binding.plan, - binding.consumer_id, - canonical.source_ids, - canonical.source_application_ids, - binding.policy, - binding.carrier_hint, - canonical.carrier, - ) + return CompiledModelInputBinding(binding.plan, binding.consumer_id, + canonical.source_ids, canonical.source_application_ids, binding.policy, + binding.carrier_hint, canonical.carrier) end -function _shared_many_input_binding( - cache, - model::CompositeModel, - plan::CompiledModelInputPlan, - consumer_id::ObjectId, +function _shared_many_input_binding(cache::_ManyInputBindingCache, + model::CompositeModel, plan::CompiledModelInputPlan, consumer_id::ObjectId, ) key = _many_binding_plan_share_key(model, plan, consumer_id) isnothing(key) && return nothing - canonical = get(cache, key, nothing) + canonical = get(cache.by_plan, key, nothing) isnothing(canonical) && return nothing + return Base.@inline _with_model_input_binding(_shared_many_binding_for_plan, + cache.bindings, canonical, plan, consumer_id) +end + +function _shared_many_binding_for_plan(canonical, plan, consumer_id) canonical.plan.slot == plan.slot || return nothing canonical.multiplicity == :many || return nothing isnothing(canonical.carrier) && return nothing - return CompiledModelInputBinding( - plan, - consumer_id, - canonical.source_ids, - canonical.source_application_ids, - canonical.policy, - canonical.carrier_hint, - canonical.carrier, - ) + return CompiledModelInputBinding(plan, consumer_id, canonical.source_ids, + canonical.source_application_ids, canonical.policy, canonical.carrier_hint, + canonical.carrier) end -function _cache_many_binding_plan!(cache, model::CompositeModel, binding) +function _cache_many_binding_plan!(binding, cache::_ManyInputBindingCache, + model::CompositeModel, +) key = _many_binding_plan_share_key(model, binding) - isnothing(key) || (cache[key] = binding) + isnothing(key) || (cache.by_plan[key] = binding) return binding end -function _share_many_input_binding!(cache, model::CompositeModel, binding) - key = _many_binding_share_key(model, binding) +@inline function _share_many_input_binding!(cache::_ManyInputBindingCache, + model::CompositeModel, binding, +) + return Base.@inline _with_model_input_binding(_share_admitted_many_input_binding!, + cache.bindings, binding, cache, model) +end + +function _share_admitted_many_input_binding!(binding, cache, model) + key = _many_binding_share_key(cache, model, binding) isnothing(key) && return binding - canonical = get(cache, key, nothing) + canonical = get(cache.by_query, key, nothing) if isnothing(canonical) - cache[key] = binding - return _cache_many_binding_plan!(cache, model, binding) + cache.by_query[key] = binding + return _cache_many_binding_plan!(binding, cache, model) end + return Base.@inline _with_model_input_binding(_share_many_binding_sources!, + cache.bindings, canonical, binding, cache, model) +end + +function _share_many_binding_sources!(canonical, binding, cache, model) if canonical.source_ids != binding.source_ids || canonical.source_application_ids != binding.source_application_ids - cache[(key, binding.consumer_id)] = binding + # The former (query, consumer) entry had no reader. The real binding + # remains in global input storage and is returned without sharing. return binding end shared = _binding_with_shared_many_sources(binding, canonical) - _cache_many_binding_plan!(cache, model, canonical) + _cache_many_binding_plan!(canonical, cache, model) return shared end -function _share_many_input_bindings!(model::CompositeModel, bindings; cache=Dict{Any,Any}()) +function _share_many_input_bindings!(model::CompositeModel, bindings) + cache = _empty_many_input_binding_cache(keytype(model.registry.objects), bindings) for index in eachindex(bindings) bindings[index] = _share_many_input_binding!(cache, model, bindings[index]) end @@ -3252,17 +3310,22 @@ function _share_many_input_bindings!(model::CompositeModel, bindings; cache=Dict end function _many_input_binding_cache(model::CompositeModel, bindings) - cache = Dict{Any,Any}() + cache = _empty_many_input_binding_cache(keytype(model.registry.objects), bindings) for binding in bindings - key = _many_binding_share_key(model, binding) - if !isnothing(key) - haskey(cache, key) || (cache[key] = binding) - _cache_many_binding_plan!(cache, model, cache[key]) - end + Base.@inline _with_model_input_binding(_seed_many_input_binding_cache!, + bindings, binding, cache, model) end return cache end +function _seed_many_input_binding_cache!(binding, cache, model) + key = _many_binding_share_key(cache, model, binding) + isnothing(key) && return nothing + haskey(cache.by_query, key) || (cache.by_query[key] = binding) + return Base.@inline _with_model_input_binding(_cache_many_binding_plan!, + cache.bindings, cache.by_query[key], cache, model) +end + function _shared_same_rate_many_storage( binding::CompiledModelInputBinding, canonical::CompiledModelInputBinding, @@ -3277,20 +3340,27 @@ function _shared_same_rate_many_storage( binding.carrier === canonical.carrier end -function _dynamic_input_binding_shares_canonical_sources( - model::CompositeModel, - binding::CompiledModelInputBinding, - many_binding_cache, +@inline function _dynamic_input_binding_shares_canonical_sources( + model::CompositeModel, binding, cache::_ManyInputBindingCache, ) + return Base.@inline _with_model_input_binding(_input_binding_shares_many_cache!, + cache.bindings, binding, model, cache) +end + +function _input_binding_shares_many_cache!(binding, model, cache) binding.multiplicity == :many || return false binding.carrier_hint === :ref_vector || return false - key = _many_binding_share_key(model, binding) + key = _many_binding_share_key(cache, model, binding) isnothing(key) && return false - canonical = get(many_binding_cache, key, nothing) - canonical isa CompiledModelInputBinding || return false + canonical = get(cache.by_query, key, nothing) + isnothing(canonical) && return false + return Base.@inline _with_model_input_binding(_input_binding_shares_many_sources, + cache.bindings, canonical, binding) +end + +function _input_binding_shares_many_sources(canonical, binding) _shared_same_rate_many_storage(binding, canonical) || return false - return binding.slot != canonical.slot || - binding.consumer_id != canonical.consumer_id + return binding.slot != canonical.slot || binding.consumer_id != canonical.consumer_id end function _shared_same_rate_many_binding_indices(bindings, binding) @@ -4568,10 +4638,10 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S nothing, distributed_outputs, ) - old_cache_key = _many_binding_share_key(model, binding) + old_cache_key = _many_binding_share_key(many_binding_cache, model, binding) if !isnothing(old_cache_key) && - get(many_binding_cache, old_cache_key, nothing) === binding - delete!(many_binding_cache, old_cache_key) + get(many_binding_cache.by_query, old_cache_key, nothing) === binding + delete!(many_binding_cache.by_query, old_cache_key) end replacement_binding = _share_many_input_binding!( many_binding_cache, diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 133eeb95c..a16e2f145 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -269,6 +269,60 @@ end check_carriers(data, simulation) end +function scope_cache_fixture(selector) + return CompositeModel( + Object(:scene; scale=:Scene), + Object(:plant_a; scale=:Plant, parent=:scene), + Object(:plant_b; scale=:Plant, parent=:scene), + Object(:anchor; scale=:Anchor, parent=:scene, status=Status(x=3f0)), + Object(:a; scale=:Reader, parent=:plant_a), + Object(:b; scale=:Reader, parent=:plant_b), + Object(:first; scale=:Leaf, parent=:plant_a, status=Status(x=7.0)), + Object(:second; scale=:Leaf, parent=:plant_b, status=Status(x=11.0)); + applications=(ModelSpec(Reader(); name=:reader, on=Many(scale=:Reader), + inputs=(single=One(id=:anchor, within=SceneScope(), var=:x, from_status=true), + values=selector)),)) +end + +@testset "Many scope anchors preserve shared columns and consumer-specific ancestors" begin + for (selector, shared, expected_b) in ( + (Many(Scope(ObjectId(:plant_a)); scale=:Leaf, var=:x, from_status=true), + true, (10.0, 15.0, 8.0)), + (Many(Ancestor(scale=:Plant); scale=:Leaf, var=:x, from_status=true), + false, (14.0, 14.0, 14.0)), + ) + model = scope_cache_fixture(selector) + simulation = run!(model; steps=1, outputs=:all) + for phase in 1:3 + if phase == 2 + register_object!(model, Object(:new; scale=:Leaf, parent=:plant_a, + status=Status(x=5.0))) + continue!(simulation; steps=1) + elseif phase == 3 + remove_object!(model, :first) + continue!(simulation; steps=1) + end + first = binding(simulation, :a, :values) + second = binding(simulation, :b, :values) + @test (first.carrier === second.carrier) === shared + @test (first.source_ids === second.source_ids) === shared + @test model_status(model, :a).total == (10.0, 15.0, 8.0)[phase] + @test model_status(model, :b).total == expected_b[phase] + for current in (first, second) + expected_count = current.consumer_id == ObjectId(:a) || shared ? + (1, 2, 1)[phase] : 1 + @test length(current.source_ids) == length(parent(current.carrier)) == expected_count + @test all(reference === PSE.refvalue(model_status(model, id), :x) + for (id, reference) in zip(current.source_ids, parent(current.carrier))) + end + end + @test outputs(simulation)[(:reader, ObjectId(:a), :total)] == + [(1.0, 10.0), (2.0, 15.0), (3.0, 8.0)] + @test outputs(simulation)[(:reader, ObjectId(:b), :total)] == + [(Float64(step), expected_b[step]) for step in 1:3] + end +end + @testset "partial applications retain their exact target selection and metadata owner" begin data = fixture() simulation = prepare(data.model) From 287d54703d1744598ee665db1c2e5fcc7e2c81a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 05:35:45 +0100 Subject: [PATCH 125/324] Admit temporal initials before typed construction and format source diagnostics --- src/composite_model/compilation.jl | 12 ++++--- .../status_view_construction.jl | 34 ++++++++++++++----- test/test-model-temporal-initial-typing.jl | 9 +++-- 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 98b7f54ce..58e5bfa93 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -7615,11 +7615,13 @@ function _temporal_source_application( elseif binding.policy isa PreviousTimeStep return last(sort!(matches; by=application_id -> application_positions[application_id])) end - error( - "Temporal model input `$(binding.input)` from ", - "`$(source_id.value).$(binding.source_var)` has ambiguous source ", - "applications `$(matches)`. Add `application=...` to the `inputs=...` selector.", - ) + io = IOBuffer() + print(io, "Temporal model input `", binding.input, "` from `", + source_id.value, '.', binding.source_var, + "` has ambiguous source applications `") + _print_selector_diagnostic(io, matches, Any[]) + print(io, "`. Add `application=...` to the `inputs=...` selector.") + error(String(take!(io))) end _distributed_temporal_source_application( diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index c5d244243..de2f06ef4 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -256,20 +256,23 @@ end # A homogeneous initial snapshot has the same exact schema as before. Matching # never constructs a type from an Any value in the finite construction path. -function _status_view_initial_matches(::Type{I}, value, many::Bool) where {I} - many || return typeof(value) === I +_status_view_initial_mode(::Type{B}) where {B<:CompiledModelInputBinding} = + Val(fieldtype(fieldtype(B, :plan), :selector) <: Many) + +function _status_view_initial_matches(::Type{I}, value, ::Val{MANY}) where {I,MANY} + MANY || return typeof(value) === I value isa Vector{Any} || return false isempty(value) && return I === Vector{Any} first_type = typeof(first(value)) - homogeneous = all(item -> item isa first_type, value) + homogeneous = all(item -> typeof(item) === first_type, value) I <: Vector || return false return homogeneous ? first_type === eltype(I) : I === Vector{Any} end -function _construct_status_view_initial(::Type{I}, value, many::Bool) where {I} - _status_view_initial_matches(I, value, many) || throw(ArgumentError( +function _construct_status_view_initial(::Type{I}, value, mode::Val{MANY}) where {I,MANY} + _status_view_initial_matches(I, value, mode) || throw(ArgumentError( "The temporal initial snapshot is outside its prepared view schema.")) - many || return value::I + MANY || return value::I values = value::Vector{Any} I === Vector{Any} && return values T = eltype(I) @@ -318,7 +321,17 @@ function _construct_status_view_temporal(::Type{TI}, recipe::_TemporalStatusView S = eltype(R) recipe.binding isa B && recipe.source_applications isa SA || throw(ArgumentError( "The temporal input is outside its prepared view schema.")) - initial = _construct_status_view_initial(I, recipe.initial, recipe.many) + mode = _status_view_initial_mode(B) + value = recipe.initial + initial = if mode isa Val{true} + value isa Vector{Any} || throw(ArgumentError( + "The temporal initial snapshot is outside its prepared view schema.")) + _construct_status_view_initial(I, value::Vector{Any}, mode) + else + value isa I || throw(ArgumentError( + "The temporal initial snapshot is outside its prepared view schema.")) + _construct_status_view_initial(I, value::I, mode) + end storage = _construct_status_view_storage(S, recipe) reference = _construct_status_view_reference(R, storage) return TI(recipe.binding::B, recipe.source_applications::SA, initial, reference) @@ -369,10 +382,15 @@ end B, SA = fieldtype(TI, :binding), fieldtype(TI, :source_applications) I, R = fieldtype(TI, :initial), fieldtype(TI, :reference) input = fieldtype(fieldtype(B, :plan), :route).parameters[1] + mode = _status_view_initial_mode(B) + Value = mode isa Val{true} ? Vector{Any} : I + initial_matches = :(parts.temporal[$index].initial isa $Value && + _status_view_initial_matches($I, parts.temporal[$index].initial::$Value, + $(QuoteNode(mode)))) append!(checks, [:(parts.temporal[$index].input === $(QuoteNode(input))), :(parts.temporal[$index].binding isa $B), :(parts.temporal[$index].source_applications isa $SA), - :(_status_view_initial_matches($I, parts.temporal[$index].initial, parts.temporal[$index].many)), + initial_matches, :(_status_view_storage_matches($(eltype(R)), parts.temporal[$index]))]) end for (index, name) in enumerate(fieldnames(P)) diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 83a7e3106..03f63b111 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -79,17 +79,22 @@ end end @testset "heterogeneous snapshots never convert values into the first schema" begin mixed = Any[Float32(1.25), Float64(2.5)] - result = PSE._construct_status_view_initial(Vector{Any}, mixed, true) + result = PSE._construct_status_view_initial(Vector{Any}, mixed, Val(true)) @test result === mixed @test typeof.(result) == [Float32, Float64] private = Any[Float32[1, 2], Float32[3, 4]] - typed = PSE._construct_status_view_initial(Vector{Vector{Float32}}, private, true) + typed = PSE._construct_status_view_initial(Vector{Vector{Float32}}, private, Val(true)) @test typed isa Vector{Vector{Float32}} @test typed[1] === private[1] @test typed[2] === private[2] # This helper narrows an already private snapshot, never copies its payload. typed[1][1] = 9 @test private[1][1] === 9f0 + # A singular temporal input may itself contain a vector; its snapshot is + # returned directly rather than interpreted as a Many staging container. + single = Float32[1, 2] + @test PSE._construct_status_view_initial(Vector{Float32}, single, Val(false)) === single + @test !PSE._status_view_initial_matches(Vector{Any}, Any[1f0, 2f0], Val(true)) end function rebuild_input(ids, initial) From 0dea67001f6d2520c437ad2a7ad4ca0f556d7020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 06:09:41 +0100 Subject: [PATCH 126/324] Keep source matching and query hashing inside concrete metadata boundaries --- src/composite_model/compilation.jl | 73 ++++++++++++++++++++---------- test/test-input-source-matching.jl | 3 ++ 2 files changed, 51 insertions(+), 25 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 58e5bfa93..25ec66403 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3130,13 +3130,20 @@ struct _ManyBindingQueryKey{S,I<:ObjectId} carrier_hint::Symbol carrier_type::DataType end -_many_binding_query_components(key::_ManyBindingQueryKey) = - (key.selector, key.anchor, key.source_var, key.process, key.application, - key.carrier_hint, key.carrier_type) Base.isequal(left::_ManyBindingQueryKey, right::_ManyBindingQueryKey) = - isequal(_many_binding_query_components(left), _many_binding_query_components(right)) -Base.hash(key::_ManyBindingQueryKey, seed::UInt) = - hash(_many_binding_query_components(key), seed) + isequal(left.selector, right.selector) && isequal(left.anchor, right.anchor) && + left.source_var === right.source_var && isequal(left.process, right.process) && + isequal(left.application, right.application) && left.carrier_hint === right.carrier_hint && + left.carrier_type === right.carrier_type +function Base.hash(key::_ManyBindingQueryKey, seed::UInt) + seed = hash(key.selector, seed) + seed = hash(key.anchor, seed) + seed = hash(key.source_var, seed) + seed = hash(key.process, seed) + seed = hash(key.application, seed) + seed = hash(key.carrier_hint, seed) + return hash(key.carrier_type, seed) +end struct _ManyBindingPlanKey{I<:ObjectId} slot::Int @@ -7721,19 +7728,18 @@ function _matching_input_source_applications( application_filter, distributed_outputs=NoCompiledDistributedOutputs(), potential_source_application_ids=(); - applications_by_id=nothing, + applications_by_id::CompiledMetadataTable, allow_empty::Bool=false, ) potential_application_id = length(potential_source_application_ids) == 1 ? only(potential_source_application_ids) : nothing use_planned_singleton = !isnothing(potential_application_id) && - !isnothing(applications_by_id) && haskey(applications_by_id, potential_application_id) matches = if use_planned_singleton application_id = potential_application_id matched = _with_metadata_entry(applications_by_id, application_id) do application - any(source_ids) do source_id + for source_id in source_ids _application_writes_object_variable( distributed_outputs, application, @@ -7742,21 +7748,34 @@ function _matching_input_source_applications( ) && return true # Targeted newborn initializers use a partial application # overlay until the lifecycle barrier extends the application. - return any(get(applications_by_object, source_id, ())) do candidate - candidate.id == application_id || return false - return source_var in _model_output_names(candidate) + for raw_candidate in get(applications_by_object, source_id, ()) + candidate_matches = Base.@inline _with_model_application( + applications_by_id, raw_candidate::CompiledModelApplication, + application_id, source_var, + ) do candidate, id, variable + candidate.id == id || return false + return variable in _model_output_names(candidate) + end + candidate_matches && return true end end + return false end matched ? Symbol[application_id] : Symbol[] else resolved = Symbol[] for source_id in source_ids - for application in get(applications_by_object, source_id, ()) - source_var in _model_output_names(application) || continue - isnothing(process_filter) || application.process == process_filter || continue - isnothing(application_filter) || application.id == application_filter || continue - application.id in resolved || push!(resolved, application.id) + for raw_application in get(applications_by_object, source_id, ()) + Base.@inline _with_model_application( + applications_by_id, raw_application::CompiledModelApplication, + resolved, source_var, process_filter, application_filter, + ) do application, matches, variable, process, application_name + variable in _model_output_names(application) || return nothing + isnothing(process) || application.process == process || return nothing + isnothing(application_name) || application.id == application_name || return nothing + application.id in matches || push!(matches, application.id) + return nothing + end end _append_distributed_input_source_applications!( resolved, @@ -8912,21 +8931,25 @@ function _validate_model_input_source!( consumer_id::ObjectId, input_sym::Symbol, source_var::Symbol, - source_ids::AbstractVector{<:ObjectId}, + source_ids::AbstractVector{I}, carrier, carrier_hint::Symbol, -) +) where {I<:ObjectId} !isnothing(carrier) && return nothing - status_source_ids = ObjectId[ + status_source_ids = I[ source_id for source_id in source_ids if _model_object(model, source_id).status isa Status ] isempty(status_source_ids) && return nothing - error( - "Input binding `$(input_sym)` on application `$(application_id)` for object ", - "`$(consumer_id.value)` reads `$(source_var)` from objects ", - "`$([id.value for id in status_source_ids])`, but no source `Status` reference is available." - ) + io = IOBuffer() + print(io, "Input binding `", input_sym, "` on application `", application_id, + "` for object `", consumer_id.value, "` reads `", source_var, "` from objects `[") + for (index, source_id) in pairs(status_source_ids) + index == 1 || print(io, ", ") + _print_selector_diagnostic(io, source_id.value, Any[]) + end + print(io, "]`, but no source `Status` reference is available.") + error(String(take!(io))) end function _validate_declared_model_input_name!(application, input_sym::Symbol) diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl index 077035beb..810ab7b02 100644 --- a/test/test-input-source-matching.jl +++ b/test/test-input-source-matching.jl @@ -53,6 +53,9 @@ end alternative = compiled.applications_by_id[:f] @test matched(compiled, distributed, (1, 2); process=alternative.process) == [:f] @test matched(compiled, distributed, (1, 2); potential=(:c,)) == [:c] + # The planned producer is absent from the first object's local/remote + # ownership and present only on the second object. + @test matched(compiled, distributed, (1, 2); potential=(:f,)) == [:f] @test isempty(matched(compiled, distributed, (1, 2); application=:missing, potential=(:missing,), allow_empty=true)) @test_throws ErrorException matched(compiled, distributed, (1, 2); From d4e25373e5f2d7c44d1bd865e1a9166cc5859bbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 06:26:44 +0100 Subject: [PATCH 127/324] Keep writer policies and selector identities inside their prepared families --- src/composite_model/compilation.jl | 41 ++++++++++++++++++++---------- src/composite_model/selectors.jl | 7 +++-- test/test-input-source-matching.jl | 6 +++++ test/test-model-input-recipes.jl | 5 ++++ 4 files changed, 43 insertions(+), 16 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 25ec66403..0465612c0 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6059,13 +6059,16 @@ end _selector_has_policy(selector::AbstractObjectMultiplicity) = haskey(criteria(selector), :policy) +_model_policy_from_admitted_application(application, source_var::Symbol) = + _policy_for_output(_application_default_model(application), source_var) + function _model_policy_from_source_application(applications_by_id, application_id::Symbol, source_var::Symbol) - application = get(applications_by_id, application_id, nothing) - isnothing(application) && error( + haskey(applications_by_id, application_id) || error( "No compiled model application with id `$(application_id)` while resolving ", "default output policy for `$(source_var)`." ) - return _policy_for_output(_application_default_model(application), source_var) + return Base.@inline _with_metadata_entry(_model_policy_from_admitted_application, + applications_by_id, application_id, source_var) end function _model_selector_policy(selector::AbstractObjectMultiplicity, applications_by_id, source_application_ids, source_var::Symbol) @@ -8884,12 +8887,17 @@ function _matches_input_source_writer( ) # This index also contains manual/stream-only writers and the targeted # initializer overlay, whose newborns are not in compiled target_ids yet. - local_writer = any(get(applications_by_object, source_id, ())) do application - isnothing(process_filter) || application.process == process_filter || return false - isnothing(application_filter) || application.id == application_filter || return false - return source_var in _model_output_names(application) + for raw_application in get(applications_by_object, source_id, ()) + local_writer = Base.@inline _with_model_application( + applications_by_id, raw_application::CompiledModelApplication, + source_var, process_filter, application_filter, + ) do application, variable, process, application_name + isnothing(process) || application.process == process || return false + isnothing(application_name) || application.id == application_name || return false + return variable in _model_output_names(application) + end + local_writer && return true end - local_writer && return true return _has_matching_distributed_input_writer( distributed_outputs, source_id, @@ -8914,13 +8922,18 @@ function _has_matching_distributed_input_writer( applications_by_id, ) owners = get(distributed_outputs.writer_ownership, (source_id, source_var), ()) - return any(owners) do owner - application = get(applications_by_id, owner.application_id, nothing) - isnothing(application) && return false - isnothing(process_filter) || application.process == process_filter || return false - isnothing(application_filter) || application.id == application_filter || return false - return true + for owner in owners + haskey(applications_by_id, owner.application_id) || continue + matched = Base.@inline _with_metadata_entry( + applications_by_id, owner.application_id, process_filter, application_filter, + ) do application, process, application_name + isnothing(process) || application.process == process || return false + isnothing(application_name) || application.id == application_name || return false + return true + end + matched && return true end + return false end _model_input_names(application) = _application_ports(application).input_names diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 28b2ae025..acc4d926f 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1491,8 +1491,11 @@ function _matching_selector_ids( # The adaptive candidate source may be a local vector, an index iterator, # or registry keys. Specialize this loop at that boundary, rather than # dispatching dynamically for every object in a heterogeneous query. - ids = Vector{keytype(model.registry.objects)}() - for id in candidates + I = keytype(model.registry.objects) + ids = Vector{I}() + for candidate in candidates + candidate isa I || continue + id = candidate::I haskey(model.registry.objects, id) || continue _selector_matches_object_id( model, matcher, id; context, default_to_context, default_scope, relation_resolved, diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl index 810ab7b02..572949b94 100644 --- a/test/test-input-source-matching.jl +++ b/test/test-input-source-matching.jl @@ -52,6 +52,10 @@ end @test matched(compiled, distributed, (1, 2); application=:c) == [:c] alternative = compiled.applications_by_id[:f] @test matched(compiled, distributed, (1, 2); process=alternative.process) == [:f] + @test PSE._matches_input_source_writer(ObjectId(2), :x, alternative.process, + nothing, compiled.applications_by_id, distributed, compiled.applications_by_object) + @test !PSE._matches_input_source_writer(ObjectId(1), :x, nothing, :missing, + compiled.applications_by_id, distributed, compiled.applications_by_object) @test matched(compiled, distributed, (1, 2); potential=(:c,)) == [:c] # The planned producer is absent from the first object's local/remote # ownership and present only on the second object. @@ -97,6 +101,8 @@ end @test PSE._matching_input_source_applications(overlay, ObjectId[ObjectId(7)], :x, nothing, nothing, PSE.NoCompiledDistributedOutputs(), (:a,); applications_by_id=compiled.applications_by_id) == [:a] + @test PSE._matches_input_source_writer(ObjectId(7), :x, nothing, :a, + compiled.applications_by_id, PSE.NoCompiledDistributedOutputs(), overlay) @test newborn.status.x === 7f0 @test PSE.refvalue(newborn.status, :x) === reference @test current_step(simulation) == 0 diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 4198c1ace..fffa9d30c 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -86,6 +86,11 @@ end compiled = simulation.compiled scenario = compiled.scenario_plan application, recipe = reader_recipe(compiled) + selector = One(id=1, within=SceneScope(), application=:source, var=:x) + @test (@inferred PSE._model_selector_policy(selector, + compiled.applications_by_id, [:source], :x)) isa HoldLast + @test_throws "No compiled model application with id `missing`" PSE._model_policy_from_source_application( + compiled.applications_by_id, :missing, :x) @test keys(scenario.input_recipes_by_application) == keys(scenario.input_plans_by_application) @test keys(scenario.input_recipes_by_application) == (:empty_a, :source, :empty_b, :reader, :other_source) From feb2681b54480de1aeedb428b12c155f33bcc647 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 06:35:49 +0100 Subject: [PATCH 128/324] Render source and policy diagnostics through the structural printer --- src/composite_model/compilation.jl | 8 ++++---- src/composite_model/selectors.jl | 6 ++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 0465612c0..07372ad1a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6094,7 +6094,7 @@ function _model_selector_policy(selector::AbstractObjectMultiplicity, applicatio all(policy -> policy == first_policy, policies) && return first_policy error( "Cannot infer default policy for model input from `$(source_var)` because ", - "selector resolves several source applications `$(source_application_ids)` with ", + "selector resolves several source applications `", _selector_diagnostic_text(source_application_ids), "` with ", "different output policies. Add `policy=...` to the `inputs=...` selector." ) end @@ -8694,8 +8694,8 @@ function _resolve_input_sources( end if !(selector isa Many) && length(source_application_ids) > 1 error( - "Input `$(input_sym)` on application `$(plan.application_id)` matched several " * - "source applications `$(source_application_ids)`. Add one of those canonical " * + "Input `$(input_sym)` on application `$(plan.application_id)` matched several ", + "source applications `", _selector_diagnostic_text(source_application_ids), "`. Add one of those canonical ", "identifiers as `application=...` to the `inputs=...` selector.", ) end @@ -8971,7 +8971,7 @@ function _validate_declared_model_input_name!(application, input_sym::Symbol) error( "Input binding `$(input_sym)` on application `$(application.id)` is not declared by ", "`inputs_` for process `$(application.process)`. Declared model inputs are ", - "`$(sort!(collect(input_names)))`." + "`", _selector_diagnostic_text(sort!(collect(input_names))), "`." ) end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index acc4d926f..78e5d0d29 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1138,6 +1138,12 @@ function _print_selector_diagnostic(io, value::T, ancestors) where {T} return nothing end +function _selector_diagnostic_text(value) + io = IOBuffer() + _print_selector_diagnostic(io, value, Any[]) + return String(take!(io)) +end + function _print_selector_diagnostic_value(io, value::AbstractString, ancestors) print(io, '"') escape_string(io, value, ('"',)) From aa1ddfd532f657320805ebf7045a23af47be7b5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 06:55:20 +0100 Subject: [PATCH 129/324] Preserve source identity families and admit final canonical producers --- src/composite_model/compilation.jl | 54 ++++++++++++++++++------------ src/composite_model/selectors.jl | 26 +++----------- test/test-input-source-matching.jl | 10 +++++- 3 files changed, 46 insertions(+), 44 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 07372ad1a..d65626959 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3443,8 +3443,10 @@ function _append_added_many_sources!( matcher = binding.matcher matching_matcher = matcher query_prepared = false - new_source_ids = ObjectId[] - for object_id in added_ids + source_ids = _input_binding_source_ids(model.registry.objects, binding.source_ids) + new_source_ids = empty(source_ids) + for raw_id in added_ids + object_id = _index_object_id(model.registry.objects, raw_id) if matcher.defaults_to_context object_id == binding.consumer_id || continue else @@ -3459,7 +3461,7 @@ function _append_added_many_sources!( _selector_matches_object_topology(model, matching_matcher, object_id; context=binding.consumer_id, default_scope) || continue end - first(_sorted_object_id_position(binding.source_ids, object_id)) || + first(_sorted_object_id_position(source_ids, object_id)) || push!(new_source_ids, object_id) end isempty(new_source_ids) && return true @@ -4362,10 +4364,10 @@ function _refresh_scene_call_bindings!( _selector_matches_any_object_id( model, binding.matcher, - added_ids; - context=binding.consumer_id, - default_to_context=true, - default_scope=_default_dependency_scope(model, binding.consumer_id), + added_ids, + binding.consumer_id, + true, + _default_dependency_scope(model, binding.consumer_id), ) || continue key = (binding.application_id, _index_object_id(model.registry.objects, binding.consumer_id)) @@ -4585,10 +4587,10 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S _selector_matches_any_object_id( model, binding.matcher, - added_ids; - context=consumer_id, - default_to_context=true, - default_scope=default_scope, + added_ids, + consumer_id, + true, + default_scope, ) || return false end appended_sources = if force_rebuild @@ -8539,16 +8541,23 @@ function _final_canonical_source_application( source_ids, source_application_ids, source_var::Symbol, - ::NoCompiledDistributedOutputs=NoCompiledDistributedOutputs(), + ::NoCompiledDistributedOutputs=NoCompiledDistributedOutputs(); + applications_by_id::CompiledMetadataTable, ) length(source_ids) == 1 || return source_application_ids matching_ids = Set(source_application_ids) - canonical_ids = Symbol[ - application.id - for application in get(applications_by_object, only(source_ids), Any[]) - if application.id in matching_ids && - _publish_mode_for_output(application.spec, source_var) == :canonical - ] + canonical_ids = Symbol[] + for raw_application in get(applications_by_object, only(source_ids), ()) + Base.@inline _with_model_application( + applications_by_id, raw_application::CompiledModelApplication, + canonical_ids, matching_ids, source_var, + ) do application, resolved, matching, variable + application.id in matching || return nothing + _publish_mode_for_output(application.spec, variable) == :canonical || return nothing + push!(resolved, application.id) + return nothing + end + end isempty(canonical_ids) && return source_application_ids return Symbol[last(canonical_ids)] end @@ -8558,7 +8567,8 @@ function _final_canonical_source_application( source_ids, source_application_ids, source_var::Symbol, - distributed_outputs::CompiledDistributedOutputs, + distributed_outputs::CompiledDistributedOutputs; + applications_by_id::CompiledMetadataTable, ) length(source_ids) == 1 || return source_application_ids matching_ids = Set(source_application_ids) @@ -8576,7 +8586,8 @@ function _final_canonical_source_application( source_ids, source_application_ids, source_var, - NoCompiledDistributedOutputs(), + NoCompiledDistributedOutputs(); + applications_by_id, ) return Symbol[last(canonical_ids)] end @@ -8680,7 +8691,8 @@ function _resolve_input_sources( source_ids, source_application_ids, source_var, - distributed_outputs, + distributed_outputs; + applications_by_id, ) end if selector isa Many && length(source_application_ids) > 1 diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 78e5d0d29..8e70e7f45 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1427,10 +1427,10 @@ end function _selector_matches_any_object_id( model::CompositeModel, matcher::CompiledSelectorMatcher, - object_ids; - context=nothing, - default_to_context::Bool=false, - default_scope=nothing, + object_ids, + context, + default_to_context::Bool, + default_scope, ) for object_id in object_ids _selector_matches_object_id( @@ -1445,24 +1445,6 @@ function _selector_matches_any_object_id( return false end -function _selector_matches_any_object_id( - model::CompositeModel, - selector::AbstractObjectMultiplicity, - object_ids; - context=nothing, - default_to_context::Bool=false, - default_scope=nothing, -) - return _selector_matches_any_object_id( - model, - _compile_selector_matcher(model, selector), - object_ids; - context=context, - default_to_context=default_to_context, - default_scope=default_scope, - ) -end - function resolve_object_ids(model::CompositeModel, selector::AbstractObjectMultiplicity; context=nothing) _validate_selector_context(selector, :object_query) return _resolve_object_ids(model, selector; context=context) diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl index 572949b94..a1794513b 100644 --- a/test/test-input-source-matching.jl +++ b/test/test-input-source-matching.jl @@ -89,7 +89,7 @@ end end @testset "planned singleton matching retains a real newborn partial overlay" begin - simulation, _ = matching_fixture() + simulation, distributed = matching_fixture() compiled = simulation.compiled newborn = register_object!(simulation.model, Object(7; status=Status(x=7f0))) reference = PSE.refvalue(newborn.status, :x) @@ -103,6 +103,14 @@ end applications_by_id=compiled.applications_by_id) == [:a] @test PSE._matches_input_source_writer(ObjectId(7), :x, nothing, :a, compiled.applications_by_id, PSE.NoCompiledDistributedOutputs(), overlay) + @test PSE._final_canonical_source_application(overlay, ObjectId[ObjectId(7)], + [:f, :a], :x; applications_by_id=compiled.applications_by_id) == [:a] + @test PSE._final_canonical_source_application(overlay, ObjectId[ObjectId(7)], + [:f, :a], :x, distributed; applications_by_id=compiled.applications_by_id) == [:a] + unmatched = [:f, :b] + @test PSE._final_canonical_source_application(overlay, ObjectId[ObjectId(7)], + unmatched, :x; applications_by_id=compiled.applications_by_id) === unmatched + @test unmatched == [:f, :b] @test newborn.status.x === 7f0 @test PSE.refvalue(newborn.status, :x) === reference @test current_step(simulation) == 0 From 92598e4e34edcd82a1da96d89d3b898ad412e902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 07:16:27 +0100 Subject: [PATCH 130/324] Keep lifecycle references and default staging inside prepared schemas --- src/composite_model/compilation.jl | 106 ++++++++++++++--------- src/composite_model/runtime_outputs.jl | 22 ++--- src/composite_model/selectors.jl | 45 +++------- test/test-model-api-stabilization.jl | 21 +++-- test/test-model-input-binding-storage.jl | 19 ++++ 5 files changed, 127 insertions(+), 86 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index d65626959..04ade9cac 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2852,7 +2852,8 @@ function _application_target_template( matched_slots = Int[] for slot in sorted_candidates matches = Base.@inline _with_metadata_entry(compiled.applications_by_id, slot) do application - _selector_matches_object_id(model, application.target_matcher, object_id) + _selector_matches_object_id(model, application.target_matcher, object_id, + nothing, false, nothing, false) end matches && push!(matched_slots, slot) end @@ -3393,6 +3394,19 @@ function _can_append_stable_many_sources(binding::CompiledModelInputBinding) ) end +# Resolve one real registered reference within its Status family, and retain +# only the actual carrier's admitted Ref family. Absence/incompatibility asks +# the caller to use its existing fallback before any shared storage changes. +@inline function _registered_source_reference(catalog, status, ::Val{VARIABLE}, + ::Type{R}, +) where {VARIABLE,R} + status isa Status || return nothing + return Base.@inline _with_registered_status(catalog, status) do admitted + reference = _status_ref_or_nothing(admitted, Val{VARIABLE}()) + return reference isa R ? reference::R : nothing + end +end + function _append_stable_many_source_references!( model::CompositeModel, binding::CompiledModelInputBinding, @@ -3404,11 +3418,11 @@ function _append_stable_many_source_references!( added_references = eltype(existing_references)[] sizehint!(added_references, length(new_source_ids)) for object_id in new_source_ids - reference = _status_ref_or_nothing( - _model_object(model, object_id).status, - binding.source_var, + reference = _registered_source_reference( + model.registry.objects.catalog, _model_object(model, object_id).status, + _input_route_source(binding.plan.route), eltype(existing_references), ) - reference isa eltype(existing_references) || return false + isnothing(reference) && return false push!(added_references, reference) end @@ -3458,8 +3472,8 @@ function _append_added_many_sources!( binding.consumer_id, default_scope) query_prepared = true end - _selector_matches_object_topology(model, matching_matcher, object_id; - context=binding.consumer_id, default_scope) || continue + _selector_matches_object_topology(model, matching_matcher, object_id, + binding.consumer_id, default_scope, false) || continue end first(_sorted_object_id_position(source_ids, object_id)) || push!(new_source_ids, object_id) @@ -3568,18 +3582,22 @@ function _update_structural_many_sources!( isnothing(binding.application) && return :fallback carrier_references = parent(binding.carrier) default_scope = _default_dependency_scope(model, binding.consumer_id) - changes = Tuple{ObjectId,Bool,Any}[] - for object_id in dirty_ids + I = keytype(model.registry.objects) + R = eltype(carrier_references) + changes = Tuple{I,Bool,Union{Nothing,R}}[] + for raw_id in dirty_ids + object_id = _index_object_id(model.registry.objects, raw_id) was_source, _ = _sorted_object_id_position(binding.source_ids, object_id) is_source = haskey(model.registry.objects, object_id) && _selector_matches_object_id( model, binding.matcher, - object_id; - context=binding.consumer_id, - default_to_context=true, - default_scope=default_scope, + object_id, + binding.consumer_id, + true, + default_scope, + false, ) && _matches_input_source_writer( object_id, binding.source_var, @@ -3593,11 +3611,11 @@ function _update_structural_many_sources!( source_reference = nothing if is_source source = _model_object(model, object_id) - source_reference = - _status_ref_or_nothing(source.status, binding.source_var) + source_reference = _registered_source_reference( + model.registry.objects.catalog, source.status, + _input_route_source(binding.plan.route), R, + ) isnothing(source_reference) && return :fallback - source_reference isa eltype(carrier_references) || - return :fallback end push!(changes, (object_id, is_source, source_reference)) end @@ -3616,7 +3634,7 @@ function _update_structural_many_sources!( _insert_with_spare_capacity!( carrier_references, position, - source_reference, + source_reference::R, ) end end @@ -4017,10 +4035,11 @@ function _append_added_many_call_targets!( if _selector_matches_object_id( model, binding.matcher, - object_id; - context=binding.consumer_id, - default_to_context=true, - default_scope=default_scope, + object_id, + binding.consumer_id, + true, + default_scope, + false, ) && !first( _sorted_object_id_position( binding.callee_object_ids, @@ -4563,7 +4582,7 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S end previous_source_ids = binding.carrier_hint == :temporal_stream ? copy(source_ids) : - ObjectId[] + empty(source_ids) binding.multiplicity == :many && binding.carrier_hint == :temporal_stream && (previous_shared_many_sources[binding.source_ids] = copy(source_ids)) @@ -4836,7 +4855,7 @@ function _extend_compiled_scene( affected_temporal_keys = Set{Tuple{Symbol,ObjectId}}() previous_temporal_sources = copy(previous_temporal_sources_seed) processed_many_sources = IdDict{Any,Nothing}() - previous_shared_many_sources = IdDict{Any,Vector{ObjectId}}() + previous_shared_many_sources = IdDict{Any,Vector{I}}() rebuild_dynamic_input_index = !pure_addition candidate_binding_indices = Set{Int}() writer_rebind_keys = nothing @@ -6664,26 +6683,31 @@ function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId return Base.@inline _with_registered_status(identity, model.registry.objects.catalog, status) end -_stage_model_output_defaults!(::Tuple{}, ::Tuple{}, preparation, context) = nothing +_stage_model_output_defaults!(preparation, ::Tuple{}, ::Tuple{}, context) = nothing function _stage_model_output_defaults!( + preparation, variables::Tuple{Symbol,Vararg{Symbol}}, defaults::Tuple{V,Vararg}, - preparation, context, ) where {V} variable = first(variables) value = first(defaults) if _publish_mode_for_output(context.application.spec, variable) == :canonical - if !(preparation isa Status && variable in propertynames(preparation)) - if preparation isa Status - preparation = _status_recipe_for_object!( + if preparation isa Status + if !(variable in propertynames(preparation)) + recipe = _status_recipe_for_object!( context.recipes, context.recipe_order, context.model, context.object_id, ) + return Base.@inline _with_canonical_status_recipe( + _stage_model_output_defaults!, context.recipes, recipe, + variables, defaults, context, + ) end + else Base.@inline _status_recipe_add_default!( context.model, preparation, @@ -6697,7 +6721,7 @@ function _stage_model_output_defaults!( end end return _stage_model_output_defaults!( - Base.tail(variables), Base.tail(defaults), preparation, context, + preparation, Base.tail(variables), Base.tail(defaults), context, ) end @@ -6726,8 +6750,10 @@ function _prepare_model_output_statuses!( ) context = (; model, application, object_id, recipes, recipe_order, conversion_records) - _stage_model_output_defaults!( - keys(defaults), values(defaults), preparation, context, + Base.@inline _with_canonical_status_preparation( + _stage_model_output_defaults!, recipes, + model.registry.objects.catalog, preparation, + keys(defaults), values(defaults), context, ) end end @@ -7102,10 +7128,11 @@ function _incremental_distributed_output_addition!( if _selector_matches_object_id( model, binding.matcher, - object_id; - context=binding.execution_object_id, - default_to_context=true, - default_scope=default_scope, + object_id, + binding.execution_object_id, + true, + default_scope, + false, ) && !first( _sorted_object_id_position( binding.destination_ids, @@ -7336,10 +7363,11 @@ function _force_distributed_producer_rebinds!(forced, model, bindings, by_variab _selector_matches_object_id( model, binding.matcher, - destination; - context=binding.consumer_id, - default_to_context=true, + destination, + binding.consumer_id, + true, default_scope, + false, ) || continue push!(forced, (binding.application_id, binding.consumer_id, binding.input)) break diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 84015f2b2..7fa17f00b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5974,10 +5974,11 @@ function _targeted_new_object_call_targets( if !_selector_matches_object_id( model, binding.matcher, - object_id; - context=context.object_id, - default_to_context=true, - default_scope=default_scope, + object_id, + context.object_id, + true, + default_scope, + false, ) ] isempty(unresolved_ids) || error( @@ -6321,10 +6322,11 @@ function _current_topology_call_targets( if !_selector_matches_object_id( model, resolved_binding.matcher, - object_id; - context=context.object_id, - default_to_context=true, - default_scope=default_scope, + object_id, + context.object_id, + true, + default_scope, + false, ) push!(unresolved_ids, object_id) continue @@ -7973,8 +7975,8 @@ function _refresh_output_request_for_application!(application, record, simulatio :output_request_incremental_object_checks, length(added_object_ids)) for raw_id in added_object_ids object_id = _index_object_id(objects, raw_id) - _selector_matches_object_id(simulation.model, record.matcher, object_id; - context=request.context) && push!(matched_ids, object_id) + _selector_matches_object_id(simulation.model, record.matcher, object_id, + request.context, false, nothing, false) && push!(matched_ids, object_id) end end owned_ids = Set{I}() diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 8e70e7f45..d0942fcb3 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1354,17 +1354,17 @@ _compiled_relation_symbol(::Val{RELATION}) where {RELATION} = RELATION function _selector_matches_object_id( model::CompositeModel, matcher::CompiledSelectorMatcher, - object_id::ObjectId; - context=nothing, - default_to_context::Bool=false, - default_scope=nothing, - relation_resolved::Bool=false, + object_id::ObjectId, + context, + default_to_context::Bool, + default_scope, + relation_resolved::Bool, ) if default_to_context && matcher.defaults_to_context && !isnothing(context) return object_id == _object_id_from_context(context) end _selector_matches_object_labels(model, matcher, object_id) || return false - return _selector_matches_object_topology(model, matcher, object_id; + return _selector_matches_object_topology(model, matcher, object_id, context, default_scope, relation_resolved) end @@ -1375,8 +1375,8 @@ end end function _selector_matches_object_topology(model::CompositeModel, - matcher::CompiledSelectorMatcher, object_id::ObjectId; - context=nothing, default_scope=nothing, relation_resolved::Bool=false) + matcher::CompiledSelectorMatcher, object_id::ObjectId, + context, default_scope, relation_resolved::Bool) scope = isnothing(matcher.scope) ? default_scope : matcher.scope if isnothing(matcher.relation) if scope isa Ancestor && @@ -1406,24 +1406,6 @@ function _selector_matches_object_topology(model::CompositeModel, _scope_contains_object(model, matcher.scope, context, object_id) end -function _selector_matches_object_id( - model::CompositeModel, - selector::AbstractObjectMultiplicity, - object_id::ObjectId; - context=nothing, - default_to_context::Bool=false, - default_scope=nothing, -) - return _selector_matches_object_id( - model, - _compile_selector_matcher(model, selector), - object_id; - context=context, - default_to_context=default_to_context, - default_scope=default_scope, - ) -end - function _selector_matches_any_object_id( model::CompositeModel, matcher::CompiledSelectorMatcher, @@ -1436,10 +1418,11 @@ function _selector_matches_any_object_id( _selector_matches_object_id( model, matcher, - object_id; - context=context, - default_to_context=default_to_context, - default_scope=default_scope, + object_id, + context, + default_to_context, + default_scope, + false, ) && return true end return false @@ -1486,7 +1469,7 @@ function _matching_selector_ids( id = candidate::I haskey(model.registry.objects, id) || continue _selector_matches_object_id( - model, matcher, id; context, default_to_context, default_scope, relation_resolved, + model, matcher, id, context, default_to_context, default_scope, relation_resolved, ) && push!(ids, id) end return _sort_object_ids!(unique!(ids)) diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index bfc775b51..64851b032 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -1084,8 +1084,11 @@ function stabilization_compiled_selector_allocations( return @allocated PlantSimEngine._selector_matches_object_id( model, matcher, - object_id; - context=context, + object_id, + context, + false, + nothing, + false, ) end @@ -1121,8 +1124,11 @@ end if PlantSimEngine._selector_matches_object_id( model, matcher, - object_id; - context=context, + object_id, + context, + false, + nothing, + false, ) ] PlantSimEngine._sort_object_ids!(matched) @@ -1157,8 +1163,11 @@ end @test_throws "No matching ancestor" PlantSimEngine._selector_matches_object_id( model, ancestor_matcher, - ObjectId(:scene); - context=ObjectId(:scene), + ObjectId(:scene), + ObjectId(:scene), + false, + nothing, + false, ) end diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index a16e2f145..64a2a0e24 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -151,6 +151,25 @@ end identity, incomplete, control.future) end +@testset "direct Many extension stages every admitted reference before committing" begin + data = fixture() + simulation = prepare(data.model) + current = binding(simulation, :a, :values) + references, source_ids = parent(current.carrier), current.source_ids + first = Status(x=7.0) + second = Status(x=9f0) + register_object!(data.model, Object(:first; scale=:Leaf, parent=:scene, status=first)) + register_object!(data.model, Object(:second; scale=:Leaf, parent=:scene, status=second)) + @test !PSE._append_stable_many_source_references!(data.model, current, + ObjectId[ObjectId(:first), ObjectId(:second)], nothing) + @test parent(current.carrier) === references + @test current.source_ids === source_ids + @test isempty(references) && isempty(source_ids) + @test PSE.refvalue(first, :x)[] === 7.0 + @test PSE.refvalue(second, :x)[] === 9f0 + @test check_carriers(data, simulation).carrier === current.carrier +end + @testset "explicit storage is admitted even after a clean zero-step preparation" begin control = ordinary_control() data = fixture() From b63b2b2d29298c56cfb7de250f9ccdeb8ae0311a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 07:44:22 +0100 Subject: [PATCH 131/324] Admit lifecycle identities and simplify passive geometry snapshots --- src/composite_model/registry_topology.jl | 89 +++++++++++---------- test/test-lifecycle-snapshot-allocations.jl | 42 ++++++++-- test/test-model-binding-index-identities.jl | 35 ++++++++ 3 files changed, 115 insertions(+), 51 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 1fad4bb28..9807831a2 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -342,7 +342,7 @@ end end """Labels and topology captured for one object at a lifecycle event.""" -struct LifecycleObjectSnapshot{G} +struct LifecycleObjectSnapshot id::ObjectId scale::Union{Nothing,Symbol} kind::Union{Nothing,Symbol} @@ -351,7 +351,7 @@ struct LifecycleObjectSnapshot{G} parent::Union{Nothing,ObjectId} children::Tuple ancestors::Tuple - geometry::G + geometry::Any end """One subtree reparenting recorded before runtime buffers refresh.""" @@ -903,6 +903,13 @@ _lifecycle_object_ids(::Nothing) = nothing _lifecycle_object_ids(object_id::ObjectId) = (object_id,) _lifecycle_object_ids(object_ids) = object_ids +function _union_lifecycle_object_ids!(destination, objects::ObjectFamilyStore, ids) + for raw_id in ids + push!(destination, _index_object_id(objects, raw_id)) + end + return destination +end + function _mark_environment_bindings_dirty!( model::CompositeModel, object_ids=nothing, @@ -921,7 +928,7 @@ function _mark_environment_bindings_dirty!( model.environment_binding_cache = preserve_schema ? cached : nothing delta.full_environment = true elseif !delta.full_environment - union!(delta.environment_dirty_ids, ids) + _union_lifecycle_object_ids!(delta.environment_dirty_ids, model.registry.objects, ids) end if !model.environment_bindings_dirty model.environment_revision += 1 @@ -951,7 +958,7 @@ function _mark_bindings_dirty!( model.binding_cache = nothing delta.structural_kind = :full else - union!(delta.structural_dirty_ids, ids) + _union_lifecycle_object_ids!(delta.structural_dirty_ids, model.registry.objects, ids) delta.structural_kind = if delta.structural_kind == :full :full elseif delta.structural_kind == :clean @@ -1050,17 +1057,19 @@ function _delete_index!(index::Dict{Symbol,Set{ObjectId}}, key, id::ObjectId) end function _index_object!(registry::ObjectRegistry, object::Object) - _validate_status_identity_available!(registry, object.status, object.id) - _push_index!(registry.by_scale, object.scale, object.id) - _push_index!(registry.by_kind, object.kind, object.id) - _push_index!(registry.by_species, object.species, object.id) + id = _index_object_id(registry.objects, object.id) + _validate_status_identity_available!(registry, object.status, id) + _push_index!(registry.by_scale, object.scale, id) + _push_index!(registry.by_kind, object.kind, id) + _push_index!(registry.by_species, object.species, id) return nothing end function _deindex_object!(registry::ObjectRegistry, object::Object) - _delete_index!(registry.by_scale, object.scale, object.id) - _delete_index!(registry.by_kind, object.kind, object.id) - _delete_index!(registry.by_species, object.species, object.id) + id = _index_object_id(registry.objects, object.id) + _delete_index!(registry.by_scale, object.scale, id) + _delete_index!(registry.by_kind, object.kind, id) + _delete_index!(registry.by_species, object.species, id) return nothing end @@ -1276,21 +1285,15 @@ function _object_ancestor_ids( end function _lifecycle_object_snapshot(model::CompositeModel, object::Object) + id = _index_object_id(model.registry.objects, object.id) ancestors = get( model.registry.ancestor_ids_by_object, - object.id, + id, (), ) - return _lifecycle_object_snapshot(object, ancestors, object.geometry) -end - -# Bind the geometry type before constructing the snapshot. The tuple types of -# children and ancestors depend on runtime topology, so asking the outer -# constructor to infer its parameter from all fields dispatches on every path -# length. The event still owns immutable topology tuples and shares geometry. -function _lifecycle_object_snapshot(object::Object, ancestors, geometry::G) where {G} - return LifecycleObjectSnapshot{G}( - object.id, + # Freeze topology, but retain the same passive geometry object without copying. + return LifecycleObjectSnapshot( + id, object.scale, object.kind, object.species, @@ -1298,7 +1301,7 @@ function _lifecycle_object_snapshot(object::Object, ancestors, geometry::G) wher object.parent, Tuple(object.children), Tuple(ancestors), - geometry, + object.geometry, ) end @@ -1369,61 +1372,61 @@ function _apply_instance_labels!(object::Object, instance) return object end -function _register_object_without_lifecycle!( +@inline function _register_object_without_lifecycle!( model::CompositeModel, object::Object; parent=object.parent, status_values_materialized::Bool=false, ) registry = model.registry - haskey(registry.objects, object.id) && error("CompositeModel already contains object id `$(object.id.value)`.") - parent_id = isnothing(parent) ? nothing : ObjectId(parent) + id = _index_object_id(registry.objects, object.id) + haskey(registry.objects, id) && error("CompositeModel already contains object id `$(id.value)`.") + parent_id = isnothing(parent) ? nothing : _index_object_id(registry.objects, ObjectId(parent)) if !isnothing(parent_id) && !haskey(registry.objects, parent_id) error("No model object with id `$(parent_id.value)`.") end - return _register_object_status!(model, object, parent_id, object.status, status_values_materialized) + return _register_object_status!(model, object, id, parent_id, object.status, status_values_materialized) end # The same conversion and ownership operations serve both catalog forms. An # unconverted source need not be a canonical family when conversion is active. -function _register_object_status!(model, object, parent_id, source_status, status_values_materialized) - _validate_status_source_identity_available!(model, source_status, object.id) +@inline function _register_object_status!(model, object, id, parent_id, source_status, status_values_materialized) + _validate_status_source_identity_available!(model, source_status, id) catalog = model.registry.objects.catalog if status_values_materialized || _no_status_conversion(model.status_conversion) return _with_registered_status(catalog, source_status) do status - _register_converted_object!(model, object, parent_id, status, status) + _register_converted_object!(model, object, id, parent_id, status, status) end end conversion_records = Dict{Any,Any}() - status = _convert_registered_status(model, object.id, source_status; conversion_records) + status = _convert_registered_status(model, id, source_status; conversion_records) registered = _with_registered_status(catalog, status) do converted - _register_converted_object!(model, object, parent_id, source_status, converted) + _register_converted_object!(model, object, id, parent_id, source_status, converted) end merge!(model.status_conversion_records, conversion_records) return registered end -function _register_converted_object!(model, object, parent_id, source_status, status) +function _register_converted_object!(model, object, id, parent_id, source_status, status) registry = model.registry - _validate_status_identity_available!(registry, status, object.id) + _validate_status_identity_available!(registry, status, id) object.status = status instance = isnothing(parent_id) ? nothing : _instance_for_object(model, parent_id) _apply_instance_labels!(object, instance) object.parent = parent_id store = registry.objects - id = object.id::keytype(store) _store_object_family_row!(store, object, id, status) _index_object!(registry, object) - _set_status_source_identity!(model, object.id, source_status) + _set_status_source_identity!(model, id, source_status) ancestors = isnothing(parent_id) ? - ObjectId[object.id] : + ObjectId[id] : _append_object_ancestor_id( - _object_ancestor_ids(registry, parent_id), object.id, + _object_ancestor_ids(registry, parent_id), id, ) - registry.ancestor_ids_by_object[object.id] = ancestors - if !isnothing(object.parent) - parent_object = registry.objects[object.parent] - object.id in parent_object.children || push!(parent_object.children, object.id) + registry.ancestor_ids_by_object[id] = ancestors + if !isnothing(parent_id) + parent_object = registry.objects[parent_id] + id in parent_object.children || push!(parent_object.children, id) end return object end @@ -1435,7 +1438,7 @@ Register a fully initialized [`Object`](@ref) in `model`. Structural bindings are marked dirty and become visible to execution after the next lifecycle refresh boundary. Prefer [`add_organ!`](@ref) for MTG-backed growth. """ -function register_object!(model::CompositeModel, object::Object; parent=object.parent) +@inline function register_object!(model::CompositeModel, object::Object; parent=object.parent) registered = _register_object_without_lifecycle!( model, object; diff --git a/test/test-lifecycle-snapshot-allocations.jl b/test/test-lifecycle-snapshot-allocations.jl index 1e988da3d..98d81cf61 100644 --- a/test/test-lifecycle-snapshot-allocations.jl +++ b/test/test-lifecycle-snapshot-allocations.jl @@ -9,11 +9,31 @@ function _lifecycle_append_allocations(append_path, ancestors, object_id) return @allocated append_path(ancestors, object_id) end -# Retain the former expression as the allocation control, independently of the -# production snapshot constructor's geometry dispatch barrier. +# Keep the historical parametric geometry layout only as an allocation control. +# It is not a runtime/prepared family or a compatibility constructor. +module _LifecycleSnapshotAllocationReference +using PlantSimEngine: ObjectId +struct Snapshot{G} + id::ObjectId + scale::Union{Nothing,Symbol} + kind::Union{Nothing,Symbol} + species::Union{Nothing,Symbol} + name::Union{Nothing,String} + parent::Union{Nothing,ObjectId} + children::Tuple + ancestors::Tuple + geometry::G +end +end + +# Keep the preceding production geometry barrier as the allocation control. function _lifecycle_reference_snapshot(model, object) ancestors = get(model.registry.ancestor_ids_by_object, object.id, ()) - return PlantSimEngine.LifecycleObjectSnapshot( + return _lifecycle_reference_snapshot(object, ancestors, object.geometry) +end + +function _lifecycle_reference_snapshot(object, ancestors, geometry::G) where {G} + return _LifecycleSnapshotAllocationReference.Snapshot{G}( object.id, object.scale, object.kind, @@ -22,7 +42,7 @@ function _lifecycle_reference_snapshot(model, object) object.parent, Tuple(object.children), Tuple(ancestors), - object.geometry, + geometry, ) end @@ -38,16 +58,20 @@ function _lifecycle_snapshot_allocations!(snapshots, snapshot, model, object) return @allocated _lifecycle_fill_snapshots!(snapshots, snapshot, model, object) end -@testset "lifecycle snapshot allocations stay within historical budget" begin - model = CompositeModel(Object(1)) +@testset "lifecycle snapshot allocations stay within historical budget" for geometry in ( + nothing, + (position=(1f0, 2f0, 3f0),), + Dict(:position => [1.0, 2.0, 3.0]), +) + model = CompositeModel(Object(1; geometry=geometry)) for id in 2:16 - register_object!(model, Object(id; parent=id - 1)) + register_object!(model, Object(id; parent=id - 1, geometry=geometry)) end leaf = model_object(model, 16) # Allocate result storage outside measurement and inspect it afterward so # every measured snapshot escapes. Both implementations are warmed first. actual_snapshots = Vector{PlantSimEngine.LifecycleObjectSnapshot}(undef, 128) - previous_snapshots = similar(actual_snapshots) + previous_snapshots = Vector{_LifecycleSnapshotAllocationReference.Snapshot}(undef, 128) actual = _lifecycle_snapshot_allocations!( actual_snapshots, PlantSimEngine._lifecycle_object_snapshot, model, leaf, ) @@ -55,6 +79,8 @@ end previous_snapshots, _lifecycle_reference_snapshot, model, leaf, ) @test actual <= previous + @test all(snapshot -> snapshot.geometry === geometry, actual_snapshots) + @test all(snapshot -> snapshot.geometry === geometry, previous_snapshots) expected_ancestors = Tuple(ObjectId.(1:16)) @test all(snapshot -> snapshot.ancestors == expected_ancestors, actual_snapshots) @test all(snapshot -> snapshot.ancestors == expected_ancestors, previous_snapshots) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 126b7d03d..f1281d7c4 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -55,6 +55,41 @@ function close_registry(model::CompositeModel) model.revision, model.environment_revision) end + +@testset "registration admits object and parent identities before status conversion" begin + root = Object(:root; status=Status(x=1f0)) + model = close_registry(CompositeModel(root; type_promotion=Dict(Float64 => Float32))) + records = copy(model.status_conversion_records) + revision = model.revision + children = copy(root.children) + + for (id, parent) in ((2, :root), (:wrong_parent, 1)) + source = Status(x=2.0) + object = Object(id; status=source) + @test_throws ArgumentError register_object!(model, object; parent) + @test object.status === source + @test isnothing(object.parent) + @test !haskey(model.registry.objects, object.id) + @test model.status_conversion_records == records + @test model.revision == revision + @test root.children == children + end + + for (id, supplied_parent, keyword_parent) in ((:implicit, :root, false), + (:explicit, nothing, true), (:detached, nothing, false)) + status = Status(x=3f0) + reference = PSE.refvalue(status, :x) + object = Object(id; parent=supplied_parent, status) + registered = keyword_parent ? register_object!(model, object; parent="root") : + register_object!(model, object) + @test registered === object + @test model_status(model, id) === status + @test PSE.refvalue(model_status(model, id), :x) === reference + @test object.parent === (id === :detached ? nothing : root.id) + @test (object.id in root.children) === (id !== :detached) + end +end + function call_fixture(closed) capture = Ref{Any}(nothing) model = CompositeModel( From cd5517551f4cd4cf01504cb312e2b81f6fabe6ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 08:02:13 +0100 Subject: [PATCH 132/324] Normalize instance roots and retain source ownership identity types --- src/composite_model/registry_topology.jl | 37 ++++++++++++------- test/test-model-binding-index-identities.jl | 40 +++++++++++++++++++++ 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 9807831a2..ebceae309 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -133,7 +133,7 @@ separately to `CompositeModel`. `objects` contains additional owned descendants. implementing the same process. `object_overrides` contains `Override` entries for exceptional organs. """ -struct ObjectInstance{T,R,O,OV,OOV} +struct ObjectInstance{T<:CompositeModelTemplate,R<:Union{Object,ObjectId},O,OV,OOV} name::Symbol template::T root::R @@ -164,7 +164,7 @@ function ObjectInstance( return ObjectInstance( Symbol(name), template, - root, + root isa Object ? root : ObjectId(root), normalized_objects, overrides, normalized_object_overrides, @@ -448,8 +448,9 @@ function _normalize_object_instances(instances) return normalized end -function _instance_root_id(instance::ObjectInstance) - return instance.root isa Object ? instance.root.id : ObjectId(instance.root) +@inline function _instance_root_id(instance::ObjectInstance) + root = instance.root + return root isa Object ? root.id : root end function _collect_model_items(items, instances) @@ -1081,17 +1082,19 @@ function _validate_status_identity_available!( return _validate_object_family_status_owner!(registry.objects, status, object_id) end -function _validate_status_source_identity_available!( +@inline function _validate_status_source_identity_available!( model::CompositeModel, status, object_id::ObjectId, ) status isa Status || return nothing - existing = get( + raw_existing = get( model.status_source_owners, _status_identity(status), nothing, ) + existing = isnothing(raw_existing) ? nothing : + _index_object_id(model.registry.objects, raw_existing) if !isnothing(existing) && existing != object_id throw( ArgumentError( @@ -1291,6 +1294,7 @@ function _lifecycle_object_snapshot(model::CompositeModel, object::Object) id, (), ) + ancestor_snapshot = ancestors isa Tuple ? ancestors : Tuple(ancestors) # Freeze topology, but retain the same passive geometry object without copying. return LifecycleObjectSnapshot( id, @@ -1300,7 +1304,7 @@ function _lifecycle_object_snapshot(model::CompositeModel, object::Object) object.name, object.parent, Tuple(object.children), - Tuple(ancestors), + ancestor_snapshot, object.geometry, ) end @@ -1353,19 +1357,26 @@ end function _instance_for_object(model::CompositeModel, id) isempty(model.instances) && return nothing - current_id = ObjectId(id) - while haskey(model.registry.objects, current_id) + objects = model.registry.objects + I = keytype(objects) + raw_id = ObjectId(id) + raw_id isa I || return nothing + current_id = raw_id::I + while haskey(objects, current_id) for instance in model.instances - _instance_root_id(instance) == current_id && return instance + root_id = _instance_root_id(instance) + root_id isa I || continue + (root_id::I) == current_id && return instance end - parent = model.registry.objects[current_id].parent + parent = objects[current_id].parent isnothing(parent) && return nothing - current_id = parent + parent isa I || return nothing + current_id = parent::I end return nothing end -function _apply_instance_labels!(object::Object, instance) +@inline function _apply_instance_labels!(object::Object, instance) isnothing(instance) && return object isnothing(object.kind) && (object.kind = instance.template.kind) isnothing(object.species) && (object.species = instance.template.species) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index f1281d7c4..d88930624 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -90,6 +90,46 @@ end end end + +@testset "instance roots retain identity through nested registration and missing lookups" begin + for root_value in (:instance_root, 17, (:plant, 2)), form in (:object, :id, :value), closed in (false, true) + root = Object(root_value; scale=:Plant, status=Status(x=1f0)) + branch = Object(:branch; parent=root.id, status=Status(x=2f0)) + template = CompositeModelTemplate(; kind=:tree, species=:configured) + supplied = form === :object ? root : form === :id ? root.id : root_value + instance = ObjectInstance(:plant, template; root=supplied) + @test instance.root === (form === :object ? root : root.id) + items = form === :object ? (branch,) : (root, branch) + model = CompositeModel(items...; instances=(instance,)) + closed && (model = close_registry(model)) + @test PSE._instance_root_id(instance) === root.id + @test PSE._instance_for_object(model, branch.id) === instance + + status = Status(x=3f0) + reference = PSE.refvalue(status, :x) + newborn = Object(:newborn; parent=branch.id, status) + @test register_object!(model, newborn) === newborn + @test newborn.kind === :tree + @test newborn.species === :configured + @test PSE._instance_for_object(model, newborn.id) === instance + @test PSE.refvalue(model_status(model, newborn.id), :x) === reference + @test resolve_object_ids(model, Many(within=Scope(:plant))) == + PSE._sort_object_ids!([root.id, branch.id, newborn.id]) + + remove_object!(model, newborn.id) + @test isnothing(PSE._instance_for_object(model, newborn.id)) + @test isnothing(PSE._instance_for_object(model, ObjectId(:missing))) + @test isnothing(PSE._instance_for_object(model, ObjectId(999f0))) + @test PSE._instance_for_object(model, branch.id) === instance + end + + root = Object(:string_root; status=Status(x=1f0)) + instance = ObjectInstance(:string_instance, CompositeModelTemplate(); root="string_root") + model = CompositeModel(root; instances=(instance,)) + @test instance.root === root.id + @test PSE._instance_for_object(model, root.id) === instance +end + function call_fixture(closed) capture = Ref{Any}(nothing) model = CompositeModel( From ffe1aeb0a33d2c1464665188d51297f58d662a04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 14 Nov 2026 09:50:26 +0100 Subject: [PATCH 133/324] Retain authored declaration kinds for prepared status schemas --- src/composite_model/authored_ports.jl | 15 +++-- src/composite_model/selectors.jl | 3 + test/test-model-authored-port-inventory.jl | 75 ++++++++++++++++++++++ 3 files changed, 89 insertions(+), 4 deletions(-) diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl index 5ddd2855b..411a032d4 100644 --- a/src/composite_model/authored_ports.jl +++ b/src/composite_model/authored_ports.jl @@ -44,11 +44,14 @@ Base.propertynames(::AuthoredOutputPorts) = (:all_names, :local_names, :distribu # One stable owner is shared by the authored recipe and compiled application. # Name and type carriers preserve declarations without retaining initialization values. -mutable struct AuthoredPortInventory{I,O,IT,OT,OET,EI,EO,C} +mutable struct AuthoredPortInventory{I,O,IT,OT,IDT,ODT,IET,OET,EI,EO,C} const inputs::I const outputs::O const input_types::IT const output_types::OT + const input_declaration_types::IDT + const output_declaration_types::ODT + const input_element_types::IET const output_element_types::OET const environment_inputs::EI const environment_outputs::EO @@ -122,15 +125,18 @@ function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) output_schema = _output_schema(spec) output_ports = _authored_output_ports(spec, output_schema) output_types = _authored_port_types(_output_value_type, output_schema) + output_declaration_types = _authored_port_types(typeof, output_schema) output_element_types = _authored_output_element_types(output_schema) model = model_(spec) input_metadata = _capture_authored_metadata(:input_ports, application_id) do schema = _input_schema(model) (AuthoredPortNames(Tuple(Symbol(name) for name in keys(schema))), - _authored_port_types(_input_expected_type, schema)) + _authored_port_types(_input_expected_type, schema), + _authored_port_types(typeof, schema), + _authored_output_element_types(schema)) end - inputs, input_types = if input_metadata isa ScenarioPreparationFailure - input_metadata, input_metadata + inputs, input_types, input_declaration_types, input_element_types = if input_metadata isa ScenarioPreparationFailure + input_metadata, input_metadata, input_metadata, input_metadata else input_metadata end @@ -160,5 +166,6 @@ function _prepare_authored_ports(spec::ModelSpec, application_id::Symbol) end end return AuthoredPortInventory(inputs, output_ports, input_types, output_types, + input_declaration_types, output_declaration_types, input_element_types, output_element_types, environment_inputs, environment_outputs, contracts) end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index d0942fcb3..981f9ef64 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -355,6 +355,9 @@ function _configured_variant_ports(contract) return ( input_types=_authored_port_types(_input_expected_type, contract.inputs), output_types=_authored_port_types(_output_value_type, contract.outputs), + input_declaration_types=_authored_port_types(typeof, contract.inputs), + output_declaration_types=_authored_port_types(typeof, contract.outputs), + input_element_types=_authored_output_element_types(contract.inputs), output_element_types=_authored_output_element_types(contract.outputs), input_names=keys(contract.inputs), output_names=keys(contract.outputs), input_default_names=keys(input_defaults), output_default_names=keys(output_defaults), diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index 1db99a14b..4d743f822 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -82,6 +82,68 @@ end @test PSE._output_element_types(Float32[]) === Tuple{} end +struct DeclarationProbe{C,A,B} <: AbstractAuthored_Port_InventoryModel + counter::C + empty::A + mixed::B +end +function PSE.inputs_(model::DeclarationProbe) + count_hook!(model.counter, :inputs) + return (required=Required(Vector{Real}), empty=Default(model.empty), mixed=Default(model.mixed)) +end +function PSE.outputs_(model::DeclarationProbe) + count_hook!(model.counter, :outputs) + return (direct=model.empty, distributed=Distributed(Default(model.mixed)), + needed=Distributed(Required(Real))) +end +PSE.run!(::DeclarationProbe, status, environment, constants, context) = nothing + +@testset "declaration evidence distinguishes Required and genuine array defaults" begin + probe = DeclarationProbe(Ref((inputs=0, outputs=0)), Real[], Real[1f0, 2.0, 1//2]) + model = CompositeModel(Object(:scene; scale=:Scene); applications=( + ModelSpec(probe; name=:declarations, on=Many(scale=:Future), + outputs_to=(OutputTo(Many(scale=:Destination)),)),)) + ports = only(model.scenario_plan_cache.authored).ports + @test probe.counter[] == (inputs=1, outputs=1) + @test values(ports.input_types) === (Vector{Real}, Vector{Real}, Vector{Real}) + @test values(ports.input_declaration_types) === + (Required{Vector{Real}}, Default{Vector{Real}}, Default{Vector{Real}}) + @test fieldtypes(typeof(ports.input_declaration_types)) === + (Type{Required{Vector{Real}}}, Type{Default{Vector{Real}}}, Type{Default{Vector{Real}}}) + @test values(ports.output_declaration_types) === + (Vector{Real}, Distributed{Default{Vector{Real}}}, Distributed{Required{Real}}) + @test fieldtypes(typeof(ports.output_declaration_types)) === + (Type{Vector{Real}}, Type{Distributed{Default{Vector{Real}}}}, Type{Distributed{Required{Real}}}) + @test keys(ports.input_element_types) === (:empty, :mixed) + @test values(ports.input_element_types) === (Tuple{}, Tuple{Float32,Float64,Rational{Int}}) + @test fieldtypes(typeof(ports.input_element_types)) === + (Type{Tuple{}}, Type{Tuple{Float32,Float64,Rational{Int}}}) + @test keys(ports.output_element_types) === (:direct, :distributed) + @test values(ports.output_element_types) === values(ports.input_element_types) + @test inventory_is_value_free(ports) + @test isnothing(model_status(model, :scene)) + + # Mutation changes fresh evidence, never the constructor's type-only snapshot. + push!(probe.empty, 3f0) + push!(probe.mixed, 4) + @test ports.input_element_types.empty === Tuple{} + @test ports.input_element_types.mixed === Tuple{Float32,Float64,Rational{Int}} + contract = PSE.model_interface(probe) # deliberate inspection, including its name validation + before = probe.counter[] + @test before == (inputs=3, outputs=3) + variant = PSE._configured_variant_ports(contract) + @test probe.counter[] == before + @test variant.input_declaration_types === ports.input_declaration_types + @test variant.output_declaration_types === ports.output_declaration_types + @test keys(variant.input_element_types) === (:empty, :mixed) + @test values(variant.input_element_types) === + (Tuple{Float32}, Tuple{Float32,Float64,Rational{Int},Int}) + @test values(variant.output_element_types) === values(variant.input_element_types) + @test inventory_is_value_free(variant) + @test probe.empty == Real[3f0] + @test probe.mixed == Real[1f0, 2.0, 1//2, 4] +end + @testset "constructor owns one instance-specific value-free port inventory" begin a = Probe(:a, Ref(hook_zero), Ref(1f0)) b = Probe(:b, Ref(hook_zero), Ref(2f0)) @@ -102,6 +164,14 @@ end @test ports.input_names === (input_name(process_model),) @test getproperty(ports.input_types, input_name(process_model)) === Vector{Float32} @test fieldtype(typeof(ports.input_types), 1) === Type{Vector{Float32}} + @test getproperty(ports.input_declaration_types, input_name(process_model)) === Default{Vector{Float32}} + @test fieldtypes(typeof(ports.input_declaration_types)) === (Type{Default{Vector{Float32}}},) + @test keys(ports.input_element_types) === (input_name(process_model),) + @test values(ports.input_element_types) === (Tuple{Float32},) + @test fieldtypes(typeof(ports.input_element_types)) === (Type{Tuple{Float32}},) + @test values(ports.output_declaration_types) === (Float32, Distributed{Default{Vector{Float32}}}) + @test fieldtypes(typeof(ports.output_declaration_types)) === + (Type{Float32}, Type{Distributed{Default{Vector{Float32}}}}) @test getproperty(ports.output_types, output_name(process_model)) === Float32 @test getproperty(ports.output_types, distributed_name(process_model)) === Vector{Float32} @test fieldtypes(typeof(ports.output_types)) === (Type{Float32}, Type{Vector{Float32}}) @@ -199,6 +269,11 @@ PSE.run!(::BrokenInput, status, environment, constants, context) = nothing @test broken_input_calls[] == 1 @test isnothing(model.scenario_plan_cache.failure) @test hasproperty(only(model.scenario_plan_cache.authored), :ports) + failed_ports = only(model.scenario_plan_cache.authored).ports + @test failed_ports.input_declaration_types === failed_ports.input_types + @test failed_ports.input_element_types === failed_ports.input_types + @test failed_ports.input_types isa PSE.ScenarioPreparationFailure + @test failed_ports.input_types.phase === :input_ports for _ in 1:2 report = PSE.compile_model_report(model) @test [app.id for app in report.applications] == [:broken] From 3dd328a55300e3332b4175e8b05e9e7dc16919b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 20:46:05 +0100 Subject: [PATCH 134/324] Prepare fixed canonical Status schemas at construction Keep official status headers and shared references stable through lifecycle updates. Prepare prospective field families, admit newborn data before publication, and preserve configured permissions during force refresh. Nine maintained test files pass 445 assertions on Julia 1.13.3. Broader feature coverage, prepared-call compilation latency, full JuliaC safe parity and 4160-day performance qualification remain in progress. --- AGENTS.md | 6 +- docs/src/guides/data/numerical_reliability.md | 25 +- docs/src/model_execution.md | 55 +- .../references/dynamic-models.md | 8 +- src/component_models/Status.jl | 217 ++++++- src/composite_model/compilation.jl | 376 +++++++----- .../execution_batch_schemas.jl | 2 +- src/composite_model/execution_cohorts.jl | 12 +- src/composite_model/object_families.jl | 51 +- .../prepared_status_manifest.jl | 464 ++++++++++++++ src/composite_model/registry_topology.jl | 206 ++++--- src/composite_model/runtime_outputs.jl | 1 + src/composite_model/selectors.jl | 105 +++- src/composite_model/status_construction.jl | 88 ++- .../status_view_construction.jl | 58 +- src/composite_model_api.jl | 1 + src/visualization/model_graph_editor_api.jl | 12 +- test/test-fixed-status-manifest.jl | 70 +++ ...st-fixed-status-prospective-distributed.jl | 42 ++ test/test-fixed-status-scope-growth.jl | 79 +++ test/test-model-call-cohort-retirement.jl | 45 +- test/test-model-cohort-store-identities.jl | 18 +- test/test-model-initializers.jl | 6 +- test/test-model-object-id.jl | 24 +- test/test-model-persistent-empty-groups.jl | 20 +- test/test-model-prepared-growth-schemas.jl | 50 +- test/test-model-public-refresh-owners.jl | 126 ++++ test/test-model-scenario-authoring.jl | 8 +- test/test-model-status-type-lifecycle.jl | 12 +- test/test-object-families.jl | 124 ++-- test/test-organ-creation-allocation.jl | 42 +- test/test-organ-status-assembly.jl | 581 ++++-------------- test/test-prepared-status-registration.jl | 103 ++++ test/test-registered-status-dispatch.jl | 153 ++--- test/test-status-construction.jl | 93 +-- test/test-status-fixed-storage.jl | 121 ++++ test/test-unified-model-object-api.jl | 228 ++----- test/test_groups.jl | 5 + 38 files changed, 2280 insertions(+), 1357 deletions(-) create mode 100644 src/composite_model/prepared_status_manifest.jl create mode 100644 test/test-fixed-status-manifest.jl create mode 100644 test/test-fixed-status-prospective-distributed.jl create mode 100644 test/test-fixed-status-scope-growth.jl create mode 100644 test/test-prepared-status-registration.jl create mode 100644 test/test-status-fixed-storage.jl diff --git a/AGENTS.md b/AGENTS.md index df9f55a0a..481d0c2b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -196,8 +196,10 @@ know its scenario timestep unless the scientific model explicitly requires it. ## Lifecycle - `add_organ!` is the high-level operation for MTG-backed growth. It creates - the node, reuses the model's MTG status policy, applies initial values, - registers the object, and returns its runtime `Status`. + the node from explicit `initial_status` data, applies the model's status + conversion/prepared-family checks, registers the object, and returns its + runtime `Status`. The MTG status accessor imports the initial tree only; + annotations/geometry stay in MTG attributes and no `node` field is inserted. - Runtime status belongs to the model registry and is not stored in MTG attributes. Use `model_status(model, node)` to access an MTG-backed object's status and `source_node(model, object)` to retrieve its associated MTG node. diff --git a/docs/src/guides/data/numerical_reliability.md b/docs/src/guides/data/numerical_reliability.md index 37313ab59..4cd3bc4e1 100644 --- a/docs/src/guides/data/numerical_reliability.md +++ b/docs/src/guides/data/numerical_reliability.md @@ -85,11 +85,26 @@ the simulation. Model parameters and environment values keep their types. Conversion happens when status storage is created or a new object is added; it is not repeated every time a model runs. -If you supply a `Status`, PlantSimEngine leaves that original object unchanged. -It creates new storage for converted values and reuses existing references -where possible for unchanged values. Each `Object` must have its own `Status`; -sharing one `Status` between objects is rejected. The same conversion rules -apply once to values added later through `register_object!` or `add_organ!`. +Retrieve the official status with `model_status(model, object)` after constructing +the model. PlantSimEngine creates a prepared container, creates new references +for converted values, and shares existing references for unchanged values. +The supplied container keeps its original fields; later writes through a shared +reference are visible from both containers. Each `Object` must have its own +`Status`; sharing one `Status` between objects is rejected. The same conversion +rules apply once to values added later through `register_object!` or `add_organ!`. + +The prepared configuration also determines which field types a newborn can +supply. Use concrete declarations for future fields and the same numeric +configuration for their initial data. For example, a `Float32` configuration can +use `type_promotion=Dict(Float64 => Float32)` to convert later `Float64` input +data as well. Incompatible fields or reference types are rejected before the +new object is registered. Existing objects retain their admitted references +when they move between application scopes. + +Declaration-based type preparation does not execute `status_transform` on +future defaults. The callback runs when the real value is materialized, and +its result must fit the prepared type family. A callback whose return type +varies outside that family needs a new, explicit model configuration. `Diagnostics.explain_initialization(model)` shows the type declared by the model, the type of the supplied value, the type after `status_transform`, and diff --git a/docs/src/model_execution.md b/docs/src/model_execution.md index 5d73ad622..dc540d7cf 100644 --- a/docs/src/model_execution.md +++ b/docs/src/model_execution.md @@ -73,6 +73,33 @@ application identifiers, input/output and environment port names, variable contracts, selector rules, declared value and call connections, and the dependency order between applications. Objects and weather rows can be added later. The constructor registers the objects you supplied without running their equations. +It also fixes the field order and allowed reference types for the configured +object statuses, including fields declared for objects that may appear later. +Values, object counts, and vector lengths remain dynamic. A field stays absent +until real data, a default, or a connection supplies its reference. + +Use `model_status` to keep the official status after construction: + +```julia +supplied = Status(x=1f0) +model = CompositeModel(Object(:leaf; scale=:Leaf, status=supplied)) +status = model_status(model, :leaf) +status.x = 2f0 +@assert supplied.x == 2f0 +object_id(model, status) # ObjectId(:leaf) +``` + +The official container shares unchanged references with the supplied status. +Its identity belongs to the registry; `object_id(model, supplied)` raises an +`ArgumentError` because the supplied container is no longer registered. Retain +`model_status(model, object)` when you need both values and object identity. +Conversions may create new references, as described in +[numeric type configuration](guides/data/numerical_reliability.md). + +Field access such as `status.x` follows names. Positional access with `status[i]` +and `Tuple(status)` follows the order fixed at preparation, rather than the +order in which producers first supplied their values. Obtain `keys(status)` +when you need to inspect the currently present fields. Starting a simulation resolves those declarations against the current objects and environment. This preparation is called **compilation**. It: @@ -119,11 +146,15 @@ initializer. Creating a fresh mutable default, such as an empty vector, is supported; object preparation keeps defaults private to each object. Keep declaration names and layouts stable while a prepared model is in use. -Graph-editor configuration changes prepare the declarations again. When redefining -layout methods interactively, explicitly refresh with -`PlantSimEngine.Advanced.refresh_bindings!(model; force=true)` before starting a -new simulation. Environment changes resolve clocks and bindings while retaining -unchanged application declarations. +Use `PlantSimEngine.Advanced.refresh_bindings!(model; force=true)` to refresh +selectors or declaration metadata within the same prepared field and type schemas. +A change that needs a different canonical Status or typed configuration schema +requires constructing a new `CompositeModel`; it cannot replace the old schema in +place. The same applies after an initial declaration failure prevented a schema +from being prepared: fix the declaration, then construct the model again. +Graph-editor configuration changes already return a newly prepared model. +Environment changes resolve clocks and bindings while retaining unchanged +application declarations. Useful inspection helpers: @@ -474,14 +505,12 @@ update_geometry!(model, :leaf_5, new_geometry) ``` Use `add_organ!` when the plant structure comes from an MTG. It creates the -node, prepares its starting values, adds the object to the simulation, and -marks its connections for updating. By default, it reuses the function you -provided to initialize values from MTG nodes. - -Set `use_status_adapter=false` only if you supply all the new organ's -attributes and values yourself, and that initialization function has no -additional work to do. Use `register_object!` when you already have a fully -prepared `Object` to add. +node, registers its explicit `initial_status`, and marks its connections for +updating. MTG `attributes` remain annotations and geometry; they do not become +runtime variables. The `status(node)` accessor supplied to `CompositeModel` +imports the initial tree only. Supply newborn scientific values explicitly, +and use `source_node(model, leaf_status)` to retrieve the new source node. +Use `register_object!` when you already have a fully prepared `Object` to add. Adding or removing objects can change which models run and where their inputs come from, so PlantSimEngine updates the affected connections. Moving diff --git a/skills/plantsimengine/references/dynamic-models.md b/skills/plantsimengine/references/dynamic-models.md index b606f497a..dce1fa7c2 100644 --- a/skills/plantsimengine/references/dynamic-models.md +++ b/skills/plantsimengine/references/dynamic-models.md @@ -48,9 +48,11 @@ new_leaf_status = add_organ!( ) ``` -`add_organ!` creates the node, reuses the model's MTG status policy, applies -initial values, attaches the status, and registers the runtime object. Do not -separately register the returned status/object. +`add_organ!` creates the node and registers explicit `initial_status` values. +The initial-tree `status(node)` import callback is not replayed during growth. +Annotations and geometry stay in MTG attributes; use `source_node` instead of +expecting a `node` status field. Do not separately register the returned +status/object. Keep initial values generic and scientifically explicit. Do not seed a newborn with arbitrary nonzero values merely to satisfy a downstream type. diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 0b956e7bd..eb567278d 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -1,12 +1,30 @@ +# N is the prepared namespace; the backing determines currently visible fields. +mutable struct _FixedStatusStorage{N,R<:Tuple,T<:NamedTuple} + refs::T + reference_epoch::UInt +end + + +# Kernel ports remain a dense NT. The immutable full snapshot captures the SAME +# refs and presence, including private/temporal overlays, never a latest owner. +struct _ProjectedStatusStorage{N,R<:Tuple,H<:NamedTuple,T<:NamedTuple} + hot::H + refs::T + reference_epoch::UInt +end + """ Status(vars) -Status type used to store the values of the variables during simulation. It is mainly used -as the structure to store the variables in the `TimeStepRow` of a `TimeStepTable` (see -[`PlantMeteo.jl` docs](https://palmstudio.github.io/PlantMeteo.jl/stable/)). +Named values stored through mutable references. A standalone `Status` contains +its supplied fields. [`CompositeModel`](@ref) prepares the official registry +container and its allowed field types; use [`model_status`](@ref) to retrieve it. +Unchanged values share their references with the supplied status, while numeric +conversion can create new references. Fields without a real reference remain +absent. Positional access follows the order chosen at preparation. -Most of the code is taken from MasonProtter/MutableNamedTuples.jl, so `Status` is a MutableNamedTuples with a few modifications, -so in essence, it is a stuct that stores a `NamedTuple` of the references to the values of the variables, which makes it mutable. +The standalone reference container is adapted from +MasonProtter/MutableNamedTuples.jl. # Examples @@ -54,18 +72,90 @@ julia> st[1] = 22.0 22.0 ``` """ -struct Status{N,T<:Tuple{Vararg{Ref}}} - vars::NamedTuple{N,T} - # `Status()` has no Ref-valued variable from which Julia could derive object - # identity. Keep an opaque token so every runtime status, including an empty - # one created before compilation adds variables, has a distinct identity. +struct Status{N,T} + vars::T identity::Base.RefValue{Nothing} + function Status(vars::NamedTuple{N,R}) where {N,R<:Tuple{Vararg{Ref}}} + return new{N,typeof(vars)}(vars, Ref(nothing)) + end + function Status(vars::_FixedStatusStorage{N}) where {N} + return new{N,typeof(vars)}(vars, Ref(nothing)) + end + function Status(vars::_ProjectedStatusStorage{N}) where {N} + return new{N,typeof(vars)}(vars, Ref(nothing)) + end +end - function Status(vars::NamedTuple{N,T}) where {N,T<:Tuple{Vararg{Ref}}} - return new{N,T}(vars, Ref(nothing)) +# The physical namespace has one finite reference union per slot. This is a +# storage bound; configuration admission is checked separately before activation. +# Nothing marks a namespace slot with no canonical Ref family. Ref{Nothing} +# remains a real present cell whose biological value is nothing. +function _fixed_status_type(names::Tuple, references::Type{<:Tuple}) + length(names) == fieldcount(references) && all(n -> n isa Symbol, names) && + length(unique(names)) == length(names) || throw(ArgumentError("Invalid prepared status namespace.")) + valid = all(fieldtypes(references)) do R + R === Nothing || all(T -> T <: Ref && isconcretetype(T), Base.uniontypes(R)) end + valid || throw(ArgumentError("Each prepared status slot needs a finite exact reference family.")) + Slots = NamedTuple{names,Tuple{map(R -> Union{Nothing,R}, fieldtypes(references))...}} + return Status{names,_FixedStatusStorage{names,references,Slots}} +end +@generated function _fixed_status(::Type{S}) where {N,R,T,S<:Status{N,_FixedStatusStorage{N,R,T}}} + empty = Expr(:tuple, fill(nothing, length(N))...) + return :(Status(_FixedStatusStorage{$(QuoteNode(N)),$R,$T}($T($empty), UInt(0)))) end +_fixed_status(names::Val{N}, references::Type{<:Tuple}) where {N} = + _fixed_status(_fixed_status_type(N, references)) +_status_storage_names(storage::NamedTuple) = keys(storage) +_status_storage_names(storage::Union{_FixedStatusStorage{N},_ProjectedStatusStorage{N}}) where {N} = + filter(name -> getfield(storage.refs, name) !== nothing, N) +_status_storage_reference_types(::Type{NamedTuple{N,R}}) where {N,R} = R +_status_storage_reference_types(::Type{<:_FixedStatusStorage{N,R}}) where {N,R} = R +_status_storage_reference_types(::Type{<:_ProjectedStatusStorage{N,R}}) where {N,R} = R +@inline _status_reference(storage::NamedTuple, key) = getfield(storage, key) +@inline function _status_reference(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}, key::Symbol) + reference = getfield(storage.refs, key) + reference === nothing && throw(KeyError(key)) + return reference +end +@inline function _status_reference(storage::_ProjectedStatusStorage{N,R,H}, key::Symbol) where {N,R,H} + hasfield(H, key) && return getfield(storage.hot, key) + reference = getfield(storage.refs, key) + reference === nothing && throw(KeyError(key)) + return reference +end +@inline _status_reference(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}, key::Int) = + _status_reference(storage, _status_storage_names(storage)[key]) +_status_storage_references(storage::NamedTuple) = values(storage) +_status_storage_references(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}) = + map(key -> _status_reference(storage, key), _status_storage_names(storage)) + +# Reference/presence edits invalidate projections; ref[] = value does not. +_status_reference_epoch(storage::NamedTuple) = UInt(0) +_status_reference_epoch(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}) = storage.reference_epoch +_status_reference_epoch(status::Status) = _status_reference_epoch(_status_vars(status)) +function _set_status_reference!(status::Status{N,<:_FixedStatusStorage}, name::Symbol, reference::Ref) where {N} + storage = _status_vars(status) + index = findfirst(isequal(name), N) + index === nothing && throw(KeyError(name)) + R = fieldtype(_status_storage_reference_types(typeof(storage)), index) + reference isa R || throw(ArgumentError("Reference is outside its prepared slot type.")) + old = getfield(storage.refs, index) + old === reference && return reference + storage.refs = typeof(storage.refs)(Base.setindex(values(storage.refs), reference, index)) + storage.reference_epoch += UInt(1) + return reference +end +function _drop_status_reference!(status::Status{N,<:_FixedStatusStorage}, name::Symbol) where {N} + storage = _status_vars(status) + old = getfield(storage.refs, name) + old === nothing && return nothing + index = findfirst(isequal(name), N) + storage.refs = typeof(storage.refs)(Base.setindex(values(storage.refs), nothing, index)) + storage.reference_epoch += UInt(1) + return old +end Status(; kwargs...) = Status(NamedTuple{keys(kwargs)}(Ref.(values(values(kwargs))))) function Status{names}(tuple::Tuple) where {names} Status(NamedTuple{names}(Ref.(tuple))) @@ -76,19 +166,19 @@ function Status(nt::NamedTuple{names}) where {names} end _status_vars(status) = getfield(status, :vars) -_status_values(status) = getindex.(values(_status_vars(status))) +_status_values(status) = getindex.(refvalues(status)) _status_namedtuple(status) = NamedTuple{keys(status)}(values(status)) _status_tuple(status) = values(status) -_status_iterate(status, iter=1) = iterate(NamedTuple(status), iter) +_status_iterate(status, iter=1) = iterate(values(status), iter) _status_firstindex(status) = 1 -_status_lastindex(status) = lastindex(NamedTuple(status)) -_status_indexed_iterate(status, i::Int, state=1) = Base.indexed_iterate(NamedTuple(status), i, state) +_status_lastindex(status) = length(status) +_status_indexed_iterate(status, i::Int, state=1) = Base.indexed_iterate(values(status), i, state) -Base.keys(::Status{names}) where {names} = names +Base.keys(status::Status) = _status_storage_names(_status_vars(status)) Base.values(st::Status) = _status_values(st) _status_identity(status::Status) = getfield(status, :identity) -refvalues(mnt::Status) = values(getfield(mnt, :vars)) -Base.@constprop :aggressive @inline refvalue(mnt::Status, key::Symbol) = getfield(getfield(mnt, :vars), key) +refvalues(mnt::Status) = _status_storage_references(_status_vars(mnt)) +Base.@constprop :aggressive @inline refvalue(mnt::Status, key::Symbol) = _status_reference(_status_vars(mnt), key) Base.NamedTuple(mnt::Status) = _status_namedtuple(mnt) Base.Tuple(mnt::Status) = _status_tuple(mnt) @@ -109,18 +199,16 @@ function Base.show(io::IO, t::Status) print(io, "Status", NamedTuple(t)) end -Base.@constprop :aggressive @inline Base.getproperty(mnt::Status, s::Symbol) = getproperty(getfield(mnt, :vars), s)[] -Base.@constprop :aggressive @inline Base.getindex(mnt::Status, i::Int) = getfield(getfield(mnt, :vars), i)[] +Base.@constprop :aggressive @inline Base.getproperty(mnt::Status, s::Symbol) = refvalue(mnt, s)[] +Base.@constprop :aggressive @inline Base.getindex(mnt::Status, i::Int) = _status_reference(_status_vars(mnt), i)[] Base.@constprop :aggressive @inline Base.getindex(mnt::Status, i::Symbol) = getproperty(mnt, i) Base.@constprop :aggressive @inline function Base.setproperty!(mnt::Status, s::Symbol, x) - nt = getfield(mnt, :vars) - getfield(nt, s)[] = x + refvalue(mnt, s)[] = x end Base.@constprop :aggressive @inline function Base.setproperty!(mnt::Status, i::Int, x) - nt = getfield(mnt, :vars) - getindex(nt, i)[] = x + _status_reference(_status_vars(mnt), i)[] = x end Base.@constprop :aggressive @inline function Base.setindex!(mnt::Status, x, i::Symbol) @@ -131,9 +219,9 @@ Base.@constprop :aggressive @inline function Base.setindex!(mnt::Status, x, i::I setproperty!(mnt, i, x) end -Base.propertynames(::Status{T,R}) where {T,R} = T -Base.length(mnt::Status) = length(getfield(mnt, :vars)) -Base.eltype(::Type{Status{N,T}}) where {N,T} = eltype.(eltype(T)) +Base.propertynames(status::Status) = keys(status) +Base.length(mnt::Status) = length(keys(mnt)) +Base.eltype(::Type{Status{N,T}}) where {N,T} = eltype.(eltype(_status_storage_reference_types(T))) Base.iterate(mnt::Status, iter=1) = _status_iterate(mnt, iter) @@ -149,3 +237,76 @@ function Base.:(==)(s1::Status, s2::Status) (propertynames(s1) == propertynames(s2)) && (values(s1) == values(s2)) end + +# A shallow copy owns its header/presence, shares biological cells, and is unregistered. +_copy_status_storage(storage::Union{NamedTuple,_ProjectedStatusStorage}) = storage +_copy_status_storage(storage::_FixedStatusStorage{N,R,T}) where {N,R,T} = + _FixedStatusStorage{N,R,T}(storage.refs, storage.reference_epoch) +Base.copy(status::Status) = Status(_copy_status_storage(_status_vars(status))) +# Keep Base's single-IdDict deepcopy: it preserves internal aliases/cycles and +# copies refs, owner metadata and the identity token together; no elementwise map. + +@inline function _initial_status_reference_storage(source::Status) + storage = _status_vars(source) + storage isa NamedTuple && return storage + storage isa Union{_FixedStatusStorage,_ProjectedStatusStorage} || throw(ArgumentError("Unknown Status backing.")) + return getfield(storage, :refs) +end +@inline function _initial_status_reference_count(source::Status) + references = _initial_status_reference_storage(source) + count = 0 + for index in 1:nfields(references) + getfield(references, index) === nothing || (count += 1) + end + return count +end +@inline function _initial_status_reference(source::Status, name::Symbol) + references = _initial_status_reference_storage(source) + return isdefined(references, name) ? getfield(references, name) : nothing +end + +# S is admitted by the prepared owner BEFORE this generated operation. No source +# NamedTuple subtype, field-count permutation or initializer value becomes proof. +@generated function _new_prepared_status(::Type{S}, source) where {N,R,T,S<:Status{N,_FixedStatusStorage{N,R,T}}} + cells = [gensym(:cell) for _ in N] + reads = [:($(cells[i]) = _initial_status_reference(source, $(QuoteNode(name)))) for (i,name) in enumerate(N)] + checks = [:( $(cells[i]) isa $(fieldtype(T,i)) || throw(ArgumentError("Initial reference is outside its prepared slot family.")) ) for i in eachindex(N)] + count = foldl((a,b)->:($a + $b), [:(Int($(cell) !== nothing)) for cell in cells]; init=:(0)) + refs = Expr(:tuple, [:( $(cells[i])::$(fieldtype(T,i)) ) for i in eachindex(N)]...) + return quote + $(Expr(:meta, :inline)) + source isa S && return source + source === nothing && return _fixed_status(S) + source isa Status || throw(ArgumentError("Initial status must be a Status or nothing.")) + $(reads...) + $(checks...) + $count == _initial_status_reference_count(source) || throw(ArgumentError("Initial status contains a name outside its prepared namespace.")) + return Status(_FixedStatusStorage{$(QuoteNode(N)),$R,$T}($T($refs), UInt(0))) + end +end + +@inline function _validate_status_reference(status::Status{N,<:_FixedStatusStorage}, name::Symbol, reference::Ref) where {N} + index = findfirst(isequal(name), N) + index === nothing && throw(KeyError(name)) + R = fieldtype(_status_storage_reference_types(typeof(_status_vars(status))), index) + reference isa R || throw(ArgumentError("Reference is outside its prepared canonical slot family.")) + return nothing +end + +_status_snapshot_references(status::Status) = _initial_status_reference_storage(status) +_dense_status_type(names::Tuple, references::Type{<:Tuple}) = Status{names,NamedTuple{names,references}} +function _projected_status_type(::Type{C}, hot_names::Tuple, hot_references::Type{<:Tuple}) where {C<:Status} + names = _status_schema_names(C) + all(n -> n in names, hot_names) || throw(ArgumentError("A kernel port is outside the prepared namespace.")) + canonical = _status_schema_references(C) + refs = map(eachindex(names)) do index + hot_index = findfirst(isequal(names[index]), hot_names) + isnothing(hot_index) ? fieldtype(canonical,index) : fieldtype(hot_references,hot_index) + end + R = Tuple{refs...} + Slots = NamedTuple{names,Tuple{map(T -> Union{Nothing,T}, refs)...}} + Hot = NamedTuple{hot_names,hot_references} + return Status{names,_ProjectedStatusStorage{names,R,Hot,Slots}} +end + +Base.hasproperty(status::Status, name::Symbol) = _initial_status_reference(status, name) !== nothing diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 04ade9cac..1f174b52f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -786,12 +786,13 @@ mutable struct AuthoredScenarioGraph{CO,MA,AC,AO,F} const failures::F end -mutable struct ScenarioPreparation{M,S,A,F,P} +mutable struct ScenarioPreparation{M,S,A,F,P,SM} const owner::M const source_specs::S const authored::A const failure::F const program::P + const status_manifest::SM resolved::Any end @@ -836,7 +837,8 @@ function _authored_specs_match(source_specs, specs) return all(pair -> pair[1] === pair[2], zip(source_specs, specs)) end -function _prepare_authored_scenario(model::CompositeModel, raw_specs) +function _prepare_authored_scenario(model::CompositeModel, raw_specs; + raw_families=_prepared_raw_status_families(model)) source_specs = Tuple(raw_specs) # Capture one declaration result per application. Invalid authoring does # not hide later valid applications from a read-only diagnostic report. @@ -925,7 +927,11 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs) recipes = Tuple(record for record in authored_records if record isa AuthoredApplicationRecipe) program = _prepare_authored_scenario_program(model, recipes) - return ScenarioPreparation(model, source_specs, authored_records, failure, program, nothing) + status_manifest = _capture_authored_metadata(:status_manifest, nothing) do + _prepare_status_manifest(model, authored_records, program, raw_families) + end + return ScenarioPreparation(model, source_specs, authored_records, failure, + program, status_manifest, nothing) end function _model_owned_scenario_preparation(model::CompositeModel, preparation::ScenarioPreparation) @@ -933,7 +939,8 @@ function _model_owned_scenario_preparation(model::CompositeModel, preparation::S # Internal reconstruction can share authored metadata, never the mutable # resolved target snapshot. This check is O(1) on lifecycle invalidation. owned = ScenarioPreparation(model, preparation.source_specs, - preparation.authored, preparation.failure, preparation.program, nothing) + preparation.authored, preparation.failure, preparation.program, + preparation.status_manifest, nothing) model.scenario_plan_cache = owned return owned end @@ -971,14 +978,38 @@ function _scenario_preparation(model::CompositeModel; force::Bool=false) preparation = model.scenario_plan_cache if force || isnothing(preparation) || !_authored_specs_match(preparation, model) - preparation = _prepare_authored_scenario(model, model.applications) - model.scenario_plan_cache = preparation + candidate = _prepare_authored_scenario(model, model.applications) + if !isnothing(candidate.failure) || candidate.status_manifest isa ScenarioPreparationFailure + # Keep captured authoring failures authoritative, as before. A later + # run must not silently fall back to an older compiled preparation. + model.scenario_plan_cache = candidate + return candidate + end + registry = try + _registry_with_prepared_status_manifest(model, candidate.status_manifest) + catch error + error isa ArgumentError || rethrow() + failure = ScenarioPreparationFailure(:status_manifest, nothing, error, catch_backtrace()) + rejected = ScenarioPreparation(model, candidate.source_specs, + candidate.authored, candidate.failure, candidate.program, failure, nothing) + # Only the captured diagnostic becomes authoritative. The registry, + # scientific headers and compiled caches remain exactly unchanged. + model.scenario_plan_cache = rejected + return rejected + end + # Validation and all potentially failing construction finished first. + # These two assignments invoke no user code and preserve every header, + # row, identity index and source reservation. + model.registry = registry + model.scenario_plan_cache = candidate + preparation = candidate end return _model_owned_scenario_preparation(model, preparation) end function _validate_authored_scenario(preparation::ScenarioPreparation) isnothing(preparation.failure) || throw(preparation.failure.error) + _authored_metadata_value(preparation.status_manifest) return nothing end @@ -2068,6 +2099,10 @@ function _refresh_bindings!( input_binding_storage=nothing, status_view_schema=nothing, ) + if force && !(model.registry.objects.catalog isa ClosedObjectFamilyCatalog) + throw(ArgumentError("This model has no prepared canonical Status registry. " * + "Fix the authoring declarations and construct a new CompositeModel.")) + end if specs !== model.applications raw_specs = specs isa Tuple ? specs : specs isa AbstractVector ? Tuple(specs) : (specs,) return _compile_scene(model, raw_specs; performance, input_binding_storage, status_view_schema) @@ -3722,11 +3757,14 @@ end C = fieldtype(CV, :canonical_status) edited_types = Tuple{private_types..., (fieldtype(TI, :reference) for TI in fieldtypes(CT))...} edited_names = (private_names..., current_names...) - construction = StatusConstructionRecipe(_status_schema_names(C), edited_names) - selected = map(construction.actions) do action - _selected_status_reference_type(action, _status_schema_references(C), edited_types) - end - Result = Status{_status_schema_names(fieldtype(CV, :status)),Tuple{selected...}} + CurrentStatus = fieldtype(CV, :status) + Hot = fieldtype(fieldtype(CurrentStatus, :vars), :hot) + hot_names = fieldnames(Hot) + hot_types = map(hot_names) do name + index = findlast(isequal(name), edited_names) + isnothing(index) ? fieldtype(Hot,name) : fieldtype(edited_types,index) + end + Result = _projected_status_type(C, hot_names, Tuple{hot_types...}) factory = ExactReferenceFactory(C, edited_types, Result, edited_names) edited = Expr(:tuple, [:(getfield(private_outputs, $index)) for index in eachindex(private_names)]..., @@ -3935,6 +3973,12 @@ function _extend_temporal_many_inputs_in_place!(view::CompiledModelStatusView, return _apply_temporal_many_extensions!(staged) end +@inline function _status_view_epoch_is_current(view, model, object_id) + canonical = model_status(model, object_id) + return view.canonical_status === canonical && + _status_reference_epoch(view.status) == _status_reference_epoch(canonical) +end + function _extend_model_status_views( model::CompositeModel, compiled::CompiledCompositeModel, @@ -3970,6 +4014,15 @@ function _extend_model_status_views( end end + for (key, previous_view) in views + application_id, raw_id = key + object_id = _index_object_id(model.registry.objects, raw_id) + haskey(model.registry.objects, object_id) || continue + current = Base.@inline _with_model_status_view(_status_view_epoch_is_current, + compiled.status_view_schema, application_id, previous_view, model, object_id) + current || push!(affected_keys, (application_id, object_id)) + end + positions = Dict( application_id => index for (index, application_id) in pairs(application_order) @@ -3984,7 +4037,9 @@ function _extend_model_status_views( previous_temporal_sources, applications_by_id, positions, distributed_outputs, compiled.status_view_schema) if extended - delete!(affected_keys, key) + current = Base.@inline _with_model_status_view(_status_view_epoch_is_current, + compiled.status_view_schema, application_id, view, model, object_id) + current && delete!(affected_keys, key) end end for key in affected_keys @@ -5203,7 +5258,7 @@ function _initialization_effective_value( return true, view.status[variable] end status = _model_object(model, object_id).status - if status isa Status && variable in propertynames(status) + if status isa Status && hasproperty(status, variable) return true, status[variable] end return false, nothing @@ -6253,7 +6308,7 @@ _input_reference_name(::Val{VARIABLE}) where {VARIABLE} = VARIABLE function _status_ref_or_nothing(status::S, variable) where {S} status isa Status || return nothing name = _input_reference_name(variable) - name in propertynames(status) || return nothing + hasproperty(status, name) || return nothing return refvalue(status, name) end @@ -6265,11 +6320,35 @@ end return reference end -function _input_reference_carrier( - ::Union{One,OptionalOne}, source_ids, reference_for, ::Type{<:Tuple}, -) - isempty(source_ids) && return nothing - return _checked_input_reference(reference_for(only(source_ids))) +# Type-only projection shared by the canonical Many constructor and manifest. +function _many_input_carrier_type(::Type{RT}) where {RT<:Tuple} + types = fieldtypes(RT) + isempty(types) && throw(ArgumentError("A Many input requires a prepared reference family.")) + all(R -> R <: Base.RefValue && isconcretetype(R), types) || + throw(ArgumentError("A Many input requires exact prepared reference types.")) + R = Union{types...} + return length(types) == 1 && isconcretetype(eltype(only(types))) ? + RefVector{eltype(only(types))} : ObjectRefVector{Vector{R}} +end + +@generated function _input_reference_carrier( + ::Union{One,OptionalOne}, source_ids, reference_for::F, ::Type{RT}, +) where {F,RT<:Tuple} + types = fieldtypes(RT) + isempty(types) && return quote + isempty(source_ids) && return nothing + throw(ArgumentError("An input source is outside its empty prepared reference family.")) + end + all(R -> R <: Base.RefValue && isconcretetype(R), types) || + return :(throw(ArgumentError("An input requires exact prepared reference classes."))) + R = Union{types...} + return quote + isempty(source_ids) && return nothing + reference = _checked_input_reference(reference_for(only(source_ids))) + isnothing(reference) && return nothing + reference isa $R || throw(ArgumentError("An input source reference is outside its prepared family.")) + return reference::$R + end end @generated function _input_reference_carrier( @@ -6280,8 +6359,8 @@ end all(R -> R <: Base.RefValue && isconcretetype(R), types) || return :(throw(ArgumentError("A Many input requires exact prepared reference types."))) R = Union{types...} - homogeneous = length(types) == 1 && isconcretetype(eltype(only(types))) - result = homogeneous ? :(RefVector(references)) : :(ObjectRefVector(references)) + C = _many_input_carrier_type(RT) + result = :($C(references)) return quote references = $R[] sizehint!(references, length(source_ids) + 1) @@ -6386,44 +6465,29 @@ Sparse reference edits staged before committing one canonical object status. Unchanged fields remain in the original status. A model-owned construction recipe supplies their order when the staged edits are committed. """ -mutable struct _CanonicalStatusRecipe{S<:Union{Nothing,Status}} +mutable struct _CanonicalStatusRecipe{S<:Status} original::S + fresh::Bool edit_names::Vector{Symbol} edit_references::Vector{Ref} changed::Bool field_changes::Int end -function _CanonicalStatusRecipe(status::S) where {S<:Union{Nothing,Status}} - return _CanonicalStatusRecipe{S}( - status, - Symbol[], - Ref[], - isnothing(status), - 0, - ) +function _CanonicalStatusRecipe(status::S, fresh::Bool) where {N,T,S<:Status{N,T}} + T <: _FixedStatusStorage || throw(ArgumentError("Canonical preparation requires its prepared fixed backing.")) + return _CanonicalStatusRecipe{S}(status, fresh, Symbol[], Ref[], fresh, 0) end -# The finite catalog witnesses every original status type before sparse edits. -# Open preparation keeps the same recipe algorithm behind its ordinary JIT barrier. -_canonical_status_recipe_storage(::OpenObjectFamilyCatalog, ::Type{I}) where {I<:ObjectId} = - Dict{I,_CanonicalStatusRecipe}() - -@generated function _canonical_status_recipe_storage(::ClosedObjectFamilyCatalog{F}, - ::Type{I}, -) where {F,I<:ObjectId} - schemas = unique([Nothing; [family.parameters[2] for family in fieldtypes(F) - if family.parameters[2] <: Status]]) - R = Union{map(S -> _CanonicalStatusRecipe{S}, schemas)...} - return :(Dict{$I,$R}()) +# Both registry modes use the SAME prepared physical status schema. The registry +# may remain open to identity values; canonical layouts never reopen at runtime. +@inline function _canonical_status_recipe_storage(model::CompositeModel, ::Type{I}) where {I<:ObjectId} + return Base.@inline _with_prepared_canonical_status_type( + _canonical_status_recipe_storage_for_schema, model, I) end +_canonical_status_recipe_storage_for_schema(::Type{S}, ::Type{I}) where {S<:Status,I<:ObjectId} = + Dict{I,_CanonicalStatusRecipe{S}}() -# The existing recipe dictionary is the witness for its actual CSR instances. -@inline function _with_canonical_status_recipe(f::F, - ::AbstractDict{I,_CanonicalStatusRecipe}, recipe, args::Vararg{Any,N}, -) where {F,I,N} - return f(recipe::_CanonicalStatusRecipe, args...) -end @generated function _with_canonical_status_recipe(f::F, ::AbstractDict{I,R}, recipe, args::Vararg{Any,N}, ) where {F,I,R,N} @@ -6449,7 +6513,7 @@ end @inline function _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) variable in recipe.edit_names && return true - return !isnothing(recipe.original) && variable in propertynames(recipe.original) + return _initial_status_reference(recipe.original, variable) !== nothing end function _status_recipe_reference( @@ -6462,9 +6526,9 @@ end function _status_recipe_reference(original, edit_names, edit_references, variable::Symbol) position = findfirst(isequal(variable), edit_names) isnothing(position) || return edit_references[position] - isnothing(original) && throw(KeyError(variable)) - variable in propertynames(original) || throw(KeyError(variable)) - return refvalue(original, variable) + reference = _initial_status_reference(original, variable) + reference === nothing && throw(KeyError(variable)) + return reference end function _status_recipe_set_reference!( @@ -6472,10 +6536,11 @@ function _status_recipe_set_reference!( variable::Symbol, reference::Ref, ) + _validate_status_reference(recipe.original, variable, reference) position = findfirst(isequal(variable), recipe.edit_names) if isnothing(position) original = recipe.original - if !isnothing(original) && variable in propertynames(original) && + if hasproperty(original, variable) && refvalue(original, variable) === reference return false end @@ -6514,84 +6579,33 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end -# Open canonical construction discovers the reference layout in the same cache. -function _finish_canonical_status_recipe(f::Callback, ::OpenObjectFamilyCatalog, - cache, recipe::_CanonicalStatusRecipe, -) where {Callback} - recipe.changed || return f(recipe.original) - original = recipe.original - existing_names = isnothing(original) ? () : propertynames(original) - existing_references = isnothing(original) ? () : refvalues(original) - construction = _status_construction_recipe!( - cache, - existing_names, - Tuple(recipe.edit_names), - ) - return f(_construct_status(construction, existing_references, Tuple(recipe.edit_references))) -end - -function _finish_canonical_status_recipe(f::Callback, model::CompositeModel, - recipe::_CanonicalStatusRecipe, -) where {Callback} - return Base.@inline _finish_canonical_status_recipe(f, model.registry.objects.catalog, - model.registry.objects.layout_cache, recipe) -end - -function _finish_canonical_status_recipe(f::Callback, catalog::ClosedObjectFamilyCatalog, - cache, recipe::_CanonicalStatusRecipe, -) where {Callback} - return _with_registered_status(catalog, recipe.original) do original - recipe.changed || return f(original) - _finish_admitted_status_recipe(f, catalog, original, recipe.edit_names, recipe.edit_references) - end -end - -# Canonical order is the original fields followed by genuinely new fields in -# edit order. Replacements do not move an existing field. -function _status_edit_schema_matches(edit_names, original_names::Tuple, result_names::Tuple) - length(result_names) >= length(original_names) || return false - for index in eachindex(original_names) - result_names[index] === original_names[index] || return false - end - next = length(original_names) + 1 - for name in edit_names - name in original_names && continue - next <= length(result_names) && name === result_names[next] || return false - next += 1 - end - return next == length(result_names) + 1 -end - -# Select and consume actual references in the exact branch. Result schema -# alternatives never escape as a large union before registration/view creation. -@generated function _finish_admitted_status_recipe(f::Callback, ::ClosedObjectFamilyCatalog{F}, original::S, edit_names, edit_references) where {Callback,F,S} - original_names = _status_schema_names(S) - results = unique(family.parameters[2] for family in fieldtypes(F) if family.parameters[2] <: Status) - branches = Expr[] - for Result in results - names = _status_schema_names(Result) - length(names) >= length(original_names) && names[1:length(original_names)] == original_names || continue - Refs = _status_schema_references(Result) - all(isconcretetype, fieldtypes(Refs)) || continue - factory = ExactReferenceFactory(S, Refs, Result, names) - refs = [gensym(:reference) for _ in names] - reads = [:($(refs[index]) = _status_recipe_reference(original, edit_names, edit_references, $(QuoteNode(name)))) - for (index,name) in enumerate(names)] - checks = [:( $(refs[index]) isa $(fieldtype(Refs,index)) ) for index in eachindex(names)] - matches = isempty(checks) ? true : reduce((left,right)->:($left && $right), checks) - typed = Expr(:tuple, [:( $(refs[index])::$(fieldtype(Refs,index)) ) for index in eachindex(names)]...) - push!(branches, quote - if _status_edit_schema_matches(edit_names, $(QuoteNode(original_names)), $(QuoteNode(names))) - $(reads...) - if $matches - return f(_construct_status($(QuoteNode(factory)), original, $typed)) - end - end - end) - end +# One prepared physical schema handles every presence pattern. Slot construction +# validates ALL edits before its single metadata assignment; no runtime type/name +# discovery, terminal-layout enumeration or alternate Open algorithm remains. +@generated function _finish_canonical_status_recipe(f::F, + recipe::_CanonicalStatusRecipe{S}, +) where {F,N,R,T,S<:Status{N,_FixedStatusStorage{N,R,T}}} + cells = [gensym(:cell) for _ in N] + reads = [quote + position = findfirst(isequal($(QuoteNode(name))), recipe.edit_names) + $(cells[i]) = isnothing(position) ? + getfield(_status_vars(recipe.original).refs, $i) : recipe.edit_references[position] + $(cells[i]) isa $(fieldtype(T,i)) || throw(ArgumentError("Staged reference is outside its prepared slot family.")) + end for (i,name) in enumerate(N)] + values = Expr(:tuple, [:( $(cells[i])::$(fieldtype(T,i)) ) for i in eachindex(N)]...) return quote - $(branches...) - throw(ArgumentError("The constructed reference schema is outside the prepared object family catalog.")) + recipe.changed || return f(recipe.original) + for name in recipe.edit_names + name in $(QuoteNode(N)) || throw(KeyError(name)) + end + $(reads...) + storage = _status_vars(recipe.original) + references = $T($values) + if references !== storage.refs + storage.refs = references + storage.reference_epoch += UInt(1) + end + return f(recipe.original) end end @@ -6608,19 +6622,28 @@ function _model_object_status_for_preparation( end function _status_recipe_for_object!( - recipes::AbstractDict{I,R}, - recipe_order::AbstractVector{I}, - model::CompositeModel, - object_id::ObjectId, + recipes::AbstractDict{I,R}, recipe_order::AbstractVector{I}, + model::CompositeModel, raw_id::ObjectId, ) where {I<:ObjectId,R<:_CanonicalStatusRecipe} - object_id = _index_object_id(recipes, object_id) - return get!(recipes, object_id) do - status = _model_object_status_for_preparation(model, object_id) - Base.@inline _with_registered_status(model.registry.objects.catalog, status) do original - push!(recipe_order, object_id) - _CanonicalStatusRecipe(original) - end + object_id = _index_object_id(recipes, raw_id) + existing = get(recipes, object_id, nothing) + isnothing(existing) || return existing + original = _model_object_status_for_preparation(model, object_id) + return Base.@inline _with_prepared_canonical_status_type( + _create_status_recipe_for_object!, model, original, recipes, recipe_order, object_id) +end + +function _create_status_recipe_for_object!(::Type{S}, original, recipes, order, object_id) where {S<:Status} + fresh = isnothing(original) + if fresh + original = Base.@inline _new_prepared_status(S, nothing) + else + original isa S || throw(ArgumentError("Register canonical data in the prepared status schema before execution.")) end + recipe = _CanonicalStatusRecipe(original::S, fresh) + push!(order, object_id) + recipes[object_id] = recipe + return recipe end function _status_preparation_for_object!( @@ -6645,10 +6668,17 @@ function _apply_status_recipes!( recipe_order::AbstractVector{I}; performance=nothing, ) where {I<:ObjectId,R<:_CanonicalStatusRecipe} + # Admission of the whole transaction precedes publication of any owner. + for object_id in recipe_order + recipe = recipes[object_id] + recipe.changed || continue + Base.@inline _with_canonical_status_recipe(_validate_status_recipe_configuration!, + recipes, recipe, model, object_id) + end for object_id in recipe_order recipe = recipes[object_id] recipe.changed || continue - _finish_canonical_status_recipe(model, recipe) do status + _finish_canonical_status_recipe(recipe) do status _replace_model_object_status!(model, object_id, status) end _runtime_performance_count!( @@ -6664,7 +6694,7 @@ function _apply_status_recipes!( performance, :lifecycle_binding_refresh_status_recipe_materializations_avoided, max( - recipe.field_changes - (isnothing(recipe.original) ? 0 : 1), + recipe.field_changes - (recipe.fresh ? 0 : 1), 0, ), ) @@ -6672,10 +6702,17 @@ function _apply_status_recipes!( return model end +@inline function _validate_status_recipe_configuration!(recipe, model, object_id) + return _validate_prepared_status_recipe(model, object_id, recipe) +end + function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId) object = _model_object(model, object_id) status = object.status - isnothing(status) && (status = _replace_model_object_status!(model, object, Status())) + if isnothing(status) + return Base.@inline _with_prepared_canonical_status_type( + _ensure_prepared_model_object_status!, model, model, object) + end status isa Status || error( "Model object `$(object_id.value)` uses model applications but its status has type ", "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." @@ -6683,6 +6720,11 @@ function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId return Base.@inline _with_registered_status(identity, model.registry.objects.catalog, status) end +function _ensure_prepared_model_object_status!(::Type{S}, model, object) where {S<:Status} + status = Base.@inline _new_prepared_status(S, nothing) + return _replace_model_object_status!(model, object, status) +end + _stage_model_output_defaults!(preparation, ::Tuple{}, ::Tuple{}, context) = nothing function _stage_model_output_defaults!( @@ -6695,7 +6737,7 @@ function _stage_model_output_defaults!( value = first(defaults) if _publish_mode_for_output(context.application.spec, variable) == :canonical if preparation isa Status - if !(variable in propertynames(preparation)) + if !(hasproperty(preparation, variable)) recipe = _status_recipe_for_object!( context.recipes, context.recipe_order, @@ -6733,7 +6775,7 @@ function _prepare_model_output_statuses!( ) isempty(applications) && return model I = keytype(model.registry.objects) - recipes = _canonical_status_recipe_storage(model.registry.objects.catalog, I) + recipes = _canonical_status_recipe_storage(model, I) recipe_order = I[] record_conversions = !_no_status_conversion(model.status_conversion) conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records @@ -6844,7 +6886,7 @@ function _prepare_model_output_destination_statuses!( resolved_destinations, ) I = keytype(model.registry.objects) - recipes = _canonical_status_recipe_storage(model.registry.objects.catalog, I) + recipes = _canonical_status_recipe_storage(model, I) recipe_order = I[] records_before = copy(model.status_conversion_records) try @@ -6860,7 +6902,7 @@ function _prepare_model_output_destination_statuses!( declaration isa Default || continue variable = Symbol(variable_) if preparation isa Status - variable in propertynames(preparation) && continue + hasproperty(preparation, variable) && continue preparation = _status_recipe_for_object!( recipes, recipe_order, @@ -6880,12 +6922,12 @@ function _prepare_model_output_destination_statuses!( end end end + return _apply_status_recipes!(model, recipes, recipe_order) catch empty!(model.status_conversion_records) merge!(model.status_conversion_records, records_before) rethrow() end - return _apply_status_recipes!(model, recipes, recipe_order) end function _model_output_destination_columns( @@ -7448,7 +7490,7 @@ function _stage_model_input_defaults!(preparation, variables::Tuple, ) where {V} variable, value = first(variables), first(defaults) if preparation isa Status - if !(variable in propertynames(preparation)) + if !(hasproperty(preparation, variable)) recipe = _status_recipe_for_object!(context.recipes, context.recipe_order, context.model, context.object_id) return _with_canonical_status_recipe(_stage_model_input_defaults!, @@ -7521,7 +7563,7 @@ function _stage_admitted_model_input_reference!(preparation, reference, binding, context, ) if preparation isa Status - if binding.input in propertynames(preparation) && + if hasproperty(preparation, binding.input) && refvalue(preparation, binding.input) === reference context.default_status_updates[(binding.consumer_id, binding.input)] = false return nothing @@ -7553,7 +7595,7 @@ function _prepare_model_input_statuses_batched!( performance=nothing, ) I = keytype(model.registry.objects) - recipes = _canonical_status_recipe_storage(model.registry.objects.catalog, I) + recipes = _canonical_status_recipe_storage(model, I) recipe_order = I[] record_conversions = !_no_status_conversion(model.status_conversion) conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records @@ -8129,14 +8171,17 @@ function _many_model_variant_types(producer) return ((model, ports.output_types, ports.output_element_types),) end -function _prepare_many_reference_types(model, consumer, input, selector, +function _prepare_input_reference_types(model, consumer, input, selector, source_var, producer_ids, applications_by_id, distributed_output_plans) references = Any[] add(R) = R in references || push!(references, R) declared_input = _configured_status_value_type(model.status_conversion, getproperty(_application_ports(consumer).input_types, input), nothing) - fallback = !isnothing(declared_input) && declared_input <: AbstractVector ? - eltype(declared_input) : Union{} + fallback = if selector isa Many + !isnothing(declared_input) && declared_input <: AbstractVector ? eltype(declared_input) : Union{} + else + isnothing(declared_input) ? Union{} : declared_input + end isconcretetype(fallback) || (fallback = Union{}) producers = isempty(producer_ids) ? (nothing,) : producer_ids for producer_id in producers @@ -8175,7 +8220,9 @@ function _prepare_many_reference_types(model, consumer, input, selector, # Real current cells need no conversion. A concrete declared future # family is still admissible even when every current source has a cell. current_complete = !isempty(current) && isempty(missing_current) - T = if isnothing(producer) || !isnothing(model.status_conversion.transform) + # The producer declaration chooses a prospective storage family; + # actual transformed source references are still admitted by RT. + T = if isnothing(producer) fallback else _configured_status_value_type(model.status_conversion, @@ -8185,10 +8232,12 @@ function _prepare_many_reference_types(model, consumer, input, selector, if isempty(candidates) || !all(isconcretetype, candidates) candidates = fallback === Union{} ? () : (fallback,) end - # A transform or abstract Required may leave the prospective type - # unknown. Existing complete references remain valid evidence. + # An abstract Required may leave the prospective family unknown. + # Existing complete references remain valid evidence; no transform + # is called here to manufacture an additional type witness. if isempty(candidates) - (current_complete || (isnothing(producer) && observed_any)) && continue + (current_complete || (isnothing(producer) && observed_any) || + (selector isa OptionalOne && isempty(current))) && continue end isempty(candidates) && throw(ArgumentError( "Many input `$(input)` on application `$(consumer.id)` has no concrete " * @@ -8201,7 +8250,8 @@ function _prepare_many_reference_types(model, consumer, input, selector, end end end - isempty(references) && throw(ArgumentError("A Many input has no prepared reference family.")) + isempty(references) && !(selector isa OptionalOne) && + throw(ArgumentError("An input has no prepared reference family.")) # Julia canonicalizes the union; its members give deterministic witness order. return Tuple{Base.uniontypes(Union{references...})...} end @@ -8282,9 +8332,9 @@ Base.@nospecializeinfer function _compiled_model_input_plan( potential_source_application_ids, breaks_same_step_cycle, _selector_window(selector), - selector isa Many ? _prepare_many_reference_types(model, application, - input, selector, source_var, potential_source_application_ids, - applications_by_id, distributed_output_plans) : Tuple{}, + _prepare_input_reference_types(model, application, input, selector, + source_var, potential_source_application_ids, + applications_by_id, distributed_output_plans), ) end diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 749b016c7..fbe56ce8b 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -675,7 +675,7 @@ function _execution_batch_type_with_call_schemas(::Type{B}, schemas::NamedTuple) I = fieldtype(prepared_target,:object_id) Store = fieldtype(fieldtype(B, :targets), :store) Owner = _execution_store_owner_type(Store) - Rows = ExecutionCohortRows{prepared_target,ExecutionCohort{prepared_target,I,Owner},Store} + Rows = ExecutionCohortRows{prepared_target,I,Owner,Store} return CompiledExecutionBatch{fieldtype(B,:application),Rows, fieldtype(B,:environment_provider),fieldtype(B,:output_publication)} end diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 82281cce4..54c9dd1a2 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -84,14 +84,14 @@ _execution_store_object_id(::ExecutionCohortStore{I}, object_id) where {I} = Obj @inline _execution_key_item(key::ExecutionCohortKey) = key.item """An ordered membership view over one application's concrete payload family.""" -struct ExecutionCohortRows{T,C<:ExecutionCohort{T},S<:ExecutionCohortStore} <: AbstractVector{T} +struct ExecutionCohortRows{T,I<:ObjectId,O,S<:ExecutionCohortStore} <: AbstractVector{T} store::S - cohort::C + cohort::ExecutionCohort{T,I,O} indices::Vector{Int} end -ExecutionCohortRows{T}(store::S, cohort::C, indices::Vector{Int}) where {T,C<:ExecutionCohort{T},S<:ExecutionCohortStore} = - ExecutionCohortRows{T,C,S}(store, cohort, indices) +ExecutionCohortRows{T}(store::S, cohort::ExecutionCohort{T,I,O}, indices::Vector{Int}) where {T,I<:ObjectId,O,S<:ExecutionCohortStore} = + ExecutionCohortRows{T,I,O,S}(store, cohort, indices) # The finite witness belongs to one application/owner boundary, never to the # runtime store. In particular Target -> RunContext -> RuntimeStorage does not @@ -206,7 +206,7 @@ _execution_cohort_types(::OpenExecutionCohortSchema, ::ExecutionCohortStore) = O = _execution_store_owner_type(S) ids = unique([fieldtype(Target, :object_id) for Target in targets]) locations = [ExecutionCohortLocation{ExecutionCohort{Target,fieldtype(Target,:object_id),O}} for Target in targets] - rows = [ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id),O},S} for Target in targets] + rows = [ExecutionCohortRows{Target,fieldtype(Target,:object_id),O,S} for Target in targets] I, U, L, R = Union{ids...}, Union{targets...}, Union{locations...}, Union{rows...} return :((identity=$I, target=$U, location=$L, rows=$R)) end @@ -216,7 +216,7 @@ end branches = Expr[] O = _execution_store_owner_type(S) for Target in fieldtypes(T) - R = ExecutionCohortRows{Target,ExecutionCohort{Target,fieldtype(Target,:object_id),O},S} + R = ExecutionCohortRows{Target,fieldtype(Target,:object_id),O,S} push!(branches, :(rows isa $R && return f(rows))) end return quote diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 7621380c0..8bd424978 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -20,15 +20,16 @@ end mutable struct OpenObjectFamilyCatalog families::Vector{AbstractObjectFamily} - slots::Dict{Tuple{DataType,DataType},Int} + slots::Dict{Tuple{Type,Type},Int} end OpenObjectFamilyCatalog() = OpenObjectFamilyCatalog( - AbstractObjectFamily[], Dict{Tuple{DataType,DataType},Int}(), + AbstractObjectFamily[], Dict{Tuple{Type,Type},Int}(), ) -struct ClosedObjectFamilyCatalog{F<:Tuple} +struct ClosedObjectFamilyCatalog{F<:Tuple,M} families::F + status_manifest::M end # Open registration crosses the ordinary JIT function barrier. Closed @@ -54,13 +55,11 @@ struct ObjectFamilyStore{I<:ObjectId,C} <: AbstractDict{I,Object} catalog::C locations::Dict{I,ObjectFamilyLocation} status_owners::IdDict{Base.RefValue{Nothing},I} - layout_cache::Dict{Tuple{Tuple,Tuple},Any} end ObjectFamilyStore{I}() where {I<:ObjectId} = ObjectFamilyStore( OpenObjectFamilyCatalog(), Dict{I,ObjectFamilyLocation}(), IdDict{Base.RefValue{Nothing},I}(), - Dict{Tuple{Tuple,Tuple},Any}(), ) ObjectFamilyStore() = ObjectFamilyStore{ObjectId}() @@ -163,11 +162,11 @@ function _store_object_family_row!(store::ObjectFamilyStore{K}, object::Object, throw(ArgumentError("Remove the registered Object before reusing its identity for another Object.")) end _validate_object_family_status_owner!(store, status, id) - slot, family = _object_family_for_write!(store.catalog, I, S) + slot, family = _object_family_for_write!(store.catalog, K, S) if !isnothing(previous) _forget_object_family_status!(store, _object_family_status_at(store.catalog, previous), id) end - entry = ObjectFamilyRow(id, status) + entry = ObjectFamilyRow{K,S}(id, status) row = if !isnothing(previous) && previous.family == slot family.rows[previous.row] = entry previous.row @@ -202,30 +201,28 @@ end function Base.empty!(store::ObjectFamilyStore) empty!(store.locations) empty!(store.status_owners) - empty!(store.layout_cache) for family in store.catalog.families empty!(family.rows) end return store end -"""Close active families of a private model before execution; replace its old store.""" -function _closed_object_family_store(store::ObjectFamilyStore) - # Preparation may have replaced an object's status several times. Empty - # historical schemas are not promises about future newborn construction. - slots = sort!(unique([location.family for location in values(store.locations)])) - families = Tuple(store.catalog.families[slot] for slot in slots) - id_types = unique([typeof(family).parameters[1] for family in families]) - isempty(id_types) && throw(ArgumentError("A closed object family store requires an identity schema.")) - I = Union{id_types...} - closed_slots = Dict(slot => index for (index, slot) in enumerate(slots)) - locations = Dict{I,ObjectFamilyLocation}( - id => ObjectFamilyLocation(closed_slots[location.family], location.row, location.object) - for (id, location) in store.locations - ) - return ObjectFamilyStore( - ClosedObjectFamilyCatalog(families), locations, - IdDict{Base.RefValue{Nothing},I}(store.status_owners), - copy(store.layout_cache), - ) +"""Freeze the real ID domain of an already prepared private registry.""" +function _closed_object_family_store(store::ObjectFamilyStore{K,<:ClosedObjectFamilyCatalog}) where {K} + # Retain every known prepared family even after all its rows are removed. + # Ordinary registries admit arbitrary ObjectId value types; explicit private + # closure narrows only that ID domain, never discovers another Status layout. + K !== ObjectId && return store + I = isempty(store) ? K : Union{unique(typeof(id) for id in keys(store))...} + manifest = store.catalog.status_manifest + S = manifest.status_type + families = (ObjectFamily{I,Nothing}(Union{Nothing,ObjectFamilyRow{I,Nothing}}[]), + ObjectFamily{I,S}(Union{Nothing,ObjectFamilyRow{I,S}}[])) + closed = ObjectFamilyStore(ClosedObjectFamilyCatalog(families, manifest), + Dict{I,ObjectFamilyLocation}(), IdDict{Base.RefValue{Nothing},I}()) + for (id, object) in store + status = _object_family_status(store, id)::Union{Nothing,S} + _store_object_family_row!(closed, object, id, status) + end + return closed end diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl new file mode 100644 index 000000000..c26affb39 --- /dev/null +++ b/src/composite_model/prepared_status_manifest.jl @@ -0,0 +1,464 @@ +# One constructor-owned manifest. This stores names, exact reference classes, +# configured selector owners and raw-family correlations, never default values. +struct PreparedStatusManifest{S,A,P,D,R} + status_type::Type{S} + authored::A + permissions::P + destinations::D + raw_families::R +end + +# One typed view of the SAME authored specification and ports. Environment +# hint result types and call plans are irrelevant to status permissions. +struct PreparedStatusApplication{S,M,P} + slot::Int + id::Symbol + spec::S + target_matcher::M + ports::P +end +_application_ports(application::PreparedStatusApplication) = application.ports + +function _prepared_raw_status_families(model) + catalog = model.registry.objects.catalog + return catalog isa ClosedObjectFamilyCatalog && catalog.status_manifest isa PreparedStatusManifest ? + catalog.status_manifest.raw_families : nothing +end + +_prepared_status_variant_slot(application, object_id) = begin + owner = _application_model_overrides(application) + isnothing(owner) ? 1 : get(owner.object_slots, object_id, 1) +end + +function _prepared_status_type_map(names, types) + return _authored_port_types(identity, NamedTuple{Tuple(names)}(Tuple(types))) +end + +function _prepared_status_add_type!(names, types, name::Symbol, R) + R === Union{} && return nothing + all(T -> T <: Ref && isconcretetype(T), Base.uniontypes(R)) || + throw(ArgumentError("A prepared status field needs exact reference classes.")) + index = findfirst(isequal(name), names) + if isnothing(index) + push!(names, name); push!(types, R) + else + types[index] = Union{types[index],R} + end + return nothing +end + +# Choose the declared numerical storage family without evaluating callbacks. +# This does not predict an arbitrary transform: its actual result is materialized +# once by the existing worker, then admitted before any canonical publication. +function _prepared_status_declared_reference(policy, T, elements) + configured = _configured_status_value_type(policy, T, elements) + isnothing(configured) && return Union{} + members = Base.uniontypes(configured) + all(isconcretetype, members) || return Union{} + return Union{map(T -> Base.RefValue{T}, members)...} +end + +function _prepared_status_variant_permission(model, application, ports) + names = Symbol[]; refs = Any[] + output_names = Symbol[]; output_refs = Any[] + for name in keys(ports.output_types) + R = _prepared_status_declared_reference(model.status_conversion, + getproperty(ports.output_types, name), get(ports.output_element_types, name, nothing)) + _prepared_status_add_type!(output_names, output_refs, name, R) + name in _model_canonical_output_names(application) || continue + _prepared_status_add_type!(names, refs, name, R) + end + for name in ports.input_names + R = _prepared_status_declared_reference(model.status_conversion, + getproperty(ports.input_types, name), get(ports.input_element_types, name, nothing)) + _prepared_status_add_type!(names, refs, name, R) + end + return (canonical=_prepared_status_type_map(names, refs), + outputs=_prepared_status_type_map(output_names, output_refs)) +end + +# Project the SAME prepared source-reference family used by the runtime carrier +# constructor. A seed Vector value is not a RefVector carrier. +function _prepared_status_input_reference(plan) + refs = fieldtypes(plan.reference_types) + isempty(refs) && return Union{} + if !(plan.selector isa Many) + return Union{refs...} + end + return Base.RefValue{_many_input_carrier_type(plan.reference_types)} +end + +function _prepared_status_application_permissions(model, recipes, program) + return map(recipes) do application + variants = Any[] + _foreach_application_variant(application) do _, ports + push!(variants, _prepared_status_variant_permission(model, application, ports)) + end + plans = Tuple(plan for plan in program.input_records + if plan isa CompiledModelInputPlan && plan.application_slot == application.slot) + # Plan reference classes are common route evidence. Effective model + # default classes above stay in their individual configured variant. + alias_names = Symbol[]; alias_refs = Any[] + for plan in plans + _prepared_status_add_type!(alias_names, alias_refs, + plan.input, _prepared_status_input_reference(plan)) + end + aliases = _prepared_status_type_map(alias_names, alias_refs) + (slot=application.slot, id=application.id, variants=Tuple(variants), aliases=aliases) + end +end + +function _prepared_status_raw_signature(model, object, recipes, destinations) + selected = Tuple((application.slot, _prepared_status_variant_slot(application, object.id)) + for application in recipes + if _prepared_status_application_matches(model, object, object.parent, application)) + routes = Any[] + for plan in destinations + application = only(a for a in recipes if a.slot == plan.application_slot) + for (execution_id, producer) in model.registry.objects + _prepared_status_application_matches(model, producer, producer.parent, application) || continue + _prepared_status_destination_matches(model, object, object.parent, + application, plan, execution_id) || continue + push!(routes, (plan.slot, execution_id, + _prepared_status_variant_slot(application, execution_id))) + end + end + labels = _prepared_status_object_labels(model, object, object.parent) + return (labels=(labels.scale, labels.kind, labels.species), + selected=selected, destinations=Tuple(routes)) +end + +function _prepare_status_manifest(model, authored, program, raw_basis) + recipes = Tuple(item for item in authored if item isa AuthoredApplicationRecipe) + permissions = _prepared_status_application_permissions(model, recipes, program) + outputs = _authored_distributed_output_plans( + _graph_record_vector(AuthoredApplicationRecipe, recipes), program.output_records) + destinations = outputs isa NoCompiledDistributedOutputPlans ? () : Tuple(outputs.plans) + names = Symbol[]; refs = Any[] + # Stable authoring order, captured once; physical absence never creates data. + for application in recipes + ports = _application_ports(application) + for name in (keys(ports.output_types)..., ports.input_names...) + name in names || (push!(names, name); push!(refs, Union{})) + end + end + raw = if isnothing(raw_basis) + observed = Any[] + for object in values(model.registry.objects) + source = object.status + source isa Status || continue + raw_names = propertynames(source) + raw_refs = Tuple(typeof(refvalue(source, name)) for name in raw_names) + signature = _prepared_status_raw_signature(model, object, recipes, destinations) + entry = (signature=signature, + schema=_prepared_status_type_map(raw_names, raw_refs)) + entry in observed || push!(observed, entry) + end + Tuple(observed) + else + # A force refresh must not promote materialized defaults or aliases to + # new RAW permissions. Preserve the genuine constructor-owned evidence. + raw_basis + end + for family in raw, (name, R) in pairs(family.schema) + _prepared_status_add_type!(names, refs, name, R) + end + for permission in permissions + for variant in permission.variants, (name, R) in pairs(variant.canonical) + _prepared_status_add_type!(names, refs, name, R) + end + for (name, R) in pairs(permission.aliases) + _prepared_status_add_type!(names, refs, name, R) + end + end + # Distributed default types use the corresponding producer variant owner. + # They enter the global storage bound even before any destination exists. + for plan in destinations + application = only(a for a in recipes if a.slot == plan.application_slot) + _foreach_application_variant(application) do _, ports + for name in plan.variable_names + R = _prepared_status_declared_reference(model.status_conversion, + getproperty(ports.output_types, name), get(ports.output_element_types, name, nothing)) + _prepared_status_add_type!(names, refs, name, R) + end + end + end + for application in recipes + ports = _application_ports(application) + for name in keys(ports.output_types) + _publish_mode_for_output(application.spec, name) === :canonical || continue + index = findfirst(isequal(name), names) + refs[index] === Union{} && throw(ArgumentError( + "Canonical field `$(name)` has no exact prospective or actual reference family. " * + "Prepare a concrete numeric configuration; arbitrary transforms and abstract Required declarations cannot supply a type witness.")) + end + end + for (application, permission) in zip(recipes, permissions) + for (variant_slot, variant) in pairs(permission.variants) + for name in _application_ports(application).input_names + hasproperty(variant.canonical, name) && continue + hasproperty(permission.aliases, name) && continue + actual = any(raw) do family + any(entry -> entry == (application.slot, variant_slot), + family.signature.selected) && hasproperty(family.schema, name) + end + actual && continue + throw(ArgumentError( + "Input field `$(name)` has no exact prospective, route or actual reference family " * + "for this application variant. Declare a concrete Required type, producer or configured initial-data family.")) + end + end + end + # Bottom is useful while accumulating absent type evidence, but Julia + # cannot encode it as a tuple field. Nothing is the physical absence marker; + # no biological Ref is created for that slot. + physical_refs = map(R -> R === Union{} ? Nothing : R, refs) + S = _fixed_status_type(Tuple(names), Tuple{physical_refs...}) + applications = map(recipes) do application + PreparedStatusApplication(application.slot, application.id, application.spec, + application.target_matcher, application.ports) + end + return PreparedStatusManifest(S, applications, permissions, destinations, raw) +end + +# The catalog references the SAME prepared manifest; runtime never finds a +# DataType through CompositeModel.scenario_plan_cache::Any. +_prepared_status_manifest(model) = _prepared_status_manifest(model.registry.objects.catalog) +_prepared_status_manifest(catalog::ClosedObjectFamilyCatalog) = catalog.status_manifest + +@inline function _with_prepared_canonical_status_type(f::F, model::CompositeModel, + args::Vararg{Any,N}) where {F,N} + return _with_prepared_canonical_status_type(f, model.registry.objects.catalog, args...) +end +@generated function _with_prepared_canonical_status_type(f::OP, + catalog::ClosedObjectFamilyCatalog{F}, args::Vararg{Any,N}) where {OP,F,N} + schemas = unique(S for family in fieldtypes(F) for S in (family.parameters[2],) + if S <: Status && fieldtype(S, :vars) <: _FixedStatusStorage) + length(schemas) == 1 || return :(throw(ArgumentError("The catalog needs exactly one prepared canonical Status type."))) + S = only(schemas) + return quote + $(Expr(:meta, :inline)) + return f($S, args...) + end +end + +# Runtime admission is Boolean over the EXISTING typed metadata. It never +# assembles a runtime NamedTuple schema, a type, or a membership-sized tuple. +@generated function _prepared_status_reference_allowed(schema::NamedTuple{Names,T}, + name::Symbol, reference) where {Names,T} + checks = Expr[] + for index in eachindex(Names) + R = fieldtype(T, index).parameters[1] + push!(checks, :(name === $(QuoteNode(Names[index])) && reference isa $R && return true)) + end + return quote + $(checks...) + return false + end +end +_prepared_status_variant_reference_allowed(variant, name, reference) = + _prepared_status_reference_allowed(variant.canonical, name, reference) +_prepared_status_output_reference_allowed(variant, name, reference) = + _prepared_status_reference_allowed(variant.outputs, name, reference) + +_prepared_status_application_reference_allowed(::Tuple{}, ::Tuple{}, model, + object, parent_id, name, reference) = false +function _prepared_status_application_reference_allowed(applications::Tuple, + permissions::Tuple, model, object, parent_id, name, reference) + application, permission = first(applications), first(permissions) + if _prepared_status_application_matches(model, object, parent_id, application) + variant = _prepared_status_variant_slot(application, object.id) + _with_metadata_entry(_prepared_status_variant_reference_allowed, + permission.variants, variant, name, reference) && return true + _prepared_status_reference_allowed(permission.aliases, name, reference) && return true + end + return _prepared_status_application_reference_allowed(Base.tail(applications), + Base.tail(permissions), model, object, parent_id, name, reference) +end + +_prepared_status_destination_reference_allowed(::Tuple{}, ::Tuple{}, plan, + model, object, parent_id, name, reference) = false +function _prepared_status_destination_reference_allowed(applications::Tuple, + permissions::Tuple, plan, model, object, parent_id, name, reference) + application, permission = first(applications), first(permissions) + if application.slot == plan.application_slot && name in plan.variable_names + # Visit registered producer identities in place. No candidate vector or + # synthetic producer is allocated by this admission path. + has_producer = false + for (execution_id, producer) in model.registry.objects + _prepared_status_application_matches(model, producer, producer.parent, application) || continue + has_producer = true + _prepared_status_destination_matches(model, object, parent_id, + application, plan, execution_id) || continue + variant = _prepared_status_variant_slot(application, execution_id) + _with_metadata_entry(_prepared_status_output_reference_allowed, + permission.variants, variant, name, reference) && return true + end + # Explicit SceneScope without a relation is independent of a producer + # context. With zero real producers, its base declaration already gives + # a prospective permission; no RAW family or override is substituted. + matcher = plan.matcher + if !has_producer && matcher.scope isa SceneScope && isnothing(matcher.relation) + topology = _prepared_status_topology(model, object, parent_id) + if _selector_matches_object_id(topology, matcher, object.id, + nothing, false, nothing, false) + return _prepared_status_output_reference_allowed( + first(permission.variants), name, reference) + end + end + return false + end + return _prepared_status_destination_reference_allowed(Base.tail(applications), + Base.tail(permissions), plan, model, object, parent_id, name, reference) +end +_prepared_status_destinations_allow(::Tuple{}, manifest, model, object, parent_id, name, reference) = false +function _prepared_status_destinations_allow(plans::Tuple, manifest, model, object, parent_id, name, reference) + _prepared_status_destination_reference_allowed(manifest.authored, manifest.permissions, + first(plans), model, object, parent_id, name, reference) && return true + return _prepared_status_destinations_allow(Base.tail(plans), manifest, + model, object, parent_id, name, reference) +end +function _prepared_status_configured_reference_allowed(manifest, model, object, parent_id, name, reference) + return _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, + model, object, parent_id, name, reference) || + _prepared_status_destinations_allow(manifest.destinations, manifest, + model, object, parent_id, name, reference) +end + +function _prepared_status_raw_variant(raw, slot) + for entry in raw.signature.selected + first(entry) == slot && return last(entry) + end + return 0 +end +_prepared_status_raw_membership_matches(::Tuple{}, raw, model, object, parent_id) = true +function _prepared_status_raw_membership_matches(applications::Tuple, raw, model, object, parent_id) + application = first(applications) + expected = _prepared_status_raw_variant(raw, application.slot) + matches = _prepared_status_application_matches(model, object, parent_id, application) + if matches + expected == _prepared_status_variant_slot(application, object.id) || return false + else + iszero(expected) || return false + end + return _prepared_status_raw_membership_matches(Base.tail(applications), raw, model, object, parent_id) +end +function _prepared_status_raw_has_destination(raw, plan, execution_id, variant) + for entry in raw.signature.destinations + entry[1] == plan.slot && entry[2] == execution_id && entry[3] == variant && return true + end + return false +end +_prepared_status_raw_destination_count(::Tuple{}, plan, raw, model, object, parent_id) = 0 +function _prepared_status_raw_destination_count(applications::Tuple, plan, raw, model, object, parent_id) + application = first(applications) + application.slot == plan.application_slot || return _prepared_status_raw_destination_count( + Base.tail(applications), plan, raw, model, object, parent_id) + count = 0 + for (execution_id, producer) in model.registry.objects + _prepared_status_application_matches(model, producer, producer.parent, application) || continue + _prepared_status_destination_matches(model, object, parent_id, + application, plan, execution_id) || continue + variant = _prepared_status_variant_slot(application, execution_id) + _prepared_status_raw_has_destination(raw, plan, execution_id, variant) || return -1 + count += 1 + end + return count +end +_prepared_status_raw_destination_total(::Tuple{}, manifest, raw, model, object, parent_id) = 0 +function _prepared_status_raw_destination_total(plans::Tuple, manifest, raw, model, object, parent_id) + count = _prepared_status_raw_destination_count(manifest.authored, + first(plans), raw, model, object, parent_id) + count < 0 && return -1 + rest = _prepared_status_raw_destination_total(Base.tail(plans), manifest, raw, model, object, parent_id) + return rest < 0 ? -1 : count + rest +end +function _prepared_status_raw_matches(raw, manifest, model, object, parent_id) + labels = _prepared_status_object_labels(model, object, parent_id) + raw.signature.labels == (labels.scale, labels.kind, labels.species) || return false + _prepared_status_raw_membership_matches(manifest.authored, raw, model, object, parent_id) || return false + return _prepared_status_raw_destination_total(manifest.destinations, manifest, + raw, model, object, parent_id) == length(raw.signature.destinations) +end +_prepared_status_raw_reference_allowed(::Nothing, name, reference) = false +_prepared_status_raw_reference_allowed(raw, name, reference) = + _prepared_status_reference_allowed(raw.schema, name, reference) + +# Each slot visit is emitted from the MANIFEST owner's target schema. Fixed storage has +# nullable exact Ref slots; no variable-length propertynames/ref tuple is built. +@generated function _prepared_status_source_allowed(manifest::PreparedStatusManifest{S}, + model, object, parent_id, source::Status, raw) where {S} + names = _status_schema_names(S) + checks = Expr[] + for name in names + push!(checks, quote + reference = _initial_status_reference(source, $(QuoteNode(name))) + if reference !== nothing + present += 1 + (_prepared_status_configured_reference_allowed(manifest, model, + object, parent_id, $(QuoteNode(name)), reference) || + _prepared_status_raw_reference_allowed(raw, $(QuoteNode(name)), reference)) || return false + end + end) + end + return quote + $(Expr(:meta, :inline)) + present = 0 + $(checks...) + return present == _initial_status_reference_count(source) + end +end + +_prepared_status_raw_source_allowed(::Tuple{}, manifest, model, object, source, parent_id) = false +function _prepared_status_raw_source_allowed(raws::Tuple, manifest, model, object, source, parent_id) + raw = first(raws) + if _prepared_status_raw_matches(raw, manifest, model, object, parent_id) + Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source, raw) && return true + end + return _prepared_status_raw_source_allowed(Base.tail(raws), manifest, model, object, source, parent_id) +end + +# Initial bootstrap supplies the SAME manifest explicitly before the catalog +# exists. Runtime delegates through its typed catalog; there is one gather/body. +function _validate_prepared_initial_status(manifest::PreparedStatusManifest, + model, object, source_status, parent_id) + isnothing(source_status) && return nothing + source_status isa Status || throw(ArgumentError("Prepared initial data must be Status or nothing.")) + allowed = Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source_status, nothing) + (allowed || _prepared_status_raw_source_allowed(manifest.raw_families, manifest, + model, object, source_status, parent_id)) && return nothing + throw(ArgumentError("Status reference classes are incompatible with this prepared object configuration/raw family.")) +end +function _validate_prepared_initial_status(model, object, source_status, parent_id) + return _validate_prepared_initial_status(_prepared_status_manifest(model), + model, object, source_status, parent_id) +end + +function _validate_prepared_status_recipe(model, object_id, recipe) + store = model.registry.objects + object = store[object_id] + original = recipe.original + if recipe.fresh + _initial_status_reference_count(original) == 0 && + isnothing(object.status) || + throw(ArgumentError("Fresh prepared status must start with an empty unregistered header.")) + else + object.status === original && + get(store.status_owners, _status_identity(original), nothing) == object_id || + throw(ArgumentError("A prepared recipe must retain this object's exact registered header.")) + source_identity = get(model.status_source_identities, object_id, nothing) + (isnothing(source_identity) || + get(model.status_source_owners, source_identity, nothing) == object_id) || + throw(ArgumentError("Prepared status source ownership changed.")) + end + manifest = _prepared_status_manifest(model) + # A reparent/Scope change never revokes cells already owned by this object. + # Only NEW edits need active permissions; old aliases grant no new rights. + for (name, reference) in zip(recipe.edit_names, recipe.edit_references) + _initial_status_reference(original, name) === reference && continue + _prepared_status_configured_reference_allowed(manifest, model, object, + object.parent, name, reference) || throw(ArgumentError( + "A staged status reference is incompatible with the prepared object configuration.")) + end + return nothing +end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index ebceae309..da51504bb 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -536,6 +536,7 @@ function _register_objects!( model, object; status_values_materialized=status_values_materialized, + prepared=false, ) push!(added, object) deleteat!(pending, index) @@ -586,8 +587,8 @@ function CompositeModel( type_promotion, status_transform, _status_conversion, _status_values_materialized, _status_conversion_records, ) - _scenario_preparation(model) - return model + preparation = _scenario_preparation(model) + return _install_prepared_canonical_registry(model, preparation) end # Graph-editor transactions also use this assembler, then finalize authored @@ -654,6 +655,68 @@ function _assemble_composite_model( return model end + +# Host-side candidate only: the caller publishes it together with its new +# ScenarioPreparation after every representability check has succeeded. +function _registry_with_prepared_status_manifest(model, manifest) + previous = model.registry + store = previous.objects + catalog = store.catalog + catalog isa ClosedObjectFamilyCatalog || return previous # constructor assembly + old = catalog.status_manifest + (manifest.status_type === old.status_type && typeof(manifest) === typeof(old)) || + throw(ArgumentError("This authoring refresh changes the prepared Status or typed configuration schema. " * + "Construct a new CompositeModel for this configuration.")) + replacement = ObjectFamilyStore(ClosedObjectFamilyCatalog(catalog.families, manifest), + store.locations, store.status_owners) + registry = ObjectRegistry(replacement, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + typeof(registry) === typeof(previous) || throw(ArgumentError( + "This authoring refresh needs a new registry schema. Construct a new CompositeModel.")) + return registry +end + +function _install_prepared_canonical_registry(model::CompositeModel, preparation) + manifest = preparation.status_manifest + # Authoring failures stay inspectable, but the execution validator rethrows + # them; this raw assembly is not an executable legacy fallback. + (!isnothing(preparation.failure) || manifest isa ScenarioPreparationFailure) && return model + return _install_prepared_canonical_registry(model, manifest, manifest.status_type) +end + +function _install_prepared_canonical_registry(model, manifest, ::Type{S}) where {S<:Status} + previous = model.registry + K = keytype(previous.objects) + pending = Pair{Object,Union{Nothing,S}}[] + for object in values(previous.objects) + source = object.status + _validate_prepared_initial_status(manifest, model, object, source, object.parent) + push!(pending, object => (isnothing(source) ? nothing : _new_prepared_status(S, source))) + end + families = (ObjectFamily{K,Nothing}(Union{Nothing,ObjectFamilyRow{K,Nothing}}[]), + ObjectFamily{K,S}(Union{Nothing,ObjectFamilyRow{K,S}}[])) + store = ObjectFamilyStore(ClosedObjectFamilyCatalog(families, manifest), + Dict{K,ObjectFamilyLocation}(), IdDict{Base.RefValue{Nothing},K}()) + for (object, status) in pending + _store_object_family_row!(store, object, object.id::K, status) + end + # Publish only after every source/configuration and owner check succeeded. + # A dense->fixed header gets its own token; source reservations stay exactly + # those recorded by the original one-time registration/conversion. + for (object, status) in pending + setfield!(object, :status, status) + end + registry = ObjectRegistry(store, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + fields = map(fieldnames(typeof(model))) do name + name === :registry ? registry : getfield(model, name) + end + prepared = CompositeModel(fields...) + preparation = model.scenario_plan_cache + _model_owned_scenario_preparation(prepared, preparation) + return prepared +end + """ CompositeModel(template::CompositeModelTemplate; root, objects=(), name=nothing, overrides=NamedTuple(), @@ -858,7 +921,9 @@ end id=node_id, scale=symbol, status=..., ...) Build a unified model directly from an MTG subtree. The MTG accessors are -retained and reused by [`add_organ!`](@ref) when the topology grows. +retained for labels, geometry and source identity during [`add_organ!`](@ref). +The `status(node)` accessor imports initial scientific values only; growth +receives its scientific data through `initial_status`. """ function CompositeModel( root::MultiScaleTreeGraph.Node; @@ -1147,10 +1212,13 @@ function _replace_model_object_status!( object.status === status && return status store = model.registry.objects object_id = object.id::keytype(store) - return _with_registered_status(store.catalog, status) do admitted + _validate_status_source_identity_available!(model, status, object_id) + _validate_prepared_initial_status(model, object, status, object.parent) + return Base.@inline _with_prepared_canonical_status_type(model, object, object_id, status) do S, object, object_id, source + admitted = isnothing(source) ? nothing : _new_prepared_status(S, source) _store_object_family_row!(store, object, object_id, admitted) setfield!(object, :status, admitted) - _set_status_source_identity!(model, object_id, admitted) + _set_status_source_identity!(model, object_id, source) return admitted end end @@ -1376,10 +1444,16 @@ function _instance_for_object(model::CompositeModel, id) return nothing end +@inline function _instance_object_labels(object::Object, instance) + isnothing(instance) && return (kind=object.kind, species=object.species) + return (kind=isnothing(object.kind) ? instance.template.kind : object.kind, + species=isnothing(object.species) ? instance.template.species : object.species) +end + @inline function _apply_instance_labels!(object::Object, instance) - isnothing(instance) && return object - isnothing(object.kind) && (object.kind = instance.template.kind) - isnothing(object.species) && (object.species = instance.template.species) + labels = _instance_object_labels(object, instance) + object.kind = labels.kind + object.species = labels.species return object end @@ -1388,6 +1462,7 @@ end object::Object; parent=object.parent, status_values_materialized::Bool=false, + prepared::Bool, ) registry = model.registry id = _index_object_id(registry.objects, object.id) @@ -1396,28 +1471,34 @@ end if !isnothing(parent_id) && !haskey(registry.objects, parent_id) error("No model object with id `$(parent_id.value)`.") end - return _register_object_status!(model, object, id, parent_id, object.status, status_values_materialized) + return _register_object_status!(model, object, id, parent_id, object.status, status_values_materialized, prepared) end # The same conversion and ownership operations serve both catalog forms. An # unconverted source need not be a canonical family when conversion is active. -@inline function _register_object_status!(model, object, id, parent_id, source_status, status_values_materialized) +@inline function _register_object_status!(model, object, id, parent_id, source_status, + status_values_materialized, prepared::Bool) _validate_status_source_identity_available!(model, source_status, id) - catalog = model.registry.objects.catalog - if status_values_materialized || _no_status_conversion(model.status_conversion) - return _with_registered_status(catalog, source_status) do status - _register_converted_object!(model, object, id, parent_id, status, status) - end - end conversion_records = Dict{Any,Any}() - status = _convert_registered_status(model, id, source_status; conversion_records) - registered = _with_registered_status(catalog, status) do converted + converted = status_values_materialized || _no_status_conversion(model.status_conversion) ? + source_status : _convert_registered_status(model, id, source_status; conversion_records) + registered = if prepared + Base.@inline _with_prepared_canonical_status_type(_register_prepared_object_status!, + model, model, object, id, parent_id, source_status, converted) + else _register_converted_object!(model, object, id, parent_id, source_status, converted) end merge!(model.status_conversion_records, conversion_records) return registered end +@inline function _register_prepared_object_status!(::Type{S}, model, object, id, + parent_id, source_status, converted) where {S} + _validate_prepared_initial_status(model, object, converted, parent_id) + status = isnothing(converted) ? nothing : _new_prepared_status(S, converted) + return _register_converted_object!(model, object, id, parent_id, source_status, status) +end + function _register_converted_object!(model, object, id, parent_id, source_status, status) registry = model.registry _validate_status_identity_available!(registry, status, id) @@ -1450,39 +1531,20 @@ are marked dirty and become visible to execution after the next lifecycle refresh boundary. Prefer [`add_organ!`](@ref) for MTG-backed growth. """ @inline function register_object!(model::CompositeModel, object::Object; parent=object.parent) + if !(model.registry.objects.catalog isa ClosedObjectFamilyCatalog) + _validate_authored_scenario(_scenario_preparation(model)) + throw(ArgumentError("The model has no executable prepared canonical registry.")) + end registered = _register_object_without_lifecycle!( model, object; parent=parent, + prepared=true, ) _record_added_objects!(model, (registered,)) return registered end -function _status_data!(data::Dict{Symbol,Any}, values) - values === nothing && return data - source = values isa Status ? NamedTuple(values) : values - source isa Union{NamedTuple,AbstractDict,Base.Pairs} || error( - "Initial organ status must be a `Status`, `NamedTuple`, `AbstractDict`, ", - "`Base.Pairs`, or `nothing`, got `$(typeof(values))`." - ) - for (key, value) in pairs(source) - if Symbol(key) == :plantsimengine_status - # ColumnarAttrs retains an empty column after a rejected node is - # removed. Treat that schema placeholder as absent without deleting - # the shared column; a real runtime status value remains forbidden. - isnothing(value) && continue - error( - "`plantsimengine_status` is runtime state, not an organ attribute. " * - "Pass scientific initial values through `initial_status` and resolve " * - "runtime status with `model_status`.", - ) - end - data[Symbol(key)] = value - end - return data -end - function _validate_organ_attributes(attributes) attributes isa Union{Status,NamedTuple,AbstractDict,Base.Pairs} || return attributes for key in keys(attributes) @@ -1496,46 +1558,32 @@ function _validate_organ_attributes(attributes) return attributes end -# Use a concrete name carrier at dynamic assembly sites. Constructing the -# partially specified Status{names} type for every organ allocates a UnionAll. -@inline function _organ_status_from_values(::Val{names}, values::Tuple) where {names} - return Status(NamedTuple{names}(Ref.(values))) +# MTG metadata never supplies newborn variables implicitly. A supplied Status +# retains its real references; registration admits the official prepared header. +_organ_status(status::Status) = (_validate_organ_attributes(status); status) +_organ_status(::Nothing) = Status() +function _organ_status(values::Union{NamedTuple,AbstractDict,Base.Pairs}) + _validate_organ_attributes(values) + data = values isa NamedTuple ? values : + (; (Symbol(key) => value for (key, value) in pairs(values))...) + return Status(data) end - -function _organ_status( - adapter::MTGObjectAdapter, - node, - initial_status; - use_status_adapter::Bool=true, -) - # Keep this call before reading node attributes: a status accessor may - # initialize attributes that must participate in the merged status. - adapted_status = use_status_adapter ? adapter.status(node) : nothing - data = Dict{Symbol,Any}() - _status_data!(data, MultiScaleTreeGraph.node_attributes(node)) - _status_data!(data, adapted_status) - data[:node] = node - _status_data!(data, initial_status) - data[:node] = node - status_names = Tuple(keys(data)) - status_values = Tuple(values(data)) - return _organ_status_from_values(Val(status_names), status_values) +function _organ_status(values) + throw(ArgumentError("Initial organ status must be a Status, NamedTuple, AbstractDict, Base.Pairs or nothing.")) end """ add_organ!(parent, runtime, link, symbol, scale; index=0, id, attributes=(), - initial_status=(), use_status_adapter=true, kind=nothing, + initial_status=(), kind=nothing, species=nothing, name=nothing) Create an MTG node and register its corresponding model object as one operation. `runtime` may be a [`CompositeModel`](@ref), [`RunContext`](@ref), or -[`Simulation`](@ref). The model reuses the MTG accessors and status -initializer supplied when it was constructed, then overlays `initial_status`. - -Set `use_status_adapter=false` only when the caller guarantees that the new -node's attributes and `initial_status` completely define its initial status. -In that mode the configured MTG status accessor is not called for the new -node. The `node` status field is always forced to the newly created node. +[`Simulation`](@ref). Only `initial_status` supplies scientific initial values. +MTG `attributes` remain annotations and geometry on the source node. The +initial-import `status(node)` accessor is not called during growth, and no +`node` variable is inserted. Use [`source_node`](@ref) to retrieve that node. +The model's normal status conversion and prepared-family checks still apply. This is the public growth API. [`register_object!`](@ref) remains the low-level registry operation for callers that already own a fully initialized `Object`. @@ -1550,7 +1598,6 @@ function add_organ!( id=nothing, attributes=NamedTuple(), initial_status=NamedTuple(), - use_status_adapter::Bool=true, kind=nothing, species=nothing, name=nothing, @@ -1565,6 +1612,7 @@ function add_organ!( # rejected ColumnarAttrs insertion would otherwise leave an empty schema # column visible on later nodes of the same organ symbol. _validate_organ_attributes(attributes) + status = _organ_status(initial_status) # Resolve the exact registered node before advancing ids or mutating either # the source MTG or the runtime registry. parent_id = object_id(model, parent_node) @@ -1573,11 +1621,10 @@ function add_organ!( # attribute store (store-wide for a columnar MTG) and is updated for # every explicit insertion, so the next automatic id is unique without # an O(n) tree lookup. - adapter.max_node_id[] += 1 + adapter.max_node_id[] + 1 else root = MultiScaleTreeGraph.get_root(parent_node) explicit_id = Int(id) - adapter.max_node_id[] = max(adapter.max_node_id[], explicit_id) isnothing(MultiScaleTreeGraph.get_node(root, explicit_id)) || error( "MTG node id `$(explicit_id)` already exists." ) @@ -1597,12 +1644,6 @@ function add_organ!( ) try new_object_id = _register_mtg_object_identity!(adapter, node) - status = _organ_status( - adapter, - node, - initial_status; - use_status_adapter=use_status_adapter, - ) object = Object( new_object_id; scale=adapter.scale(node), @@ -1614,6 +1655,7 @@ function add_organ!( status=status, ) registered = register_object!(model, object) + adapter.max_node_id[] = max(adapter.max_node_id[], node_id) return registered.status catch _unregister_mtg_object_identity!(adapter, node) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 7fa17f00b..fdf5ddffd 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4028,6 +4028,7 @@ function _model_execution_target_change_reason( V = typeof(target.status_view) status_view isa V || return :status_view status_view = status_view::V + _status_reference_epoch(status_view.status) == _status_reference_epoch(status_view.canonical_status) || return :status_epoch target.status_view.status === status_view.status || return :status_view target.status_view.canonical_status === status_view.canonical_status || return :canonical_status diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 981f9ef64..511c8a9c0 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -957,6 +957,9 @@ end return root_id in _object_ancestor_ids(model.registry, object_id) end +@inline _point_named_scope_root(model::CompositeModel, scope::Scope) = _named_scope_root_id(model, scope) +@inline _point_scope_root_exists(model::CompositeModel, id) = haskey(model.registry.objects, id) + @inline _point_scope_contains(topology, ::Union{Nothing,SceneScope}, origin, object) = true @inline _point_scope_contains(topology, ::Self, origin, object) = @@ -992,7 +995,7 @@ _missing_point_scope_anchor(::CompositeModel, scope::Ancestor, id) = return !isnothing(ancestor) && _relation_same_object(topology, ancestor, object) end -function _scope_contains_object(model::CompositeModel, scope, context, object_id::ObjectId) +function _scope_contains_object(model, scope, context, object_id::ObjectId) scope isa Union{Nothing,SceneScope} && return _point_scope_contains(model, scope, context, object_id) return if scope isa Self @@ -1012,14 +1015,10 @@ function _scope_contains_object(model::CompositeModel, scope, context, object_id isnothing(current_id) && error("`Ancestor(...)` selectors require a current object context.") _point_scope_contains(model, scope, current_id, object_id) elseif scope isa Scope - _object_is_in_subtree( - model, - object_id, - _named_scope_root_id(model, scope), - ) + _relation_in_subtree(model, object_id, _point_named_scope_root(model, scope)) elseif scope isa CompiledNamedScope - haskey(model.registry.objects, scope.root_id) && - _object_is_in_subtree(model, object_id, scope.root_id) + _point_scope_root_exists(model, scope.root_id) && + _relation_in_subtree(model, object_id, scope.root_id) else error( "Unsupported object scope selector `$(scope)` of type `$(typeof(scope))`.", @@ -1344,7 +1343,7 @@ function _selector_resolution_error( error(String(take!(io))) end -function _matches_object_criteria(object::Object; scale=nothing, kind=nothing, species=nothing, id=nothing) +function _matches_object_criteria(object; scale=nothing, kind=nothing, species=nothing, id=nothing) _object_matches_selector_value(object.scale, scale) || return false _object_matches_selector_value(object.kind, kind) || return false _object_matches_selector_value(object.species, species) || return false @@ -1355,7 +1354,7 @@ end _compiled_relation_symbol(::Val{RELATION}) where {RELATION} = RELATION function _selector_matches_object_id( - model::CompositeModel, + model, matcher::CompiledSelectorMatcher, object_id::ObjectId, context, @@ -1377,7 +1376,7 @@ end scale=matcher.scale, kind=matcher.kind, species=matcher.species, id=matcher.id) end -function _selector_matches_object_topology(model::CompositeModel, +function _selector_matches_object_topology(model, matcher::CompiledSelectorMatcher, object_id::ObjectId, context, default_scope, relation_resolved::Bool) scope = isnothing(matcher.scope) ? default_scope : matcher.scope @@ -1625,3 +1624,87 @@ function _default_dependency_scope(model::CompositeModel, context::ObjectId) (object.scale == :Scene || object.kind == :scene) && return SceneScope() return Self() end + + +# Pre-registration matching sees the exact admitted parent and the labels that +# normal registration would inherit. Every other object remains the real model. +struct _PreparedStatusObjectTopology{M,P,K,SP} + model::M + object::Object + parent::P + kind::K + species::SP +end + +function _prepared_status_object_labels(model, object, parent_id) + instance = isnothing(parent_id) ? nothing : _instance_for_object(model, parent_id) + labels = _instance_object_labels(object, instance) + return (scale=object.scale, kind=labels.kind, species=labels.species, id=object.id) +end + +function _prepared_status_topology(model, object, parent_id) + if get(model.registry.objects, object.id, nothing) === object && + isequal(object.parent, parent_id) + return model + end + labels = _prepared_status_object_labels(model, object, parent_id) + return _PreparedStatusObjectTopology(model, object, parent_id, labels.kind, labels.species) +end + +@inline _relation_same_object(topology::_PreparedStatusObjectTopology, left, right) = + _relation_same_object(topology.model, left, right) +@inline function _relation_parent(topology::_PreparedStatusObjectTopology, id) + return id == topology.object.id ? topology.parent : _relation_parent(topology.model, id) +end +@inline function _relation_in_subtree(topology::_PreparedStatusObjectTopology, id, root) + id == topology.object.id || return _relation_in_subtree(topology.model, id, root) + id == root && return true + isnothing(topology.parent) && return false + return _relation_in_subtree(topology.model, topology.parent, root) +end +@inline function _scope_ancestor(topology::_PreparedStatusObjectTopology, origin, scale, include_self) + origin == topology.object.id || return _scope_ancestor(topology.model, origin, scale, include_self) + include_self && (isnothing(scale) || topology.object.scale == scale) && return origin + isnothing(topology.parent) && return nothing + return _scope_ancestor(topology.model, topology.parent, scale, true) +end +_missing_point_scope_anchor(topology::_PreparedStatusObjectTopology, scope, id) = + _missing_point_scope_anchor(topology.model, scope, id) +@inline _point_scope_root_exists(topology::_PreparedStatusObjectTopology, id) = + id == topology.object.id || _point_scope_root_exists(topology.model, id) +@inline function _point_named_scope_root(topology::_PreparedStatusObjectTopology, scope::Scope) + root_id, _ = _named_scope_root_candidate(topology.model, scope) + _point_scope_root_exists(topology, root_id) && return root_id + return _named_scope_root_id(topology.model, scope) # Preserve the existing diagnostic. +end +@inline function _selector_matches_object_labels(topology::_PreparedStatusObjectTopology, + matcher::CompiledSelectorMatcher, id::ObjectId) + id == topology.object.id || return _selector_matches_object_labels(topology.model, matcher, id) + labels = (scale=topology.object.scale, kind=topology.kind, species=topology.species, id=id) + return _matches_object_criteria(labels; scale=matcher.scale, kind=matcher.kind, + species=matcher.species, id=matcher.id) +end + +function _prepared_status_scope_is_current(model, topology, scope) + scope isa Scope && return _point_scope_root_exists(topology, + first(_named_scope_root_candidate(model, scope))) + scope isa CompiledNamedScope && return _point_scope_root_exists(topology, scope.root_id) + return true +end + +function _prepared_status_application_matches(model, object, parent_id, application) + topology = _prepared_status_topology(model, object, parent_id) + _prepared_status_scope_is_current(model, topology, application.target_matcher.scope) || return false + return _selector_matches_object_id(topology, application.target_matcher, + object.id, nothing, false, nothing, false) +end + +function _prepared_status_destination_matches(model, object, parent_id, application, + destination_plan, execution_id) + # The permission caller owns this REAL producer and its configured variant. + # Do not aggregate contexts or infer a producer from destination labels. + topology = _prepared_status_topology(model, object, parent_id) + _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope) || return false + return _selector_matches_object_id(topology, destination_plan.matcher, + object.id, execution_id, true, _default_dependency_scope(model, execution_id), false) +end diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl index 416882e0a..998cab76d 100644 --- a/src/composite_model/status_construction.jl +++ b/src/composite_model/status_construction.jl @@ -6,45 +6,11 @@ struct StatusConstructionRecipe{Names,A<:Tuple} actions::A end -function StatusConstructionRecipe(existing_names::Tuple, edit_names::Tuple) - names = collect(Symbol, existing_names) - actions = Any[ExistingStatusReference{index}() for index in eachindex(names)] - for (index, name) in pairs(edit_names) - position = findfirst(isequal(name), names) - action = EditedStatusReference{index}() - if isnothing(position) - push!(names, name) - push!(actions, action) - else - actions[position] = action - end - end - selections = Tuple(actions) - return StatusConstructionRecipe{Tuple(names),typeof(selections)}(selections) -end - @inline _status_construction_reference(::ExistingStatusReference{I}, existing, edited) where {I} = getfield(existing, I) @inline _status_construction_reference(::EditedStatusReference{I}, existing, edited) where {I} = getfield(edited, I) -function _construct_status( - recipe::StatusConstructionRecipe{Names}, - existing::Tuple, - edited::Tuple, -) where {Names} - references = map(recipe.actions) do action - _status_construction_reference(action, existing, edited) - end - return Status(NamedTuple{Names}(references)) -end - -function _status_construction_recipe!(cache, existing_names::Tuple, edit_names::Tuple) - return get!(cache, (existing_names, edit_names)) do - StatusConstructionRecipe(existing_names, edit_names) - end -end - """An exact reference layout using the canonical StatusConstructionRecipe.""" struct ExactReferenceFactory{Existing,Edited,Result,R} construction::R @@ -54,10 +20,13 @@ struct ExactReferenceFactory{Existing,Edited,Result,R} end _status_schema_names(::Type{Nothing}) = () -_status_schema_names(::Type{Status{Names,Refs}}) where {Names,Refs} = Names -_status_schema_references(::Type{Status{Names,Refs}}) where {Names,Refs} = Refs +_status_schema_names(::Type{Status{Names,T}}) where {Names,T} = Names +_status_schema_references(::Type{Status{Names,T}}) where {Names,T} = + _status_storage_reference_types(T) _status_schema_values(::Nothing) = () -_status_schema_values(status::Status) = refvalues(status) +_status_schema_values(status::Status{N,<:NamedTuple}) where {N} = refvalues(status) +_status_schema_values(status::Status{N,<:Union{_FixedStatusStorage,_ProjectedStatusStorage}}) where {N} = + values(_status_snapshot_references(status)) _selected_status_reference_type(::ExistingStatusReference{I}, existing, edited) where {I} = fieldtype(existing, I) @@ -72,17 +41,46 @@ function ExactReferenceFactory(::Type{Existing}, ::Type{Edited}, ::Type{Result}, throw(ArgumentError("An exact reference factory requires concrete status/reference schemas.")) fieldcount(Edited) == length(edit_names) && all(T -> T <: Ref, fieldtypes(Edited)) || throw(ArgumentError("Edited reference types do not match their declared field names.")) + storage = fieldtype(Result, :vars) + projected = storage <: _ProjectedStatusStorage + wanted = projected ? fieldnames(fieldtype(storage, :hot)) : _status_schema_names(Result) + original_names = _status_schema_names(Existing) original_refs = Existing === Nothing ? Tuple{} : _status_schema_references(Existing) - construction = StatusConstructionRecipe(_status_schema_names(Existing), edit_names) - selected_types = map(construction.actions) do action - _selected_status_reference_type(action, original_refs, Edited) + actions = map(wanted) do name + edited = findlast(isequal(name), edit_names) + isnothing(edited) || return EditedStatusReference{edited}() + original = findfirst(isequal(name), original_names) + isnothing(original) && throw(ArgumentError("A requested kernel reference has no source.")) + ExistingStatusReference{original}() end - _status_schema_names(Result) == typeof(construction).parameters[1] && - Tuple{selected_types...} === _status_schema_references(Result) || - throw(ArgumentError("Reference selections do not produce the admitted status schema.")) + selected = map(action -> _selected_status_reference_type(action, original_refs, Edited), actions) + expected = projected ? fieldtype(storage, :hot).parameters[2] : _status_schema_references(Result) + all(index -> fieldtype(expected,index) <: selected[index], eachindex(selected)) || + throw(ArgumentError("Reference selections are outside the admitted status schema.")) + construction = StatusConstructionRecipe{wanted,typeof(actions)}(actions) return ExactReferenceFactory{Existing,Edited,Result,typeof(construction)}(construction) end -@inline function _construct_status(factory::ExactReferenceFactory{Existing,Edited,Result}, original::Existing, edited::Edited) where {Existing,Edited,Result} - return _construct_status(factory.construction, _status_schema_values(original), edited)::Result +@generated function _construct_status(factory::ExactReferenceFactory{Existing,Edited,Result}, original::Existing, edited::Edited) where {Existing,Edited,Result} + Storage = fieldtype(Result, :vars) + projected = Storage <: _ProjectedStatusStorage + Names = projected ? fieldnames(fieldtype(Storage, :hot)) : _status_schema_names(Result) + Refs = projected ? fieldtype(Storage, :hot).parameters[2] : _status_schema_references(Result) + # Actions are metadata carried by the sole existing factory, not runtime types. + hot = [:( _status_construction_reference(getfield(factory.construction.actions,$i), + _status_schema_values(original), edited)::$(fieldtype(Refs,i)) ) for i in eachindex(Names)] + Hot = NamedTuple{Names,Refs} + projected || return :(Status($Hot($(Expr(:tuple,hot...))))::Result) + FullNames = _status_schema_names(Result) + Full = fieldtype(Storage, :refs) + full = [begin + index = findfirst(isequal(name), Names) + isnothing(index) ? :(_initial_status_reference(original,$(QuoteNode(name)))::$(fieldtype(Full,i))) : + :(getfield(hot,$index)::$(fieldtype(Full,i))) + end for (i,name) in enumerate(FullNames)] + return quote + hot = $Hot($(Expr(:tuple,hot...))) + snapshot = $Full($(Expr(:tuple,full...))) + return Status($Storage(hot, snapshot, _status_reference_epoch(original)))::Result + end end diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index de2f06ef4..a09055598 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -30,8 +30,12 @@ function _temporal_copy_payload_types(V, B, C) end if C <: Status && input in _status_schema_names(C) index = findfirst(isequal(input), _status_schema_names(C)) - Value = eltype(fieldtype(_status_schema_references(C), index)) - add(many && Value <: AbstractVector ? eltype(Value) : Value) + for Reference in Base.uniontypes(fieldtype(_status_schema_references(C), index)) + Reference === Nothing && continue + Reference <: Ref || continue + Value = eltype(Reference) + add(many && Value <: AbstractVector ? eltype(Value) : Value) + end end for View in _model_status_view_family_types(V), TI in fieldtypes(fieldtype(View, :temporal_inputs)) Other = fieldtype(TI, :binding) @@ -83,7 +87,7 @@ end function _gather_temporal_initial(binding::CompiledModelInputBinding, status::Status, payloads) initial = _input_value(binding.carrier) if isnothing(initial) - binding.input in propertynames(status) || error( + hasproperty(status, binding.input) || error( "Temporal input `$(binding.input)` on application ", "`$(binding.application_id)` has neither a resolved source carrier nor an ", "initialized status value. Resolved source objects: ", @@ -247,9 +251,9 @@ function _assemble_model_status_view(canonical_status, model, application, objec "Compiled application input `$(name)` has more than one Many binding.") push!(seen_many, name) end - parts = (; canonical_status, temporal, private_names, private_values, - many_names, many_ids, execution_stamp, - layout_cache=model.registry.objects.layout_cache) + hot_names = Tuple(unique((_model_input_names(application)..., _model_output_names(application)...))) + parts = (; canonical_status, temporal, private_names, private_values, hot_names, + many_names, many_ids, execution_stamp) view = _construct_model_status_view(status_view_schema, application.id, parts) return _admit_model_status_view!(status_view_schema, application.id, view) end @@ -378,6 +382,27 @@ end :(length(parts.private_values) == $(fieldcount(P))), :(length(parts.many_names) == $(fieldcount(BI))), :(length(parts.many_ids) == $(fieldcount(BI)))] + S = fieldtype(V, :status) + Backing = fieldtype(S, :vars) + Backing <: _ProjectedStatusStorage || return :(false) + Hot = fieldtype(Backing, :hot) + append!(checks, [:(parts.hot_names == $(QuoteNode(fieldnames(Hot))))]) + temporal_names = map(fieldtypes(T)) do TI + fieldtype(fieldtype(fieldtype(TI,:binding),:plan),:route).parameters[1] + end + for (index, name) in enumerate(fieldnames(Hot)) + private_index = findfirst(isequal(name), fieldnames(P)) + temporal_index = findfirst(isequal(name), temporal_names) + R = fieldtype(Hot,index) + if !isnothing(private_index) + fieldtype(P,private_index) === R || return :(false) + elseif !isnothing(temporal_index) + fieldtype(fieldtype(T,temporal_index),:reference) === R || return :(false) + else + push!(checks, :(hasproperty(parts.canonical_status,$(QuoteNode(name))) && + refvalue(parts.canonical_status,$(QuoteNode(name))) isa $R)) + end + end for (index, TI) in enumerate(fieldtypes(T)) B, SA = fieldtype(TI, :binding), fieldtype(TI, :source_applications) I, R = fieldtype(TI, :initial), fieldtype(TI, :reference) @@ -421,8 +446,7 @@ end edited = Expr(:tuple, [:(getfield(private_outputs, $index)) for index in 1:fieldcount(P)]..., [:(getfield(getfield(temporal_inputs, $index), :reference)) for index in 1:fieldcount(T)]...) - status = fieldcount(P) + fieldcount(T) == 0 ? :(parts.canonical_status) : - :(_construct_status($(QuoteNode(factory)), parts.canonical_status, $edited)) + status = :(_construct_status($(QuoteNode(factory)), parts.canonical_status, $edited)) bound = Expr(:tuple, [begin B = fieldtype(BI, index) I = fieldtype(fieldtype(B, :ids), :ids) @@ -497,17 +521,15 @@ function _open_status_view_type(parts) T = Tuple{temporals...} P = NamedTuple{Tuple(parts.private_names), Tuple{(Base.RefValue{typeof(value)} for value in parts.private_values)...}} - S = if isempty(parts.private_names) && isempty(parts.temporal) - C - else - factory = _status_construction_recipe!(parts.layout_cache, - propertynames(parts.canonical_status), - (parts.private_names..., (recipe.input for recipe in parts.temporal)...)) - original = _status_schema_references(C) - edited = Tuple{fieldtypes(P)..., (fieldtype(TI, :reference) for TI in temporals)...} - selections = map(action -> _selected_status_reference_type(action, original, edited), factory.actions) - Status{typeof(factory).parameters[1], Tuple{selections...}} + hot_references = map(parts.hot_names) do name + private_index = findfirst(isequal(name), parts.private_names) + isnothing(private_index) || return fieldtype(P,private_index) + temporal_index = findfirst(recipe -> recipe.input === name, parts.temporal) + isnothing(temporal_index) || return fieldtype(T,temporal_index).parameters[4] + hasproperty(parts.canonical_status,name) || throw(ArgumentError("A declared kernel port has no initialized value.")) + typeof(refvalue(parts.canonical_status,name)) end + S = _projected_status_type(C, parts.hot_names, Tuple{hot_references...}) bound_types = map(parts.many_names, parts.many_ids) do name, ids Value = if (index = findfirst(recipe -> recipe.input === name, parts.temporal)) !== nothing _open_status_view_storage_type(parts.temporal[index]) diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index 6d1fa9b79..b6f611147 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -12,6 +12,7 @@ include("composite_model/execution_cohorts.jl") include("composite_model/execution_storage.jl") include("composite_model/execution_cohort_refresh.jl") include("composite_model/compilation.jl") +include("composite_model/prepared_status_manifest.jl") include("composite_model/bound_many.jl") include("composite_model/status_view_construction.jl") include("composite_model/output_targets.jl") diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index 672fd672e..f39eadede 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -314,8 +314,16 @@ function apply_model_graph_edit( candidate.scenario_plan_cache = preparation _model_owned_scenario_preparation(candidate, preparation).resolved = nothing end - _scenario_preparation(candidate) - return candidate + final_preparation = if !isnothing(preparation) && _authored_specs_match(preparation, candidate) + _scenario_preparation(candidate) + else + # This API already returns a NEW model. Its copied live state is the + # genuine input data for a newly prepared namespace, unlike force in place. + fresh = _prepare_authored_scenario(candidate, candidate.applications; raw_families=nothing) + candidate.scenario_plan_cache = fresh + fresh + end + return _install_prepared_canonical_registry(candidate, final_preparation) end function _model_edit_application_id(spec) diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl new file mode 100644 index 000000000..d654b462c --- /dev/null +++ b/test/test-fixed-status-manifest.jl @@ -0,0 +1,70 @@ +module FixedStatusManifestChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "fixed_status_manifest_source" verbose=false +PSE.@process "fixed_status_manifest_reader" verbose=false + +struct Source{X,Y,C} <: AbstractFixed_Status_Manifest_SourceModel + x::X + y::Y + calls::C +end +function PSE.outputs_(source::Source) + source.calls[] += 1 + return (x=source.x, y=source.y) +end +PSE.run!(::Source, status, environment, constants, context) = nothing +struct Reader <: AbstractFixed_Status_Manifest_ReaderModel end +PSE.inputs_(::Reader) = (x=Default(0f0),) +PSE.outputs_(::Reader) = (;) +PSE.run!(::Reader, status, environment, constants, context) = nothing + +@testset "future declarations bound storage without cross-config numeric admission" begin + a = Source(1f0, 2.0, Ref(0)) + b = Source(1.0, 2f0, Ref(0)) + model = CompositeModel(Object(:scene; scale=:Scene, status=Status(keep=3f0)); + applications=(ModelSpec(a; name=:a, on=Many(scale=:Leaf, kind=:a)), + ModelSpec(b; name=:b, on=Many(scale=:Leaf, kind=:b)))) + manifest = model.scenario_plan_cache.status_manifest + @test manifest isa PSE.PreparedStatusManifest + S = manifest.status_type + names = PSE._status_schema_names(S) + refs = PSE._status_schema_references(S) + @test (:x in names) && (:y in names) && (:keep in names) + @test Base.RefValue{Float32} <: fieldtype(refs, findfirst(isequal(:x), names)) + @test Base.RefValue{Float64} <: fieldtype(refs, findfirst(isequal(:x), names)) + @test a.calls[] == b.calls[] == 1 + + # This pair fits the GLOBAL slot unions, but no configured kind=:a family. + bad = Object(:bad; scale=:Leaf, kind=:a, status=Status(x=9f0, y=9f0)) + before = length(model.registry.objects) + @test_throws ArgumentError register_object!(model, bad) + @test length(model.registry.objects) == before + @test !haskey(model.registry.objects, ObjectId(:bad)) + good = Object(:good; scale=:Leaf, kind=:a, status=Status(x=9f0, y=9.0)) + x = PSE.refvalue(good.status, :x) + register_object!(model, good) + @test typeof(model_status(model, :good)) === S + @test PSE.refvalue(model_status(model, :good), :x) === x + @test a.calls[] == b.calls[] == 1 +end + +@testset "One uses the prospective source reference witness before first birth" begin + source = Source(1.0, 2.0, Ref(0)) + model = CompositeModel(Object(:scene; scale=:Scene); + applications=(ModelSpec(source; name=:source, on=Many(scale=:Leaf)), + ModelSpec(Reader(); name=:reader, on=One(scale=:Scene), + inputs=(x=One(scale=:Leaf),)))) + preparation = model.scenario_plan_cache + plan = only(record for record in preparation.program.input_records + if record isa PSE.CompiledModelInputPlan && record.application_id === :reader) + @test plan.reference_types === Tuple{Base.RefValue{Float64}} + @test source.calls[] == 1 + leaf = Object(:first; scale=:Leaf, status=Status(x=4.0, y=5.0)) + x = PSE.refvalue(leaf.status, :x) + register_object!(model, leaf) + run!(model; steps=1, outputs=:none) + @test PSE.refvalue(model_status(model, :scene), :x) === x + @test source.calls[] == 2 # ordinary fresh staging read, no manifest replay +end +end diff --git a/test/test-fixed-status-prospective-distributed.jl b/test/test-fixed-status-prospective-distributed.jl new file mode 100644 index 000000000..bf010ad5f --- /dev/null +++ b/test/test-fixed-status-prospective-distributed.jl @@ -0,0 +1,42 @@ +module FixedStatusProspectiveDistributedChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "fixed_status_future_distributed" verbose=false + +struct Source{T} <: AbstractFixed_Status_Future_DistributedModel + value::T +end +PSE.inputs_(::Source) = (;) +PSE.outputs_(source::Source) = (x=Distributed(Default(source.value)),) +function PSE.run!(source::Source, status, environment, constants, context) + targets = output_targets(context, (:x,)) + for index in eachindex(targets.columns.x) + targets.columns.x[index] = source.value + end + return nothing +end + +@testset "provided distributed data is admitted before its declared producer exists" begin + root = Object(:plant; scale=:Plant) + model = CompositeModel(root; applications=( + ModelSpec(Source(7.0); name=:source, on=Many(scale=:Scene), + outputs_to=(OutputTo(Many(SceneScope(), scale=:Leaf)),)),)) + # No current Scene, destination or observed x-family exists at preparation. + @test length(model.registry.objects) == 1 + supplied = Status(x=4.0) + reference = PSE.refvalue(supplied, :x) + leaf = Object(:leaf; scale=:Leaf, parent=root.id, status=supplied) + @test register_object!(model, leaf) === leaf + canonical = model_status(model, leaf.id) + @test canonical.x === 4.0 + @test PSE.refvalue(canonical, :x) === reference + + scene = Object(:scene; scale=:Scene, parent=root.id) + @test register_object!(model, scene) === scene + run!(model; steps=1, outputs=:none) + @test model_status(model, leaf.id) === canonical + @test PSE.refvalue(model_status(model, leaf.id), :x) === reference + @test canonical.x === 7.0 + @test reference[] === 7.0 +end +end diff --git a/test/test-fixed-status-scope-growth.jl b/test/test-fixed-status-scope-growth.jl new file mode 100644 index 000000000..b60ad539c --- /dev/null +++ b/test/test-fixed-status-scope-growth.jl @@ -0,0 +1,79 @@ +module FixedStatusScopeGrowthChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +PSE.@process "fixed_status_scope_growth" verbose=false + +struct Increment{T} <: AbstractFixed_Status_Scope_GrowthModel + initial::T +end +PSE.outputs_(model::Increment) = (x=model.initial,) +function PSE.run!(model::Increment, status, environment, constants, context) + status.x += one(model.initial) + return nothing +end + +@testset "reparenting retains historical cells while newborns obey their own scope" begin + supplied = Status(x=3f0) + cell = PSE.refvalue(supplied, :x) + model = CompositeModel( + Object(:north; scale=:Plant), Object(:south; scale=:Plant), + Object(:leaf; scale=:Leaf, parent=:north, status=supplied); + applications=( + ModelSpec(Increment(0f0); name=:north_growth, + on=Many(scale=:Leaf, within=Scope(ObjectId(:north)))), + ModelSpec(Increment(0.0); name=:south_growth, + on=Many(scale=:Leaf, within=Scope(ObjectId(:south)))), + )) + official = model_status(model, :leaf) + @test official !== supplied + @test PSE.refvalue(official, :x) === cell + @test_throws ArgumentError object_id(model, supplied) + @test object_id(model, official) == ObjectId(:leaf) + @test isnothing(model_status(model, :north)) + @test isnothing(model_status(model, :south)) + prepared_type = typeof(official) + + simulation = run!(model; steps=1, outputs=:none) + @test official.x === 4f0 + reparent_object!(model, :leaf, :south) + step!(simulation) + @test model_status(model, :leaf) === official + @test PSE.refvalue(official, :x) === cell + @test official.x === 5f0 + + # Float32 fits the global storage union but has never been admitted as + # newborn data in the Float64 southern configuration. + rejected = Object(:rejected; scale=:Leaf, parent=:south, status=Status(x=7f0)) + old_status = rejected.status + object_count = length(model.registry.objects) + children = copy(model.registry.objects[ObjectId(:south)].children) + source_owners = copy(model.status_source_owners) + conversion_records = copy(model.status_conversion_records) + @test_throws ArgumentError register_object!(model, rejected) + @test length(model.registry.objects) == object_count + @test !haskey(model.registry.objects, ObjectId(:rejected)) + @test rejected.status === old_status + @test model.registry.objects[ObjectId(:south)].children == children + @test model.status_source_owners == source_owners + @test model.status_conversion_records == conversion_records + + newborn = Object(:newborn; scale=:Leaf, parent=:south, status=Status(x=8.0)) + newborn_cell = PSE.refvalue(newborn.status, :x) + register_object!(model, newborn) + @test typeof(model_status(model, :newborn)) === prepared_type + @test PSE.refvalue(model_status(model, :newborn), :x) === newborn_cell + step!(simulation) + @test official.x === 6f0 + @test model_status(model, :newborn).x === 9.0 + + # Preparing Status storage does not restrict the public identity domain. + tuple_id = (:southern_leaf, 1) + register_object!(model, Object(tuple_id; scale=:Leaf, parent=:south, + status=Status(x=1.0))) + step!(simulation) + tuple_status = model_status(model, ObjectId(tuple_id)) + @test typeof(tuple_status) === prepared_type + @test object_id(model, tuple_status) == ObjectId(tuple_id) + @test tuple_status.x === 2.0 +end +end diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl index cd6dff2ef..7468a6409 100644 --- a/test/test-model-call-cohort-retirement.jl +++ b/test/test-model-call-cohort-retirement.jl @@ -166,28 +166,17 @@ Base.hash(owner::OwnerAlias, seed::UInt) = hash(owner.value, seed) @test value.value[] === 3.0 end -# The future Symbol Leaf descriptor uses the type of an actual complete Leaf -# status already owned by this scene. It constructs no future Status or object. -function closed_registry_with_future_leaf(model) +# Freeze only the real identity domain. The canonical Status schema is already +# prepared at CompositeModel construction, even when no Leaf remains active. +function with_finite_registry(model) previous = model.registry - closed = PSE._closed_object_family_store(previous.objects) - S = typeof(model_status(model, 1)) - future = PSE.ObjectFamily{ObjectId{Symbol},S}( - Union{Nothing,PSE.ObjectFamilyRow{ObjectId{Symbol},S}}[]) - families = (closed.catalog.families..., future) - store = PSE.ObjectFamilyStore(PSE.ClosedObjectFamilyCatalog(families), - closed.locations, closed.status_owners, copy(closed.layout_cache)) - registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + objects = PSE._closed_object_family_store(previous.objects) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) - return PSE.CompositeModel( - registry, model.applications, model.environment, model.instances, - model.source_adapter, model.status_conversion, model.status_conversion_records, - model.status_source_owners, model.status_source_identities, - model.scenario_plan_cache, model.binding_cache, model.environment_binding_cache, - model.bindings_dirty, model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, model.revision, - model.environment_revision, - ) + fields = map(fieldnames(typeof(model))) do name + name === :registry ? registry : getfield(model, name) + end + return PSE.CompositeModel(fields...) end current_target(simulation) = only(only(only(simulation.execution_plan.groups).batches).targets) view_ids(values) = [target.object_id for target in values] @@ -221,7 +210,7 @@ function publish_current_left!(data) end @testset "closed memberships use the global future identity schema" begin - data = fixture(; transform=closed_registry_with_future_leaf) + data = fixture(; transform=with_finite_registry) I = Union{ObjectId{Symbol},ObjectId{Int}} @test keytype(data.model.registry.objects) === I applications = data.simulation.compiled.applications_by_id @@ -256,8 +245,8 @@ end end @testset "ordinary and prepared public calls retain state histories and membership through birth and removal" begin - ordinary = fixture(; transform=closed_registry_with_future_leaf, outputs=:all) - prepared = prepared_tree(fixture(; transform=closed_registry_with_future_leaf, outputs=:all)) + ordinary = fixture(; transform=with_finite_registry, outputs=:all) + prepared = prepared_tree(fixture(; transform=with_finite_registry, outputs=:all)) fixtures = (ordinary, prepared) references = [PSE.refvalue(model_status(data.model, 2), :leaf_visits) for data in fixtures] held = [data.left for data in fixtures] @@ -296,7 +285,7 @@ end @test stream_values(ordinary.simulation) == stream_values(prepared.simulation) end -@testset "ordinary open identity domains still accept a later Symbol Leaf" begin +@testset "ordinary identity domains still accept a later Symbol Leaf" begin data = fixture() continue!(data.simulation; steps=2) register_object!(data.model, Object(:later_leaf; scale=:Leaf, parent=:caller, @@ -307,9 +296,9 @@ end @test ObjectId(:later_leaf) in view_ids(call_targets(data.capture[], :left)) end -@testset "an initially empty Many keeps its explicit future Symbol Leaf identity family" begin +@testset "an initially empty Many retains its prepared Status and real Symbol identity family" begin function empty_closed(model) - closed = closed_registry_with_future_leaf(model) + closed = with_finite_registry(model) remove_object!(closed, 1) remove_object!(closed, 2) return closed @@ -327,8 +316,8 @@ end @test model_status(data.model, :future_leaf).leaf_visits == 2 @test view_ids(data.left) == [ObjectId(:future_leaf)] @test eltype(data.left.binding.callee_object_ids) === I - # Identity metadata under ordinary open execution: no full prepared Target - # family for a future Symbol is claimed by this case. + # The caller already supplies the Symbol ID family. This checks canonical + # identity metadata; batch admission remains ordinary in this case. @test data.left.batch_schema isa PSE.OpenExecutionBatchSchema end diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index 3a4da0859..1043c3c77 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -37,15 +37,7 @@ function fixture(closed) ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)))) if closed previous = model.registry - store = PSE._closed_object_family_store(previous.objects) - # Admit this ID/status family by the type of the real supplied Leaf. - # No future object, value, callback or status is constructed here. - S = typeof(model_status(model, 1)) - future = PSE.ObjectFamily{ObjectId{Symbol},S}( - Union{Nothing,PSE.ObjectFamilyRow{ObjectId{Symbol},S}}[]) - objects = PSE.ObjectFamilyStore( - PSE.ClosedObjectFamilyCatalog((store.catalog.families...,future)), - store.locations, store.status_owners, copy(store.layout_cache)) + objects = PSE._closed_object_family_store(previous.objects) registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) model = PSE.CompositeModel(registry, model.applications, model.environment, @@ -65,9 +57,9 @@ end function check_store(simulation, closed) store = simulation.temporal_streams.cohorts I = closed ? Union{ObjectId{Int},ObjectId{Symbol}} : ObjectId - O = closed ? Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} : Any - CK = closed ? PSE.ExecutionCohortKey{O,DataType} : Tuple{O,Symbol,DataType} - LK = closed ? PSE.ExecutionCohortKey{O,I} : Tuple{O,Symbol,I} + O = Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} + CK = PSE.ExecutionCohortKey{O,DataType} + LK = PSE.ExecutionCohortKey{O,I} @test typeof(store) === PSE.ExecutionCohortStore{I,O,CK,LK} @test typeof(typeof(store)()) === typeof(store) @test fieldtype(typeof(simulation.execution_plan), :cohorts) === typeof(store) @@ -256,7 +248,7 @@ end end end -@testset "open refresh retires an unvisited scheduled owner through the same store" begin +@testset "ordinary refresh retires an unvisited scheduled owner through the same store" begin for closed in (false,true) data = fixture(closed) simulation = run!(data.model;steps=0,outputs=:none) diff --git a/test/test-model-initializers.jl b/test/test-model-initializers.jl index 783cf15e1..2a4000b3e 100644 --- a/test/test-model-initializers.jl +++ b/test/test-model-initializers.jl @@ -289,10 +289,12 @@ function PlantSimEngine.run!( ) status.returned_status_is_registered = model_status(runtime, leaf_status) === leaf_status + leaf_node = source_node(runtime, leaf_status) status.source_identity_matches = - source_node(runtime, leaf_status) === leaf_status.node + object_id(runtime, leaf_node) == object_id(runtime, leaf_status) && + MultiScaleTreeGraph.parent(leaf_node) === source_node(context) status.runtime_attribute_absent = !haskey( - node_attributes(leaf_status.node), + node_attributes(leaf_node), :plantsimengine_status, ) status.initialized_mass = run_initializer!( diff --git a/test/test-model-object-id.jl b/test/test-model-object-id.jl index 2d80d3128..78f56e38f 100644 --- a/test/test-model-object-id.jl +++ b/test/test-model-object-id.jl @@ -160,7 +160,6 @@ end :Leaf, 2; index=2, - initial_status=(signal=0.0,), ) @test length(MultiScaleTreeGraph.children(copied_plant)) == copied_child_count @test object_ids(model) == registered_before @@ -172,14 +171,13 @@ end :Leaf, 2; index=2, - initial_status=(signal=0.0,), ) new_leaf_id = ObjectId((:Leaf, 4)) - @test MultiScaleTreeGraph.node_id(new_leaf_status.node) == 4 + @test MultiScaleTreeGraph.node_id(source_node(model, new_leaf_status)) == 4 @test object_id(model, new_leaf_status) == new_leaf_id - @test object_id(model, new_leaf_status.node) == new_leaf_id + @test object_id(model, source_node(model, new_leaf_status)) == new_leaf_id @test model_status(model, new_leaf_id) === new_leaf_status - @test source_node(model, new_leaf_status) === new_leaf_status.node + @test source_node(model, new_leaf_status) === source_node(model, new_leaf_status) simulation = run!(model; steps=1, outputs=:none) probe_status = model_object(model, (:Scene, 1)).status @@ -215,12 +213,11 @@ end :Leaf, 2; index=1, - initial_status=(signal=1.0,), ) - @test MultiScaleTreeGraph.node_id(added.node) == 4 - @test MultiScaleTreeGraph.parent(added.node) === plant - @test source_node(model, ObjectId(4)) === added.node + @test MultiScaleTreeGraph.node_id(source_node(model, added)) == 4 + @test MultiScaleTreeGraph.parent(source_node(model, added)) === plant + @test source_node(model, ObjectId(4)) === source_node(model, added) @test MultiScaleTreeGraph.new_id(root) == 5 @test MultiScaleTreeGraph.node_id(detached) == 3 end @@ -317,11 +314,10 @@ end index=2, id=10, attributes=(runtime_id=:reusable_leaf,), - initial_status=(signal=0.0,), ) - @test new_leaf_status.node !== old_leaf - @test MultiScaleTreeGraph.node_id(new_leaf_status.node) != old_raw_id - @test object_id(model, new_leaf_status.node) == reusable_id + @test source_node(model, new_leaf_status) !== old_leaf + @test MultiScaleTreeGraph.node_id(source_node(model, new_leaf_status)) != old_raw_id + @test object_id(model, source_node(model, new_leaf_status)) == reusable_id @test_throws ArgumentError object_id(model, old_leaf) end @@ -331,7 +327,7 @@ end Node(plant, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 2)) model = CompositeModel( root; - status=node -> Status(node=node, signal=0.0), + status=node -> Status(signal=0.0), ) simulation = run!(model; steps=1, outputs=:none) initial_step = current_step(simulation) diff --git a/test/test-model-persistent-empty-groups.jl b/test/test-model-persistent-empty-groups.jl index 14c0a65cc..f65eeefd3 100644 --- a/test/test-model-persistent-empty-groups.jl +++ b/test/test-model-persistent-empty-groups.jl @@ -48,10 +48,16 @@ end environment_plan = simulation.environment_bindings.application_plans_by_id[:counter] Empty = NamedTuple{(),Tuple{}} I = ObjectId{Symbol} - # This is a supplied future reference descriptor, not inferred from an - # output default and not instantiated as a placeholder Status. - Full = Status{(:count,),Tuple{Base.RefValue{Int}}} - View = PSE.CompiledModelStatusView{Full,Full,Tuple{},Empty,Empty} + # The real constructor already prepared count's prospective Ref class. + # Project only the model's hot ports; instantiate no future Status/default. + Canonical = model.scenario_plan_cache.status_manifest.status_type + ports = PSE._application_ports(application) + names = Tuple(unique((ports.input_names..., keys(ports.output_types)...))) + references = PSE._status_schema_references(Canonical) + HotReferences = Tuple{(fieldtype(references, + findfirst(isequal(name), PSE._status_schema_names(Canonical))) for name in names)...} + Hot = PSE._projected_status_type(Canonical, names, HotReferences) + View = PSE.CompiledModelStatusView{Hot,Canonical,Tuple{},Empty,Empty} Context = PSE.RunContext{typeof(compiled),typeof(application),Tuple{},Empty,Empty, typeof(simulation.temporal_streams),typeof(simulation.output_retention), typeof(simulation.constants),PSE.NoEnvironmentOverride,I,typeof(simulation.environment_bindings)} @@ -60,7 +66,7 @@ end Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} Store = typeof(simulation.temporal_streams.cohorts) Owner = PSE._execution_store_owner_type(Store) - Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I,Owner},Store} + Rows = PSE.ExecutionCohortRows{Target,I,Owner,Store} Batch = PSE.CompiledExecutionBatch{typeof(application),Rows, PSE.RawGlobalModelEnvironment{Nothing},PSE.CompiledOutputPublication{Tuple{}}} before_callbacks = declarations[] @@ -88,7 +94,9 @@ end @test only(simulation.execution_plan.groups) === future @test only(simulation.execution_plan.groups_by_application_slot) === future @test eltype(future.batches) === Batch - @test only(only(future.batches).targets).status_view.status === born.status + view = only(only(future.batches).targets).status_view + @test view.canonical_status === born.status + @test PSE.refvalue(view.status, :count) === PSE.refvalue(born.status, :count) remove_object!(model,:born) step!(simulation) @test typeof(simulation.execution_plan) === Plan diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index 0e19c0486..1bada54dc 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -26,7 +26,7 @@ PSE.outputs_(::HardController) = (ticks=0, pulse_total=0.0) PSE.outputs_(::GrowthController) = ( ticks=0, pulse_total=0.0, created=false, births=0, born_value=0.0, ) -PSE.inputs_(::LeafState) = (seed=Required(Real),) +PSE.inputs_(::LeafState) = (seed=Required(Float64),) PSE.outputs_(::LeafState) = (value=0.0, visits=0) function PSE.run!(::Pulse, status, environment, constants, context) @@ -98,32 +98,15 @@ function make_growth(; environment=nothing, fail_initializer=false) return (; model, birth_day, seed) end -# Exact reference-field types required by this deliberately finite fixture. -# These are empty family descriptors, never fake scientific statuses or values. -const LeafSeedStatus = Status{(:seed,),Tuple{Base.RefValue{Float64}}} -const LeafFullStatus = Status{(:seed,:value,:visits), - Tuple{Base.RefValue{Float64},Base.RefValue{Float64},Base.RefValue{Int}}} - -empty_family(::Type{S}) where {S} = PSE.ObjectFamily{ObjectId{Symbol},S}( - Union{Nothing,PSE.ObjectFamilyRow{ObjectId{Symbol},S}}[]) - -function with_closed_registry(model::PSE.CompositeModel; future=()) +function with_finite_registry(model::PSE.CompositeModel) previous = model.registry - closed = PSE._closed_object_family_store(previous.objects) - families = (closed.catalog.families..., map(empty_family, future)...) - store = PSE.ObjectFamilyStore(PSE.ClosedObjectFamilyCatalog(families), - closed.locations, closed.status_owners, copy(closed.layout_cache)) - registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + objects = PSE._closed_object_family_store(previous.objects) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) - return PSE.CompositeModel( - registry, model.applications, model.environment, model.instances, - model.source_adapter, model.status_conversion, model.status_conversion_records, - model.status_source_owners, model.status_source_identities, - model.scenario_plan_cache, model.binding_cache, model.environment_binding_cache, - model.bindings_dirty, model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, model.revision, - model.environment_revision, - ) + fields = map(fieldnames(typeof(model))) do name + name === :registry ? registry : getfield(model, name) + end + return PSE.CompositeModel(fields...) end function future_leaf_batch_type(simulation) @@ -135,9 +118,16 @@ function future_leaf_batch_type(simulation) @assert isempty(application.target_ids) Empty = NamedTuple{(),Tuple{}} I = ObjectId{Symbol} - # This descriptor is explicitly admitted alongside LeafSeedStatus above. - # No Leaf, Status, scientific default, or callback is instantiated here. - View = PSE.CompiledModelStatusView{LeafFullStatus,LeafFullStatus,Tuple{},Empty,Empty} + # Project the already prepared physical namespace and exact port references. + # No future Leaf, default value, Status, getter or kernel is constructed. + Canonical = PSE._scenario_preparation(simulation.model).status_manifest.status_type + ports = PSE._application_ports(application) + names = Tuple(unique((ports.input_names..., keys(ports.output_types)...))) + references = PSE._status_schema_references(Canonical) + HotReferences = Tuple{(fieldtype(references, + findfirst(isequal(name), PSE._status_schema_names(Canonical))) for name in names)...} + Hot = PSE._projected_status_type(Canonical, names, HotReferences) + View = PSE.CompiledModelStatusView{Hot,Canonical,Tuple{},Empty,Empty} Context = PSE.RunContext{typeof(compiled),typeof(application),Tuple{},Empty,Empty, typeof(simulation.temporal_streams),typeof(simulation.output_retention), typeof(simulation.constants),PSE.NoEnvironmentOverride,I,typeof(simulation.environment_bindings)} @@ -146,7 +136,7 @@ function future_leaf_batch_type(simulation) Tuple{},Empty,Empty,Tuple{},Tuple{},Binding,Context,I} Store = typeof(simulation.temporal_streams.cohorts) Owner = PSE._execution_store_owner_type(Store) - Rows = PSE.ExecutionCohortRows{Target,PSE.ExecutionCohort{Target,I,Owner},Store} + Rows = PSE.ExecutionCohortRows{Target,I,Owner,Store} return PSE.CompiledExecutionBatch{typeof(application),Rows, PSE.RawGlobalModelEnvironment{typeof(environment_plan.prepared_source)}, PSE.CompiledOutputPublication{Tuple{}}} @@ -154,7 +144,7 @@ end function prepare_schema_growth(; environment=nothing, fail_initializer=false) setup = make_growth(; environment, fail_initializer) - model = with_closed_registry(setup.model;future=(LeafSeedStatus,LeafFullStatus)) + model = with_finite_registry(setup.model) simulation = run!(model;steps=0,outputs=:none) controller = only(simulation.execution_plan.groups) controller_batch = only(controller.batches) diff --git a/test/test-model-public-refresh-owners.jl b/test/test-model-public-refresh-owners.jl index a4e89447e..a5904a611 100644 --- a/test/test-model-public-refresh-owners.jl +++ b/test/test-model-public-refresh-owners.jl @@ -165,6 +165,132 @@ end end end + +@testset "force rebinds status permissions before staging a new selector's defaults" begin + first_spec = ModelSpec(Counter(); name=:probe, on=Many(kind=:a)) + model = CompositeModel(Object(:a; kind=:a), Object(:b; kind=:b); + applications=(first_spec,)) + previous = model.scenario_plan_cache + catalog = model.registry.objects.catalog + families = catalog.families + @test isempty(previous.status_manifest.raw_families) + replacement = ModelSpec(Counter(); name=:probe, on=Many(kind=:b)) + @test typeof(replacement) === typeof(first_spec) + model.applications[1] = replacement + current = Advanced.refresh_bindings!(model; force=true) + preparation = model.scenario_plan_cache + @test preparation !== previous + @test preparation.status_manifest !== catalog.status_manifest + @test model.registry.objects.catalog.status_manifest === preparation.status_manifest + @test model.registry.objects.catalog.families === families + @test preparation.status_manifest.raw_families === previous.status_manifest.raw_families + @test isnothing(model_status(model, :a)) + @test model_status(model, :b).visits == 0 + + b = Object(:born_b; kind=:b) + register_object!(model, b) + wrong = Object(:wrong_a; kind=:a, status=Status(visits=2)) + source = wrong.status + @test_throws ArgumentError register_object!(model, wrong) + @test wrong.status === source + @test !haskey(model.registry.objects, wrong.id) + inactive = Object(:inactive_a; kind=:a) + register_object!(model, inactive) + run!(model; steps=1, outputs=:none) + @test model_status(model, :b).visits == 1 + @test model_status(model, b.id).visits == 1 + @test isnothing(model_status(model, inactive.id)) + @test current.scenario_plan.authoring.preparation === preparation +end + +@testset "force does not turn materialized defaults into RAW evidence" begin + model = CompositeModel(Object(:leaf; kind=:a); + applications=(ModelSpec(Counter(); name=:probe, on=Many(kind=:a)),)) + raw = model.scenario_plan_cache.status_manifest.raw_families + @test isempty(raw) + run!(model; steps=0, outputs=:none) + status = model_status(model, :leaf) + reference = PSE.refvalue(status, :visits) + Advanced.refresh_bindings!(model; force=true) + @test model.scenario_plan_cache.status_manifest.raw_families === raw + @test model.registry.objects.catalog.status_manifest === model.scenario_plan_cache.status_manifest + @test model_status(model, :leaf) === status + @test PSE.refvalue(status, :visits) === reference + @test object_id(model, status) === ObjectId(:leaf) +end + +PSE.@process "force_authority_new_status_field" verbose=false +struct ChangingFields{M,D,K} <: AbstractForce_Authority_New_Status_FieldModel + extra::M + declarations::D + kernels::K +end +PSE.inputs_(::ChangingFields) = (;) +function PSE.outputs_(model::ChangingFields) + model.declarations[] += 1 + return model.extra[] ? (visits=0, extra=0) : (visits=0,) +end +function PSE.run!(model::ChangingFields, status, environment, constants, context) + model.kernels[] += 1 + status.visits += 1 + return nothing +end + +@testset "an incompatible mutable declaration records an authoritative error without publishing state" begin + extra, declarations, kernels = Ref(false), Ref(0), Ref(0) + original = ModelSpec(ChangingFields(extra, declarations, kernels); name=:probe, on=One(id=:leaf)) + supplied = Status(visits=5) + model = CompositeModel(Object(:leaf; status=supplied); applications=(original,)) + run!(model; steps=0, outputs=:none) + registry, preparation, compiled = model.registry, model.scenario_plan_cache, model.binding_cache + environment = model.environment_binding_cache + status = model_status(model, :leaf) + reference = PSE.refvalue(status, :visits) + source_owners = copy(model.status_source_owners) + source_ids = copy(model.status_source_identities) + extra[] = true # SAME immutable ModelSpec and SAME mutable model instance + @test only(model.applications) === original + failure = try + Advanced.refresh_bindings!(model; force=true) + nothing + catch exception + exception + end + @test failure isa ArgumentError + @test occursin("Construct a new CompositeModel", sprint(showerror, failure)) + rejected = model.scenario_plan_cache + @test rejected !== preparation + @test rejected.status_manifest isa PSE.ScenarioPreparationFailure + @test rejected.status_manifest.phase === :status_manifest + @test rejected.status_manifest.error === failure + @test model.registry === registry + @test model.binding_cache === compiled + @test model.environment_binding_cache === environment + @test model_status(model, :leaf) === status + @test PSE.refvalue(status, :visits) === reference + @test status.visits == 5 + @test model.status_source_owners == source_owners + @test model.status_source_identities == source_ids + @test object_id(model, status) === ObjectId(:leaf) + after_failure = declarations[] + @test_throws ArgumentError run!(model; steps=1, outputs=:none) + @test_throws ArgumentError Advanced.refresh_bindings!(model) + @test declarations[] == after_failure + @test kernels[] == 0 + @test status.visits == 5 + + extra[] = false + @test_throws ArgumentError run!(model; steps=0, outputs=:none) + @test declarations[] == after_failure + Advanced.refresh_bindings!(model; force=true) # explicit recovery within old S + @test model.registry.objects.catalog.status_manifest === model.scenario_plan_cache.status_manifest + run!(model; steps=1, outputs=:none) + @test model_status(model, :leaf) === status + @test PSE.refvalue(status, :visits) === reference + @test status.visits == 6 + @test kernels[] == 1 +end + end module SelectiveRefreshOwnerChecks diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl index fdfa8fff8..9e2f14d17 100644 --- a/test/test-model-scenario-authoring.jl +++ b/test/test-model-scenario-authoring.jl @@ -274,7 +274,13 @@ PSE.run!(::BrokenDeclarations, status, environment, constants, context) = (statu @test any(row -> occursin("intentional authored declaration failure", row.message), report.diagnostics) @test calls[] == 1 # diagnostic recovery works on its owned structural copy fail[] = false - PSE.Advanced.refresh_bindings!(model; force=true) + # The failed output hook supplied no schema at construction. Fixing it + # requires an actual prepared model, not in-place discovery of a new S. + original_preparation = model.scenario_plan_cache + @test_throws ArgumentError PSE.Advanced.refresh_bindings!(model; force=true) + @test model.scenario_plan_cache === original_preparation + model = CompositeModel(Object(:root; scale=:Scene); + applications=Tuple(model.applications), environment=model.environment) @test isnothing(model.scenario_plan_cache.failure) @test final_state(run!(model)).visits == 1 # A failed force refresh must not let an older compiled cache hide the diff --git a/test/test-model-status-type-lifecycle.jl b/test/test-model-status-type-lifecycle.jl index 5f1eafb89..341e42846 100644 --- a/test/test-model-status-type-lifecycle.jl +++ b/test/test-model-status-type-lifecycle.jl @@ -406,7 +406,7 @@ end plant, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 2), ) - imported_source = Status(node=leaf, biomass=2.5) + imported_source = Status(biomass=2.5, area=1.0) model = CompositeModel( root; @@ -416,7 +416,8 @@ end imported = model_status(model, leaf) @test imported !== imported_source - @test imported.node === leaf + @test source_node(model, imported) === leaf + @test imported.area === Float32(1) @test imported.biomass === Float32(2.5) @test imported_source.biomass === 2.5 @@ -430,13 +431,14 @@ end index=2, initial_status=(biomass=3.5, area=2.0), ) - registered = model_status(model, added.node) + registered = model_status(model, source_node(model, added)) @test added === registered - @test model_object(model, added.node).status === added + @test model_object(model, source_node(model, added)).status === added @test added.biomass === Float32(3.5) @test added.area === Float32(2) - @test added.node isa MultiScaleTreeGraph.Node + @test source_node(model, added) isa MultiScaleTreeGraph.Node + @test !hasproperty(added, :node) end @testset "refresh, reparent, steps, and removal do not repeat transforms" begin diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 40e6a415a..cac7401b6 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -16,8 +16,9 @@ const PSE = PlantSimEngine store = model.registry.objects @test store isa PSE.ObjectFamilyStore - @test store.catalog isa PSE.OpenObjectFamilyCatalog - @test length(store.catalog.families) == 3 + @test store.catalog isa PSE.ClosedObjectFamilyCatalog + @test length(store.catalog.families) == 2 # None + one prepared physical S + canonical = model_status(model, 1) @test model_object(model, 1) === first for object in (first, second, empty) @test model_object(model, object.id) === object @@ -32,23 +33,35 @@ const PSE = PlantSimEngine @test failure isa ErrorException @test sprint(showerror, failure) == "No model object with id `$(id)`." end - @test model_status(model, 1) === supplied - @test PSE.refvalue(model_status(model, supplied), :value) === reference + @test canonical !== supplied + @test PSE.refvalue(canonical, :value) === reference + @test_throws ArgumentError model_status(model, supplied) @test isnothing(model_status(model, (:plant, 3))) @test Set(keys(store)) == Set((ObjectId(1), ObjectId(:leaf), ObjectId((:plant, 3)))) @test Set(values(store)) == Set((first, second, empty)) @test Dict(store)[ObjectId(1)] === first @test copy(store)[ObjectId(:leaf)] === second @test get(store, ObjectId(:absent), nothing) === nothing - @test object_id(model, supplied) === ObjectId(1) + @test object_id(model, canonical) === ObjectId(1) + @test_throws ArgumentError object_id(model, supplied) model_status(model, 1).value = 4f0 @test supplied.value === first.status.value === 4f0 location = store.locations[ObjectId(1)] family = store.catalog.families[location.family] - @test family isa PSE.ObjectFamily{ObjectId{Int},typeof(supplied)} - @test family.rows[location.row].status === supplied + @test family isa PSE.ObjectFamily{keytype(store),typeof(canonical)} + @test family.rows[location.row].status === canonical +end + +# Genuine model configuration declares the replacement's numerical types at +# preparation; no dummy object or explicit canonical Status prototype is needed. +PSE.@process "canonical_family_replacement" verbose=false +struct FamilyReplacement{D} <: AbstractCanonical_Family_ReplacementModel + defaults::D end +PSE.inputs_(::FamilyReplacement) = (;) +PSE.outputs_(model::FamilyReplacement) = model.defaults +PSE.run!(::FamilyReplacement, status, environment, constants, context) = nothing @noinline function escape_registered_status!(sink, model, id, count) for _ in 1:count @@ -60,10 +73,13 @@ end registered_status_allocations(sink, model, id, count) = @allocated escape_registered_status!(sink, model, id, count) -@testset "escaping open-family lookups reuse the canonical Status box" begin +@testset "escaping prepared-family lookups reuse the official Status box" begin supplied = Status(value=1f0, items=Float32[2], counter=0, label=:leaf, active=true) object = Object(:leaf; status=supplied) - model = CompositeModel(object) + replacement_defaults = (value=4.0, items=[5.0], counter=1, label=:updated, active=false) + model = CompositeModel(object; applications=(ModelSpec( + FamilyReplacement(replacement_defaults); name=:replacement, on=One(id=:leaf)),)) + canonical = model_status(model, object.id) sink = Ref{Any}() for _ in 1:2 escape_registered_status!(sink, model, object.id, 1000) @@ -71,7 +87,8 @@ registered_status_allocations(sink, model, id, count) = end @test registered_status_allocations(sink, model, object.id, 1) == 0 @test registered_status_allocations(sink, model, object.id, 1000) == 0 - @test sink[] === supplied === object.status + @test sink[] === canonical === object.status + @test sink[] !== supplied @test all(index -> PSE.refvalues(sink[])[index] === PSE.refvalues(supplied)[index], eachindex(PSE.refvalues(supplied))) location = model.registry.objects.locations[object.id] @@ -82,53 +99,69 @@ registered_status_allocations(sink, model, id, count) = @test supplied.items == Float32[3] replacement = Status(value=4.0, items=[5.0], counter=1, label=:updated, active=false) - PSE._replace_model_object_status!(model, object, replacement) + official_replacement = PSE._replace_model_object_status!(model, object, replacement) for _ in 1:2 escape_registered_status!(sink, model, object.id, 1000) registered_status_allocations(sink, model, object.id, 1000) end @test registered_status_allocations(sink, model, object.id, 1000) == 0 - @test sink[] === replacement === object.status + @test sink[] === official_replacement === object.status + @test sink[] !== replacement @test PSE.refvalue(sink[], :items) === PSE.refvalue(replacement, :items) - @test object_id(model, replacement) === object.id + @test object_id(model, official_replacement) === object.id + @test_throws ArgumentError object_id(model, replacement) + @test_throws ArgumentError object_id(model, canonical) @test_throws ArgumentError object_id(model, supplied) @test supplied.items == Float32[3] end -@testset "status replacement moves family membership and exclusive ownership" begin +@testset "status replacement keeps the prepared family and exclusive official ownership" begin original = Status(value=1f0) first = Object(:first; status=original) occupied = Status(value=9.0) second = Object(:second; status=occupied) - model = CompositeModel(first, second) + model = CompositeModel(first, second; applications=(ModelSpec( + FamilyReplacement((value=3.0, counter=2)); name=:replacement, on=One(id=:first)),)) store = model.registry.objects + first_official = model_status(model, :first) + second_official = model_status(model, :second) previous = store.locations[first.id] replacement = Status(value=3.0, counter=2) - @test PSE._replace_model_object_status!(model, first, replacement) === replacement + official = PSE._replace_model_object_status!(model, first, replacement) + @test official !== replacement current = store.locations[first.id] - @test current.family != previous.family - @test isnothing(store.catalog.families[previous.family].rows[previous.row]) + @test current.family == previous.family + @test current.row == previous.row + @test store.catalog.families[current.family].rows[current.row].status === official @test model_object(model, :first) === first - @test first.status === model_status(model, :first) === replacement - @test object_id(model, replacement) === first.id + @test first.status === model_status(model, :first) === official + @test PSE.refvalue(official, :value) === PSE.refvalue(replacement, :value) + @test object_id(model, official) === first.id + @test_throws ArgumentError object_id(model, replacement) + @test_throws ArgumentError object_id(model, first_official) @test_throws ArgumentError object_id(model, original) @test original.value === 1f0 @test_throws ArgumentError PSE._replace_model_object_status!(model, first, occupied) - @test first.status === model_status(model, :first) === replacement - @test model_status(model, :second) === occupied + @test_throws ArgumentError PSE._replace_model_object_status!(model, first, second_official) + @test first.status === model_status(model, :first) === official + @test model_status(model, :second) === second_official @test store.locations[first.id] == current @test_throws ArgumentError PSE._replace_model_object_status!( model, Object(:first; status=Status(value=0.0)), Status(value=12.0)) @test model_object(model, :first) === first - @test model_status(model, :first) === replacement + @test model_status(model, :first) === official @test isnothing(PSE._replace_model_object_status!(model, first, nothing)) @test isnothing(model_status(model, :first)) - @test_throws ArgumentError object_id(model, replacement) - @test PSE._replace_model_object_status!(model, first, original) === original - @test object_id(model, original) === first.id + @test_throws ArgumentError object_id(model, official) + restored = PSE._replace_model_object_status!(model, first, original) + @test restored !== original + @test restored === model_status(model, :first) + @test PSE.refvalue(restored, :value) === PSE.refvalue(original, :value) + @test object_id(model, restored) === first.id + @test_throws ArgumentError object_id(model, original) end PSE.@process "canonical_family_increment" verbose = false @@ -200,7 +233,7 @@ end id = object_id(model, born) node = source_node(model, born) @test model_status(model, node) === born - @test born.node === node + @test !hasproperty(born, :node) @test source_node(model, id) === node @test object_id(model, node) === id @test born.value === 7f0 @@ -240,7 +273,8 @@ end grown = add_organ!(tip, model, :+, :Tip, 2; attributes=(new_field=4,)) @test typeof(source_node(model, grown)) === typeof(root) - @test grown.new_field === 4 + @test !hasproperty(grown, :new_field) + @test source_node(model, grown)[:new_field] === 4 # Explicit raw construction can create a different detached node family, # but cannot attach it to the homogeneous children vector of this tree. @@ -261,6 +295,7 @@ end copied_object = model_object(copied, :leaf) copied_status = model_status(copied, :leaf) @test copied_object !== object + @test copied_status !== model_status(model, :leaf) @test copied_status !== original @test copied_object.status === copied_status @test object_id(copied, copied_status) === ObjectId(:leaf) @@ -283,23 +318,33 @@ end @test closed.catalog.families isa Tuple @test keytype(closed.locations) === ObjectId{Int} @test closed[first.id] === first - @test (@inferred PSE._object_family_status(closed, first.id)) === first_status + canonical = model_status(model, first.id) + S = typeof(canonical) + inferred = Core.Compiler.return_type(PSE._object_family_status, + Tuple{typeof(closed),typeof(first.id)}) + @test inferred === Union{Nothing,S} + @test PSE._object_family_status(closed, first.id) === canonical + @test PSE.refvalue(canonical, :value) === PSE.refvalue(first_status, :value) store_type = typeof(closed) born = Object(2; status=Status(value=2f0)) + register_object!(model, born) closed[born.id] = born @test typeof(closed) === store_type @test length(closed) == 2 @test PSE._object_family_status(closed, born.id) === born.status @test closed.status_owners[PSE._status_identity(born.status)] === born.id - @test_throws ArgumentError setindex!(closed, Object(3; status=Status(value=3.0)), ObjectId(3)) + foreign = CompositeModel(Object(3; status=Status(value=3.0))) + @test_throws ArgumentError setindex!(closed, model_object(foreign, 3), ObjectId(3)) @test !haskey(closed, ObjectId(3)) @test length(closed) == 2 delete!(closed, born.id) @test length(closed) == 1 @test !haskey(closed.status_owners, PSE._status_identity(born.status)) + remove_object!(model, born.id) replacement = Object(2; status=Status(value=8f0)) + register_object!(model, replacement) closed[replacement.id] = replacement @test closed[replacement.id] === replacement @test PSE._object_family_status(closed, replacement.id).value === 8f0 @@ -310,24 +355,23 @@ end @test PSE._object_family_status(mixed_closed, ObjectId(1)).value === 1f0 @test isnothing(PSE._object_family_status(mixed_closed, ObjectId(:leaf))) - historical = CompositeModel(Object(:leaf; status=Status(value=1f0))) - PSE._replace_model_object_status!(historical, :leaf, Status(value=2.0, count=1)) - @test length(historical.registry.objects.catalog.families) == 2 - active = PSE._closed_object_family_store(historical.registry.objects) - @test length(active.catalog.families) == 1 - @test PSE._object_family_status(active, ObjectId(:leaf)).value === 2.0 - @test_throws ArgumentError setindex!(active, - Object(:newborn; status=Status(value=3f0)), ObjectId(:newborn)) + # Runtime discovery/retirement of arbitrary Status types is obsolete. + # Empty None+S retention is covered by test-prepared-status-registration. statuses = [Status(value=Float32(index), payload=ntuple(identity, index)) for index in 1:8] eight = CompositeModel((Object(index; status=status) for (index, status) in enumerate(statuses))...) eight_closed = PSE._closed_object_family_store(eight.registry.objects) - allowed = Union{typeof.(statuses)...} + official = [model_status(eight, index) for index in 1:8] + S = typeof(Base.first(official)) + allowed = Union{Nothing,S} inferred = Core.Compiler.return_type(PSE._object_family_status, Tuple{typeof(eight_closed),ObjectId{Int}}) @test inferred === allowed for (index, status) in enumerate(statuses) - @test PSE._object_family_status(eight_closed, ObjectId(index)) === status + canonical = PSE._object_family_status(eight_closed, ObjectId(index)) + @test canonical === official[index] + @test PSE.refvalue(canonical, :value) === PSE.refvalue(status, :value) + @test PSE.refvalue(canonical, :payload) === PSE.refvalue(status, :payload) end end diff --git a/test/test-organ-creation-allocation.jl b/test/test-organ-creation-allocation.jl index 7359a7abe..21efa1978 100644 --- a/test/test-organ-creation-allocation.jl +++ b/test/test-organ-creation-allocation.jl @@ -83,10 +83,17 @@ end end end +PlantSimEngine.@process "organ_creation_area" verbose=false +struct OrganCreationAreaModel <: AbstractOrgan_Creation_AreaModel end +PlantSimEngine.inputs_(::OrganCreationAreaModel) = NamedTuple() +PlantSimEngine.outputs_(::OrganCreationAreaModel) = (area=0.0,) +PlantSimEngine.run!(::OrganCreationAreaModel, status, environment, constants, context) = nothing + @testset "organ insertion preserves ids, status identity, and lifecycle snapshots" begin root = Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) plant = Node(root, MultiScaleTreeGraph.NodeMTG("+", :Plant, 1, 1)) - model = CompositeModel(root) + model = CompositeModel(root; applications=( + ModelSpec(OrganCreationAreaModel(); name=:area, on=Many(scale=:Leaf)),)) @test isempty(model.instances) @test isnothing(PlantSimEngine._instance_for_object(model, ObjectId(2))) @@ -95,7 +102,6 @@ end @test_throws ErrorException add_organ!( plant, model, :+, :Leaf, 2; attributes=(plantsimengine_status=nothing,), - use_status_adapter=false, ) @test object_ids(model) == initial_ids @test model.source_adapter.max_node_id[] == initial_max_id @@ -106,19 +112,19 @@ end id=40, attributes=(area=2.0,), initial_status=(area=3.0,), - use_status_adapter=false, ) automatic = add_organ!( plant, model, :+, :Leaf, 2; - use_status_adapter=false, ) @test object_id(model, explicit) == ObjectId(40) @test object_id(model, automatic) == ObjectId(41) + explicit_node = source_node(model, explicit) + automatic_node = source_node(model, automatic) @test explicit.area == 3.0 - @test explicit.node[:area] == 2.0 - @test model_status(model, explicit.node) === explicit - @test source_node(model, explicit) === explicit.node - @test !haskey(MultiScaleTreeGraph.node_attributes(explicit.node), :plantsimengine_status) + @test explicit_node[:area] == 2.0 + @test model_status(model, explicit_node) === explicit + @test source_node(model, explicit) === explicit_node + @test !haskey(MultiScaleTreeGraph.node_attributes(explicit_node), :plantsimengine_status) @test last(model.lifecycle_delta.added).ancestors == ( ObjectId(1), ObjectId(2), ObjectId(41), ) @@ -131,8 +137,8 @@ end remove_object!(model, ObjectId(40)) @test_throws ArgumentError object_id(model, explicit) - @test_throws ArgumentError object_id(model, explicit.node) - @test model_status(model, automatic.node) === automatic + @test_throws ArgumentError object_id(model, explicit_node) + @test model_status(model, automatic_node) === automatic @test only(model.lifecycle_delta.removed).ancestors == ( ObjectId(1), ObjectId(2), ObjectId(40), ) @@ -158,9 +164,9 @@ end environment=(duration=Hour(1),), ) simulation = run!(model; steps=0, outputs=:none) - first = add_organ!(plant_a, model, :+, :Leaf, 2; use_status_adapter=false) - second = add_organ!(plant_b, model, :+, :Leaf, 2; use_status_adapter=false) - sibling = add_organ!(plant_a, model, :+, :Leaf, 2; use_status_adapter=false) + first = add_organ!(plant_a, model, :+, :Leaf, 2) + second = add_organ!(plant_b, model, :+, :Leaf, 2) + sibling = add_organ!(plant_a, model, :+, :Leaf, 2) first_id = object_id(model, first) second_id = object_id(model, second) sibling_id = object_id(model, sibling) @@ -168,9 +174,9 @@ end @test model_object(model, second).species == :probe_species @test PlantSimEngine._instance_for_object(model, sibling_id).name == :first continue!(simulation) - @test model_status(model, first.node).signal == 1.0 - @test model_status(model, sibling.node).signal == 1.0 - @test model_status(model, second.node).signal == 10.0 + @test model_status(model, source_node(model, first)).signal == 1.0 + @test model_status(model, source_node(model, sibling)).signal == 1.0 + @test model_status(model, source_node(model, second)).signal == 10.0 compiled = simulation.compiled @test Set(compiled.applications_by_id[:first__allocation_probe].target_ids) == @@ -179,8 +185,8 @@ end [second_id] remove_object!(model, first_id) continue!(simulation) - @test model_status(model, sibling.node).signal == 2.0 - @test model_status(model, second.node).signal == 20.0 + @test model_status(model, source_node(model, sibling)).signal == 2.0 + @test model_status(model, source_node(model, second)).signal == 20.0 @test simulation.compiled.applications_by_id[:first__allocation_probe].target_ids == [sibling_id] end diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index ed1b8b14c..aae47895f 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -1,482 +1,121 @@ -# The oracle deliberately retains the former Dict assembly sequence. Do not -# implement it with _status_data! or the production organ-status assembler: -# they are the code under test, including their ordering and alias behavior. -function _organ_assembly_reference_overlay!(destination, source) - source === nothing && return destination - source isa Union{Status,NamedTuple,AbstractDict,Base.Pairs} || - error("unsupported organ-status source") - entries = source isa Status ? NamedTuple(source) : source - for (raw_key, value) in pairs(entries) - key = Symbol(raw_key) - if key === :plantsimengine_status - value === nothing && continue - error("reserved runtime-status value") - end - destination[key] = value - end - return destination -end - -function _organ_assembly_reference(node, adapted_status, initial_status) - data = Dict{Symbol,Any}() - _organ_assembly_reference_overlay!(data, MultiScaleTreeGraph.node_attributes(node)) - _organ_assembly_reference_overlay!(data, adapted_status) - data[:node] = node - _organ_assembly_reference_overlay!(data, initial_status) - data[:node] = node - names = Tuple(keys(data)) - # Wrap every scientific value exactly once, even when that value is itself - # a Ref. The all-Ref NamedTuple dispatch then preserves these fresh carriers. - return Status(NamedTuple{names}(Ref.(Tuple(values(data))))) -end - -function _organ_assembly_source(kind, values) - kind === :nothing && return nothing - kind === :namedtuple && return values - kind === :symbol_dict && return Dict{Symbol,Any}(pairs(values)) - kind === :string_dict && return Dict{String,Any}( - String(key) => value for (key, value) in pairs(values) - ) - kind === :pairs && return pairs(values) - kind === :status && return Status(; values...) - error("unsupported test source kind") -end - -function _organ_assembly_fixture(adapted_status; attributes=NamedTuple()) - root = MultiScaleTreeGraph.Node( - MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0), - ) - model = CompositeModel( - root; - status=node -> node === root ? nothing : adapted_status, - ) - node = MultiScaleTreeGraph.Node( - root, - MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 1), - attributes, - ) - return model, node -end - -function _organ_assembly_assert_reference(actual, expected) - @test propertynames(actual) == propertynames(expected) - @test Tuple(actual) == Tuple(expected) - @test typeof(actual) === typeof(expected) - for name in propertynames(expected) - @test actual[name] === expected[name] - @test PlantSimEngine.refvalue(actual, name) !== - PlantSimEngine.refvalue(expected, name) - end -end - -@testset "organ status assembly independent overlay oracle" begin - source_kinds = (:nothing, :namedtuple, :symbol_dict, :string_dict, :pairs, :status) - for adapted_kind in source_kinds, initial_kind in source_kinds - payload = [1, 2] - nested_reference = Ref(7) - adapted = _organ_assembly_source(adapted_kind, ( - overlap=2, - adapter_only=22, - node=:adapter_node, - payload=payload, - nested_reference=nested_reference, - plantsimengine_status=nothing, - )) - initial = _organ_assembly_source(initial_kind, ( - overlap=3, - initial_only=33, - node=:initial_node, - plantsimengine_status=nothing, - )) - model, node = _organ_assembly_fixture(adapted; attributes=( - overlap=1, - attribute_only=11, - node=:attribute_node, - )) - actual = PlantSimEngine._organ_status(model.source_adapter, node, initial) - expected = _organ_assembly_reference(node, adapted, initial) - _organ_assembly_assert_reference(actual, expected) - @test actual.node === node - @test !hasproperty(actual, :plantsimengine_status) - @test node[:node] === :attribute_node - @test actual.overlap == (initial_kind !== :nothing ? 3 : adapted_kind !== :nothing ? 2 : 1) - if adapted_kind !== :nothing - @test actual.payload === payload - @test actual.nested_reference === nested_reference - end - end -end - -@testset "organ status assembly retains former Dict field order across widths" begin - # Include sizes on both sides of table growth boundaries, with :node first - # introduced either by attributes or between the two overlay stages. - for attribute_count in (0, 7, 15, 31, 63), initial_count in (0, 1, 7, 17), attribute_node in (false, true) - attributes = Dict{Symbol,Any}( - Symbol("attribute_", i) => i for i in 1:attribute_count - ) - attribute_node && (attributes[:node] = :attribute_node) - initial = Dict{Symbol,Any}( - Symbol("initial_", i) => i for i in 1:initial_count - ) - initial[:node] = :initial_node - model, node = _organ_assembly_fixture(nothing; attributes=attributes) - actual = PlantSimEngine._organ_status(model.source_adapter, node, initial) - expected = _organ_assembly_reference(node, nothing, initial) - _organ_assembly_assert_reference(actual, expected) - end -end - -@testset "organ status assembly observes adapter effects before attributes" begin - root = MultiScaleTreeGraph.Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) +module ExplicitOrganStatusTests +using PlantSimEngine, Test +import MultiScaleTreeGraph as MTG +const PSE = PlantSimEngine + +PSE.@process "explicit_organ_status" verbose=false +struct Probe{T} <: AbstractExplicit_Organ_StatusModel + ambient::T +end +PSE.inputs_(model::Probe{T}) where {T} = (seed=Required(T), ambient=Default(model.ambient)) +PSE.outputs_(::Probe{T}) where {T} = (value=zero(T), payload=T[]) +PSE.run!(::Probe, status, environment, constants, context) = + (status.value = status.seed + status.ambient; nothing) + +function fixture(::Type{T}=Float32) where {T} + root = MTG.Node(1, MTG.NodeMTG(:/, :Scene, 1, 0), (note="scene",)) + MTG.Node(2, root, MTG.NodeMTG(:+, :Leaf, 1, 1), (note="existing", seed=T(1))) calls = Ref(0) - model = CompositeModel(root; status=node -> begin - node === root && return nothing + import_status(node) = begin calls[] += 1 - node[:created_by_adapter] = calls[] - node[:overlap] = 9 - return (overlap=10,) - end) - node = MultiScaleTreeGraph.Node( - root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 1), (overlap=1,), - ) - bypassed = PlantSimEngine._organ_status( - model.source_adapter, node, nothing; use_status_adapter=false, - ) - @test calls[] == 0 - @test bypassed.overlap == 1 - @test !hasproperty(bypassed, :created_by_adapter) - adapted = PlantSimEngine._organ_status(model.source_adapter, node, (overlap=11,)) - @test calls[] == 1 - @test adapted.created_by_adapter == 1 - @test adapted.overlap == 11 - @test node[:overlap] == 9 -end - -@testset "organ status assembly copies carriers and shares scientific payloads" begin - payload = [1, 2] - nested_reference = Ref(7) - source = Status(payload=payload, nested_reference=nested_reference, scalar=1) - model, node = _organ_assembly_fixture(source) - first = PlantSimEngine._organ_status(model.source_adapter, node, nothing) - second = PlantSimEngine._organ_status(model.source_adapter, node, nothing) - for name in (:payload, :nested_reference, :scalar) - @test PlantSimEngine.refvalue(first, name) !== PlantSimEngine.refvalue(source, name) - @test PlantSimEngine.refvalue(first, name) !== PlantSimEngine.refvalue(second, name) + MTG.symbol(node) === :Leaf ? Status(seed=node[:seed], payload=T[0]) : nothing end - @test first.payload === payload === second.payload - @test first.nested_reference === nested_reference === second.nested_reference - push!(payload, 3) - nested_reference[] = 8 - @test first.payload == [1, 2, 3] - @test first.nested_reference[] == 8 - source.scalar = 99 - source.payload = [4] - source.nested_reference = Ref(9) - @test first.scalar == second.scalar == 1 - @test first.payload === payload - @test first.nested_reference === nested_reference - first.scalar = 2 - @test second.scalar == 1 -end - -@testset "organ status assembly rejects real reserved values in either overlay" begin - kinds = (:namedtuple, :symbol_dict, :string_dict, :pairs, :status) - for kind in kinds, reserved in (false, Ref(nothing), Status(signal=1)) - invalid = _organ_assembly_source(kind, (plantsimengine_status=reserved,)) - model, node = _organ_assembly_fixture(invalid) - @test_throws ErrorException PlantSimEngine._organ_status( - model.source_adapter, node, nothing, - ) - @test_throws ErrorException PlantSimEngine._organ_status( - model.source_adapter, node, invalid; use_status_adapter=false, - ) + model = CompositeModel(root; status=import_status, + applications=(ModelSpec(Probe(T(2)); name=:probe, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + return (; root, model, simulation, calls) +end +function ownership_snapshot(data) + adapter = data.model.source_adapter + return (ids=object_ids(data.model), max_id=adapter.max_node_id[], + tree_next_id=MTG.new_id(data.root), + children=copy(MTG.children(data.root)), forward=copy(adapter.object_ids_by_node), + reverse=copy(adapter.nodes_by_object_id), added=length(data.model.lifecycle_delta.added), + conversion_records=copy(data.model.status_conversion_records)) +end + +@testset "explicit scientific data share references and leave metadata on the MTG" begin + for T in (Float32, BigFloat) + data = fixture(T) + imports = data.calls[] + payload = T[3, 4] + given = Status(seed=T(3), payload=payload) + seed_ref, payload_ref = PSE.refvalue(given, :seed), PSE.refvalue(given, :payload) + newborn = add_organ!(data.root, data.model, :+, :Leaf, 1; + attributes=(note="annotation", geometry_cache=[1, 2], seed=T(99)), + initial_status=given) + node = source_node(data.model, newborn) + @test data.calls[] == imports + @test newborn !== given + @test PSE.refvalue(newborn, :seed) === seed_ref + @test PSE.refvalue(newborn, :payload) === payload_ref + @test newborn.payload === payload + @test newborn.seed == T(3) + @test !hasproperty(newborn, :node) && !hasproperty(newborn, :note) + @test !hasproperty(newborn, :geometry_cache) + @test MTG.node_attributes(node)[:note] == "annotation" + @test node[:seed] == T(99) + @test model_status(data.model, node) === newborn + @test_throws ArgumentError object_id(data.model, given) + continue!(data.simulation; steps=0) + @test newborn.ambient == T(2) && newborn.value == zero(T) + @test typeof(newborn) === typeof(model_status(data.model, 2)) + @test typeof(newborn.seed) === typeof(newborn.ambient) === typeof(newborn.value) === T + second = add_organ!(data.root, data.model, :+, :Leaf, 1; + initial_status=(seed=T(4),)) + third = add_organ!(data.root, data.model, :+, :Leaf, 1; + initial_status=(seed=T(5),)) + continue!(data.simulation; steps=0) + @test second.payload == third.payload == T[] + @test second.payload !== third.payload + @test second.payload !== model_status(data.model, 2).payload + @test data.calls[] == imports + step!(data.simulation) + @test newborn.value == T(5) && second.value == T(6) && third.value == T(7) + given.seed = T(7) + @test newborn.seed == T(7) + push!(payload, T(5)) + @test newborn.payload == T[3, 4, 5] end end -@testset "organ status assembly failures remove newborn identities and recover" begin - for failure in (:adapter_throw, :invalid_adapter, :invalid_initial, :reserved_adapter, :reserved_initial, :reserved_attribute) - root = MultiScaleTreeGraph.Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) - newborn = Ref{Any}(nothing) - model = CompositeModel(root; status=node -> begin - node === root && return nothing - newborn[] = node - failure === :adapter_throw && error("intentional assembly failure") - failure === :invalid_adapter && return 17 - failure === :reserved_adapter && return (plantsimengine_status=Status(signal=1),) - failure === :reserved_attribute && (node[:plantsimengine_status] = Status(signal=1)) - return nothing - end) - initial = failure === :invalid_initial ? 17 : - failure === :reserved_initial ? (plantsimengine_status=Status(signal=1),) : nothing - initial_ids = object_ids(model) - initial_forward = copy(model.source_adapter.object_ids_by_node) - initial_reverse = copy(model.source_adapter.nodes_by_object_id) - initial_added = length(model.lifecycle_delta.added) - @test_throws ErrorException add_organ!( - root, model, :+, :Leaf, 1; initial_status=initial, - ) - @test isempty(MultiScaleTreeGraph.children(root)) - @test object_ids(model) == initial_ids - @test model.source_adapter.object_ids_by_node == initial_forward - @test model.source_adapter.nodes_by_object_id == initial_reverse - @test length(model.lifecycle_delta.added) == initial_added - @test_throws ArgumentError object_id(model, newborn[]) - # ColumnarAttrs may retain an empty reserved column after failed adapter - # mutation; that placeholder must not poison the next valid insertion. - recovered = add_organ!( - root, model, :+, :Leaf, 1; - initial_status=(signal=3,), use_status_adapter=false, - ) - @test recovered.signal == 3 - @test recovered.node === only(MultiScaleTreeGraph.children(root)) - @test model_status(model, recovered.node) === recovered - @test !hasproperty(recovered, :plantsimengine_status) +@testset "invalid explicit data never activate a newborn or reserve its model ID" begin + data = fixture() + before = ownership_snapshot(data) + for (invalid, expected) in ((17, ArgumentError), + ((plantsimengine_status=nothing,), ErrorException), + (Status(plantsimengine_status=nothing), ErrorException)) + @test_throws expected add_organ!(data.root, data.model, :+, :Leaf, 1; + initial_status=invalid) + @test ownership_snapshot(data) == before end -end - -@testset "Status value constructors preserve nested Ref distinction" begin - reference = Ref(7) - carrier_status = Status((value=reference,)) - tuple_status = Status{(:value,)}((reference,)) - keyword_status = Status(value=reference) - @test carrier_status.value == 7 - @test PlantSimEngine.refvalue(carrier_status, :value) === reference - @test tuple_status.value === reference - @test keyword_status.value === reference - @test PlantSimEngine.refvalue(tuple_status, :value) !== reference - @test PlantSimEngine.refvalue(keyword_status, :value) !== reference -end - -function _organ_assembly_assert_live(model, node; initial_status=NamedTuple(), use_status_adapter=true) - actual = PlantSimEngine._organ_status( - model.source_adapter, node, initial_status; - use_status_adapter=use_status_adapter, - ) - expected = _organ_assembly_reference(node, nothing, initial_status) - _organ_assembly_assert_reference(actual, expected) - @test actual.node === node - return actual -end - -@testset "organ status repeated layouts read each newborn's live values" begin - root = MultiScaleTreeGraph.Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) - model = CompositeModel(root) - first_payload, second_payload = [1], [2] - first = add_organ!(root, model, :+, :Leaf, 1; - attributes=(value=1, payload=first_payload, nullable=nothing), - ) - second = add_organ!(root, model, :+, :Leaf, 1; - attributes=(value=2, payload=second_payload, nullable=nothing), - initial_status=nothing, - ) - _organ_assembly_assert_reference(first, _organ_assembly_reference(first.node, nothing, NamedTuple())) - _organ_assembly_assert_reference(second, _organ_assembly_reference(second.node, nothing, nothing)) - @test first.value == 1 - @test second.value == 2 - @test first.payload === first_payload - @test second.payload === second_payload - @test first.node !== second.node - @test PlantSimEngine.refvalue(first, :value) !== PlantSimEngine.refvalue(second, :value) - second.node[:value] = 3 - reread = _organ_assembly_assert_live(model, second.node; initial_status=nothing) - @test reread.value == 3 - @test first.value == 1 - @test second.value == 2 -end - -@testset "organ status layouts follow column schema and row-local presence" begin - model, node = _organ_assembly_fixture(nothing; attributes=(kept=1, nullable=nothing, local_value=3)) - root = MultiScaleTreeGraph.get_root(node) - _organ_assembly_assert_live(model, node) - delete!(node, :local_value) - absent = _organ_assembly_assert_live(model, node) - @test !hasproperty(absent, :local_value) - @test hasproperty(absent, :nullable) - @test absent.nullable === nothing - node[:added_column] = 4 - @test _organ_assembly_assert_live(model, node).added_column == 4 - sibling = MultiScaleTreeGraph.Node( - root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 2, 1), (kept=2, local_value=9), - ) - sibling_status = _organ_assembly_assert_live(model, sibling; initial_status=nothing) - @test sibling_status.local_value == 9 - @test !hasproperty(sibling_status, :nullable) - @test !hasproperty(sibling_status, :added_column) - node[:local_value] = 5 - @test _organ_assembly_assert_live(model, node).local_value == 5 - MultiScaleTreeGraph.drop_column!(root, :Leaf, :added_column) - @test !hasproperty(_organ_assembly_assert_live(model, node), :added_column) - MultiScaleTreeGraph.rename_column!(root, :Leaf, :kept, :renamed) - renamed = _organ_assembly_assert_live(model, node) - @test renamed.renamed == 1 - @test !hasproperty(renamed, :kept) - MultiScaleTreeGraph.drop_column!(root, :Leaf, :local_value) - @test !hasproperty(_organ_assembly_assert_live(model, sibling), :local_value) -end - -@testset "organ status layouts include defaults while respecting explicit absence" begin - root = MultiScaleTreeGraph.Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) - model = CompositeModel(root) - MultiScaleTreeGraph.add_column!(root, :Leaf, :temperature, Float64; default=20.0) - first = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 1), (value=1,)) - second = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 2, 1), (value=2, temperature=25.0)) - @test _organ_assembly_assert_live(model, first).temperature == 20.0 - @test _organ_assembly_assert_live(model, second).temperature == 25.0 - pop!(first, :temperature) - @test !hasproperty(_organ_assembly_assert_live(model, first), :temperature) - third = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 3, 1), (value=3,)) - @test _organ_assembly_assert_live(model, third; initial_status=nothing).temperature == 20.0 - MultiScaleTreeGraph.add_column!(root, :Leaf, :humidity, Float64; default=0.5) - @test _organ_assembly_assert_live(model, first).humidity == 0.5 - @test _organ_assembly_assert_live(model, second).humidity == 0.5 -end - -@testset "organ status layouts survive row relocation and column widening" begin - root = MultiScaleTreeGraph.Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) - model = CompositeModel(root) - first_payload, last_payload = [1], [2] - first = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 1), (value=1, payload=first_payload)) - last = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 2, 1), (value=2, payload=last_payload)) - _organ_assembly_assert_live(model, first) - _organ_assembly_assert_live(model, last) - # Deleting the first row relocates the last row in the columnar bucket. - MultiScaleTreeGraph.delete_node!(first) - relocated = _organ_assembly_assert_live(model, last) - @test relocated.value == 2 - @test relocated.payload === last_payload - wide_payload = [3] - widened = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 3, 1), (value="wide", payload=wide_payload)) - @test _organ_assembly_assert_live(model, widened).value == "wide" - @test _organ_assembly_assert_live(model, last).value === 2 - last[:value] = 3 // 2 - reread = _organ_assembly_assert_live(model, last; initial_status=nothing) - @test reread.value === 3 // 2 - @test reread.payload === last_payload -end - -@testset "organ status layouts observe callbacks returning nothing on every call" begin - root = MultiScaleTreeGraph.Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) - calls = Ref(0) - model = CompositeModel(root; status=node -> begin - node === root && return nothing - calls[] += 1 - node[:callback_value] = calls[] - node[:signal] += 1 - if isodd(calls[]) - node[:odd_only] = calls[] - else - delete!(node, :odd_only) - end - return nothing - end) - node = MultiScaleTreeGraph.Node(root, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 1), (signal=1,)) - for call in 1:3 - status = _organ_assembly_assert_live(model, node) - @test calls[] == call - @test status.callback_value == call - @test status.signal == call + 1 - @test hasproperty(status, :odd_only) == isodd(call) + for initial in ((seed=1.0,), (seed=1f0, unprepared=2f0)) + @test_throws ArgumentError add_organ!(data.root, data.model, :+, :Leaf, 1; + initial_status=initial) + @test ownership_snapshot(data) == before end - bypassed = _organ_assembly_assert_live(model, node; use_status_adapter=false) - @test calls[] == 3 - @test bypassed.callback_value == 3 -end - -@testset "organ status equal layouts remain independent between model instances" begin - first_payload, second_payload = [1], [2] - first_reference, second_reference = Ref(1), Ref(2) - first_model, first_node = _organ_assembly_fixture(nothing; - attributes=(value=1, payload=first_payload, scientific_ref=first_reference), - ) - second_model, second_node = _organ_assembly_fixture(nothing; - attributes=(value=2, payload=second_payload, scientific_ref=second_reference), - ) - first = _organ_assembly_assert_live(first_model, first_node) - second = _organ_assembly_assert_live(second_model, second_node) - repeated_first = _organ_assembly_assert_live(first_model, first_node; initial_status=nothing) - @test first.payload === repeated_first.payload === first_payload - @test second.payload === second_payload - @test first.scientific_ref === first_reference - @test second.scientific_ref === second_reference - @test first.node === repeated_first.node === first_node - @test second.node === second_node - @test PlantSimEngine.refvalue(first, :value) !== PlantSimEngine.refvalue(repeated_first, :value) - first_node[:value] = 3 - @test _organ_assembly_assert_live(first_model, first_node).value == 3 - @test _organ_assembly_assert_live(second_model, second_node).value == 2 -end - -@testset "organ helper and Status constructors preserve historical wrapping across widths" begin - for width in (0, 1, 8, 36, 64, 129) - names = ntuple(i -> Symbol("constructor_value_", i), width) - data = ntuple(i -> isodd(i) ? Float32(i) : BigFloat(i), width) - named = NamedTuple{names}(data) - historical = Status(NamedTuple{names}(Ref.(data))) - constructed = ( - Status{names}(data), Status(named), Status(; named...), - PlantSimEngine._organ_status_from_values(Val(names), data), - ) - for status in constructed - _organ_assembly_assert_reference(status, historical) - @test PlantSimEngine._status_identity(status) !== PlantSimEngine._status_identity(historical) - end - for name in names - @test PlantSimEngine.refvalue(constructed[1], name) !== PlantSimEngine.refvalue(constructed[2], name) - @test PlantSimEngine.refvalue(constructed[2], name) !== PlantSimEngine.refvalue(constructed[3], name) - @test PlantSimEngine.refvalue(constructed[3], name) !== PlantSimEngine.refvalue(constructed[4], name) - end + given = Status(seed=3f0, payload=Float32[]) + newborn = add_organ!(data.root, data.model, :+, :Leaf, 1; initial_status=given) + after = ownership_snapshot(data) + @test_throws ArgumentError add_organ!(data.root, data.model, :+, :Leaf, 1; initial_status=given) + @test ownership_snapshot(data) == after + @test PSE.refvalue(newborn, :seed) === PSE.refvalue(given, :seed) +end + +@testset "the initial data grammar has one Status construction path" begin + payload = Float32[1, 2] + for source in ((value=3f0, payload=payload), Dict(:value=>3f0, :payload=>payload), + Dict("value"=>3f0, "payload"=>payload), pairs((value=3f0, payload=payload))) + status = PSE._organ_status(source) + @test status.value === 3f0 && status.payload === payload + @test !hasproperty(status, :node) end - + given = Status(value=3f0, payload=payload) + @test PSE._organ_status(given) === given + @test isempty(PSE._organ_status(nothing)) nested = Ref(7) - array_reference = Ref([8, 9], 2) - payload = [10] - named = (single=Float32(1.25), precise=BigFloat("2.5"), nested=nested, array_ref=array_reference, payload=payload) - names, data = keys(named), values(named) - historical = Status(NamedTuple{names}(Ref.(data))) - constructed = ( - Status{names}(data), Status(named), Status(; named...), - PlantSimEngine._organ_status_from_values(Val(names), data), - ) - for status in constructed - _organ_assembly_assert_reference(status, historical) - @test status.nested === nested - @test status.array_ref === array_reference - @test PlantSimEngine.refvalue(status, :nested) !== nested - @test PlantSimEngine.refvalue(status, :array_ref) !== array_reference - end - nested[] = 11 - array_reference[] = 12 - push!(payload, 13) - for status in constructed - @test status.nested[] == 11 - @test status.array_ref[] == 12 - @test status.payload === payload - @test status.payload == [10, 13] - end - # A NamedTuple containing only carriers continues to use the inner - # constructor, rather than treating those carriers as scientific values. - carriers = Status((nested=nested, array_ref=array_reference)) - @test PlantSimEngine.refvalue(carriers, :nested) === nested - @test PlantSimEngine.refvalue(carriers, :array_ref) === array_reference - - for (names, data) in (((:a,), ()), ((), (1,)), ((:a, :b), (1,))) - historical_error = try - Status(NamedTuple{names}(Ref.(data))) - catch caught - caught - end - actual_error = try - Status{names}(data) - catch caught - caught - end - @test historical_error isa Exception - @test typeof(actual_error) === typeof(historical_error) - helper_error = try - PlantSimEngine._organ_status_from_values(Val(names), data) - catch caught - caught - end - @test typeof(helper_error) === typeof(historical_error) - end + status = PSE._organ_status((value=nested,)) + @test PSE.refvalue(status, :value) === nested + @test status.value == 7 +end end diff --git a/test/test-prepared-status-registration.jl b/test/test-prepared-status-registration.jl new file mode 100644 index 000000000..ba4775cf7 --- /dev/null +++ b/test/test-prepared-status-registration.jl @@ -0,0 +1,103 @@ +module PreparedStatusRegistrationChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine + +PSE.@process "prepared_registration_source" verbose=false +struct Source{T} <: AbstractPrepared_Registration_SourceModel + initial::T +end +PSE.inputs_(::Source) = NamedTuple() +PSE.outputs_(model::Source) = (x=model.initial,) +PSE.run!(::Source, status, environment, constants, context) = nothing + +function fixture() + first = Object(:plant_a; scale=:Plant) + second = Object(17; scale=:Plant) + a = Object(:leaf_a; scale=:Leaf, parent=first.id, status=Status(x=1f0)) + b = Object(:leaf_b; scale=:Leaf, parent=second.id, status=Status(x=2.0)) + template(value) = CompositeModelTemplate(( + ModelSpec(Source(value); name=:source, on=Many(scale=:Leaf)),); + kind=:tree, species=:same) + model = CompositeModel( + ObjectInstance(:a, template(0f0); root=first, objects=(a,)), + ObjectInstance(:b, template(0.0); root=second, objects=(b,))) + return (; model, first, second, a, b) +end + +@testset "prepared registration preserves IDs, scopes, references and inactive None" begin + data = fixture() + model = data.model + store = model.registry.objects + @test keytype(store) === ObjectId + @test isnothing(model_status(model, data.first.id)) + @test isnothing(model_status(model, data.second.id)) + manifest = PSE._scenario_preparation(model).status_manifest + @test store.catalog.status_manifest === manifest + S = manifest.status_type + @test typeof(model_status(model, data.a.id)) === S + @test typeof(model_status(model, data.b.id)) === S + + # Both instances have the same labels and global slot bounds contain32/64. + # Scope, not those marginal bounds, must reject64 under the32 application. + wrong_source = Status(x=3.0) + wrong = Object(:wrong; scale=:Leaf, parent=data.first.id, status=wrong_source) + before = copy(data.first.children) + records = copy(model.status_conversion_records) + @test_throws ArgumentError register_object!(model, wrong) + @test wrong.status === wrong_source + @test isnothing(wrong.kind) && isnothing(wrong.species) + @test data.first.children == before + @test model.status_conversion_records == records + @test !haskey(store, wrong.id) + + supplied = Status(x=4f0) + reference = PSE.refvalue(supplied, :x) + newborn = Object((:new, 2); scale=:Leaf, parent=data.first.id, status=supplied) + @test register_object!(model, newborn) === newborn + @test typeof(model_status(model, newborn.id)) === S + @test PSE.refvalue(model_status(model, newborn.id), :x) === reference + @test newborn.kind === :tree && newborn.species === :same + # The official header has its own token; biological references stay shared. + @test model_status(model, newborn.id) !== supplied + @test_throws ArgumentError object_id(model, supplied) + @test object_id(model, model_status(model, newborn.id)) === newborn.id + + override_source = Status(x=5.0) + override_ref = PSE.refvalue(override_source, :x) + moved_parent = Object(:override_parent; scale=:Leaf, parent=data.first.id, status=override_source) + @test register_object!(model, moved_parent; parent=data.second.id) === moved_parent + @test moved_parent.parent === data.second.id + @test PSE.refvalue(model_status(model, moved_parent.id), :x) === override_ref + @test PSE._prepared_status_application_matches(model, moved_parent, data.second.id, + only(recipe for recipe in manifest.authored if recipe.id === :b__source)) +end + +@testset "empty prepared catalogs retain None and S without biological values" begin + model = CompositeModel(Object(:only)) + S = PSE._scenario_preparation(model).status_manifest.status_type + closed = PSE._closed_object_family_store(model.registry.objects) + C = typeof(closed.catalog) + @test isnothing(model_status(model, :only)) + empty!(closed) + @test isempty(closed) + @test typeof(closed.catalog) === C + @test PSE._with_prepared_canonical_status_type(identity, closed.catalog) === S + @test all(isempty(family.rows) for family in closed.catalog.families) +end + +@testset "future explicit Scope is inactive until its real root is registered" begin + selector = Many(Scope(ObjectId(:future_root)), scale=:Leaf) + model = CompositeModel(Object(:seed; status=Status(x=1f0)); applications=( + ModelSpec(Source(0f0); name=:future, on=selector),)) + # Preparation only records prospective types; the public query still rejects + # an unresolved current scope instead of silently changing query semantics. + @test_throws ErrorException resolve_object_ids(model, selector) + source = Status(x=2f0) + reference = PSE.refvalue(source, :x) + root = Object(:future_root; scale=:Leaf, status=source) + @test register_object!(model, root) === root + @test PSE.refvalue(model_status(model, root.id), :x) === reference + @test resolve_object_ids(model, selector) == [root.id] +end + +end diff --git a/test/test-registered-status-dispatch.jl b/test/test-registered-status-dispatch.jl index 46530d0a6..7d13de21a 100644 --- a/test/test-registered-status-dispatch.jl +++ b/test/test-registered-status-dispatch.jl @@ -3,30 +3,10 @@ module RegisteredStatusDispatchChecks using PlantSimEngine, Test const PSE = PlantSimEngine -const Seed32 = Status{(:seed,),Tuple{Base.RefValue{Float32}}} -const Seed64 = Status{(:seed,),Tuple{Base.RefValue{Float64}}} -const SeedReal = Status{(:seed,),Tuple{Base.RefValue{Real}}} -const SeedAny = Status{(:seed,),Tuple{Base.RefValue{Any}}} -const Full32 = Status{(:seed,:value,:visits), - Tuple{Base.RefValue{Float32},Base.RefValue{Float64},Base.RefValue{Int}}} -const Full64 = Status{(:seed,:value,:visits), - Tuple{Base.RefValue{Float64},Base.RefValue{Float64},Base.RefValue{Int}}} -const FullReal = Status{(:seed,:value,:visits), - Tuple{Base.RefValue{Real},Base.RefValue{Float64},Base.RefValue{Int}}} -const FullAny = Status{(:seed,:value,:visits), - Tuple{Base.RefValue{Any},Base.RefValue{Float64},Base.RefValue{Int}}} - -function closed_model(model, future::Tuple) +function with_finite_registry(model) previous = model.registry - active = PSE._closed_object_family_store(previous.objects) - I = keytype(active) - empty_families = map(future) do S - PSE.ObjectFamily{I,S}(Union{Nothing,PSE.ObjectFamilyRow{I,S}}[]) - end - families = (active.catalog.families..., empty_families...) - store = PSE.ObjectFamilyStore(PSE.ClosedObjectFamilyCatalog(families), - active.locations, active.status_owners, active.layout_cache) - registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + objects = PSE._closed_object_family_store(previous.objects) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) fields = map(fieldnames(typeof(model))) do name name === :registry ? registry : getfield(model, name) @@ -34,67 +14,98 @@ function closed_model(model, future::Tuple) return PSE.CompositeModel(fields...) end -@testset "eight erased statuses execute inside their concrete family branch" begin +@testset "erased statuses share one prepared schema and retain their real references" begin supplied = [Status(value=Float32(index), payload=ntuple(identity, index)) for index in 1:8] model = CompositeModel((Object(index; status=status) for (index,status) in enumerate(supplied))...) catalog = PSE._closed_object_family_store(model.registry.objects).catalog + official = [model_status(model, index) for index in 1:8] + S = PSE._scenario_preparation(model).status_manifest.status_type seen = DataType[] for index in 1:8 erased = model_object(model, index).status matched = PSE._with_registered_status(catalog, erased) do status push!(seen, typeof(status)) status.value += 1f0 - status === supplied[index] + status === official[index] end @test matched + @test erased !== supplied[index] + @test PSE.refvalue(erased, :value) === PSE.refvalue(supplied[index], :value) + @test PSE.refvalue(erased, :payload) === PSE.refvalue(supplied[index], :payload) @test supplied[index].value === Float32(index + 1) + @test_throws ArgumentError object_id(model, supplied[index]) end - @test seen == typeof.(supplied) + @test seen == fill(S, 8) @test_throws ArgumentError PSE._with_registered_status(identity, catalog, Status(unknown=1)) end -@testset "newborn registration and finishing retain real reference types" begin - model = closed_model(CompositeModel(Object(:owner; status=Status(count=0))), - (Seed32,Seed64,SeedReal,SeedAny,Full32,Full64,FullReal,FullAny)) - for (id, seed, Expected) in ((:a, Status(seed=3f0), Full32), - (:b, Status(seed=4.0), Full64), - (:c, Status((seed=Ref{Real}(5f0),)), FullReal), - (:d, Status((seed=Ref{Any}(6f0),)), FullAny)) +PSE.@process "registered_status_finisher" verbose=false +struct Finisher <: AbstractRegistered_Status_FinisherModel end +PSE.inputs_(::Finisher) = NamedTuple() +PSE.outputs_(::Finisher) = (value=0.5, visits=0) +PSE.run!(::Finisher, status, environment, constants, context) = nothing + +@testset "newborn registration and finishing retain real reference classes" begin + # These are genuine initial data, all retained and checked below. Their Ref + # classes provide the raw seed family; ports provide value/visits permissions. + existing = ( + Status(seed=1f0, value=0.5, visits=0), + Status(seed=2.0, value=0.5, visits=0), + Status((seed=Ref{Real}(3f0), value=Ref(0.5), visits=Ref(0))), + Status((seed=Ref{Any}(4f0), value=Ref(0.5), visits=Ref(0))), + ) + model = with_finite_registry(CompositeModel( + Object(:owner; status=Status(count=0)), + (Object(Symbol(:existing_, index); parent=:owner, scale=:Leaf, status=status) + for (index,status) in enumerate(existing))...; + applications=(ModelSpec(Finisher(); name=:finish, on=Many(scale=:Leaf)),))) + S = PSE._scenario_preparation(model).status_manifest.status_type + for (index, supplied) in enumerate(existing) + @test typeof(model_status(model, Symbol(:existing_, index))) === S + @test PSE.refvalue(model_status(model, Symbol(:existing_, index)), :seed) === + PSE.refvalue(supplied, :seed) + end + for (id, seed) in ((:a, Status(seed=3f0)), (:b, Status(seed=4.0)), + (:c, Status((seed=Ref{Real}(5f0),))), + (:d, Status((seed=Ref{Any}(6f0),)))) object = Object(id; parent=:owner, scale=:Leaf, status=seed) @test register_object!(model, object) === object - @test model_status(model, id) === seed - @test object_id(model, seed) === ObjectId(id) + canonical = model_status(model, id) + @test canonical !== seed + @test typeof(canonical) === S + @test_throws ArgumentError object_id(model, seed) + @test object_id(model, canonical) === ObjectId(id) seed_ref = PSE.refvalue(seed, :seed) value, visits = Ref(0.5), Ref(0) - recipe = PSE._CanonicalStatusRecipe(seed) + I = keytype(model.registry.objects) + recipes = PSE._canonical_status_recipe_storage(model, I) + order = I[] + recipe = PSE._status_recipe_for_object!(recipes, order, model, ObjectId(id)) PSE._status_recipe_set_reference!(recipe, :value, value) PSE._status_recipe_set_reference!(recipe, :visits, visits) - PSE._finish_canonical_status_recipe(model, recipe) do status - @test typeof(status) === Expected - PSE._replace_model_object_status!(model, object, status) - end + PSE._apply_status_recipes!(model, recipes, order) full = model_status(model, id) - @test typeof(full) === Expected + @test full === canonical === object.status + @test typeof(full) === S @test PSE.refvalue(full, :seed) === seed_ref @test PSE.refvalue(full, :value) === value @test PSE.refvalue(full, :visits) === visits - @test full === object.status - @test object_id(model, full) === ObjectId(id) - @test_throws ArgumentError object_id(model, seed) - if Expected === FullAny + @test (full.seed, full.value, full.visits) == (seed.seed, 0.5, 0) + if id === :d seed_ref[] = :later @test full.seed === :later - elseif Expected === FullReal + elseif id === :c seed_ref[] = 9.0 @test full.seed === 9.0 end end - unsupported = Object(:wrong; parent=:owner, status=Status(seed=Int8(1))) + unsupported = Object(:wrong; parent=:owner, scale=:Leaf, status=Status(seed=Int8(1))) original = unsupported.status + before = copy(model_object(model, :owner).children) @test_throws ArgumentError register_object!(model, unsupported) @test unsupported.status === original @test !haskey(model.registry.objects, ObjectId(:wrong)) - @test !(ObjectId(:wrong) in model_object(model, :owner).children) + @test model_object(model, :owner).children == before end PSE.@process "registered_status_review_private" verbose=false @@ -108,19 +119,17 @@ function PSE.run!(::PrivateWriter, status, environment, constants, context) return nothing end -@testset "private stream-only schema is not a canonical object family" begin +@testset "private stream-only references stay absent from canonical storage" begin source = CompositeModel(Object(:leaf; status=Status(seed=1.0)); applications=(ModelSpec(PrivateWriter(); name=:private_writer, on=One(id=:leaf), output_routing=(x=:stream_only,)),)) - model = closed_model(source, ()) + model = with_finite_registry(source) canonical = model_status(model, :leaf) @test propertynames(canonical) == (:seed,) - - # The private (seed,x) status belongs to this application's runtime view. - # It must not need an unused (seed,x) canonical registry family. + @test !hasproperty(canonical, :x) simulation = run!(model; steps=2, outputs=:all) @test model_status(model, :leaf) === canonical - @test propertynames(model_status(model, :leaf)) == (:seed,) + @test propertynames(canonical) == (:seed,) rows = collect_outputs(simulation, :leaf, :x; sink=nothing) @test getproperty.(rows, :value) == [1.0, 2.0] end @@ -131,13 +140,15 @@ end push!(seen, (name,typeof(value))) value end - model = closed_model(CompositeModel(Object(:owner; status=Status(count=0)); - type_promotion=Dict(Float64=>Float32), status_transform=transform), (Seed32,)) + model = with_finite_registry(CompositeModel( + Object(:owner; status=Status(count=0)), + Object(:existing; parent=:owner, scale=:Leaf, status=Status(seed=1.0)); + type_promotion=Dict(Float64=>Float32), status_transform=transform)) baseline_calls = length(seen) supplied = Status(seed=3.0) - born = register_object!(model, Object(:leaf; parent=:owner, status=supplied)) + born = register_object!(model, Object(:leaf; parent=:owner, scale=:Leaf, status=supplied)) effective = model_status(model, :leaf) - @test typeof(effective) === Seed32 + @test typeof(effective) === PSE._scenario_preparation(model).status_manifest.status_type @test effective === born.status @test effective.seed === 3f0 @test supplied.seed === 3.0 @@ -145,21 +156,25 @@ end @test last(seen) == (:seed,Float64) @test PSE.refvalue(effective, :seed) !== PSE.refvalue(supplied, :seed) @test object_id(model, effective) === ObjectId(:leaf) - @test_throws ArgumentError register_object!(model, Object(:other; status=supplied)) + @test_throws ArgumentError register_object!(model, Object(:other; scale=:Leaf, status=supplied)) @test length(seen) == baseline_calls + 1 @test !haskey(model.registry.objects, ObjectId(:other)) end -@testset "unadmitted edited reference types fail without replacing live state" begin - seed = Status(seed=2.0) - model = closed_model(CompositeModel(Object(:leaf; status=seed)), (Full64,)) - recipe = PSE._CanonicalStatusRecipe(seed) - PSE._status_recipe_set_reference!(recipe, :value, Ref(0f0)) - PSE._status_recipe_set_reference!(recipe, :visits, Ref(0)) - publish = status -> PSE._replace_model_object_status!(model, :leaf, status) - @test_throws ArgumentError PSE._finish_canonical_status_recipe(publish, model, recipe) - @test model_status(model, :leaf) === seed - @test object_id(model, seed) === ObjectId(:leaf) +@testset "incompatible edited references fail before changing live cells" begin + supplied = Status(seed=2.0) + model = with_finite_registry(CompositeModel(Object(:leaf; scale=:Leaf, status=supplied); + applications=(ModelSpec(Finisher(); name=:finish, on=Many(scale=:Leaf)),))) + official = model_status(model, :leaf) + seed_ref = PSE.refvalue(official, :seed) + recipe = PSE._CanonicalStatusRecipe(official, false) + @test_throws ArgumentError PSE._status_recipe_set_reference!(recipe, :value, Ref(0f0)) + @test isempty(recipe.edit_names) + @test model_status(model, :leaf) === official + @test !hasproperty(official, :value) && !hasproperty(official, :visits) + @test PSE.refvalue(official, :seed) === seed_ref + @test object_id(model, official) === ObjectId(:leaf) + @test_throws ArgumentError object_id(model, supplied) end end diff --git a/test/test-status-construction.jl b/test/test-status-construction.jl index f8a860e22..09d397bcc 100644 --- a/test/test-status-construction.jl +++ b/test/test-status-construction.jl @@ -6,79 +6,41 @@ using Test const PSE = PlantSimEngine -@testset "cached layouts preserve order and use the actual reference types" begin - model = CompositeModel(Object(:object; status=Status())) +@testset "exact projection preserves order and actual reference identities" begin original = Status(keep=1, replace=2.0) keep = PSE.refvalue(original, :keep) replacement = Ref(3.0f0) tail = Ref([4.0]) - edits = PSE._CanonicalStatusRecipe(original) - @test fieldtype(typeof(edits), :original) === typeof(original) - @test (@inferred PSE._status_recipe_has_variable(edits, :keep)) - @test isempty(edits.edit_names) - @test isempty(edits.edit_references) - @test !PSE._status_recipe_set_reference!(edits, :keep, keep) - @test PSE._status_recipe_set_reference!(edits, :replace, replacement) - @test PSE._status_recipe_set_reference!(edits, :tail, tail) - @test !PSE._status_recipe_set_reference!(edits, :tail, tail) - constructed = PSE._finish_canonical_status_recipe(identity, model, edits) - @test propertynames(constructed) == (:keep, :replace, :tail) - @test PSE.refvalue(constructed, :keep) === keep - @test PSE.refvalue(constructed, :replace) === replacement - @test PSE.refvalue(constructed, :tail) === tail - @test PSE._status_recipe_reference(edits, :keep) === keep - @test PSE._status_recipe_reference(edits, :replace) === replacement - @test_throws KeyError PSE._status_recipe_reference(edits, :absent) - @test PSE._finish_canonical_status_recipe(identity, model, PSE._CanonicalStatusRecipe(original)) === original - - cache = model.registry.objects.layout_cache - layout = only(values(cache)) - same_shape = PSE._CanonicalStatusRecipe(Status(keep=8, replace=9.0)) - PSE._status_recipe_set_reference!(same_shape, :replace, Ref(big"10.0")) - PSE._status_recipe_set_reference!(same_shape, :tail, Ref([11.0f0])) - another = PSE._finish_canonical_status_recipe(identity, model, same_shape) - @test typeof(another) !== typeof(constructed) - @test another.replace isa BigFloat - @test another.tail isa Vector{Float32} - @test length(cache) == 1 - @test only(values(cache)) === layout - @test all(isbits, values(cache)) - @test all(key -> key isa Tuple{Tuple{Vararg{Symbol}},Tuple{Vararg{Symbol}}}, keys(cache)) + Result = PSE._dense_status_type((:keep, :replace, :tail), + Tuple{typeof(keep),typeof(replacement),typeof(tail)}) + Edited = Tuple{typeof(replacement),typeof(tail)} + factory = PSE.ExactReferenceFactory(typeof(original), Edited, Result, (:replace,:tail)) + constructed = PSE._construct_status(factory, original, (replacement,tail)) + @test propertynames(constructed) == (:keep,:replace,:tail) + @test PSE.refvalue(constructed,:keep) === keep + @test PSE.refvalue(constructed,:replace) === replacement + @test PSE.refvalue(constructed,:tail) === tail + @test Tuple(constructed) == (1,3f0,[4.0]) + constructed.replace = 5f0 + @test replacement[] === 5f0 + @test original.replace === 2.0 storage = [12.0] - external = Ref(storage, 1) - external_edit = PSE._CanonicalStatusRecipe(Status(keep=1)) - PSE._status_recipe_set_reference!(external_edit, :external, external) - external_status = PSE._finish_canonical_status_recipe(identity, model, external_edit) - @test PSE.refvalue(external_status, :external) === external + external = Ref(storage,1) + External = PSE._dense_status_type((:keep,:external),Tuple{typeof(keep),typeof(external)}) + external_factory = PSE.ExactReferenceFactory(typeof(original),Tuple{typeof(external)}, + External,(:external,)) + external_status = PSE._construct_status(external_factory,original,(external,)) + @test PSE.refvalue(external_status,:external) === external storage[1] = 13.0 - @test external_status.external == 13.0 + @test external_status.external === 13.0 - empty_a = PSE._finish_canonical_status_recipe(identity, model, PSE._CanonicalStatusRecipe(nothing)) - empty_b = PSE._finish_canonical_status_recipe(identity, model, PSE._CanonicalStatusRecipe(nothing)) + Empty = PSE._dense_status_type((),Tuple{}) + empty_factory = PSE.ExactReferenceFactory(Nothing,Tuple{},Empty,()) + empty_a = PSE._construct_status(empty_factory,nothing,()) + empty_b = PSE._construct_status(empty_factory,nothing,()) @test propertynames(empty_a) == () - @test getfield(empty_a, :identity) !== getfield(empty_b, :identity) - @test all(isbits, values(cache)) - projected = PSE._closed_object_family_store(model.registry.objects) - @test projected.layout_cache == cache - @test projected.layout_cache !== cache - recipes = @inferred PSE._canonical_status_recipe_storage(projected.catalog, keytype(projected)) - Original = typeof(model_status(model, :object)) - @test valtype(typeof(recipes)) === Union{PSE._CanonicalStatusRecipe{Nothing}, - PSE._CanonicalStatusRecipe{Original}} - @test isempty(recipes) - order = keytype(projected)[] - staged = PSE._status_recipe_for_object!(recipes, order, model, ObjectId(:object)) - @test staged.original === model_status(model, :object) - @test typeof(staged) === PSE._CanonicalStatusRecipe{Original} - @test PSE._status_recipe_for_object!(recipes, order, model, ObjectId(:object)) === staged - @test order == [ObjectId(:object)] - @test isempty(CompositeModel(Object(:other)).registry.objects.layout_cache) - discarded = PSE.ObjectFamilyStore() - merge!(discarded.layout_cache, cache) - empty!(discarded) - @test isempty(discarded.layout_cache) - @test !isempty(cache) + @test getfield(empty_a,:identity) !== getfield(empty_b,:identity) end PSE.@process "status_construction_defaults" verbose=false @@ -112,7 +74,6 @@ PSE.run!(::MutableDefaults, status, environment, constants, context) = nothing @test second == Float32[1] @test third == Float32[9] @test initial[] == [9.0] - @test all(isbits, values(model.registry.objects.layout_cache)) end PSE.@process "status_construction_producer" verbose=false @@ -171,6 +132,7 @@ PSE.run!(::TransactionDefault, status, environment, constants, context) = nothin ModelSpec(TransactionDefault(1.0); name=:first_default, on=One(id=:first)), ModelSpec(TransactionDefault(2.0); name=:second_default, on=One(id=:second)), ), environment=(duration=Hour(1),), status_transform=transform) + @test isempty(converted) # type preparation never runs the pending transform first = model_status(model, :first) second = model_status(model, :second) records = copy(model.status_conversion_records) @@ -217,7 +179,6 @@ PSE.run!(::DistributedDefaults, status, environment, constants, context) = nothi @test model_status(model, :right_new).flow == Float32[4] @test model_status(model, :left_leaf).flow == Float32[1] @test model_status(model, :right_leaf).flow == Float32[2] - @test all(isbits, values(model.registry.objects.layout_cache)) end end diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl new file mode 100644 index 000000000..51b439c1b --- /dev/null +++ b/test/test-status-fixed-storage.jl @@ -0,0 +1,121 @@ +module FixedStatusStorageChecks +using PlantSimEngine, Test +const PSE = PlantSimEngine +const RF32 = Base.RefValue{Float32} +const RF64 = Base.RefValue{Float64} +const RR = Base.RefValue{Rational{Int}} +const RV32 = Base.RefValue{Vector{Float32}} +const RC32 = Base.RefValue{PSE.RefVector{Float32}} +const RN = Base.RefValue{Nothing} +const NAMES = (:x,:q,:seed,:literal,:private_only) +const SCHEMA = PSE._fixed_status_type(NAMES, Tuple{Union{RF32,RF64},RR,Union{RV32,RC32},RN,Nothing}) + +@testset "fixed canonical namespace has real presence, exact refs and stable identity" begin + source = Status(x=3f0, q=1//2, seed=Float32[2]) + state = PSE._new_prepared_status(SCHEMA, source) + @test state isa SCHEMA + @test PSE._new_prepared_status(SCHEMA,state) === state + @test keys(state) === (:x,:q,:seed) + @test Tuple(state) == (3f0,1//2,Float32[2]) + @test !hasproperty(state,:literal) && !hasproperty(state,:private_only) + @test fieldtype(PSE._status_schema_references(SCHEMA),5) === Nothing + @test_throws KeyError state.literal + for name in keys(source) + @test PSE.refvalue(state,name) === PSE.refvalue(source,name) + end + header = PSE._status_identity(state) + epoch = PSE._status_reference_epoch(state) + state.x = 5f0 + @test source.x === 5f0 + @test PSE._status_reference_epoch(state) == epoch + PSE._set_status_reference!(state,:x,PSE.refvalue(state,:x)) + @test PSE._status_reference_epoch(state) == epoch + literal = Ref(nothing) + PSE._set_status_reference!(state,:literal,literal) + @test hasproperty(state,:literal) && state.literal === nothing + @test keys(state) === (:x,:q,:seed,:literal) + @test PSE._status_identity(state) === header + @test PSE._status_reference_epoch(state) == epoch+1 + @test_throws ArgumentError PSE._set_status_reference!(state,:private_only,Ref(1)) + @test_throws ArgumentError PSE._set_status_reference!(state,:private_only,Ref(nothing)) + @test !hasproperty(state,:private_only) + PrivateProjection = PSE._projected_status_type(SCHEMA,(:private_only,),Tuple{RF32}) + private_ref = Ref(7f0) + private_view = PSE._construct_status( + PSE.ExactReferenceFactory(SCHEMA,Tuple{RF32},PrivateProjection,(:private_only,)), + state,(private_ref,)) + @test private_view.private_only === 7f0 + @test PSE.refvalue(private_view,:private_only) === private_ref + @test !hasproperty(state,:private_only) + @test_throws ArgumentError PSE._new_prepared_status(SCHEMA,Status(x="invalid")) + @test_throws ArgumentError PSE._new_prepared_status(SCHEMA,Status(unprepared=1)) + carrier = PSE.RefVector([Ref(8f0)]) + carrier_ref = Ref(carrier) + PSE._set_status_reference!(state,:seed,carrier_ref) + @test PSE.refvalue(state,:seed) === carrier_ref + @test carrier !== source.seed + shallow = copy(state) + @test PSE.refvalue(shallow,:x) === PSE.refvalue(state,:x) + @test PSE._status_identity(shallow) !== header + PSE._drop_status_reference!(shallow,:literal) + @test !hasproperty(shallow,:literal) && hasproperty(state,:literal) + PSE._set_status_reference!(shallow,:literal,literal) + @test keys(shallow) === keys(state) +end + +@testset "dense hot and full namespace snapshot use identical private overrides" begin + owner = PSE._new_prepared_status(SCHEMA,Status(x=3f0,q=1//2,seed=Float32[2])) + private = Ref(100.0) + Projected = PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF64,RR}) + factory = PSE.ExactReferenceFactory(SCHEMA,Tuple{RF64},Projected,(:x,)) + old = PSE._construct_status(factory,owner,(private,)) + @test old.x === 100.0 && first(Tuple(old)) === 100.0 + @test PSE.refvalue(old,:x) === private + @test PSE.refvalue(old,:seed) === PSE.refvalue(owner,:seed) + @test keys(old) === (:x,:q,:seed) + replacement = Ref(4f0) + PSE._set_status_reference!(owner,:x,replacement) + PSE._set_status_reference!(owner,:literal,Ref(nothing)) + @test keys(old) === (:x,:q,:seed) && !hasproperty(old,:literal) + @test old.x === 100.0 && PSE.refvalue(old,:x) === private + Fresh = PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF32,RR}) + current = PSE._construct_status(PSE.ExactReferenceFactory(SCHEMA,Tuple{},Fresh,()),owner,()) + @test PSE.refvalue(current,:x) === replacement + @test current.x === first(Tuple(current)) === 4f0 + @test keys(current) === (:x,:q,:seed,:literal) + @test PSE._status_reference_epoch(old) < PSE._status_reference_epoch(current) + owner.q = 2//3 + @test old.q == current.q == 2//3 + old.x = 101.0 + @test private[] === 101.0 && owner.x === 4f0 +end + +@testset "sparse recipe commits metadata once without replacing its canonical header" begin + state = PSE._new_prepared_status(SCHEMA,Status(x=1f0,q=1//2,seed=Float32[])) + original = state + epoch = PSE._status_reference_epoch(state) + recipe = PSE._CanonicalStatusRecipe(state,false) + replacement = Ref(2.0) + @test PSE._status_recipe_set_reference!(recipe,:x,replacement) + @test PSE.refvalue(state,:x) !== replacement + @test PSE._finish_canonical_status_recipe(identity,recipe) === original + @test PSE.refvalue(state,:x) === replacement + @test PSE._status_reference_epoch(state) == epoch+1 + @test PSE._finish_canonical_status_recipe(identity,recipe) === original + @test PSE._status_reference_epoch(state) == epoch+1 + @test_throws ArgumentError PSE._status_recipe_set_reference!(recipe,:x,Ref("bad")) + @test PSE.refvalue(state,:x) === replacement +end + +@testset "deepcopy preserves internal ref aliases, RefAny and RefReal stay exact" begin + S = PSE._fixed_status_type((:a,:b,:abstract,:opaque),Tuple{RF32,RF32,Base.RefValue{Real},Base.RefValue{Any}}) + reference = Ref(1f0) + source = Status((a=reference,b=reference,abstract=Ref{Real}(2f0),opaque=Ref{Any}(3f0))) + state = PSE._new_prepared_status(S,source) + copied = deepcopy(state) + @test PSE.refvalue(copied,:a) === PSE.refvalue(copied,:b) + @test PSE.refvalue(copied,:a) !== reference + @test typeof(PSE.refvalue(state,:abstract)) === Base.RefValue{Real} + @test typeof(PSE.refvalue(state,:opaque)) === Base.RefValue{Any} +end +end diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index 3a1ba8a35..f24701699 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -936,7 +936,7 @@ end mtg_root = Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) mtg_plant = Node(mtg_root, MultiScaleTreeGraph.NodeMTG("+", :Plant, 1, 1)) mtg_leaf = Node(mtg_plant, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 2)) - mtg_leaf_status = Status(signal=2.0) + mtg_leaf_status = Status(signal=2.0, age=0) mtg_status = node -> node === mtg_leaf ? mtg_leaf_status : nothing mtg_object_id = node -> Symbol(lowercase(string(symbol(node))), "_", node_id(node)) @test all(object -> isnothing(object.status), objects_from_mtg(mtg_root)) @@ -964,7 +964,8 @@ end ), ) @test only(model_objects(mtg_scene; scale=:Leaf)).parent == ObjectId(:plant_2) - @test only(model_objects(mtg_scene; scale=:Leaf)).status === mtg_leaf_status + @test PlantSimEngine.refvalue(only(model_objects(mtg_scene; scale=:Leaf)).status, :signal) === + PlantSimEngine.refvalue(mtg_leaf_status, :signal) @test position(only(model_objects(mtg_scene; scale=:Leaf))) == (x=1.0, y=2.0) run!(mtg_scene) @test only(model_objects(mtg_scene; scale=:Leaf)).status.signal == 3.0 @@ -981,11 +982,12 @@ end initial_status=(signal=5.0, age=1), kind=:plant, ) - @test !haskey(node_attributes(new_leaf_status.node), :plantsimengine_status) - @test model_status(mtg_scene, new_leaf_status.node) === new_leaf_status - @test source_node(mtg_scene, new_leaf_status) === new_leaf_status.node + @test !haskey(node_attributes(source_node(mtg_scene, new_leaf_status)), :plantsimengine_status) + @test model_status(mtg_scene, source_node(mtg_scene, new_leaf_status)) === new_leaf_status + @test source_node(mtg_scene, new_leaf_status) === source_node(mtg_scene, new_leaf_status) @test new_leaf_status.signal == 5.0 - @test new_leaf_status.color == :green + @test !hasproperty(new_leaf_status, :color) + @test source_node(mtg_scene, new_leaf_status)[:color] === :green @test new_leaf_status.age == 1 new_leaf_object = only( object for object in model_objects(mtg_scene; scale=:Leaf) @@ -995,7 +997,7 @@ end @test new_leaf_object.parent == ObjectId(:plant_2) @test model_object(mtg_scene, :leaf_4) === new_leaf_object @test model_object(mtg_scene, ObjectId(:leaf_4)) === new_leaf_object - @test model_object(mtg_scene, new_leaf_status.node) === new_leaf_object + @test model_object(mtg_scene, source_node(mtg_scene, new_leaf_status)) === new_leaf_object @test model_object(mtg_scene, new_leaf_status) === new_leaf_object @test_throws ErrorException model_object(mtg_scene, :absent_leaf) @test Advanced.bindings_dirty(mtg_scene) @@ -1020,197 +1022,47 @@ end 2; index=3, ) - @test node_id(auto_id_leaf_status.node) == 5 + @test node_id(source_node(mtg_scene, auto_id_leaf_status)) == 5 @test !haskey( - node_attributes(auto_id_leaf_status.node), + node_attributes(source_node(mtg_scene, auto_id_leaf_status)), :plantsimengine_status, ) - @test model_status(mtg_scene, auto_id_leaf_status.node) === + @test model_status(mtg_scene, source_node(mtg_scene, auto_id_leaf_status)) === auto_id_leaf_status - @testset "MTG organ status adapter policy" begin + @testset "MTG scientific import is initial-only and growth data are explicit" begin status_adapter_calls = Ref(0) - latest_adapter_status = Ref{Any}(nothing) status_adapter = node -> begin status_adapter_calls[] += 1 node[:status_adapter_mutation] = status_adapter_calls[] - adapted_source_status = Status( - node=:adapter_node_must_be_replaced, - signal=6.0, - adapter_only=:present, - ) - latest_adapter_status[] = adapted_source_status - return adapted_source_status + symbol(node) === :Leaf ? Status(signal=node[:signal], age=node[:age]) : nothing end - - adapter_root = - Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) - adapter_plant = Node( - adapter_root, - MultiScaleTreeGraph.NodeMTG("+", :Plant, 1, 1), - ) - status_adapter_scene = - CompositeModel(adapter_root; status=status_adapter) - calls_after_adaptation = status_adapter_calls[] - bypassed_initial_status = Status( - signal=5.0, - age=1, - node=:initial_node_must_be_replaced, - ) - - children_before_rejected_status = length(children(adapter_plant)) - @test_throws ErrorException add_organ!( - adapter_plant, - status_adapter_scene, - :+, - :Leaf, - 2; - index=99, - attributes=(plantsimengine_status=Status(signal=99.0),), - use_status_adapter=false, - ) - @test length(children(adapter_plant)) == children_before_rejected_status - - bypassed_status = add_organ!( - adapter_plant, - status_adapter_scene, - :+, - :Leaf, - 2; - index=1, - id=3, - attributes=( - signal=4.0, - color=:green, - node=:attribute_node_must_be_replaced, - ), - initial_status=bypassed_initial_status, - use_status_adapter=false, - ) - - bypassed_reference = Dict{Symbol,Any}() - PlantSimEngine._status_data!( - bypassed_reference, - node_attributes(bypassed_status.node), - ) - bypassed_reference[:node] = bypassed_status.node - PlantSimEngine._status_data!( - bypassed_reference, - bypassed_initial_status, - ) - bypassed_reference[:node] = bypassed_status.node - bypassed_reference_names = Tuple(keys(bypassed_reference)) - bypassed_reference_values = Tuple(values(bypassed_reference)) - - @test status_adapter_calls[] == calls_after_adaptation - @test propertynames(bypassed_status) == bypassed_reference_names - @test Tuple(bypassed_status) == bypassed_reference_values - @test bypassed_status.signal == 5.0 - @test bypassed_status.color === :green - @test bypassed_status.age == 1 - @test bypassed_status.node === - MultiScaleTreeGraph.get_node(adapter_root, 3) - @test bypassed_initial_status.node === - :initial_node_must_be_replaced - @test bypassed_status.node[:node] === - :attribute_node_must_be_replaced - @test bypassed_status.node[:signal] == 4.0 - @test !hasproperty(bypassed_status, :adapter_only) - @test !hasproperty(bypassed_status, :status_adapter_mutation) - @test !haskey( - node_attributes(bypassed_status.node), - :status_adapter_mutation, - ) - @test PlantSimEngine.refvalue(bypassed_status, :signal) !== - PlantSimEngine.refvalue(bypassed_initial_status, :signal) - @test PlantSimEngine.refvalue(bypassed_status, :age) !== - PlantSimEngine.refvalue(bypassed_initial_status, :age) - @test !haskey( - node_attributes(bypassed_status.node), - :plantsimengine_status, - ) - @test model_status(status_adapter_scene, bypassed_status.node) === - bypassed_status - bypassed_initial_status.age = 99 - @test bypassed_status.age == 1 - - adapted_initial_status = Status( - signal=5.0, - age=2, - node=:initial_node_must_be_replaced, - ) - - adapted_status = add_organ!( - adapter_plant, - status_adapter_scene, - :+, - :Leaf, - 2; - index=2, - id=4, - attributes=( - signal=4.0, - color=:blue, - node=:attribute_node_must_be_replaced, - ), - initial_status=adapted_initial_status, - ) - - adapted_source_status = latest_adapter_status[] - adapted_reference = Dict{Symbol,Any}() - PlantSimEngine._status_data!( - adapted_reference, - node_attributes(adapted_status.node), - ) - PlantSimEngine._status_data!( - adapted_reference, - adapted_source_status, - ) - adapted_reference[:node] = adapted_status.node - PlantSimEngine._status_data!( - adapted_reference, - adapted_initial_status, - ) - adapted_reference[:node] = adapted_status.node - adapted_reference_names = Tuple(keys(adapted_reference)) - adapted_reference_values = Tuple(values(adapted_reference)) - - @test status_adapter_calls[] == calls_after_adaptation + 1 - @test adapted_source_status isa Status - @test propertynames(adapted_status) == adapted_reference_names - @test Tuple(adapted_status) == adapted_reference_values - @test adapted_source_status.node === - :adapter_node_must_be_replaced - @test adapted_initial_status.node === - :initial_node_must_be_replaced - @test adapted_status.node[:signal] == 4.0 - @test adapted_source_status.signal == 6.0 - @test adapted_status.signal == 5.0 - @test adapted_status.color === :blue - @test adapted_status.age == 2 - @test adapted_status.adapter_only === :present - @test adapted_status.node === - MultiScaleTreeGraph.get_node(adapter_root, 4) - @test adapted_status.node[:node] === - :attribute_node_must_be_replaced - @test adapted_status.status_adapter_mutation == - calls_after_adaptation + 1 - @test adapted_status.node[:status_adapter_mutation] == - calls_after_adaptation + 1 - @test PlantSimEngine.refvalue(adapted_status, :adapter_only) !== - PlantSimEngine.refvalue(adapted_source_status, :adapter_only) - @test PlantSimEngine.refvalue(adapted_status, :age) !== - PlantSimEngine.refvalue(adapted_initial_status, :age) - @test !haskey( - node_attributes(adapted_status.node), - :plantsimengine_status, - ) - @test model_status(status_adapter_scene, adapted_status.node) === - adapted_status - adapted_source_status.adapter_only = :mutated_after_add - adapted_initial_status.age = 99 - @test adapted_status.adapter_only === :present - @test adapted_status.age == 2 + adapter_root = Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) + adapter_plant = Node(adapter_root, MultiScaleTreeGraph.NodeMTG("+", :Plant, 1, 1)) + Node(adapter_plant, MultiScaleTreeGraph.NodeMTG("+", :Leaf, 1, 2), + (signal=6.0, age=0, annotation="initial")) + scene = CompositeModel(adapter_root; status=status_adapter) + calls_after_import = status_adapter_calls[] + given = Status(signal=5.0, age=1) + before = length(children(adapter_plant)) + @test_throws ErrorException add_organ!(adapter_plant, scene, :+, :Leaf, 2; + attributes=(plantsimengine_status=nothing,), initial_status=given) + @test length(children(adapter_plant)) == before + grown = add_organ!(adapter_plant, scene, :+, :Leaf, 2; + attributes=(signal=4.0, color=:green), initial_status=given) + grown_node = source_node(scene, grown) + @test status_adapter_calls[] == calls_after_import + @test grown.signal === 5.0 && grown.age == 1 + @test !hasproperty(grown, :node) && !hasproperty(grown, :color) + @test !hasproperty(grown, :status_adapter_mutation) + @test grown_node[:signal] === 4.0 && grown_node[:color] === :green + @test get(node_attributes(grown_node), :status_adapter_mutation, nothing) === nothing + @test model_status(scene, grown_node) === grown + @test PlantSimEngine.refvalue(grown, :signal) === PlantSimEngine.refvalue(given, :signal) + @test PlantSimEngine.refvalue(grown, :age) === PlantSimEngine.refvalue(given, :age) + @test_throws ArgumentError object_id(scene, given) + given.age = 99 + @test grown.age == 99 end temporal_mtg_root = diff --git a/test/test_groups.jl b/test/test_groups.jl index 1f209ce0d..1f1ef7c60 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -6,6 +6,8 @@ const TEST_GROUPS = ( "Registered object identity" => ( "test-model-object-id.jl", "test-object-families.jl", + "test-prepared-status-registration.jl", + "test-fixed-status-scope-growth.jl", ), "Concrete runtime object identities" => ( "test-model-concrete-object-identities.jl", @@ -54,6 +56,7 @@ const TEST_GROUPS = ( "test-model-prepared-scenario.jl", "test-model-scenario-authoring.jl", "test-model-authored-port-inventory.jl", + "test-fixed-status-manifest.jl", "test-model-authored-input-graph.jl", "test-model-prepared-authoring-owner.jl", "test-model-public-refresh-owners.jl", @@ -237,6 +240,7 @@ const TEST_GROUPS = ( ), "Distributed output runtime" => ( "test-model-distributed-output-runtime.jl", + "test-fixed-status-prospective-distributed.jl", "test-model-runtime-stream-extensions.jl", ), "Distributed output assignment API" => ( @@ -277,6 +281,7 @@ const TEST_GROUPS = ( ), "Status" => ( "test-Status.jl", + "test-status-fixed-storage.jl", ), "TimeStepTable" => ( "test-TimeStepTable.jl", From 83bcbaf1c904b6073877698dce4aa12c9f4572c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 21:21:34 +0100 Subject: [PATCH 135/324] Reuse official Status boxes and invalidate rejected timelines Query prepared presence slots without constructing names or reference tuples. Keep the existing runtime generations authoritative after rejected authoring refreshes, including existing fixed and dynamic simulations. Three maintained test files pass 442 assertions, including all fourteen previously failing zero-allocation checks. JuliaC safe, broader feature tests and matched downstream performance remain under validation. --- benchmark/test-PSE-benchmark.jl | 33 ++++++------ benchmark/test-organ-lifecycle-benchmark.jl | 4 +- benchmark/test/runtests.jl | 3 +- src/component_models/Status.jl | 18 ++++++- src/composite_model/compilation.jl | 29 ++++++++--- src/composite_model/object_families.jl | 22 ++++---- src/composite_model/runtime_outputs.jl | 4 +- src/visualization/model_graph_editor_api.jl | 2 +- test/test-model-public-refresh-owners.jl | 58 +++++++++++++++++++-- test/test-model-status-type-lifecycle.jl | 29 +++++++++-- test/test-status-fixed-storage.jl | 35 +++++++++++++ 11 files changed, 190 insertions(+), 47 deletions(-) diff --git a/benchmark/test-PSE-benchmark.jl b/benchmark/test-PSE-benchmark.jl index 056d0877d..b23277ddd 100644 --- a/benchmark/test-PSE-benchmark.jl +++ b/benchmark/test-PSE-benchmark.jl @@ -21,30 +21,31 @@ PlantSimEngine.outputs_(m::ToyInternodeCrazyEmergence) = (TT_cu_emergence=0.0,) function PlantSimEngine.run!(m::ToyInternodeCrazyEmergence, status, environment, constants=nothing, context=nothing) model = runtime_model(context) + node = source_node(context) - #root = get_root(status.node) + #root = get_root(source_node(context)) #if nleaves(root) > 10000 # return nothing #end - if length(MultiScaleTreeGraph.children(status.node)) == 1 && status.TT_cu - status.TT_cu_emergence >= m.TT_emergence + if length(MultiScaleTreeGraph.children(node)) == 1 && status.TT_cu - status.TT_cu_emergence >= m.TT_emergence - status_new_internode = add_organ!(status.node, model, "<", :Internode, 2; index=1, initial_status=(carbon_biomass=1.0, TT_cu_emergence=0.0)) - add_organ!(status_new_internode.node, model, "+", :Leaf, 2; index=1, initial_status=(carbon_biomass=1.0,)) + status_new_internode = add_organ!(node, model, "<", :Internode, 2; index=1, initial_status=(carbon_biomass=1.0, TT_cu_emergence=0.0)) + add_organ!(source_node(model, status_new_internode), model, "+", :Leaf, 2; index=1, initial_status=(carbon_biomass=1.0,)) status_new_internode.TT_cu_emergence = status.TT_cu - elseif (length(MultiScaleTreeGraph.children(status.node)) >= 2 && length(MultiScaleTreeGraph.children(status.node)) < 7) && status.TT_cu - status.TT_cu_emergence >= m.TT_emergence - status_new_internode = add_organ!(status.node, model, "<", :Internode, 2; index=1, initial_status=(carbon_biomass=1.0, TT_cu_emergence=0.0)) - add_organ!(status.node, model, "+", :Leaf, 2; index=4, initial_status=(carbon_biomass=1.0,)) - add_organ!(status.node, model, "+", :Leaf, 2; index=5, initial_status=(carbon_biomass=1.0,)) + elseif (length(MultiScaleTreeGraph.children(node)) >= 2 && length(MultiScaleTreeGraph.children(node)) < 7) && status.TT_cu - status.TT_cu_emergence >= m.TT_emergence + status_new_internode = add_organ!(node, model, "<", :Internode, 2; index=1, initial_status=(carbon_biomass=1.0, TT_cu_emergence=0.0)) + add_organ!(node, model, "+", :Leaf, 2; index=4, initial_status=(carbon_biomass=1.0,)) + add_organ!(node, model, "+", :Leaf, 2; index=5, initial_status=(carbon_biomass=1.0,)) status_new_internode.TT_cu_emergence = status.TT_cu - elseif (length(MultiScaleTreeGraph.children(status.node)) >= 7 && length(MultiScaleTreeGraph.children(status.node)) < 30) && status.TT_cu - status.TT_cu_emergence >= m.TT_emergence - add_organ!(status.node, model, "+", :Leaf, 2; index=6, initial_status=(carbon_biomass=1.0,)) - add_organ!(status.node, model, "+", :Leaf, 2; index=7, initial_status=(carbon_biomass=1.0,)) - add_organ!(status.node, model, "+", :Leaf, 2; index=8, initial_status=(carbon_biomass=1.0,)) - add_organ!(status.node, model, "+", :Leaf, 2; index=9, initial_status=(carbon_biomass=1.0,)) - add_organ!(status.node, model, "+", :Leaf, 2; index=10, initial_status=(carbon_biomass=1.0,)) - add_organ!(status.node, model, "+", :Leaf, 2; index=11, initial_status=(carbon_biomass=1.0,)) + elseif (length(MultiScaleTreeGraph.children(node)) >= 7 && length(MultiScaleTreeGraph.children(node)) < 30) && status.TT_cu - status.TT_cu_emergence >= m.TT_emergence + add_organ!(node, model, "+", :Leaf, 2; index=6, initial_status=(carbon_biomass=1.0,)) + add_organ!(node, model, "+", :Leaf, 2; index=7, initial_status=(carbon_biomass=1.0,)) + add_organ!(node, model, "+", :Leaf, 2; index=8, initial_status=(carbon_biomass=1.0,)) + add_organ!(node, model, "+", :Leaf, 2; index=9, initial_status=(carbon_biomass=1.0,)) + add_organ!(node, model, "+", :Leaf, 2; index=10, initial_status=(carbon_biomass=1.0,)) + add_organ!(node, model, "+", :Leaf, 2; index=11, initial_status=(carbon_biomass=1.0,)) end @@ -53,7 +54,7 @@ end function _benchmark_mtg_status(node) - data = Dict{Symbol,Any}(:node => node) + data = Dict{Symbol,Any}() scale = MultiScaleTreeGraph.symbol(node) scale in (:Leaf, :Internode) && (data[:carbon_biomass] = 1.0) scale == :Plant && (data[:carbon_allocation] = zeros(4)) diff --git a/benchmark/test-organ-lifecycle-benchmark.jl b/benchmark/test-organ-lifecycle-benchmark.jl index 6ca3ba68e..ed40be6a8 100644 --- a/benchmark/test-organ-lifecycle-benchmark.jl +++ b/benchmark/test-organ-lifecycle-benchmark.jl @@ -53,7 +53,7 @@ function PlantSimEngine.run!( end _organ_lifecycle_status(node) = - PlantSimEngine.Status(node=node, signal=0.0) + PlantSimEngine.Status(signal=0.0) function setup_organ_topology_benchmark(nobjects::Int) nobjects > 0 || throw(ArgumentError("`nobjects` must be positive.")) @@ -104,7 +104,7 @@ Base.@noinline function benchmark_adapt_organ_status_recipe_model(topology) on=PlantSimEngine.Many(scale=:Leaf), ), ), - status=node -> PlantSimEngine.Status(node=node), + status=node -> PlantSimEngine.Status(), ) end diff --git a/benchmark/test/runtests.jl b/benchmark/test/runtests.jl index 135b75a67..266c3eb9f 100644 --- a/benchmark/test/runtests.jl +++ b/benchmark/test/runtests.jl @@ -170,7 +170,8 @@ if benchmark_test_enabled("organ lifecycle benchmark API smoke") added_id = PlantSimEngine.ObjectId(data.next_node_id) @test PlantSimEngine.object_id(data.model, status) == added_id @test PlantSimEngine.model_status(data.model, added_id) === status - @test PlantSimEngine.source_node(data.model, status) === status.node + @test PlantSimEngine.source_node(data.model, status) === + MultiScaleTreeGraph.get_node(data.root, data.next_node_id) @test status.signal == 1.0 @test data.model.bindings_dirty nodes = Any[] diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index eb567278d..7cbb81e75 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -309,4 +309,20 @@ function _projected_status_type(::Type{C}, hot_names::Tuple, hot_references::Typ return Status{names,_ProjectedStatusStorage{names,R,Hot,Slots}} end -Base.hasproperty(status::Status, name::Symbol) = _initial_status_reference(status, name) !== nothing +@inline _status_storage_hasproperty(storage::NamedTuple, name::Symbol) = + hasfield(typeof(storage), name) +@generated function _status_storage_hasproperty( + storage::Union{_FixedStatusStorage{N},_ProjectedStatusStorage{N}}, + name::Symbol, +) where {N} + branches = [:(name === $(QuoteNode(field)) && + return getfield(getfield(storage, :refs), $index) !== nothing) + for (index, field) in enumerate(N)] + return quote + $(Expr(:meta, :inline)) + $(branches...) + return false + end +end +Base.@constprop :aggressive @inline Base.hasproperty(status::Status, name::Symbol) = + _status_storage_hasproperty(_status_vars(status), name) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1f174b52f..6223cda2c 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -974,6 +974,16 @@ end end end +function _publish_failed_scenario_preparation!(model::CompositeModel, preparation) + previous = getfield(model, :scenario_plan_cache) + model.scenario_plan_cache = preparation + model.bindings_dirty = true + # Reuse the generation already checked by fixed plans and application + # barriers; ordinary execution gains no new lookup or scan. + _record_runtime_owner_replacement!(model, previous, preparation) + return preparation +end + function _scenario_preparation(model::CompositeModel; force::Bool=false) preparation = model.scenario_plan_cache if force || isnothing(preparation) || @@ -982,8 +992,7 @@ function _scenario_preparation(model::CompositeModel; force::Bool=false) if !isnothing(candidate.failure) || candidate.status_manifest isa ScenarioPreparationFailure # Keep captured authoring failures authoritative, as before. A later # run must not silently fall back to an older compiled preparation. - model.scenario_plan_cache = candidate - return candidate + return _publish_failed_scenario_preparation!(model, candidate) end registry = try _registry_with_prepared_status_manifest(model, candidate.status_manifest) @@ -994,8 +1003,7 @@ function _scenario_preparation(model::CompositeModel; force::Bool=false) candidate.authored, candidate.failure, candidate.program, failure, nothing) # Only the captured diagnostic becomes authoritative. The registry, # scientific headers and compiled caches remain exactly unchanged. - model.scenario_plan_cache = rejected - return rejected + return _publish_failed_scenario_preparation!(model, rejected) end # Validation and all potentially failing construction finished first. # These two assignments invoke no user code and preserve every header, @@ -2200,7 +2208,12 @@ function _refresh_owned_runtime_bindings!( ) preparation = getfield(getfield(current.scenario_plan, :authoring), :preparation) preparation.owner === model || _unprepared_runtime_configuration() - getfield(model, :scenario_plan_cache) === preparation || _unprepared_runtime_configuration() + published = getfield(model, :scenario_plan_cache) + if published !== preparation + published isa ScenarioPreparation || _unprepared_runtime_configuration() + _validate_authored_scenario(published) + _unprepared_runtime_configuration() + end _authored_specs_match(preparation, model) || _unprepared_runtime_configuration() # Adapter snapshots do not replace live metadata. The current published # owner and lifecycle delta determine the running simulation's refresh. @@ -5254,7 +5267,7 @@ function _initialization_effective_value( (application_id, object_id), nothing, ) - if !isnothing(view) && variable in propertynames(view.status) + if !isnothing(view) && hasproperty(view.status, variable) return true, view.status[variable] end status = _model_object(model, object_id).status @@ -8209,7 +8222,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, _matches_object_criteria(object; scale=matcher.scale, kind=matcher.kind, species=matcher.species, id=matcher.id) || continue status = object.status - status isa Status && source_var in propertynames(status) || continue + status isa Status && hasproperty(status, source_var) || continue reference = refvalue(status, source_var) reference isa Base.RefValue || continue add(typeof(reference)) @@ -9080,7 +9093,7 @@ end function _status_has_variable(model::CompositeModel, object_id::ObjectId, variable::Symbol) object = _model_object(model, object_id) object.status isa Status || return false - return variable in propertynames(object.status) + return hasproperty(object.status, variable) end function _validate_model_required_inputs!(model::CompositeModel, applications, applications_by_id, input_bindings) diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 8bd424978..1bfd85533 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -108,12 +108,6 @@ function _object_family_status_at(::OpenObjectFamilyCatalog, location::ObjectFam return getfield(location.object, :status) end -@inline function _object_family_status_at(family::ObjectFamily{I,S}, row::Int) where {I,S} - entry = family.rows[row] - isnothing(entry) && throw(ArgumentError("The object family row is no longer registered.")) - return entry.status::S -end - # A finite union retains the concrete Status families across a runtime slot. # Object counts, IDs and row positions are deliberately absent from the type. @generated function _object_family_status_at(catalog::ClosedObjectFamilyCatalog{F}, location::ObjectFamilyLocation) where {F} @@ -122,10 +116,20 @@ end result_type = Union{status_types...} branch = :(throw(BoundsError(catalog.families, location.family))) for slot in reverse(1:fieldcount(F)) - value = :(_object_family_status_at(getfield(catalog.families, $slot), location.row)) - branch = Expr(:if, :(location.family == $slot), value, branch) + check = quote + family = getfield(catalog.families, $slot) + isnothing(family.rows[location.row]) && throw(ArgumentError( + "The object family row is no longer registered.", + )) + end + branch = Expr(:if, :(location.family == $slot), check, branch) + end + return quote + $branch + # Reuse the official box; extracting the immutable header from a typed + # family row would rebox it when the caller stores the result as Any. + getfield(location.object, :status)::$result_type end - return Expr(:(::), branch, result_type) end _object_family_status(store::ObjectFamilyStore, id) = diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index fdf5ddffd..d7ead6110 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1752,7 +1752,7 @@ end end function _set_status_if_present!(status::Status, variable::Symbol, value) - variable in propertynames(status) || error( + hasproperty(status, variable) || error( "Cannot materialize input `$(variable)` because consumer status has no such variable." ) status[variable] = value @@ -1861,7 +1861,7 @@ end @inline function _output_reference_from_status(status::S, operation::F, ::Val{VARIABLE}, args::Vararg{Any,N}, ) where {S,F,VARIABLE,N} - status isa Status && VARIABLE in propertynames(status) || throw(ArgumentError( + status isa Status && hasproperty(status, VARIABLE) || throw(ArgumentError( "The requested output is absent from the selected status.", )) return operation(refvalue(status, VARIABLE), args...) diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index f39eadede..e2668935f 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -863,7 +863,7 @@ function _apply_model_graph_edit!(model::CompositeModel, edit::BreakModelCycle) for application in applications for object_id in application.target_ids object = _model_object(model, object_id) - supplied = object.status isa Status && edit.input in Symbol.(propertynames(object.status)) + supplied = object.status isa Status && hasproperty(object.status, edit.input) supplied || _set_model_object_status!(model, object_id, edit.input, edit.initial_value) end end diff --git a/test/test-model-public-refresh-owners.jl b/test/test-model-public-refresh-owners.jl index a5904a611..665c39e7b 100644 --- a/test/test-model-public-refresh-owners.jl +++ b/test/test-model-public-refresh-owners.jl @@ -220,14 +220,16 @@ end end PSE.@process "force_authority_new_status_field" verbose=false -struct ChangingFields{M,D,K} <: AbstractForce_Authority_New_Status_FieldModel +struct ChangingFields{M,F,D,K} <: AbstractForce_Authority_New_Status_FieldModel extra::M + fail::F declarations::D kernels::K end PSE.inputs_(::ChangingFields) = (;) function PSE.outputs_(model::ChangingFields) model.declarations[] += 1 + model.fail[] && error("intentional captured output declaration failure") return model.extra[] ? (visits=0, extra=0) : (visits=0,) end function PSE.run!(model::ChangingFields, status, environment, constants, context) @@ -238,10 +240,14 @@ end @testset "an incompatible mutable declaration records an authoritative error without publishing state" begin extra, declarations, kernels = Ref(false), Ref(0), Ref(0) - original = ModelSpec(ChangingFields(extra, declarations, kernels); name=:probe, on=One(id=:leaf)) + original = ModelSpec(ChangingFields(extra, Ref(false), declarations, kernels); name=:probe, on=One(id=:leaf)) supplied = Status(visits=5) model = CompositeModel(Object(:leaf; status=supplied); applications=(original,)) - run!(model; steps=0, outputs=:none) + simulation = run!(model; steps=0, outputs=:all) + fixed = PSE._simulation_with_execution_plan(simulation, + PSE._fixed_execution_plan(simulation.execution_plan)) + history = copy(outputs(simulation)[(:probe,ObjectId(:leaf),:visits)]) + step = simulation.current_step registry, preparation, compiled = model.registry, model.scenario_plan_cache, model.binding_cache environment = model.environment_binding_cache status = model_status(model, :leaf) @@ -273,6 +279,16 @@ end @test model.status_source_identities == source_ids @test object_id(model, status) === ObjectId(:leaf) after_failure = declarations[] + continued_failure = try + continue!(simulation; steps=1) + nothing + catch exception + exception + end + @test continued_failure === failure + @test_throws ArgumentError continue!(fixed; steps=1) + @test simulation.current_step == fixed.current_step == step + @test outputs(simulation)[(:probe,ObjectId(:leaf),:visits)] == history @test_throws ArgumentError run!(model; steps=1, outputs=:none) @test_throws ArgumentError Advanced.refresh_bindings!(model) @test declarations[] == after_failure @@ -291,6 +307,42 @@ end @test kernels[] == 1 end +@testset "a captured declaration failure also blocks an existing timeline" begin + fail, declarations, kernels = Ref(false), Ref(0), Ref(0) + process = ChangingFields(Ref(false), fail, declarations, kernels) + spec = ModelSpec(process; name=:probe, on=One(id=:leaf)) + model = CompositeModel(Object(:leaf; status=Status(visits=5)); applications=(spec,)) + simulation = run!(model; steps=0, outputs=:all) + status = model_status(model, :leaf) + reference = PSE.refvalue(status, :visits) + history = copy(outputs(simulation)[(:probe,ObjectId(:leaf),:visits)]) + step, registry, compiled = simulation.current_step, model.registry, model.binding_cache + fail[] = true + failure = try + Advanced.refresh_bindings!(model; force=true) + nothing + catch exception + exception + end + @test failure isa ErrorException + after_failure = declarations[] + continued_failure = try + continue!(simulation; steps=1) + nothing + catch exception + exception + end + @test continued_failure === failure + @test only(model.applications) === spec + @test simulation.current_step == step + @test outputs(simulation)[(:probe,ObjectId(:leaf),:visits)] == history + @test model.registry === registry && model.binding_cache === compiled + @test model_status(model, :leaf) === status + @test PSE.refvalue(status, :visits) === reference + @test status.visits == 5 && kernels[] == 0 + @test declarations[] == after_failure +end + end module SelectiveRefreshOwnerChecks diff --git a/test/test-model-status-type-lifecycle.jl b/test/test-model-status-type-lifecycle.jl index 341e42846..72f9e6e1c 100644 --- a/test/test-model-status-type-lifecycle.jl +++ b/test/test-model-status-type-lifecycle.jl @@ -227,10 +227,14 @@ end initial_status = Status((external_value=external_reference,)) @test PlantSimEngine.refvalue(initial_status, :external_value) === external_reference + existing_storage = [1.5] + existing_reference = Ref(existing_storage, 1) + existing_source = Status((external_value=existing_reference,)) model = CompositeModel( Object(:scene; scale=:Scene), - Object(:plant; scale=:Plant, parent=:scene); + Object(:plant; scale=:Plant, parent=:scene), + Object(:existing_leaf; scale=:Leaf, parent=:plant, status=existing_source); applications=( ModelSpec( StatusTypeLifecycleIncrementModel(); @@ -253,7 +257,11 @@ end environment=(duration=Hour(1),), ) Advanced.refresh_bindings!(model) - register_object!( + existing = model_status(model, :existing_leaf) + @test existing !== existing_source + @test PlantSimEngine.refvalue(existing, :external_value) === existing_reference + @test existing.external_value == 1.5 + registered = register_object!( model, Object( :late_leaf; @@ -262,11 +270,16 @@ end status=initial_status, ), ) + official = registered.status + @test official !== initial_status + @test PlantSimEngine.refvalue(official, :external_value) === external_reference + @test_throws ArgumentError object_id(model, initial_status) Advanced.refresh_bindings!(model) refreshed = model_status(model, :late_leaf) + @test refreshed === official @test propertynames(refreshed) == - (:external_value, :value, :seen, :bound_value) + (:value, :seen, :bound_value, :external_value) @test PlantSimEngine.refvalue(refreshed, :external_value) === external_reference @test PlantSimEngine.refvalue(refreshed, :bound_value) === @@ -354,9 +367,11 @@ end end @testset "register_object! converts status after compilation" begin + existing_source = Status(initial_value=1.5) model = CompositeModel( Object(:scene; scale=:Scene), - Object(:plant; scale=:Plant, parent=:scene); + Object(:plant; scale=:Plant, parent=:scene), + Object(:existing_leaf; scale=:Leaf, parent=:plant, status=existing_source); applications=( ModelSpec( StatusTypeLifecycleIncrementModel(); @@ -368,6 +383,8 @@ end type_promotion=Dict(Float64 => Float32), ) simulation = run!(model; outputs=:all) + @test model_status(model, :existing_leaf).initial_value === Float32(1.5) + @test existing_source.initial_value === 1.5 late_leaf = Object( :late_leaf; @@ -375,9 +392,13 @@ end parent=:plant, status=Status(initial_value=2.5), ) + source = late_leaf.status registered = register_object!(model, late_leaf) @test registered === late_leaf + @test registered.status !== source + @test source.initial_value === 2.5 + @test_throws ArgumentError object_id(model, source) @test registered.status === model_status(model, :late_leaf) @test registered.status.initial_value === Float32(2.5) @test !(:value in propertynames(registered.status)) diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 51b439c1b..0deb10d11 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -118,4 +118,39 @@ end @test typeof(PSE.refvalue(state,:abstract)) === Base.RefValue{Real} @test typeof(PSE.refvalue(state,:opaque)) === Base.RefValue{Any} end + +_fixed_status_presence(status, name::Symbol) = hasproperty(status, name) +function _store_fixed_status_presence!(result::Base.RefValue{Bool}, status, name::Symbol) + result[] = hasproperty(status, name) + return nothing +end +_fixed_status_presence_allocations(result, status, name::Symbol) = + @allocated _store_fixed_status_presence!(result, status, name) + +@testset "presence queries inspect cells without reading values or constructing names" begin + dense = Status((x=Ref{Float32}(), literal=Ref(nothing))) + fixed = PSE._new_prepared_status(SCHEMA,Status(x=3f0,q=1//2,seed=Float32[])) + Projected = PSE._projected_status_type(SCHEMA,(:private_only,),Tuple{RF32}) + view = PSE._construct_status( + PSE.ExactReferenceFactory(SCHEMA,Tuple{RF32},Projected,(:private_only,)), + fixed,(Ref(7f0),)) + result = Ref(false) + for (status, name, expected) in ((dense,:x,true), (dense,:literal,true), + (dense,:missing,false), (dense,:vars,false), (Status(),:missing,false), + (fixed,:x,true), (fixed,:literal,false), (fixed,:private_only,false), + (fixed,:missing,false), (view,:private_only,true), (view,:literal,false), + (view,:missing,false)) + @test (@inferred _fixed_status_presence(status,name)) === expected + _store_fixed_status_presence!(result,status,name) + _fixed_status_presence_allocations(result,status,name) + @test _fixed_status_presence_allocations(result,status,name) == 0 + @test result[] === expected + end + PSE._set_status_reference!(fixed,:literal,Ref(nothing)) + @test (@inferred _fixed_status_presence(fixed,:literal)) === true + @test fixed.literal === nothing + @test (@inferred _fixed_status_presence(view,:literal)) === false + @test keys(fixed) === (:x,:q,:seed,:literal) + @test keys(view) === (:x,:q,:seed,:private_only) +end end From 605e34e0481e9fa6abc915017c3efd5b18fe79a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 21:46:54 +0100 Subject: [PATCH 136/324] Retain prepared names and identity types through admission Construct hot port names from their existing authored witnesses. Admit object and parent IDs once for prospective matching and status construction, and retain the canonical Status return witness for missing or present state. Validate captured failures without dispatch through erased preparation metadata. Seven whole maintained files pass 883 assertions on Julia 1.13.3 with all source, dependency and process-drain guards passing. Stock safe verification and full scenario qualification remain in progress. --- src/composite_model/compilation.jl | 35 +++++++++++------- .../prepared_status_manifest.jl | 5 +-- src/composite_model/registry_topology.jl | 4 ++- src/composite_model/selectors.jl | 34 ++++++++++-------- .../status_view_construction.jl | 12 ++++++- .../test-model-status-view-cache-admission.jl | 27 ++++++++++++++ test/test-prepared-status-registration.jl | 36 +++++++++++++++++-- test/test-registered-status-dispatch.jl | 26 ++++++++++++++ test/test-selector-candidate-empty-scope.jl | 8 +++-- 9 files changed, 152 insertions(+), 35 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6223cda2c..08f2624cf 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1015,9 +1015,15 @@ function _scenario_preparation(model::CompositeModel; force::Bool=false) return _model_owned_scenario_preparation(model, preparation) end -function _validate_authored_scenario(preparation::ScenarioPreparation) - isnothing(preparation.failure) || throw(preparation.failure.error) - _authored_metadata_value(preparation.status_manifest) +@inline function _validate_authored_scenario(preparation::ScenarioPreparation) + failure = getfield(preparation, :failure) + if failure isa ScenarioPreparationFailure + _throw_preparation_error(getfield(failure, :error)) + end + manifest = getfield(preparation, :status_manifest) + if manifest isa ScenarioPreparationFailure + _throw_preparation_error(getfield(manifest, :error)) + end return nothing end @@ -6721,21 +6727,26 @@ end function _ensure_model_object_status!(model::CompositeModel, object_id::ObjectId) object = _model_object(model, object_id) - status = object.status + return Base.@inline _with_prepared_canonical_status_type( + _ensure_prepared_model_object_status!, model, model, object, object_id) +end + +@inline function _ensure_prepared_model_object_status!(::Type{S}, model, object, + object_id, +) where {S<:Status} + status = getfield(object, :status) if isnothing(status) - return Base.@inline _with_prepared_canonical_status_type( - _ensure_prepared_model_object_status!, model, model, object) + replacement = Base.@inline _new_prepared_status(S, nothing) + status = _replace_model_object_status!(model, object, replacement) end status isa Status || error( "Model object `$(object_id.value)` uses model applications but its status has type ", "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." ) - return Base.@inline _with_registered_status(identity, model.registry.objects.catalog, status) -end - -function _ensure_prepared_model_object_status!(::Type{S}, model, object) where {S<:Status} - status = Base.@inline _new_prepared_status(S, nothing) - return _replace_model_object_status!(model, object, status) + status isa S || throw(ArgumentError( + "The status schema is outside the prepared object family catalog.", + )) + return status::S end _stage_model_output_defaults!(preparation, ::Tuple{}, ::Tuple{}, context) = nothing diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index c26affb39..5b6f3b92b 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -299,8 +299,9 @@ function _prepared_status_destination_reference_allowed(applications::Tuple, # a prospective permission; no RAW family or override is substituted. matcher = plan.matcher if !has_producer && matcher.scope isa SceneScope && isnothing(matcher.relation) - topology = _prepared_status_topology(model, object, parent_id) - if _selector_matches_object_id(topology, matcher, object.id, + id = _index_object_id(model.registry.objects, object.id) + topology = _prepared_status_topology(model, object, id, parent_id) + if _selector_matches_object_id(topology, matcher, id, nothing, false, nothing, false) return _prepared_status_output_reference_allowed( first(permission.variants), name, reference) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index da51504bb..b1f821309 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1213,7 +1213,9 @@ function _replace_model_object_status!( store = model.registry.objects object_id = object.id::keytype(store) _validate_status_source_identity_available!(model, status, object_id) - _validate_prepared_initial_status(model, object, status, object.parent) + raw_parent = object.parent + parent_id = isnothing(raw_parent) ? nothing : _index_object_id(store, raw_parent) + _validate_prepared_initial_status(model, object, status, parent_id) return Base.@inline _with_prepared_canonical_status_type(model, object, object_id, status) do S, object, object_id, source admitted = isnothing(source) ? nothing : _new_prepared_status(S, source) _store_object_family_row!(store, object, object_id, admitted) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 511c8a9c0..a58656f61 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1628,9 +1628,10 @@ end # Pre-registration matching sees the exact admitted parent and the labels that # normal registration would inherit. Every other object remains the real model. -struct _PreparedStatusObjectTopology{M,P,K,SP} +struct _PreparedStatusObjectTopology{M,I<:ObjectId,P,K,SP} model::M object::Object + id::I parent::P kind::K species::SP @@ -1642,28 +1643,29 @@ function _prepared_status_object_labels(model, object, parent_id) return (scale=object.scale, kind=labels.kind, species=labels.species, id=object.id) end -function _prepared_status_topology(model, object, parent_id) - if get(model.registry.objects, object.id, nothing) === object && - isequal(object.parent, parent_id) +function _prepared_status_topology(model, object, id, parent_id) + parent = isnothing(parent_id) ? nothing : _index_object_id(model.registry.objects, parent_id) + if get(model.registry.objects, id, nothing) === object && + isequal(object.parent, parent) return model end - labels = _prepared_status_object_labels(model, object, parent_id) - return _PreparedStatusObjectTopology(model, object, parent_id, labels.kind, labels.species) + labels = _prepared_status_object_labels(model, object, parent) + return _PreparedStatusObjectTopology(model, object, id, parent, labels.kind, labels.species) end @inline _relation_same_object(topology::_PreparedStatusObjectTopology, left, right) = _relation_same_object(topology.model, left, right) @inline function _relation_parent(topology::_PreparedStatusObjectTopology, id) - return id == topology.object.id ? topology.parent : _relation_parent(topology.model, id) + return id == topology.id ? topology.parent : _relation_parent(topology.model, id) end @inline function _relation_in_subtree(topology::_PreparedStatusObjectTopology, id, root) - id == topology.object.id || return _relation_in_subtree(topology.model, id, root) + id == topology.id || return _relation_in_subtree(topology.model, id, root) id == root && return true isnothing(topology.parent) && return false return _relation_in_subtree(topology.model, topology.parent, root) end @inline function _scope_ancestor(topology::_PreparedStatusObjectTopology, origin, scale, include_self) - origin == topology.object.id || return _scope_ancestor(topology.model, origin, scale, include_self) + origin == topology.id || return _scope_ancestor(topology.model, origin, scale, include_self) include_self && (isnothing(scale) || topology.object.scale == scale) && return origin isnothing(topology.parent) && return nothing return _scope_ancestor(topology.model, topology.parent, scale, true) @@ -1671,7 +1673,7 @@ end _missing_point_scope_anchor(topology::_PreparedStatusObjectTopology, scope, id) = _missing_point_scope_anchor(topology.model, scope, id) @inline _point_scope_root_exists(topology::_PreparedStatusObjectTopology, id) = - id == topology.object.id || _point_scope_root_exists(topology.model, id) + id == topology.id || _point_scope_root_exists(topology.model, id) @inline function _point_named_scope_root(topology::_PreparedStatusObjectTopology, scope::Scope) root_id, _ = _named_scope_root_candidate(topology.model, scope) _point_scope_root_exists(topology, root_id) && return root_id @@ -1679,7 +1681,7 @@ _missing_point_scope_anchor(topology::_PreparedStatusObjectTopology, scope, id) end @inline function _selector_matches_object_labels(topology::_PreparedStatusObjectTopology, matcher::CompiledSelectorMatcher, id::ObjectId) - id == topology.object.id || return _selector_matches_object_labels(topology.model, matcher, id) + id == topology.id || return _selector_matches_object_labels(topology.model, matcher, id) labels = (scale=topology.object.scale, kind=topology.kind, species=topology.species, id=id) return _matches_object_criteria(labels; scale=matcher.scale, kind=matcher.kind, species=matcher.species, id=matcher.id) @@ -1693,18 +1695,20 @@ function _prepared_status_scope_is_current(model, topology, scope) end function _prepared_status_application_matches(model, object, parent_id, application) - topology = _prepared_status_topology(model, object, parent_id) + id = _index_object_id(model.registry.objects, object.id) + topology = _prepared_status_topology(model, object, id, parent_id) _prepared_status_scope_is_current(model, topology, application.target_matcher.scope) || return false return _selector_matches_object_id(topology, application.target_matcher, - object.id, nothing, false, nothing, false) + id, nothing, false, nothing, false) end function _prepared_status_destination_matches(model, object, parent_id, application, destination_plan, execution_id) # The permission caller owns this REAL producer and its configured variant. # Do not aggregate contexts or infer a producer from destination labels. - topology = _prepared_status_topology(model, object, parent_id) + id = _index_object_id(model.registry.objects, object.id) + topology = _prepared_status_topology(model, object, id, parent_id) _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope) || return false return _selector_matches_object_id(topology, destination_plan.matcher, - object.id, execution_id, true, _default_dependency_scope(model, execution_id), false) + id, execution_id, true, _default_dependency_scope(model, execution_id), false) end diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index a09055598..3c98d11a9 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -197,6 +197,15 @@ function _compile_model_status_view_for_application(application, model, object_i distributed_outputs, execution_stamp, status_view_schema, input_binding_storage) end +# Use the existing authored name witnesses before constructing the gathered +# record. Runtime unique/Vector -> Tuple loses the hot namespace cardinality. +@generated function _status_view_hot_names(::AuthoredPortNames{INPUTS}, + ::AuthoredOutputPorts{ALL,LOCAL}, +) where {INPUTS,ALL,LOCAL} + names = Tuple(unique((INPUTS..., LOCAL...))) + return QuoteNode(names) +end + # All modes gather the same values, in the original conversion/snapshot order. # Selection below concerns exact component construction, never scientific logic. function _assemble_model_status_view(canonical_status, model, application, object_id, @@ -251,7 +260,8 @@ function _assemble_model_status_view(canonical_status, model, application, objec "Compiled application input `$(name)` has more than one Many binding.") push!(seen_many, name) end - hot_names = Tuple(unique((_model_input_names(application)..., _model_output_names(application)...))) + ports = _application_ports(application) + hot_names = _status_view_hot_names(ports.inputs, ports.outputs) parts = (; canonical_status, temporal, private_names, private_values, hot_names, many_names, many_ids, execution_stamp) view = _construct_model_status_view(status_view_schema, application.id, parts) diff --git a/test/test-model-status-view-cache-admission.jl b/test/test-model-status-view-cache-admission.jl index 90a0c610c..62828b9f9 100644 --- a/test/test-model-status-view-cache-admission.jl +++ b/test/test-model-status-view-cache-admission.jl @@ -89,6 +89,33 @@ function assert_cells(data, before) @test all(after[name] === reference for (name, reference) in before) end +@testset "view construction uses the finite authored hot namespace" begin + for mode in (:one, :many) + data = fixture(mode) + compiled = data.simulation.compiled + application = compiled.applications_by_id[:consumer] + ports = PSE._application_ports(application) + names = @inferred PSE._status_view_hot_names(ports.inputs,ports.outputs) + @test names === (mode === :many ? (:signals,:value,:visits) : (:signal,:value,:visits)) + @test typeof(names) === Tuple{Symbol,Symbol,Symbol} + previous = view_cache(data)[VIEW_KEY] + schema = PSE.CompiledMetadataTable((consumer=typeof(previous)[],)) + bindings = [binding for binding in compiled.input_bindings + if binding.application_id === :consumer] + positions = Dict(id => index for (index,id) in pairs(compiled.application_order)) + current = PSE._compile_model_status_view(data.model,application,ObjectId(:consumer), + bindings,compiled.applications_by_id,positions,compiled.distributed_outputs, + previous.execution_stamp,schema,compiled.input_bindings) + @test typeof(current) === typeof(previous) + @test current.canonical_status === previous.canonical_status + @test fieldnames(fieldtype(typeof(PSE._status_vars(current.status)),:hot)) === names + @test all(PSE.refvalue(current.status,name) === PSE.refvalue(previous.status,name) + for name in names) + @test current.execution_stamp === previous.execution_stamp + @test isempty(schema[:consumer]) + end +end + @testset "cached view admission keeps compatible scalar, Many and temporal owners" begin for mode in (:one, :many, :temporal) data, control = fixture(mode), fixture(mode) diff --git a/test/test-prepared-status-registration.jl b/test/test-prepared-status-registration.jl index ba4775cf7..db174a076 100644 --- a/test/test-prepared-status-registration.jl +++ b/test/test-prepared-status-registration.jl @@ -10,9 +10,9 @@ PSE.inputs_(::Source) = NamedTuple() PSE.outputs_(model::Source) = (x=model.initial,) PSE.run!(::Source, status, environment, constants, context) = nothing -function fixture() +function fixture(second_id=17) first = Object(:plant_a; scale=:Plant) - second = Object(17; scale=:Plant) + second = Object(second_id; scale=:Plant) a = Object(:leaf_a; scale=:Leaf, parent=first.id, status=Status(x=1f0)) b = Object(:leaf_b; scale=:Leaf, parent=second.id, status=Status(x=2.0)) template(value) = CompositeModelTemplate(( @@ -72,6 +72,38 @@ end only(recipe for recipe in manifest.authored if recipe.id === :b__source)) end +@testset "prospective matching uses the finite registry identity family" begin + data = fixture(:plant_b) + previous = data.model.registry + objects = PSE._closed_object_family_store(previous.objects) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + fields = map(fieldnames(typeof(data.model))) do name + name === :registry ? registry : getfield(data.model, name) + end + model = PSE.CompositeModel(fields...) + @test keytype(model.registry.objects) === ObjectId{Symbol} + + wrong = Object(:wrong_closed; scale=:Leaf, status=Status(x=6.0)) + wrong_source = wrong.status + children = copy(data.first.children) + @test_throws ArgumentError register_object!(model, wrong; parent=data.first.id) + @test wrong.status === wrong_source + @test isnothing(wrong.parent) && isnothing(wrong.kind) && isnothing(wrong.species) + @test data.first.children == children + @test !haskey(model.registry.objects, wrong.id) + + source = Status(x=7.0) + cell = PSE.refvalue(source, :x) + newborn = Object(:new_closed; scale=:Leaf, parent=data.first.id, status=source) + @test register_object!(model, newborn; parent=data.second.id) === newborn + @test newborn.parent === data.second.id + @test newborn.kind === :tree && newborn.species === :same + @test PSE.refvalue(model_status(model, newborn.id), :x) === cell + @test resolve_object_ids(model, Many(Scope(:b), scale=:Leaf)) == [data.b.id, newborn.id] + @test resolve_object_ids(model, Many(Scope(:a), scale=:Leaf)) == [data.a.id] +end + @testset "empty prepared catalogs retain None and S without biological values" begin model = CompositeModel(Object(:only)) S = PSE._scenario_preparation(model).status_manifest.status_type diff --git a/test/test-registered-status-dispatch.jl b/test/test-registered-status-dispatch.jl index 7d13de21a..24bfc304a 100644 --- a/test/test-registered-status-dispatch.jl +++ b/test/test-registered-status-dispatch.jl @@ -45,6 +45,32 @@ PSE.inputs_(::Finisher) = NamedTuple() PSE.outputs_(::Finisher) = (value=0.5, visits=0) PSE.run!(::Finisher, status, environment, constants, context) = nothing +@testset "ensuring a required status admits root and registered parent identities" begin + model = with_finite_registry(CompositeModel( + Object(:root; scale=:Leaf),Object(:child; scale=:Leaf,parent=:root); + applications=(ModelSpec(Finisher();name=:finish,on=Many(scale=:Leaf)),))) + I = keytype(model.registry.objects) + S = PSE._scenario_preparation(model).status_manifest.status_type + @test I === typeof(ObjectId(:root)) + statuses = map((:root,:child)) do id + @test model_status(model,id) === nothing + status = @inferred PSE._ensure_model_object_status!(model,ObjectId(id)) + @test typeof(status) === S + @test model_status(model,id) === status + @test isempty(status) + @test (@inferred PSE._ensure_model_object_status!(model,ObjectId(id))) === status + status + end + @test model_object(model,:root).parent === nothing + @test model_object(model,:child).parent === ObjectId(:root) + simulation = run!(model;steps=1,outputs=:all) + for (id,status) in zip((:root,:child),statuses) + @test model_status(model,id) === status + @test status.value === 0.5 && status.visits === 0 + @test outputs(simulation)[(:finish,ObjectId(id),:value)] == [(1.0,0.5)] + end +end + @testset "newborn registration and finishing retain real reference classes" begin # These are genuine initial data, all retained and checked below. Their Ref # classes provide the raw seed family; ports provide value/visits permissions. diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 3961dcee7..8df21e4d3 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -123,8 +123,10 @@ end Object(leaf_id; scale=:Leaf, kind, species, parent=axis_id), ) closed && (model = _closed_selector_candidate_fixture(model)) - @test (model.registry.objects.catalog isa PlantSimEngine.ClosedObjectFamilyCatalog) === closed + @test model.registry.objects.catalog isa PlantSimEngine.ClosedObjectFamilyCatalog I = keytype(model.registry.objects) + expected_id_type = closed ? Union{map(id -> typeof(ObjectId(id)), ids)...} : ObjectId + @test I === expected_id_type index = PlantSimEngine._selector_candidate_index(model, nothing) frozen_empty = PlantSimEngine._freeze_selector_candidate_index(index) @test keytype(index.by_id) === keytype(frozen_empty.by_id) === I @@ -159,7 +161,9 @@ end end # Both reverse indexes exist BEFORE the selected future object. - # Open accepts every identity family; Closed keeps its actual union. + # Ordinary ID storage accepts every identity family; explicitly + # narrowed ID storage keeps its actual union. Both use the prepared + # canonical Status catalog. for raw_future in (leaf_id + 1000, :future_leaf, 1.5) future_id = ObjectId(raw_future) @test !haskey(model.registry.objects, future_id) From 9087d5655a77d31d3f39c13ae05ea50e41d90c82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 22:33:30 +0100 Subject: [PATCH 137/324] Admit status preparations before input reference callbacks Keep the actual canonical Status or staged recipe through the input callback, admit configured reference classes inside the existing permissions, and preserve nominal raw Status and object identity during registration. Six complete maintained files pass 483 assertions with all source/input/runtime/drain guards. The complete input-recipe file still exposes a prospective from_status permission gap under investigation; no full-suite or native qualification is claimed. --- src/composite_model/compilation.jl | 18 ++++----- .../prepared_status_manifest.jl | 29 ++++++++++++--- src/composite_model/registry_topology.jl | 10 +++-- test/test-model-input-recipes.jl | 37 +++++++++++++++++++ test/test-model-object-id.jl | 20 ++++++++-- 5 files changed, 92 insertions(+), 22 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 08f2624cf..5f97d19e7 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -7570,20 +7570,20 @@ function _stage_model_bound_input_reference!(binding, context) get(context.final_references, (binding.application_id, binding.consumer_id, binding.input), nothing) isnothing(reference) && (reference = _model_input_status_reference(binding)) - return Base.@inline _with_model_input_status_reference( - _stage_model_bound_input_reference_with_reference!, binding, - reference, preparation, binding, context) + return Base.@inline _with_canonical_status_preparation( + _stage_model_bound_input_reference_with_preparation!, context.recipes, + context.model.registry.objects.catalog, preparation, reference, binding, context) end -function _stage_model_bound_input_reference_with_reference!(reference, - preparation, binding, context, +@inline function _stage_model_bound_input_reference_with_preparation!(preparation, + reference, binding, context, ) - return _with_canonical_status_preparation(_stage_admitted_model_input_reference!, - context.recipes, context.model.registry.objects.catalog, preparation, - reference, binding, context) + return Base.@inline _with_model_input_status_reference( + _stage_admitted_model_input_reference!, binding, + reference, preparation, binding, context) end -function _stage_admitted_model_input_reference!(preparation, reference, binding, +function _stage_admitted_model_input_reference!(reference, preparation, binding, context, ) if preparation isa Status diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 5b6f3b92b..0f9d56627 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -319,11 +319,26 @@ function _prepared_status_destinations_allow(plans::Tuple, manifest, model, obje return _prepared_status_destinations_allow(Base.tail(plans), manifest, model, object, parent_id, name, reference) end -function _prepared_status_configured_reference_allowed(manifest, model, object, parent_id, name, reference) - return _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, - model, object, parent_id, name, reference) || - _prepared_status_destinations_allow(manifest.destinations, manifest, - model, object, parent_id, name, reference) +@generated function _prepared_status_configured_reference_allowed( + manifest::PreparedStatusManifest{S}, model, object, parent_id, name, reference, +) where {S} + # The sparse CSR keeps Ref instances erased; admit them through the SAME + # prepared physical bounds before visiting the active configuration. + references = unique(R for slot in fieldtypes(_status_schema_references(S)) + for R in Base.uniontypes(slot) if R <: Ref) + branches = [quote + if reference isa $R + return _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, + model, object, parent_id, name, reference::$R) || + _prepared_status_destinations_allow(manifest.destinations, manifest, + model, object, parent_id, name, reference::$R) + end + end for R in references] + return quote + $(Expr(:meta, :inline)) + $(branches...) + return false + end end function _prepared_status_raw_variant(raw, slot) @@ -453,12 +468,14 @@ function _validate_prepared_status_recipe(model, object_id, recipe) throw(ArgumentError("Prepared status source ownership changed.")) end manifest = _prepared_status_manifest(model) + raw_parent = object.parent + parent_id = isnothing(raw_parent) ? nothing : _index_object_id(store, raw_parent) # A reparent/Scope change never revokes cells already owned by this object. # Only NEW edits need active permissions; old aliases grant no new rights. for (name, reference) in zip(recipe.edit_names, recipe.edit_references) _initial_status_reference(original, name) === reference && continue _prepared_status_configured_reference_allowed(manifest, model, object, - object.parent, name, reference) || throw(ArgumentError( + parent_id, name, reference) || throw(ArgumentError( "A staged status reference is incompatible with the prepared object configuration.")) end return nothing diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index b1f821309..467a64369 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1480,10 +1480,14 @@ end # unconverted source need not be a canonical family when conversion is active. @inline function _register_object_status!(model, object, id, parent_id, source_status, status_values_materialized, prepared::Bool) + source_status isa Union{Nothing,Status} || throw(ArgumentError( + "Initial object status must be a Status or nothing.")) _validate_status_source_identity_available!(model, source_status, id) conversion_records = Dict{Any,Any}() converted = status_values_materialized || _no_status_conversion(model.status_conversion) ? source_status : _convert_registered_status(model, id, source_status; conversion_records) + converted isa Union{Nothing,Status} || throw(ArgumentError( + "Converted object status must be a Status or nothing.")) registered = if prepared Base.@inline _with_prepared_canonical_status_type(_register_prepared_object_status!, model, model, object, id, parent_id, source_status, converted) @@ -1537,14 +1541,14 @@ refresh boundary. Prefer [`add_organ!`](@ref) for MTG-backed growth. _validate_authored_scenario(_scenario_preparation(model)) throw(ArgumentError("The model has no executable prepared canonical registry.")) end - registered = _register_object_without_lifecycle!( + _register_object_without_lifecycle!( model, object; parent=parent, prepared=true, ) - _record_added_objects!(model, (registered,)) - return registered + _record_added_objects!(model, (object,)) + return object end function _validate_organ_attributes(attributes) diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index fffa9d30c..03f7f3434 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -117,6 +117,43 @@ end binding.input === :left ? :x : :y) for binding in fresh) end +@testset "restaging admitted scalar and Many inputs retains official cells" begin + many_model = CompositeModel(Object(:reader; scale=:Reader), + Object(:source; scale=:Leaf); + applications=( + ModelSpec(Writer(3f0); name=:source, on=One(id=:source)), + ModelSpec(AggregateReader(); name=:aggregate, on=One(id=:reader), + inputs=(values=Many(SceneScope(); scale=:Leaf, + application=:source, var=:x),)), + ), environment=(duration=Hour(1),)) + for model in (pair_model(), many_model) + simulation = run!(model; steps=0, outputs=:all) + compiled = simulation.compiled + # The finite owner contains only the real bindings just compiled here. + B = Union{map(typeof, compiled.input_bindings)...} + bindings = Vector{B}(compiled.input_bindings) + statuses = Dict(id => model_status(model,id) for id in keys(model.registry.objects)) + references = Dict((binding.application_id,binding.consumer_id,binding.input) => + PSE.refvalue(statuses[binding.consumer_id],binding.input) for binding in bindings) + before = copy(model.status_conversion_records) + PSE._prepare_model_input_statuses_batched!(model,compiled.applications, + compiled.applications_by_id,bindings; final_references=references) + @test all(model_status(model,id) === status for (id,status) in statuses) + @test all(PSE.refvalue(model_status(model,binding.consumer_id),binding.input) === + references[(binding.application_id,binding.consumer_id,binding.input)] for binding in bindings) + @test model.status_conversion_records == before + continue!(simulation) + if model === many_model + @test input_carrier(only(bindings)) isa PSE.RefVector{Float32} + @test model_status(model,:reader).total === 3.0 + @test outputs(simulation)[(:aggregate,ObjectId(:reader),:total)] == [(1.0,3.0)] + else + @test model_status(model,2).total === 6f0 + @test outputs(simulation)[(:reader,ObjectId(2),:total)] == [(1.0,6f0)] + end + end +end + @testset "inferred input groups drive initial and newborn execution in dependency order" begin model = CompositeModel(Object(1; scale=:Leaf); applications=( diff --git a/test/test-model-object-id.jl b/test/test-model-object-id.jl index 78f56e38f..93cd461e3 100644 --- a/test/test-model-object-id.jl +++ b/test/test-model-object-id.jl @@ -349,10 +349,15 @@ end end @testset "registered Status identity resolution" begin - status = Status(signal=1.0) - object = Object(:leaf; scale=:Leaf, status=status) + supplied_status = Status(signal=1.0) + signal_reference = PlantSimEngine.refvalue(supplied_status, :signal) + object = Object(:leaf; scale=:Leaf, status=supplied_status) model = CompositeModel(object) + status = model_status(model, object) + @test status !== supplied_status + @test PlantSimEngine.refvalue(status, :signal) === signal_reference + @test_throws ArgumentError object_id(model, supplied_status) @test object_id(model, status) == ObjectId(:leaf) @test _registered_object_id_allocations(model, status) == 0 @test object_id(model, object) == ObjectId(:leaf) @@ -370,8 +375,15 @@ end Object(:empty_a; scale=:Leaf, status=empty_status_a), Object(:empty_b; scale=:Leaf, status=empty_status_b), ) - @test object_id(empty_model, empty_status_a) == ObjectId(:empty_a) - @test object_id(empty_model, empty_status_b) == ObjectId(:empty_b) + registered_empty_a = model_status(empty_model, :empty_a) + registered_empty_b = model_status(empty_model, :empty_b) + @test registered_empty_a !== empty_status_a + @test registered_empty_b !== empty_status_b + @test registered_empty_a !== registered_empty_b + @test object_id(empty_model, registered_empty_a) == ObjectId(:empty_a) + @test object_id(empty_model, registered_empty_b) == ObjectId(:empty_b) + @test_throws ArgumentError object_id(empty_model, empty_status_a) + @test_throws ArgumentError object_id(empty_model, empty_status_b) shared_status = Status(signal=2.0) @test_throws ArgumentError CompositeModel( From aa62df8a85f61c00538d41b88744bc566f3b2772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 23:05:02 +0100 Subject: [PATCH 138/324] Admit newborn statuses at the registry entry boundary --- src/composite_model/registry_topology.jl | 41 ++++++++++++----------- test/test-prepared-status-registration.jl | 31 +++++++++++++++++ 2 files changed, 52 insertions(+), 20 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 467a64369..94b9e71af 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -536,7 +536,6 @@ function _register_objects!( model, object; status_values_materialized=status_values_materialized, - prepared=false, ) push!(added, object) deleteat!(pending, index) @@ -1464,7 +1463,6 @@ end object::Object; parent=object.parent, status_values_materialized::Bool=false, - prepared::Bool, ) registry = model.registry id = _index_object_id(registry.objects, object.id) @@ -1473,35 +1471,39 @@ end if !isnothing(parent_id) && !haskey(registry.objects, parent_id) error("No model object with id `$(parent_id.value)`.") end - return _register_object_status!(model, object, id, parent_id, object.status, status_values_materialized, prepared) + source_status = object.status + source_status isa Union{Nothing,Status} || throw(ArgumentError( + "Initial object status must be a Status or nothing.")) + return _register_object_status!(model, object, id, parent_id, source_status, status_values_materialized) end # The same conversion and ownership operations serve both catalog forms. An # unconverted source need not be a canonical family when conversion is active. -@inline function _register_object_status!(model, object, id, parent_id, source_status, - status_values_materialized, prepared::Bool) - source_status isa Union{Nothing,Status} || throw(ArgumentError( - "Initial object status must be a Status or nothing.")) +@inline function _register_object_status!(model, object, id, parent_id, + source_status::Union{Nothing,Status}, status_values_materialized) _validate_status_source_identity_available!(model, source_status, id) + if status_values_materialized || _no_status_conversion(model.status_conversion) + return _register_converted_status!(model, object, id, parent_id, source_status, source_status) + end conversion_records = Dict{Any,Any}() - converted = status_values_materialized || _no_status_conversion(model.status_conversion) ? - source_status : _convert_registered_status(model, id, source_status; conversion_records) + converted = _convert_registered_status(model, id, source_status; conversion_records) converted isa Union{Nothing,Status} || throw(ArgumentError( "Converted object status must be a Status or nothing.")) - registered = if prepared - Base.@inline _with_prepared_canonical_status_type(_register_prepared_object_status!, - model, model, object, id, parent_id, source_status, converted) - else - _register_converted_object!(model, object, id, parent_id, source_status, converted) - end + registered = _register_converted_status!(model, object, id, parent_id, source_status, converted) merge!(model.status_conversion_records, conversion_records) return registered end -@inline function _register_prepared_object_status!(::Type{S}, model, object, id, - parent_id, source_status, converted) where {S} - _validate_prepared_initial_status(model, object, converted, parent_id) - status = isnothing(converted) ? nothing : _new_prepared_status(S, converted) +@inline function _register_converted_status!(model, object, id, parent_id, + source_status::Union{Nothing,Status}, converted::Union{Nothing,Status}) + catalog = model.registry.objects.catalog + status = if catalog isa ClosedObjectFamilyCatalog + manifest = catalog.status_manifest + _validate_prepared_initial_status(manifest, model, object, converted, parent_id) + isnothing(converted) ? nothing : _new_prepared_status(manifest.status_type, converted) + else + converted + end return _register_converted_object!(model, object, id, parent_id, source_status, status) end @@ -1545,7 +1547,6 @@ refresh boundary. Prefer [`add_organ!`](@ref) for MTG-backed growth. model, object; parent=parent, - prepared=true, ) _record_added_objects!(model, (object,)) return object diff --git a/test/test-prepared-status-registration.jl b/test/test-prepared-status-registration.jl index db174a076..67da4e892 100644 --- a/test/test-prepared-status-registration.jl +++ b/test/test-prepared-status-registration.jl @@ -104,6 +104,37 @@ end @test resolve_object_ids(model, Many(Scope(:a), scale=:Leaf)) == [data.a.id] end +@testset "registration retains conversion receipts only for actual materialization" begin + for promote in (false, true) + calls = Ref(0) + transform(variable, value) = (calls[] += 1; value) + model = CompositeModel(Object(:root; scale=:Scene), + Object(:seed; scale=:Leaf, parent=:root, status=Status(x=1f0)); + applications=(ModelSpec(Source(0f0); name=:source, on=Many(scale=:Leaf)),), + type_promotion=promote ? Dict(Float64 => Float32) : nothing, + status_transform=promote ? transform : nothing) + @test model_status(model, :root) === nothing + calls[] = 0 + records = copy(model.status_conversion_records) + supplied = promote ? Status(x=2.0) : Status(x=2f0) + reference = PSE.refvalue(supplied, :x) + object = Object(:born; scale=:Leaf, parent=:root, status=supplied) + @test register_object!(model, object) === object + official = model_status(model, object) + @test official.x === 2f0 + @test supplied.x === (promote ? 2.0 : 2f0) + @test (PSE.refvalue(official, :x) === reference) === !promote + @test calls[] == Int(promote) + if promote + receipt = model.status_conversion_records[(:supplied_status, nothing, object.id, :x)] + @test receipt.original_type === Float64 + @test receipt.effective_type === Float32 + else + @test model.status_conversion_records == records + end + end +end + @testset "empty prepared catalogs retain None and S without biological values" begin model = CompositeModel(Object(:only)) S = PSE._scenario_preparation(model).status_manifest.status_type From d18915fc5ed9791df8ad47d273fbebf71d899723 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 23:14:52 +0100 Subject: [PATCH 139/324] Prepare future from-status sources with their real reference families --- src/composite_model/compilation.jl | 23 ++- .../prepared_status_manifest.jl | 190 +++++++++++++++--- src/composite_model/selectors.jl | 6 +- test/test-model-input-binding-storage.jl | 168 +++++++++++++++- 4 files changed, 343 insertions(+), 44 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 5f97d19e7..ead2e0473 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6333,8 +6333,8 @@ end @inline function _checked_input_reference(reference) isnothing(reference) && return nothing - reference isa Base.RefValue || throw(ArgumentError( - "Input reference carriers require Base.RefValue storage; got `$(typeof(reference))`.", + reference isa Ref || throw(ArgumentError( + "Input reference carriers require Ref storage; got `$(typeof(reference))`.", )) return reference end @@ -6343,10 +6343,11 @@ end function _many_input_carrier_type(::Type{RT}) where {RT<:Tuple} types = fieldtypes(RT) isempty(types) && throw(ArgumentError("A Many input requires a prepared reference family.")) - all(R -> R <: Base.RefValue && isconcretetype(R), types) || + all(R -> R <: Ref && isconcretetype(R), types) || throw(ArgumentError("A Many input requires exact prepared reference types.")) R = Union{types...} - return length(types) == 1 && isconcretetype(eltype(only(types))) ? + return length(types) == 1 && only(types) <: Base.RefValue && + isconcretetype(eltype(only(types))) ? RefVector{eltype(only(types))} : ObjectRefVector{Vector{R}} end @@ -6358,7 +6359,7 @@ end isempty(source_ids) && return nothing throw(ArgumentError("An input source is outside its empty prepared reference family.")) end - all(R -> R <: Base.RefValue && isconcretetype(R), types) || + all(R -> R <: Ref && isconcretetype(R), types) || return :(throw(ArgumentError("An input requires exact prepared reference classes."))) R = Union{types...} return quote @@ -6375,7 +6376,7 @@ end ) where {F,RT<:Tuple} types = fieldtypes(RT) isempty(types) && return :(throw(ArgumentError("A Many input requires a prepared reference family."))) - all(R -> R <: Base.RefValue && isconcretetype(R), types) || + all(R -> R <: Ref && isconcretetype(R), types) || return :(throw(ArgumentError("A Many input requires exact prepared reference types."))) R = Union{types...} C = _many_input_carrier_type(RT) @@ -7443,7 +7444,7 @@ function _force_distributed_producer_rebinds!(forced, model, bindings, by_variab end _model_input_status_reference(binding) = - binding.carrier isa Base.RefValue ? + binding.carrier isa Ref ? binding.carrier : Ref(binding.carrier) function _model_input_status_references(bindings) @@ -7469,7 +7470,7 @@ function _model_input_status_reference_types(B) Carrier === Nothing && continue isconcretetype(Carrier) || throw(ArgumentError( "An input status reference requires an exact prepared carrier type.")) - Reference = Carrier <: Base.RefValue ? Carrier : Base.RefValue{Carrier} + Reference = Carrier <: Ref ? Carrier : Base.RefValue{Carrier} isconcretetype(Reference) || throw(ArgumentError( "An input status reference requires an exact prepared reference type.")) Reference in references || push!(references, Reference) @@ -7815,7 +7816,7 @@ input_carrier(binding::CompiledModelInputBinding) = binding.carrier has_reference_carrier(binding::CompiledModelInputBinding) = !isnothing(binding.carrier) input_value(binding::CompiledModelInputBinding) = _input_value(binding.carrier) _input_value(::Nothing) = nothing -_input_value(carrier::Base.RefValue) = carrier[] +_input_value(carrier::Ref) = carrier[] _input_value(carrier::RefVector) = carrier _input_value(carrier::ObjectRefVector) = carrier @@ -8235,7 +8236,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, status = object.status status isa Status && hasproperty(status, source_var) || continue reference = refvalue(status, source_var) - reference isa Base.RefValue || continue + reference isa Ref || continue add(typeof(reference)) observed_any = true delete!(missing_current, object.id) @@ -9646,7 +9647,7 @@ function _model_binding_carrier_kind(binding::CompiledModelInputBinding) binding.carrier_hint == :optional_default && return :optional_default carrier = binding.carrier isnothing(carrier) && return :unresolved - carrier isa Base.RefValue && return :ref + carrier isa Ref && return :ref carrier isa RefVector && return :ref_vector carrier isa ObjectRefVector && return :object_ref_vector return :custom diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 0f9d56627..b742f4abc 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -58,7 +58,7 @@ function _prepared_status_declared_reference(policy, T, elements) return Union{map(T -> Base.RefValue{T}, members)...} end -function _prepared_status_variant_permission(model, application, ports) +function _prepared_status_variant_permission(model, application, ports, plans) names = Symbol[]; refs = Any[] output_names = Symbol[]; output_refs = Any[] for name in keys(ports.output_types) @@ -73,8 +73,27 @@ function _prepared_status_variant_permission(model, application, ports) getproperty(ports.input_types, name), get(ports.input_element_types, name, nothing)) _prepared_status_add_type!(names, refs, name, R) end + source_names = Symbol[]; source_refs = Any[] + for plan in plans + _input_route_from_status(plan.route) || continue + configured = _configured_status_value_type(model.status_conversion, + getproperty(ports.input_types, plan.input), + get(ports.input_element_types, plan.input, nothing)) + T = plan.selector isa Many ? + (!isnothing(configured) && configured <: AbstractVector ? eltype(configured) : Union{}) : + (isnothing(configured) ? Union{} : configured) + T === Union{} && continue + # Real/Any are value bounds, not requests to replace Ref32/Ref64 by + # invariant Ref{Real}/Ref{Any}. Keep only already prepared real classes. + classes = Tuple(R for slot in fieldtypes(plan.reference_types) + for R in Base.uniontypes(slot) if R <: Ref && + isconcretetype(R) && eltype(R) <: T) + isempty(classes) && continue + _prepared_status_add_type!(source_names, source_refs, plan.input, Union{classes...}) + end return (canonical=_prepared_status_type_map(names, refs), - outputs=_prepared_status_type_map(output_names, output_refs)) + outputs=_prepared_status_type_map(output_names, output_refs), + source_inputs=_prepared_status_type_map(source_names, source_refs)) end # Project the SAME prepared source-reference family used by the runtime carrier @@ -90,12 +109,12 @@ end function _prepared_status_application_permissions(model, recipes, program) return map(recipes) do application + plans = Tuple(plan for plan in program.input_records + if plan isa CompiledModelInputPlan && plan.application_slot == application.slot) variants = Any[] _foreach_application_variant(application) do _, ports - push!(variants, _prepared_status_variant_permission(model, application, ports)) + push!(variants, _prepared_status_variant_permission(model, application, ports, plans)) end - plans = Tuple(plan for plan in program.input_records - if plan isa CompiledModelInputPlan && plan.application_slot == application.slot) # Plan reference classes are common route evidence. Effective model # default classes above stay in their individual configured variant. alias_names = Symbol[]; alias_refs = Any[] @@ -104,11 +123,15 @@ function _prepared_status_application_permissions(model, recipes, program) plan.input, _prepared_status_input_reference(plan)) end aliases = _prepared_status_type_map(alias_names, alias_refs) - (slot=application.slot, id=application.id, variants=Tuple(variants), aliases=aliases) + sources = Tuple((plan=plan, references=_prepared_status_type_map( + (plan.source_var,), (Union{fieldtypes(plan.reference_types)...},))) + for plan in plans if _input_route_from_status(plan.route)) + (slot=application.slot, id=application.id, variants=Tuple(variants), + aliases=aliases, sources=sources) end end -function _prepared_status_raw_signature(model, object, recipes, destinations) +function _prepared_status_raw_signature(model, object, recipes, permissions, destinations) selected = Tuple((application.slot, _prepared_status_variant_slot(application, object.id)) for application in recipes if _prepared_status_application_matches(model, object, object.parent, application)) @@ -117,15 +140,25 @@ function _prepared_status_raw_signature(model, object, recipes, destinations) application = only(a for a in recipes if a.slot == plan.application_slot) for (execution_id, producer) in model.registry.objects _prepared_status_application_matches(model, producer, producer.parent, application) || continue - _prepared_status_destination_matches(model, object, object.parent, + _prepared_status_route_matches(model, object, object.parent, application, plan, execution_id) || continue push!(routes, (plan.slot, execution_id, _prepared_status_variant_slot(application, execution_id))) end end + sources = Any[] + for (application, permission) in zip(recipes, permissions), source in permission.sources + for (consumer_id, consumer) in model.registry.objects + _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue + _prepared_status_route_matches(model, object, object.parent, + application, source.plan, consumer_id) || continue + push!(sources, (source.plan.slot, consumer_id, + _prepared_status_variant_slot(application, consumer_id))) + end + end labels = _prepared_status_object_labels(model, object, object.parent) return (labels=(labels.scale, labels.kind, labels.species), - selected=selected, destinations=Tuple(routes)) + selected=selected, destinations=Tuple(routes), sources=Tuple(sources)) end function _prepare_status_manifest(model, authored, program, raw_basis) @@ -149,7 +182,7 @@ function _prepare_status_manifest(model, authored, program, raw_basis) source isa Status || continue raw_names = propertynames(source) raw_refs = Tuple(typeof(refvalue(source, name)) for name in raw_names) - signature = _prepared_status_raw_signature(model, object, recipes, destinations) + signature = _prepared_status_raw_signature(model, object, recipes, permissions, destinations) entry = (signature=signature, schema=_prepared_status_type_map(raw_names, raw_refs)) entry in observed || push!(observed, entry) @@ -170,6 +203,12 @@ function _prepare_status_manifest(model, authored, program, raw_basis) for (name, R) in pairs(permission.aliases) _prepared_status_add_type!(names, refs, name, R) end + for source in permission.sources, variant in permission.variants + input = source.plan.input + hasproperty(variant.source_inputs, input) || continue + _prepared_status_add_type!(names, refs, source.plan.source_var, + getproperty(variant.source_inputs, input)) + end end # Distributed default types use the corresponding producer variant owner. # They enter the global storage bound even before any destination exists. @@ -288,7 +327,7 @@ function _prepared_status_destination_reference_allowed(applications::Tuple, for (execution_id, producer) in model.registry.objects _prepared_status_application_matches(model, producer, producer.parent, application) || continue has_producer = true - _prepared_status_destination_matches(model, object, parent_id, + _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue variant = _prepared_status_variant_slot(application, execution_id) _with_metadata_entry(_prepared_status_output_reference_allowed, @@ -319,7 +358,67 @@ function _prepared_status_destinations_allow(plans::Tuple, manifest, model, obje return _prepared_status_destinations_allow(Base.tail(plans), manifest, model, object, parent_id, name, reference) end -@generated function _prepared_status_configured_reference_allowed( +_prepared_status_source_input_admission(variant, input, reference) = + hasproperty(variant.source_inputs, input) ? + (true, _prepared_status_reference_allowed(variant.source_inputs, input, reference)) : + (false, true) + +# Return whether a declaration contributes a right, all declarations agree, +# and every applicable route reference family admits the actual class. +# Observed extra RT classes support existing references/reparenting; they do not +# create new initial-data permissions in a different configured source context. +_prepared_status_source_routes_admission(::Tuple{}, application, permission, + model, object, parent_id, name, reference) = (false, true, true) +function _prepared_status_source_routes_admission(sources::Tuple, application, permission, + model, object, parent_id, name, reference) + source = first(sources) + declared, allowed = false, true + if source.plan.source_var === name + has_consumer = false + for (consumer_id, consumer) in model.registry.objects + _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue + has_consumer = true + _prepared_status_route_matches(model, object, parent_id, + application, source.plan, consumer_id) || continue + _prepared_status_reference_allowed(source.references, name, reference) || + return (false, false, false) + has_type, matches = _with_metadata_entry(_prepared_status_source_input_admission, + permission.variants, _prepared_status_variant_slot(application, consumer_id), + source.plan.input, reference) + declared |= has_type + allowed &= matches + end + matcher = source.plan.matcher + if !has_consumer && matcher.scope isa SceneScope && isnothing(matcher.relation) + id = _index_object_id(model.registry.objects, object.id) + topology = _prepared_status_topology(model, object, id, parent_id) + if _selector_matches_object_id(topology, matcher, id, + nothing, false, nothing, false) + _prepared_status_reference_allowed(source.references, name, reference) || + return (false, false, false) + declared, allowed = _prepared_status_source_input_admission( + first(permission.variants), source.plan.input, reference) + end + end + end + next_declared, next_allowed, compatible = _prepared_status_source_routes_admission( + Base.tail(sources), application, permission, model, object, parent_id, name, reference) + return (declared | next_declared, allowed & next_allowed, compatible) +end +_prepared_status_sources_admission(::Tuple{}, ::Tuple{}, model, object, + parent_id, name, reference) = (false, true, true) +function _prepared_status_sources_admission(applications::Tuple, permissions::Tuple, + model, object, parent_id, name, reference) + declared, allowed, compatible = _prepared_status_source_routes_admission( + first(permissions).sources, first(applications), first(permissions), + model, object, parent_id, name, reference) + compatible || return (false, false, false) + next_declared, next_allowed, compatible = _prepared_status_sources_admission( + Base.tail(applications), Base.tail(permissions), model, object, parent_id, name, reference) + return (declared | next_declared, allowed & next_allowed, compatible) +end + +@generated function _prepared_status_configured_reference_admission( manifest::PreparedStatusManifest{S}, model, object, parent_id, name, reference, ) where {S} # The sparse CSR keeps Ref instances erased; admit them through the SAME @@ -328,16 +427,22 @@ end for R in Base.uniontypes(slot) if R <: Ref) branches = [quote if reference isa $R - return _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, - model, object, parent_id, name, reference::$R) || + declared, source_allowed, compatible = _prepared_status_sources_admission( + manifest.authored, manifest.permissions, model, object, parent_id, + name, reference::$R) + compatible || return (false, false) + allowed = (declared && source_allowed) || + _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, + model, object, parent_id, name, reference::$R) || _prepared_status_destinations_allow(manifest.destinations, manifest, model, object, parent_id, name, reference::$R) + return (allowed, true) end end for R in references] return quote $(Expr(:meta, :inline)) $(branches...) - return false + return (false, false) end end @@ -359,9 +464,9 @@ function _prepared_status_raw_membership_matches(applications::Tuple, raw, model end return _prepared_status_raw_membership_matches(Base.tail(applications), raw, model, object, parent_id) end -function _prepared_status_raw_has_destination(raw, plan, execution_id, variant) - for entry in raw.signature.destinations - entry[1] == plan.slot && entry[2] == execution_id && entry[3] == variant && return true +function _prepared_status_raw_has_context(contexts, plan, origin_id, variant) + for entry in contexts + entry[1] == plan.slot && entry[2] == origin_id && entry[3] == variant && return true end return false end @@ -373,10 +478,10 @@ function _prepared_status_raw_destination_count(applications::Tuple, plan, raw, count = 0 for (execution_id, producer) in model.registry.objects _prepared_status_application_matches(model, producer, producer.parent, application) || continue - _prepared_status_destination_matches(model, object, parent_id, + _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue variant = _prepared_status_variant_slot(application, execution_id) - _prepared_status_raw_has_destination(raw, plan, execution_id, variant) || return -1 + _prepared_status_raw_has_context(raw.signature.destinations, plan, execution_id, variant) || return -1 count += 1 end return count @@ -389,12 +494,41 @@ function _prepared_status_raw_destination_total(plans::Tuple, manifest, raw, mod rest = _prepared_status_raw_destination_total(Base.tail(plans), manifest, raw, model, object, parent_id) return rest < 0 ? -1 : count + rest end +_prepared_status_raw_source_count(::Tuple{}, application, raw, model, object, parent_id) = 0 +function _prepared_status_raw_source_count(sources::Tuple, application, raw, model, object, parent_id) + source = first(sources) + count = 0 + for (consumer_id, consumer) in model.registry.objects + _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue + _prepared_status_route_matches(model, object, parent_id, + application, source.plan, consumer_id) || continue + variant = _prepared_status_variant_slot(application, consumer_id) + _prepared_status_raw_has_context(raw.signature.sources, source.plan, + consumer_id, variant) || return -1 + count += 1 + end + rest = _prepared_status_raw_source_count(Base.tail(sources), application, + raw, model, object, parent_id) + return rest < 0 ? -1 : count + rest +end +_prepared_status_raw_source_total(::Tuple{}, ::Tuple{}, raw, model, object, parent_id) = 0 +function _prepared_status_raw_source_total(applications::Tuple, permissions::Tuple, + raw, model, object, parent_id) + count = _prepared_status_raw_source_count(first(permissions).sources, + first(applications), raw, model, object, parent_id) + count < 0 && return -1 + rest = _prepared_status_raw_source_total(Base.tail(applications), Base.tail(permissions), + raw, model, object, parent_id) + return rest < 0 ? -1 : count + rest +end function _prepared_status_raw_matches(raw, manifest, model, object, parent_id) labels = _prepared_status_object_labels(model, object, parent_id) raw.signature.labels == (labels.scale, labels.kind, labels.species) || return false _prepared_status_raw_membership_matches(manifest.authored, raw, model, object, parent_id) || return false - return _prepared_status_raw_destination_total(manifest.destinations, manifest, - raw, model, object, parent_id) == length(raw.signature.destinations) + _prepared_status_raw_destination_total(manifest.destinations, manifest, + raw, model, object, parent_id) == length(raw.signature.destinations) || return false + return _prepared_status_raw_source_total(manifest.authored, manifest.permissions, + raw, model, object, parent_id) == length(raw.signature.sources) end _prepared_status_raw_reference_allowed(::Nothing, name, reference) = false _prepared_status_raw_reference_allowed(raw, name, reference) = @@ -411,8 +545,9 @@ _prepared_status_raw_reference_allowed(raw, name, reference) = reference = _initial_status_reference(source, $(QuoteNode(name))) if reference !== nothing present += 1 - (_prepared_status_configured_reference_allowed(manifest, model, - object, parent_id, $(QuoteNode(name)), reference) || + allowed, compatible = _prepared_status_configured_reference_admission(manifest, model, + object, parent_id, $(QuoteNode(name)), reference) + compatible && (allowed || _prepared_status_raw_reference_allowed(raw, $(QuoteNode(name)), reference)) || return false end end) @@ -474,9 +609,10 @@ function _validate_prepared_status_recipe(model, object_id, recipe) # Only NEW edits need active permissions; old aliases grant no new rights. for (name, reference) in zip(recipe.edit_names, recipe.edit_references) _initial_status_reference(original, name) === reference && continue - _prepared_status_configured_reference_allowed(manifest, model, object, - parent_id, name, reference) || throw(ArgumentError( - "A staged status reference is incompatible with the prepared object configuration.")) + allowed, compatible = _prepared_status_configured_reference_admission(manifest, + model, object, parent_id, name, reference) + allowed && compatible || throw(ArgumentError( + "A staged status reference is incompatible with the prepared object configuration.")) end return nothing end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index a58656f61..4ce4036b4 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1702,10 +1702,10 @@ function _prepared_status_application_matches(model, object, parent_id, applicat id, nothing, false, nothing, false) end -function _prepared_status_destination_matches(model, object, parent_id, application, +function _prepared_status_route_matches(model, object, parent_id, application, destination_plan, execution_id) - # The permission caller owns this REAL producer and its configured variant. - # Do not aggregate contexts or infer a producer from destination labels. + # The permission caller owns this REAL route origin and configured variant. + # Output destinations and from-status input sources use the same predicate. id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope) || return false diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 64a2a0e24..5e7da10d3 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -6,8 +6,9 @@ const PSE = PlantSimEngine PSE.@process "input_binding_storage_reader" verbose=false PSE.@process "input_binding_storage_capture" verbose=false -struct Reader <: AbstractInput_Binding_Storage_ReaderModel end -PSE.inputs_(::Reader) = (single=Required(Float32), values=Default(Float64[])) +struct Reader{T} <: AbstractInput_Binding_Storage_ReaderModel end +Reader() = Reader{Float64}() +PSE.inputs_(::Reader{T}) where {T} = (single=Required(Float32), values=Default(T[])) PSE.outputs_(::Reader) = (total=0.0,) function PSE.run!(::Reader, status, environment, constants, context) status.total = Float64(status.single) + sum(bound_input(context, :values); init=0.0) @@ -159,7 +160,13 @@ end first = Status(x=7.0) second = Status(x=9f0) register_object!(data.model, Object(:first; scale=:Leaf, parent=:scene, status=first)) - register_object!(data.model, Object(:second; scale=:Leaf, parent=:scene, status=second)) + # The unprepared numerical class is rejected before it can become active. + @test_throws ArgumentError register_object!(data.model, + Object(:second; scale=:Leaf, parent=:scene, status=second)) + @test !haskey(data.model.registry.objects,ObjectId(:second)) + register_object!(data.model,Object(:second;scale=:Leaf,parent=:scene)) + @test model_status(data.model,:second) === nothing + # A valid first reference followed by genuine absence must not append either. @test !PSE._append_stable_many_source_references!(data.model, current, ObjectId[ObjectId(:first), ObjectId(:second)], nothing) @test parent(current.carrier) === references @@ -170,6 +177,161 @@ end @test check_carriers(data, simulation).carrier === current.carrier end +@testset "from-status permissions retain source route and numerical configuration" begin + model = CompositeModel(Object(:scene;scale=:Scene), + Object(:root_a;parent=:scene),Object(:root_b;parent=:scene), + Object(:anchor;scale=:Anchor,parent=:scene,status=Status(x=3f0)), + Object(:reader_a;scale=:Reader,parent=:root_a), + Object(:reader_b;scale=:Reader,parent=:root_b), + Object(:leaf_a;scale=:Leaf,parent=:root_a,status=Status(x=5f0)); + applications=Tuple(ModelSpec(Reader{T}();name=name,on=One(id=id),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(scale=:Leaf,within=Scope(ObjectId(root)),var=:x,from_status=true), + )) for (T,name,id,root) in ((Float32,:reader_a,:reader_a,:root_a), + (Float64,:reader_b,:reader_b,:root_b)))) + simulation = run!(model;steps=0,outputs=:all) + first = model_status(model,:leaf_a) + old_reference = PSE.refvalue(first,:x) + # B's RT also keeps A's real Ref32 for reparenting. It is not a new RAW right. + rt_b = binding(simulation,:reader_b,:values).plan.reference_types + @test Base.RefValue{Float32} in fieldtypes(rt_b) + bad = Status(x=7f0) + identity_before = copy(model.status_source_identities) + revision = model.revision + @test_throws ArgumentError register_object!(model, + Object(:bad;scale=:Leaf,parent=:root_b,status=bad)) + @test !haskey(model.registry.objects,ObjectId(:bad)) + @test model.status_source_identities == identity_before + @test model.revision == revision + good = Status(x=7.0) + good_reference = PSE.refvalue(good,:x) + register_object!(model,Object(:good;scale=:Leaf,parent=:root_b,status=good)) + step!(simulation) + @test model_status(model,:leaf_a) === first + @test PSE.refvalue(first,:x) === old_reference + @test PSE.refvalue(model_status(model,:good),:x) === good_reference + @test model_status(model,:reader_a).total == 8.0 + @test model_status(model,:reader_b).total == 10.0 + @test outputs(simulation)[(:reader_a,ObjectId(:reader_a),:total)] == [(1.0,8.0)] + @test outputs(simulation)[(:reader_b,ObjectId(:reader_b),:total)] == [(1.0,10.0)] + reparent_object!(model,:leaf_a,:root_b) + step!(simulation) + @test model_status(model,:leaf_a) === first + @test PSE.refvalue(first,:x) === old_reference + @test model_status(model,:reader_a).total == 3.0 + @test model_status(model,:reader_b).total == 15.0 + @test_throws ArgumentError register_object!(model, + Object(:still_bad;scale=:Leaf,parent=:root_b,status=Status(x=9f0))) + @test !haskey(model.registry.objects,ObjectId(:still_bad)) +end + +@testset "from-status routes preserve real array references in One and Many" begin + anchor_storage, known_storage, born_storage = Float32[3], [5.0], [7.0] + anchor_reference = Ref(anchor_storage,1) + known_reference = Ref(known_storage,1) + born_reference = Ref(born_storage,1) + model = CompositeModel(Object(:scene;scale=:Scene), + Object(:outside;parent=:scene),Object(:inside;parent=:scene), + Object(:anchor;scale=:Anchor,parent=:scene,status=Status((x=anchor_reference,))), + Object(:known;scale=:Leaf,parent=:outside,status=Status((x=known_reference,))), + Object(:reader;scale=:Reader,parent=:inside); + applications=(ModelSpec(Reader();name=:reader,on=One(id=:reader),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(scale=:Leaf,within=Scope(ObjectId(:inside)),var=:x,from_status=true), + )),)) + simulation = run!(model;steps=0,outputs=:all) + single = binding(simulation,:reader,:single) + many = binding(simulation,:reader,:values) + @test typeof(anchor_reference) in fieldtypes(single.plan.reference_types) + @test typeof(known_reference) in fieldtypes(many.plan.reference_types) + @test single.carrier === anchor_reference + @test PSE.refvalue(model_status(model,:reader),:single) === anchor_reference + @test PSE.input_value(single) === 3f0 + carrier, source_ids = many.carrier, many.source_ids + @test carrier isa PSE.ObjectRefVector && isempty(carrier) + @test eltype(typeof(born_reference)) === Float64 + register_object!(model,Object(:born;scale=:Leaf,parent=:inside, + status=Status((x=born_reference,)))) + @test PSE.refvalue(model_status(model,:born),:x) === born_reference + step!(simulation) + many = binding(simulation,:reader,:values) + @test many.carrier === carrier && many.source_ids === source_ids + @test only(parent(carrier)) === born_reference + @test model_status(model,:reader).total === 10.0 + anchor_storage[1] = 4f0 + born_storage[1] = 9.0 + step!(simulation) + @test PSE.refvalue(model_status(model,:anchor),:x) === anchor_reference + @test PSE.refvalue(model_status(model,:reader),:single) === anchor_reference + @test PSE.refvalue(model_status(model,:born),:x) === born_reference + @test only(parent(binding(simulation,:reader,:values).carrier)) === born_reference + @test PSE.input_value(binding(simulation,:reader,:single)) === 4f0 + @test model_status(model,:reader).total === 13.0 + @test outputs(simulation)[(:reader,ObjectId(:reader),:total)] == [(1.0,10.0),(2.0,13.0)] +end + +@testset "abstract from-status value bounds preserve their finite real Ref classes" begin + for T in (Real,Any) + model = CompositeModel(Object(:scene;scale=:Scene), + Object(:outside;parent=:scene),Object(:inside;parent=:scene), + Object(:anchor;scale=:Anchor,parent=:scene,status=Status(x=3f0)), + Object(:reader;scale=:Reader,parent=:inside), + Object(:known32;scale=:Leaf,parent=:outside,status=Status(x=1f0)), + Object(:known64;scale=:Leaf,parent=:outside,status=Status(x=2.0)), + Object(:known_real;scale=:Leaf,parent=:outside,status=Status((x=Ref{Real}(3f0),))), + Object(:known_any;scale=:Leaf,parent=:outside,status=Status((x=Ref{Any}(4f0),))); + applications=(ModelSpec(Reader{T}();name=:reader,on=One(id=:reader),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(scale=:Leaf,within=Scope(ObjectId(:inside)),var=:x,from_status=true), + )),)) + simulation = run!(model;steps=0,outputs=:all) + current = binding(simulation,:reader,:values) + carrier, ids = current.carrier, current.source_ids + @test isempty(carrier) + statuses = [Status(x=5f0),Status(x=7.0),Status((x=Ref{Real}(9f0),))] + T === Any && push!(statuses,Status((x=Ref{Any}(11f0),))) + cells = [PSE.refvalue(status,:x) for status in statuses] + for (index,status) in enumerate(statuses) + id = Symbol(:born_,index) + register_object!(model,Object(id;scale=:Leaf,parent=:inside,status)) + @test PSE.refvalue(model_status(model,id),:x) === cells[index] + end + # Any remains a finite prepared family, not permission to invent Ref{BigFloat}. + @test_throws ArgumentError register_object!(model, + Object(:unknown;scale=:Leaf,parent=:inside,status=Status(x=BigFloat(1)))) + @test !haskey(model.registry.objects,ObjectId(:unknown)) + step!(simulation) + current = binding(simulation,:reader,:values) + @test current.carrier === carrier && current.source_ids === ids + @test all(actual === expected for (actual,expected) in zip(parent(carrier),cells)) + @test cells[1][] === 5f0 && cells[2][] === 7.0 && cells[3][] === 9f0 + T === Any && @test cells[4][] === 11f0 + @test model_status(model,:reader).total == (T === Any ? 35.0 : 24.0) + end +end + +@testset "all applicable from-status route reference bounds precede RAW fallback" begin + model = CompositeModel(Object(:scene;scale=:Scene), + Object(:anchor;scale=:Anchor,parent=:scene,status=Status(x=3f0)), + Object(:reader_a;scale=:Reader,parent=:scene),Object(:reader_b;scale=:Reader,parent=:scene), + Object(:leaf_a;scale=:Leaf,parent=:scene,status=Status(x=5f0)); + applications=( + ModelSpec(Reader{Float32}();name=:reader_a,on=One(id=:reader_a),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(scale=:Leaf,within=SceneScope(),var=:x,from_status=true))), + ModelSpec(Reader{Float64}();name=:reader_b,on=One(id=:reader_b),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(id=:future,within=SceneScope(),var=:x,from_status=true))))) + simulation = prepare(model) + @test fieldtypes(binding(simulation,:reader_b,:values).plan.reference_types) == (Base.RefValue{Float64},) + reference = Status(x=9f0) + @test_throws ArgumentError register_object!(model, + Object(:future;scale=:Leaf,parent=:scene,status=reference)) + @test !haskey(model.registry.objects,ObjectId(:future)) + @test PSE.refvalue(reference,:x)[] === 9f0 + @test isempty(binding(simulation,:reader_b,:values).source_ids) +end + @testset "explicit storage is admitted even after a clean zero-step preparation" begin control = ordinary_control() data = fixture() From 4b608fe30b80ee1e0f49c5732929cbd0f009301a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 23:22:30 +0100 Subject: [PATCH 140/324] Inline the admitted status handoff at registration --- src/composite_model/registry_topology.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 94b9e71af..f4cc1f375 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1483,13 +1483,13 @@ end source_status::Union{Nothing,Status}, status_values_materialized) _validate_status_source_identity_available!(model, source_status, id) if status_values_materialized || _no_status_conversion(model.status_conversion) - return _register_converted_status!(model, object, id, parent_id, source_status, source_status) + return Base.@inline _register_converted_status!(model, object, id, parent_id, source_status, source_status) end conversion_records = Dict{Any,Any}() converted = _convert_registered_status(model, id, source_status; conversion_records) converted isa Union{Nothing,Status} || throw(ArgumentError( "Converted object status must be a Status or nothing.")) - registered = _register_converted_status!(model, object, id, parent_id, source_status, converted) + registered = Base.@inline _register_converted_status!(model, object, id, parent_id, source_status, converted) merge!(model.status_conversion_records, conversion_records) return registered end From 84e948eb6a2a49a97e772dc46ab8445c5bdb7774 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 23:27:17 +0100 Subject: [PATCH 141/324] Keep initial status admission in the registration entry --- src/composite_model/registry_topology.jl | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index f4cc1f375..97a878c6c 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1474,13 +1474,6 @@ end source_status = object.status source_status isa Union{Nothing,Status} || throw(ArgumentError( "Initial object status must be a Status or nothing.")) - return _register_object_status!(model, object, id, parent_id, source_status, status_values_materialized) -end - -# The same conversion and ownership operations serve both catalog forms. An -# unconverted source need not be a canonical family when conversion is active. -@inline function _register_object_status!(model, object, id, parent_id, - source_status::Union{Nothing,Status}, status_values_materialized) _validate_status_source_identity_available!(model, source_status, id) if status_values_materialized || _no_status_conversion(model.status_conversion) return Base.@inline _register_converted_status!(model, object, id, parent_id, source_status, source_status) From 0832e2d42b9faebd9844832f1b79419e6050da0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 15 Nov 2026 23:43:58 +0100 Subject: [PATCH 142/324] Publish admitted objects in the same registration worker --- src/composite_model/registry_topology.jl | 4 --- test/test-model-input-binding-storage.jl | 31 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 97a878c6c..caf3a559e 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1497,10 +1497,6 @@ end else converted end - return _register_converted_object!(model, object, id, parent_id, source_status, status) -end - -function _register_converted_object!(model, object, id, parent_id, source_status, status) registry = model.registry _validate_status_identity_available!(registry, status, id) object.status = status diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 5e7da10d3..6d7c3d42b 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -310,6 +310,37 @@ end end end +@testset "a canonical source right is independent of a consumer's Default seed" begin + source = ModelSpec(Reader{Float64}();name=:source,on=Many(scale=:Leaf),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(scale=:Absent,within=SceneScope(),var=:x,from_status=true), + )) + reader = ModelSpec(Reader{Float32}();name=:reader,on=One(id=:reader),inputs=( + single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), + values=Many(scale=:Leaf,within=SceneScope(),var=:total,from_status=true,after=:source), + )) + model = CompositeModel(Object(:scene;scale=:Scene), + Object(:anchor;parent=:scene,scale=:Anchor,status=Status(x=3f0)), + Object(:existing;parent=:scene,scale=:Leaf,kind=:old,status=Status(total=0.0)), + Object(:reader;parent=:scene,scale=:Reader);applications=(source,reader)) + simulation = run!(model;steps=0,outputs=:all) + route = binding(simulation,:reader,:values) + @test Base.RefValue{Float32} in fieldtypes(route.plan.reference_types) + @test Base.RefValue{Float64} in fieldtypes(route.plan.reference_types) + data = Status(total=7.0) + cell = PSE.refvalue(data,:total) + # kind=:new has no matching RAW family; the prepared source application + # declares total::Float64. The reader's Float32[] is its initial DATA role. + register_object!(model,Object(:new;parent=:scene,scale=:Leaf,kind=:new,status=data)) + @test PSE.refvalue(model_status(model,:new),:total) === cell + step!(simulation) + route = binding(simulation,:reader,:values) + @test any(reference -> reference === cell,parent(route.carrier)) + @test PSE.refvalue(model_status(model,:new),:total) === cell + @test model_status(model,:reader).total === 9.0 + @test outputs(simulation)[(:reader,ObjectId(:reader),:total)] == [(1.0,9.0)] +end + @testset "all applicable from-status route reference bounds precede RAW fallback" begin model = CompositeModel(Object(:scene;scale=:Scene), Object(:anchor;scale=:Anchor,parent=:scene,status=Status(x=3f0)), From 8619cb54bc70097a6ae074ae84b57e0067271f20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 00:33:23 +0100 Subject: [PATCH 143/324] Stabilize prepared status evidence, transforms and diagnostics --- docs/src/guides/data/numerical_reliability.md | 17 ++- src/composite_model/compilation.jl | 30 +++- .../prepared_status_manifest.jl | 141 ++++++++++++------ src/composite_model/registry_topology.jl | 19 ++- src/composite_model/selectors.jl | 15 +- src/composite_model/status_conversion.jl | 34 ++++- test/test-fixed-status-manifest.jl | 49 ++++++ ...est-model-diagnostic-authoring-recovery.jl | 73 +++++++++ test/test-model-input-binding-storage.jl | 38 +++++ test/test-model-status-type-particles.jl | 86 ++++++++++- test/test-resolved-input-materialization.jl | 118 +++++++++++++-- test/test-status-construction.jl | 46 ++++++ 12 files changed, 586 insertions(+), 80 deletions(-) diff --git a/docs/src/guides/data/numerical_reliability.md b/docs/src/guides/data/numerical_reliability.md index 4cd3bc4e1..0ec088da3 100644 --- a/docs/src/guides/data/numerical_reliability.md +++ b/docs/src/guides/data/numerical_reliability.md @@ -102,9 +102,20 @@ new object is registered. Existing objects retain their admitted references when they move between application scopes. Declaration-based type preparation does not execute `status_transform` on -future defaults. The callback runs when the real value is materialized, and -its result must fit the prepared type family. A callback whose return type -varies outside that family needs a new, explicit model configuration. +future defaults. It queries the callback's return type for each variable and +declared value type, then applies the configured numeric rules to that type. +The callback still runs once when the real value is materialized, and its +actual result must fit the prepared family. + +Choose value-type parameters explicitly in the callback. For example, +`Particles{Float64,2}([value - spread, value + spread])` fixes the particle count +without sampling or converting a dummy value during preparation. Constructing +`Particles(vector)` can leave the count unknown to inference even when the +vector happens to contain two values. If Julia cannot determine a fixed set of +concrete result types, preparation reports a diagnostic instead of using `Any`. Type inference +can differ between Julia versions, so prefer a concrete constructor for a +configured scientific type. Changes outside the prepared family need a new +model configuration. `Diagnostics.explain_initialization(model)` shows the type declared by the model, the type of the supplied value, the type after `status_transform`, and diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index ead2e0473..5c406b90d 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -837,6 +837,25 @@ function _authored_specs_match(source_specs, specs) return all(pair -> pair[1] === pair[2], zip(source_specs, specs)) end +# Select an existing captured cause in the same order as scene resolution. +# This runs only while building a failed preparation, never in a kernel or the +# runtime validator, and does not re-evaluate a declaration or route. +function _first_authored_program_failure(program::AuthoredScenarioProgram) + for records in program.output_records + records isa ScenarioPreparationFailure && return records + for record in records + record isa ScenarioPreparationFailure && return record + end + end + for record in program.input_records + record isa ScenarioPreparationFailure && return record + end + for failure in values(program.graph.failures) + failure isa ScenarioPreparationFailure && return failure + end + return nothing +end + function _prepare_authored_scenario(model::CompositeModel, raw_specs; raw_families=_prepared_raw_status_families(model)) source_specs = Tuple(raw_specs) @@ -930,6 +949,13 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs; status_manifest = _capture_authored_metadata(:status_manifest, nothing) do _prepare_status_manifest(model, authored_records, program, raw_families) end + if isnothing(failure) && status_manifest isa ScenarioPreparationFailure + # A missing field family may be downstream of a rejected logical route + # or contract. Preserve that original cause rather than replacing it + # with the secondary manifest diagnostic. Every saved record remains + # available to the partial diagnostic compiler. + failure = _first_authored_program_failure(program) + end return ScenarioPreparation(model, source_specs, authored_records, failure, program, status_manifest, nothing) end @@ -8200,7 +8226,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, source_var, producer_ids, applications_by_id, distributed_output_plans) references = Any[] add(R) = R in references || push!(references, R) - declared_input = _configured_status_value_type(model.status_conversion, + declared_input = _configured_status_value_type(model.status_conversion, input, getproperty(_application_ports(consumer).input_types, input), nothing) fallback = if selector isa Many !isnothing(declared_input) && declared_input <: AbstractVector ? eltype(declared_input) : Union{} @@ -8250,7 +8276,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, T = if isnothing(producer) fallback else - _configured_status_value_type(model.status_conversion, + _configured_status_value_type(model.status_conversion, source_var, getproperty(output_types, source_var), get(element_types, source_var, nothing)) end candidates = isnothing(T) ? () : Base.uniontypes(T) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index b742f4abc..b2c071dbb 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -8,6 +8,24 @@ struct PreparedStatusManifest{S,A,P,D,R} raw_families::R end +# RAW membership, labels and reference classes are constructor evidence DATA. +# Their cardinality must not change the model/context type when S is unchanged. +struct PreparedRawStatusFamily{I<:ObjectId} + labels::NTuple{3,Union{Nothing,Symbol}} + selected::Vector{Tuple{Int,Int}} + destinations::Vector{Tuple{Int,I,Int}} + sources::Vector{Tuple{Int,I,Int}} + names::Vector{Symbol} + reference_types::Vector{DataType} +end + +function _same_prepared_raw_family(left::PreparedRawStatusFamily, + right::PreparedRawStatusFamily) + return left.labels === right.labels && left.selected == right.selected && + left.destinations == right.destinations && left.sources == right.sources && + left.names == right.names && left.reference_types == right.reference_types +end + # One typed view of the SAME authored specification and ports. Environment # hint result types and call plans are irrelevant to status permissions. struct PreparedStatusApplication{S,M,P} @@ -50,8 +68,8 @@ end # Choose the declared numerical storage family without evaluating callbacks. # This does not predict an arbitrary transform: its actual result is materialized # once by the existing worker, then admitted before any canonical publication. -function _prepared_status_declared_reference(policy, T, elements) - configured = _configured_status_value_type(policy, T, elements) +function _prepared_status_declared_reference(policy, name::Symbol, T, elements) + configured = _configured_status_value_type(policy, name, T, elements) isnothing(configured) && return Union{} members = Base.uniontypes(configured) all(isconcretetype, members) || return Union{} @@ -62,21 +80,21 @@ function _prepared_status_variant_permission(model, application, ports, plans) names = Symbol[]; refs = Any[] output_names = Symbol[]; output_refs = Any[] for name in keys(ports.output_types) - R = _prepared_status_declared_reference(model.status_conversion, + R = _prepared_status_declared_reference(model.status_conversion, name, getproperty(ports.output_types, name), get(ports.output_element_types, name, nothing)) _prepared_status_add_type!(output_names, output_refs, name, R) name in _model_canonical_output_names(application) || continue _prepared_status_add_type!(names, refs, name, R) end for name in ports.input_names - R = _prepared_status_declared_reference(model.status_conversion, + R = _prepared_status_declared_reference(model.status_conversion, name, getproperty(ports.input_types, name), get(ports.input_element_types, name, nothing)) _prepared_status_add_type!(names, refs, name, R) end source_names = Symbol[]; source_refs = Any[] for plan in plans _input_route_from_status(plan.route) || continue - configured = _configured_status_value_type(model.status_conversion, + configured = _configured_status_value_type(model.status_conversion, plan.input, getproperty(ports.input_types, plan.input), get(ports.input_element_types, plan.input, nothing)) T = plan.selector isa Many ? @@ -132,10 +150,11 @@ function _prepared_status_application_permissions(model, recipes, program) end function _prepared_status_raw_signature(model, object, recipes, permissions, destinations) - selected = Tuple((application.slot, _prepared_status_variant_slot(application, object.id)) + I = keytype(model.registry.objects) + selected = Tuple{Int,Int}[(application.slot, _prepared_status_variant_slot(application, object.id)) for application in recipes - if _prepared_status_application_matches(model, object, object.parent, application)) - routes = Any[] + if _prepared_status_application_matches(model, object, object.parent, application)] + routes = Tuple{Int,I,Int}[] for plan in destinations application = only(a for a in recipes if a.slot == plan.application_slot) for (execution_id, producer) in model.registry.objects @@ -146,7 +165,7 @@ function _prepared_status_raw_signature(model, object, recipes, permissions, des _prepared_status_variant_slot(application, execution_id))) end end - sources = Any[] + sources = Tuple{Int,I,Int}[] for (application, permission) in zip(recipes, permissions), source in permission.sources for (consumer_id, consumer) in model.registry.objects _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue @@ -158,7 +177,7 @@ function _prepared_status_raw_signature(model, object, recipes, permissions, des end labels = _prepared_status_object_labels(model, object, object.parent) return (labels=(labels.scale, labels.kind, labels.species), - selected=selected, destinations=Tuple(routes), sources=Tuple(sources)) + selected=selected, destinations=routes, sources=sources) end function _prepare_status_manifest(model, authored, program, raw_basis) @@ -176,24 +195,26 @@ function _prepare_status_manifest(model, authored, program, raw_basis) end end raw = if isnothing(raw_basis) - observed = Any[] + I = keytype(model.registry.objects) + observed = PreparedRawStatusFamily{I}[] for object in values(model.registry.objects) source = object.status source isa Status || continue - raw_names = propertynames(source) - raw_refs = Tuple(typeof(refvalue(source, name)) for name in raw_names) + raw_names = Symbol[name for name in propertynames(source)] + raw_refs = DataType[typeof(refvalue(source, name)) for name in raw_names] signature = _prepared_status_raw_signature(model, object, recipes, permissions, destinations) - entry = (signature=signature, - schema=_prepared_status_type_map(raw_names, raw_refs)) - entry in observed || push!(observed, entry) + entry = PreparedRawStatusFamily{I}(signature.labels, signature.selected, + signature.destinations, signature.sources, raw_names, raw_refs) + any(previous -> _same_prepared_raw_family(previous, entry), observed) || + push!(observed, entry) end - Tuple(observed) + observed else # A force refresh must not promote materialized defaults or aliases to # new RAW permissions. Preserve the genuine constructor-owned evidence. raw_basis end - for family in raw, (name, R) in pairs(family.schema) + for family in raw, (name, R) in zip(family.names, family.reference_types) _prepared_status_add_type!(names, refs, name, R) end for permission in permissions @@ -216,7 +237,7 @@ function _prepare_status_manifest(model, authored, program, raw_basis) application = only(a for a in recipes if a.slot == plan.application_slot) _foreach_application_variant(application) do _, ports for name in plan.variable_names - R = _prepared_status_declared_reference(model.status_conversion, + R = _prepared_status_declared_reference(model.status_conversion, name, getproperty(ports.output_types, name), get(ports.output_element_types, name, nothing)) _prepared_status_add_type!(names, refs, name, R) end @@ -229,23 +250,20 @@ function _prepare_status_manifest(model, authored, program, raw_basis) index = findfirst(isequal(name), names) refs[index] === Union{} && throw(ArgumentError( "Canonical field `$(name)` has no exact prospective or actual reference family. " * - "Prepare a concrete numeric configuration; arbitrary transforms and abstract Required declarations cannot supply a type witness.")) + "Prepare a concrete numeric configuration and a finite `status_transform` return family (including value-type parameters such as a particle count). Abstract Required declarations need actual or route type evidence.")) end end - for (application, permission) in zip(recipes, permissions) - for (variant_slot, variant) in pairs(permission.variants) - for name in _application_ports(application).input_names - hasproperty(variant.canonical, name) && continue - hasproperty(permission.aliases, name) && continue - actual = any(raw) do family - any(entry -> entry == (application.slot, variant_slot), - family.signature.selected) && hasproperty(family.schema, name) - end - actual && continue - throw(ArgumentError( - "Input field `$(name)` has no exact prospective, route or actual reference family " * - "for this application variant. Declare a concrete Required type, producer or configured initial-data family.")) - end + # This check needs a storage TYPE, not a new right to introduce data. A + # Required reader can share a canonical field linked by another applicable + # application on the same object. Its own permission stays unchanged: it + # cannot use the global slot union to supply an unauthorized RAW reference. + for application in recipes + for name in _application_ports(application).input_names + index = findfirst(isequal(name), names) + refs[index] !== Union{} && continue + throw(ArgumentError( + "Input field `$(name)` has no exact prospective, route or actual reference family " * + "in the prepared Status namespace. Declare a concrete Required type, producer or configured initial-data family.")) end end # Bottom is useful while accumulating absent type evidence, but Julia @@ -388,6 +406,20 @@ function _prepared_status_source_routes_admission(sources::Tuple, application, p declared |= has_type allowed &= matches end + pending_id = _prepared_status_pending_consumer_id(model, object, parent_id, application) + if !isnothing(pending_id) + has_consumer = true + if _prepared_status_route_matches(model, object, parent_id, + application, source.plan, pending_id) + _prepared_status_reference_allowed(source.references, name, reference) || + return (false, false, false) + has_type, matches = _with_metadata_entry(_prepared_status_source_input_admission, + permission.variants, _prepared_status_variant_slot(application, pending_id), + source.plan.input, reference) + declared |= has_type + allowed &= matches + end + end matcher = source.plan.matcher if !has_consumer && matcher.scope isa SceneScope && isnothing(matcher.relation) id = _index_object_id(model.registry.objects, object.id) @@ -447,7 +479,7 @@ end end function _prepared_status_raw_variant(raw, slot) - for entry in raw.signature.selected + for entry in raw.selected first(entry) == slot && return last(entry) end return 0 @@ -466,7 +498,9 @@ function _prepared_status_raw_membership_matches(applications::Tuple, raw, model end function _prepared_status_raw_has_context(contexts, plan, origin_id, variant) for entry in contexts - entry[1] == plan.slot && entry[2] == origin_id && entry[3] == variant && return true + # ObjectId uses identity equality; this also avoids dispatch through + # an abstract identity payload in the nominal evidence vector. + entry[1] == plan.slot && entry[2] === origin_id && entry[3] == variant && return true end return false end @@ -481,7 +515,7 @@ function _prepared_status_raw_destination_count(applications::Tuple, plan, raw, _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue variant = _prepared_status_variant_slot(application, execution_id) - _prepared_status_raw_has_context(raw.signature.destinations, plan, execution_id, variant) || return -1 + _prepared_status_raw_has_context(raw.destinations, plan, execution_id, variant) || return -1 count += 1 end return count @@ -503,10 +537,17 @@ function _prepared_status_raw_source_count(sources::Tuple, application, raw, mod _prepared_status_route_matches(model, object, parent_id, application, source.plan, consumer_id) || continue variant = _prepared_status_variant_slot(application, consumer_id) - _prepared_status_raw_has_context(raw.signature.sources, source.plan, + _prepared_status_raw_has_context(raw.sources, source.plan, consumer_id, variant) || return -1 count += 1 end + pending_id = _prepared_status_pending_consumer_id(model, object, parent_id, application) + if !isnothing(pending_id) && _prepared_status_route_matches(model, object, parent_id, + application, source.plan, pending_id) + variant = _prepared_status_variant_slot(application, pending_id) + _prepared_status_raw_has_context(raw.sources, source.plan, pending_id, variant) || return -1 + count += 1 + end rest = _prepared_status_raw_source_count(Base.tail(sources), application, raw, model, object, parent_id) return rest < 0 ? -1 : count + rest @@ -523,16 +564,20 @@ function _prepared_status_raw_source_total(applications::Tuple, permissions::Tup end function _prepared_status_raw_matches(raw, manifest, model, object, parent_id) labels = _prepared_status_object_labels(model, object, parent_id) - raw.signature.labels == (labels.scale, labels.kind, labels.species) || return false + raw.labels === (labels.scale, labels.kind, labels.species) || return false _prepared_status_raw_membership_matches(manifest.authored, raw, model, object, parent_id) || return false _prepared_status_raw_destination_total(manifest.destinations, manifest, - raw, model, object, parent_id) == length(raw.signature.destinations) || return false + raw, model, object, parent_id) == length(raw.destinations) || return false return _prepared_status_raw_source_total(manifest.authored, manifest.permissions, - raw, model, object, parent_id) == length(raw.signature.sources) + raw, model, object, parent_id) == length(raw.sources) end _prepared_status_raw_reference_allowed(::Nothing, name, reference) = false -_prepared_status_raw_reference_allowed(raw, name, reference) = - _prepared_status_reference_allowed(raw.schema, name, reference) +function _prepared_status_raw_reference_allowed(raw::PreparedRawStatusFamily, + name::Symbol, reference) + index = findfirst(isequal(name), raw.names) + isnothing(index) && return false + return typeof(reference) === raw.reference_types[index] +end # Each slot visit is emitted from the MANIFEST owner's target schema. Fixed storage has # nullable exact Ref slots; no variable-length propertynames/ref tuple is built. @@ -560,13 +605,13 @@ _prepared_status_raw_reference_allowed(raw, name, reference) = end end -_prepared_status_raw_source_allowed(::Tuple{}, manifest, model, object, source, parent_id) = false -function _prepared_status_raw_source_allowed(raws::Tuple, manifest, model, object, source, parent_id) - raw = first(raws) - if _prepared_status_raw_matches(raw, manifest, model, object, parent_id) +function _prepared_status_raw_source_allowed(raws::AbstractVector{<:PreparedRawStatusFamily}, + manifest, model, object, source, parent_id) + for raw in raws + _prepared_status_raw_matches(raw, manifest, model, object, parent_id) || continue Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source, raw) && return true end - return _prepared_status_raw_source_allowed(Base.tail(raws), manifest, model, object, source, parent_id) + return false end # Initial bootstrap supplies the SAME manifest explicitly before the catalog diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index caf3a559e..48752cb54 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -677,9 +677,11 @@ end function _install_prepared_canonical_registry(model::CompositeModel, preparation) manifest = preparation.status_manifest - # Authoring failures stay inspectable, but the execution validator rethrows - # them; this raw assembly is not an executable legacy fallback. - (!isnothing(preparation.failure) || manifest isa ScenarioPreparationFailure) && return model + # A valid captured manifest can represent the raw data and the valid + # authored recipes even when another declaration failed. Install that same + # schema for topology admission and partial diagnostics, without retrying a + # hook. The preparation validator still blocks all execution on its error. + manifest isa ScenarioPreparationFailure && return model return _install_prepared_canonical_registry(model, manifest, manifest.status_type) end @@ -1174,15 +1176,14 @@ end function _set_status_source_identity!( model::CompositeModel, object_id::ObjectId, - status, + identity::Union{Nothing,Base.RefValue{Nothing}}, ) previous = get(model.status_source_identities, object_id, nothing) if !isnothing(previous) && get(model.status_source_owners, previous, nothing) == object_id delete!(model.status_source_owners, previous) end - if status isa Status - identity = _status_identity(status) + if !isnothing(identity) model.status_source_owners[identity] = object_id model.status_source_identities[object_id] = identity else @@ -1219,7 +1220,8 @@ function _replace_model_object_status!( admitted = isnothing(source) ? nothing : _new_prepared_status(S, source) _store_object_family_row!(store, object, object_id, admitted) setfield!(object, :status, admitted) - _set_status_source_identity!(model, object_id, source) + identity = isnothing(source) ? nothing : _status_identity(source) + _set_status_source_identity!(model, object_id, identity) return admitted end end @@ -1506,7 +1508,8 @@ end store = registry.objects _store_object_family_row!(store, object, id, status) _index_object!(registry, object) - _set_status_source_identity!(model, id, source_status) + identity = isnothing(source_status) ? nothing : _status_identity(source_status) + _set_status_source_identity!(model, id, identity) ancestors = isnothing(parent_id) ? ObjectId[id] : _append_object_ancestor_id( diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 4ce4036b4..06bcfb5d9 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1670,6 +1670,11 @@ end isnothing(topology.parent) && return nothing return _scope_ancestor(topology.model, topology.parent, scale, true) end +function _default_dependency_scope(topology::_PreparedStatusObjectTopology, context::ObjectId) + context == topology.id || return _default_dependency_scope(topology.model, context) + (topology.object.scale == :Scene || topology.kind == :scene) && return SceneScope() + return Self() +end _missing_point_scope_anchor(topology::_PreparedStatusObjectTopology, scope, id) = _missing_point_scope_anchor(topology.model, scope, id) @inline _point_scope_root_exists(topology::_PreparedStatusObjectTopology, id) = @@ -1710,5 +1715,13 @@ function _prepared_status_route_matches(model, object, parent_id, application, topology = _prepared_status_topology(model, object, id, parent_id) _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope) || return false return _selector_matches_object_id(topology, destination_plan.matcher, - id, execution_id, true, _default_dependency_scope(model, execution_id), false) + id, execution_id, true, _default_dependency_scope(topology, execution_id), false) +end + +# This is the actual object awaiting registration, never a manufactured origin. +function _prepared_status_pending_consumer_id(model, object, parent_id, application) + id = _index_object_id(model.registry.objects, object.id) + get(model.registry.objects, id, nothing) === object && return nothing + _prepared_status_application_matches(model, object, parent_id, application) || return nothing + return id end diff --git a/src/composite_model/status_conversion.jl b/src/composite_model/status_conversion.jl index fe9f30559..fa4dd973c 100644 --- a/src/composite_model/status_conversion.jl +++ b/src/composite_model/status_conversion.jl @@ -126,13 +126,43 @@ _matching_status_type_rule(rules, value) = # The value materializer and the type-only preparation use the same join. _status_array_element_type(types) = foldl(typejoin, types) +# The variable is a type parameter only in this cold preparation query. The +# scientific callback is not evaluated; the real materializer below still owns +# its one invocation and validates the actual resulting reference class. +struct _StatusTransformForVariable{VARIABLE,F} + transform::F +end +(operation::_StatusTransformForVariable{VARIABLE})(value) where {VARIABLE} = + operation.transform(VARIABLE, value) + +function _configured_status_value_type(policy::StatusConversionPolicy, + variable::Symbol, T, elements) + isnothing(policy.transform) && return _configured_status_type_rules(policy, T, elements) + T === Union{} && return nothing + operation = _StatusTransformForVariable{variable,typeof(policy.transform)}(policy.transform) + transformed = Base.promote_op(operation, T) + # An always-throwing callback cannot produce an incompatible value. Preserve + # its declared storage and let the real worker report its original failure. + transformed === Union{} && return _configured_status_type_rules(policy, T, elements) + finite = all(isconcretetype, Base.uniontypes(transformed)) + # Keep an unchanged abstract Required bound (Real/Any), which filters real RT + # classes later. An unknown result for a concrete declaration proves no class. + (finite || transformed === T) || return nothing + # When the outer type is unchanged, retained element types choose the same + # declared numeric configuration as before. They do not promise callback + # semantics: the real result must still pass exact reference admission. + # A different outer type has no captured element configuration. + configured_elements = transformed === T ? elements : nothing + return _configured_status_type_rules(policy, transformed, configured_elements) +end + # No conversion function or initializer is called here. A concrete target fixes # the converted scalar type. An abstract target cannot be predicted in general. -function _configured_status_value_type(policy::StatusConversionPolicy, T, elements) +function _configured_status_type_rules(policy::StatusConversionPolicy, T, elements) T === Union{} && return nothing if T isa Union results = map(Base.uniontypes(T)) do member - _configured_status_value_type(policy, member, nothing) + _configured_status_type_rules(policy, member, nothing) end any(isnothing, results) && return nothing return Union{results...} diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index d654b462c..85512b05c 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -67,4 +67,53 @@ end @test PSE.refvalue(model_status(model, :scene), :x) === x @test source.calls[] == 2 # ordinary fresh staging read, no manifest replay end +@testset "RAW evidence cardinality does not alter an otherwise equal prepared owner" begin + make = function (leaves) + source = Source(1.0,2.0,Ref(0)) + objects = Object[Object(:scene;scale=:Scene)] + leaves && push!(objects,Object(:leaf;scale=:Leaf,parent=:scene, + status=Status(x=3.0,y=4.0))) + return CompositeModel(objects...;applications=( + ModelSpec(source;name=:source,on=Many(scale=:Leaf)),)) + end + populated, empty = make(true), make(false) + left = PSE._prepared_status_manifest(populated) + right = PSE._prepared_status_manifest(empty) + @test left.status_type === right.status_type + owner_type_equal = typeof(left) === typeof(right) + @test owner_type_equal + model_type_equal = typeof(populated) === typeof(empty) + @test model_type_equal + @test length(left.raw_families) == 1 # Even redundant evidence is retained. + @test isempty(right.raw_families) + @test only(left.raw_families).names == [:x,:y] + @test only(left.raw_families).reference_types == [Base.RefValue{Float64},Base.RefValue{Float64}] +end + +@testset "nominal RAW data retains unique classes, exact aliases and force provenance" begin + storage = Float32[3] + external = Ref(storage,1) + initial = Status((x=Ref{Real}(5f0),y=Ref(4.0),external=external)) + source = Source(1.0,2.0,Ref(0)) + model = CompositeModel(Object(:leaf;scale=:Leaf,status=initial); + applications=(ModelSpec(source;name=:source,on=Many(scale=:Leaf)),)) + raw = PSE._prepared_status_manifest(model).raw_families + @test length(raw) == 1 + @test only(raw).names == [:x,:y,:external] + @test PSE.refvalue(model_status(model,:leaf),:external) === external + late_storage = Float32[7] + late = Status((x=Ref{Real}(9f0),y=Ref(8.0),external=Ref(late_storage,1))) + late_cells = PSE.refvalues(late) + register_object!(model,Object(:late;scale=:Leaf,status=late)) + official = model_status(model,:late) + @test all(PSE.refvalue(official,name) === reference for + (name,reference) in zip((:x,:y,:external),late_cells)) + Advanced.refresh_bindings!(model;force=true) + @test PSE._prepared_status_manifest(model).raw_families === raw + @test model_status(model,:late) === official + @test PSE.refvalue(official,:external) === late_cells[3] + late_storage[1] = 11f0 + @test official.external === 11f0 +end + end diff --git a/test/test-model-diagnostic-authoring-recovery.jl b/test/test-model-diagnostic-authoring-recovery.jl index 5a86aaa62..7a4738805 100644 --- a/test/test-model-diagnostic-authoring-recovery.jl +++ b/test/test-model-diagnostic-authoring-recovery.jl @@ -51,6 +51,9 @@ PSE.process(::BadProcess) = 42 @test preparation.failure === preparation.authored[2] @test preparation.failure.phase === :output_ports @test preparation.failure.application_id === :broken + @test preparation.status_manifest isa PSE.PreparedStatusManifest + @test model.registry.objects.catalog isa PSE.ClosedObjectFamilyCatalog + @test PSE._prepared_status_manifest(model) === preparation.status_manifest for _ in 1:2 report = PSE.compile_model_report(model) @@ -61,6 +64,9 @@ PSE.process(::BadProcess) = 42 @test broken_calls[] == 1 # module-global state cannot be hidden by deepcopy @test report.model !== model @test report.model.scenario_plan_cache.failure.error === preparation.failure.error + @test report.model.registry.objects.catalog isa PSE.ClosedObjectFamilyCatalog + @test PSE._prepared_status_manifest(report.model) === + report.model.scenario_plan_cache.status_manifest end @test isnothing(model_status(model, :root)) @test model.scenario_plan_cache === preparation @@ -69,6 +75,9 @@ PSE.process(::BadProcess) = 42 # Runtime and topology/cadence refreshes keep the original error frozen. register_object!(model, Object(:other; scale=:Scene)) + @test model_status(model, :other) === nothing + @test PSE._prepared_status_manifest(model) === preparation.status_manifest + @test broken_calls[] == 1 model.environment = (duration=Hour(2),) mark_environment_binding_dirty!(model) @test_throws OpaqueDeclarationError run!(model; steps=0) @@ -88,18 +97,29 @@ end ModelSpec(Coupled(); name=:after, on=One(id=:root), inputs=(driver=One(within=Self(), application=:before, var=:before),)), )) + preparation = model.scenario_plan_cache + original = model_status(model, :root) + original_driver = PSE.refvalue(original, :driver) + @test model.registry.objects.catalog isa PSE.ClosedObjectFamilyCatalog report = PSE.compile_model_report(model) @test [application.id for application in report.applications] == [:before, :after] @test [application.slot for application in report.applications] == [1, 3] + @test typeof(model_status(report.model, :root)) === preparation.status_manifest.status_type @test length(report.input_bindings) == 1 binding = only(report.input_bindings) @test binding.application_id === :after @test binding.input === :driver @test binding.source_ids == [ObjectId(:root)] @test binding.source_application_ids == [:before] + @test binding.plan.application_slot == 3 + @test binding.plan.slot == only(preparation.program.input_records).slot @test PSE.refvalue(model_status(report.model, :root), :driver) === PSE.refvalue(model_status(report.model, :root), :before) @test model_status(model, :root).driver == 0.0 + @test model_status(model, :root) === original + @test PSE.refvalue(original, :driver) === original_driver + @test PSE.refvalue(model_status(report.model, :root), :driver) !== original_driver + @test !any(row -> row.phase === :input_status, report.diagnostics) @test !any(row -> occursin("BoundsError", row.message), report.diagnostics) @test broken_calls[] == 1 end @@ -200,4 +220,57 @@ end end end +const masked_contract_reads = Ref(0) +struct MaskedContractReader <: AbstractDiagnostic_Authoring_Recovery_CoupledModel end +PSE.inputs_(::MaskedContractReader) = (driver=Required(Real),) +PSE.outputs_(::MaskedContractReader) = (after=0.0,) +PSE.run!(::MaskedContractReader, status, environment, constants, context) = nothing +PSE.variable_contracts_(::Good{:contract_signal}) = + (contract_signal=VariableContract(unit=:source_unit),) +function PSE.variable_contracts_(::MaskedContractReader) + masked_contract_reads[] += 1 + return (driver=VariableContract(unit=:sink_unit),) +end + +@testset "a captured route contract error precedes its missing manifest family" begin + masked_contract_reads[] = 0 + model = CompositeModel(Object(:source), Object(:reader); applications=( + ModelSpec(Good{:contract_signal}(); name=:source, on=One(id=:source)), + ModelSpec(MaskedContractReader(); name=:reader, on=One(id=:reader), + inputs=(driver=One(SceneScope(); id=:source, + application=:source, var=:contract_signal),)), + ), environment=(duration=Hour(1),)) + preparation = model.scenario_plan_cache + route_failure = only(preparation.program.input_records) + @test route_failure isa PSE.ScenarioPreparationFailure + @test route_failure.phase === :input_plans + @test occursin("Incompatible variable contracts", sprint(showerror, route_failure.error)) + @test preparation.status_manifest isa PSE.ScenarioPreparationFailure + @test preparation.status_manifest.error !== route_failure.error + @test preparation.failure === route_failure + reads = masked_contract_reads[] + @test reads > 0 + for operation in ( + () -> run!(model; steps=0, outputs=:none), + () -> Advanced.refresh_bindings!(model), + ) + caught = try + operation() + catch error + error + end + @test caught === route_failure.error + @test model.scenario_plan_cache === preparation + @test masked_contract_reads[] == reads + @test model_status(model, :source) === nothing + @test model_status(model, :reader) === nothing + end + # The aggregate first failure does not erase the valid authored records. + report = PSE.compile_model_report(model) + @test [application.id for application in report.applications] == [:source, :reader] + @test any(row -> row.phase === :input_plans && + occursin("Incompatible variable contracts", row.message), report.diagnostics) + @test masked_contract_reads[] == reads +end + end diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 6d7c3d42b..967c95745 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -270,6 +270,44 @@ end @test outputs(simulation)[(:reader,ObjectId(:reader),:total)] == [(1.0,10.0),(2.0,13.0)] end +@testset "a real pending Self consumer admits its declared source field" begin + model = CompositeModel(Object(:scene;scale=:Scene);applications=( + ModelSpec(Reader{Float32}();name=:reader,on=Many(scale=:Leaf),inputs=( + single=One(within=Self(),var=:x,from_status=true), + values=Many(scale=:Absent,within=SceneScope(),var=:x,from_status=true), + )),)) + first = Status(x=3f0) + first_cell = PSE.refvalue(first,:x) + register_object!(model,Object(:first;scale=:Leaf,parent=:scene,status=first)) + official_first = model_status(model,:first) + @test PSE.refvalue(official_first,:x) === first_cell + @test !hasproperty(official_first,:single) # Wiring still belongs to the barrier. + simulation = run!(model;steps=1,outputs=:all) + @test PSE.refvalue(official_first,:single) === first_cell + @test model_status(model,:first).total === 3.0 + second = Status(x=5f0) + second_cell = PSE.refvalue(second,:x) + register_object!(model,Object(:second;scale=:Leaf,parent=:scene,status=second)) + official_second = model_status(model,:second) + @test PSE.refvalue(official_second,:x) === second_cell + @test !hasproperty(official_second,:single) + step!(simulation) + @test model_status(model,:first) === official_first + @test model_status(model,:second) === official_second + @test PSE.refvalue(official_first,:single) === first_cell + @test PSE.refvalue(official_second,:single) === second_cell + @test binding(simulation,:first,:single).carrier === first_cell + @test binding(simulation,:second,:single).carrier === second_cell + @test model_status(model,:second).total === 5.0 + @test outputs(simulation)[(:reader,ObjectId(:first),:total)] == [(1.0,3.0),(2.0,3.0)] + @test outputs(simulation)[(:reader,ObjectId(:second),:total)] == [(2.0,5.0)] + # The globally prepared x class is not a right for an unrelated object role. + before = length(model.registry.objects) + @test_throws ArgumentError register_object!(model, + Object(:wrong_role;scale=:Other,parent=:scene,status=Status(x=7f0))) + @test length(model.registry.objects) == before +end + @testset "abstract from-status value bounds preserve their finite real Ref classes" begin for T in (Real,Any) model = CompositeModel(Object(:scene;scale=:Scene), diff --git a/test/test-model-status-type-particles.jl b/test/test-model-status-type-particles.jl index b9893a48c..07aed8f74 100644 --- a/test/test-model-status-type-particles.jl +++ b/test/test-model-status-type-particles.jl @@ -34,7 +34,7 @@ function status_type_particle_transform(variable, value) variable in (:uncertain, :propagated) || return value value isa Float64 || return value spread = variable === :uncertain ? 1.0 : 0.0 - return Particles([value - spread, value + spread]) + return Particles{Float64,2}([value - spread, value + spread]) end @testset "real MonteCarloMeasurements particles propagate through status and streams" begin @@ -77,3 +77,87 @@ end graph_json = model_graph_view_json(model) @test occursin("Particles", graph_json) end + +# Type-only preparation must not replay the value callback, including callbacks +# with observable counters. The original particle propagation oracle stays above. +struct StatusTypeParticleTransformCounter + calls::Dict{Symbol,Int} +end +function (counter::StatusTypeParticleTransformCounter)(variable, value) + counter.calls[variable] = get(counter.calls, variable, 0) + 1 + return status_type_particle_transform(variable, value) +end + +struct StatusTypeParticleDefaultProducer <: AbstractStatus_Type_Particle_PropagationModel end +PlantSimEngine.inputs_(::StatusTypeParticleDefaultProducer) = NamedTuple() +PlantSimEngine.outputs_(::StatusTypeParticleDefaultProducer) = (propagated=3.0,) +PlantSimEngine.run!(::StatusTypeParticleDefaultProducer, status, environment, constants, context) = nothing + +PlantSimEngine.@process "status_type_particle_reader" verbose=false +struct StatusTypeParticleReader <: AbstractStatus_Type_Particle_ReaderModel end +PlantSimEngine.inputs_(::StatusTypeParticleReader) = (single=Required(Real), several=Default(Float64[])) +PlantSimEngine.outputs_(::StatusTypeParticleReader) = (count=0,) +PlantSimEngine.run!(::StatusTypeParticleReader, status, environment, constants, context) = + (status.count = length(status.several); nothing) + +@testset "transformed defaults prepare exact One and Many reference families" begin + calls = Dict{Symbol,Int}() + transform = StatusTypeParticleTransformCounter(calls) + model = CompositeModel(Object(:source; scale=:Leaf), Object(:reader; scale=:Plant); + applications=( + ModelSpec(StatusTypeParticleDefaultProducer(); name=:source, on=One(id=:source)), + ModelSpec(StatusTypeParticleReader(); name=:reader, on=One(id=:reader), inputs=( + single=One(SceneScope(); id=:source, application=:source, var=:propagated), + several=Many(SceneScope(); scale=:Leaf, application=:source, var=:propagated))), + ), type_promotion=Dict(Float64=>Float32), status_transform=transform) + @test isempty(calls) + preparation = model.scenario_plan_cache + plans = preparation.program.input_records + @test length(plans) == 2 + particle_reference = Base.RefValue{Particles{Float64,2}} + allowed_references = (Base.RefValue{Float32}, particle_reference) + # The counter callback may infer both concrete return branches. Preparation + # must retain Particle2, stay within that finite family and never call it. + for plan in plans + references = fieldtypes(plan.reference_types) + @test particle_reference in references + @test all(R -> R in allowed_references, references) + end + @test isempty(calls) + run!(model; steps=0, outputs=:none) + source = model_status(model, :source) + reader = model_status(model, :reader) + @test source.propagated isa Particles{Float64,2} + @test source.propagated.particles == [3.0, 3.0] + reference = PlantSimEngine.refvalue(source, :propagated) + @test all(plan -> typeof(reference) in fieldtypes(plan.reference_types), plans) + @test PlantSimEngine.refvalue(reader, :single) === PlantSimEngine.refvalue(source, :propagated) + @test only(parent(reader.several)) === PlantSimEngine.refvalue(source, :propagated) + @test get(calls, :propagated, 0) == 1 +end + +# The value-only Vector constructor leaves N unknown to inference; never execute +# it on a dummy biological value to discover a prospective storage family. +struct StatusTypeUnpreparedParticleTransform + calls::Base.RefValue{Int} +end +function (transform::StatusTypeUnpreparedParticleTransform)(variable, value) + transform.calls[] += 1 + variable === :propagated && value isa Float64 && return Particles([value, value]) + return value +end + +@testset "non-finite transform results have a preparation diagnostic without replay" begin + calls = Ref(0) + model = CompositeModel(Object(:source; scale=:Leaf); + applications=(ModelSpec(StatusTypeParticleDefaultProducer(); name=:source, on=One(id=:source)),), + status_transform=StatusTypeUnpreparedParticleTransform(calls)) + @test calls[] == 0 + failure = model.scenario_plan_cache.status_manifest + @test failure isa PlantSimEngine.ScenarioPreparationFailure + @test failure.error isa ArgumentError + @test occursin("finite `status_transform` return family", sprint(showerror, failure.error)) + @test_throws r"finite `status_transform` return family" run!(model; steps=0, outputs=:none) + @test calls[] == 0 + @test model_object(model, :source).status === nothing +end diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index ed0a2da03..09a817316 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -140,7 +140,7 @@ PSE.run!(model::ManyReader, status, environment, constants, context) = end end -function array_scene(values, policy; existing) +function array_scene(values, policy; existing, status_transform=nothing) source = ArraySource(values, Ref(0)) objects = existing ? (Object(:leaf; scale=:Leaf), Object(:reader; scale=:Reader)) : (Object(:reader; scale=:Reader),) @@ -148,7 +148,7 @@ function array_scene(values, policy; existing) ModelSpec(source; name=:source, on=Many(scale=:Leaf)), ModelSpec(ArrayManyReader(0f0); name=:reader, on=One(id=:reader), inputs=(x=Many(SceneScope(); scale=:Leaf, application=:source, var=:x),)), - ), environment=(duration=Hour(1),), type_promotion=policy) + ), environment=(duration=Hour(1),), type_promotion=policy, status_transform) return model, source end @@ -232,6 +232,74 @@ end @test model_status(model, :reader).seen === 7f0 end + +@testset "unchanged array transform types retain their configured element family" begin + calls = Dict{Symbol,Int}() + transform = (variable, value) -> begin + calls[variable] = get(calls, variable, 0) + 1 + value + end + model, source = array_scene(Real[1.0, 2.0], Dict(Float64=>Float32); + existing=false, status_transform=transform) + @test isempty(calls) + @test source.declarations[] == 1 + preparation = model.scenario_plan_cache + source_ports = only(recipe for recipe in preparation.authored if recipe.id === :source).ports + plan = only(preparation.program.input_records) + @test plan.reference_types === Tuple{Base.RefValue{Vector{Float32}}} + simulation = run!(model; steps=0, outputs=:all) + carrier = only(simulation.compiled.input_bindings).carrier + # Output staging reads fresh defaults once, even with no source targets. + @test source.declarations[] == 2 + @test get(calls, :x, 0) == 0 + @test model.scenario_plan_cache === preparation + @test PSE._application_ports(simulation.compiled.applications_by_id[:source]) === source_ports + @test only(preparation.program.input_records) === plan + register_object!(model, Object(:leaf; scale=:Leaf)) + @test source.declarations[] == 2 + @test get(calls, :x, 0) == 0 + continue!(simulation; steps=1) + @test model_status(model, :leaf).x isa Vector{Float32} + @test model_status(model, :leaf).x == Float32[1, 2] + @test model_status(model, :reader).seen === 3f0 + @test get(calls, :x, 0) == 1 + # Growth stages fresh defaults for the added source; metadata stays owned. + @test source.declarations[] == 3 + @test model.scenario_plan_cache === preparation + @test PSE._application_ports(simulation.compiled.applications_by_id[:source]) === source_ports + @test only(preparation.program.input_records) === plan + @test plan.reference_types === Tuple{Base.RefValue{Vector{Float32}}} + @test only(simulation.compiled.input_bindings).carrier === carrier + @test only(parent(carrier)) === PSE.refvalue(model_status(model, :leaf), :x) +end + +@testset "changed array elements cannot silently widen a prepared transform family" begin + changed = Ref(false) + calls = Dict{Symbol,Int}() + transform = (variable, value) -> begin + calls[variable] = get(calls, variable, 0) + 1 + variable === :x && value isa Vector{Real} && changed[] && return Real[1, 2.0] + value + end + model, source = array_scene(Real[1.0, 2.0], Dict(Float64=>Float32); + existing=false, status_transform=transform) + @test isempty(calls) + @test only(model.scenario_plan_cache.program.input_records).reference_types === + Tuple{Base.RefValue{Vector{Float32}}} + register_object!(model, Object(:leaf; scale=:Leaf)) + previous_reader = model_status(model, :reader) + previous_leaf = model_status(model, :leaf) + records = copy(model.status_conversion_records) + changed[] = true + @test_throws ArgumentError Advanced.refresh_bindings!(model) + @test model_status(model, :reader) === previous_reader === nothing + @test model_status(model, :leaf) === previous_leaf === nothing + @test model.status_conversion_records == records + @test get(calls, :x, 0) == 1 + @test source.value == Real[1.0, 2.0] + @test all(value -> value isa Float64, source.value) +end + @testset "configured Float32 refs coexist with prospective Float64 producer defaults" begin source = Status(x=1f0) model = CompositeModel(Object(:source; scale=:Leaf, status=source), @@ -483,6 +551,7 @@ end PSE.RefVector{Float32} ambiguous = required_scene(AbstractVector) @test only(ambiguous.scenario_plan_cache.program.input_records) isa PSE.ScenarioPreparationFailure + @test ambiguous.scenario_plan_cache.failure === only(ambiguous.scenario_plan_cache.program.input_records) @test_throws "no concrete configured source type" run!(ambiguous; steps=0, outputs=:none) # A known Ref in another scope is eligible after reparenting, but cannot @@ -497,6 +566,10 @@ end application=:writer, var=:x),)), ), environment=(duration=Hour(1),)) @test only(scoped.scenario_plan_cache.program.input_records) isa PSE.ScenarioPreparationFailure + @test scoped.scenario_plan_cache.status_manifest isa PSE.PreparedStatusManifest + @test scoped.scenario_plan_cache.failure === nothing + @test PSE._first_authored_program_failure(scoped.scenario_plan_cache.program) === + only(scoped.scenario_plan_cache.program.input_records) @test_throws "no concrete configured source type" run!(scoped; steps=0, outputs=:none) end @@ -532,6 +605,7 @@ end @test only(simulation.compiled.input_bindings).carrier isa PSE.RefVector{Float32} ambiguous = status_only(AbstractVector) @test only(ambiguous.scenario_plan_cache.program.input_records) isa PSE.ScenarioPreparationFailure + @test ambiguous.scenario_plan_cache.failure === only(ambiguous.scenario_plan_cache.program.input_records) @test_throws "no concrete configured source type" run!(ambiguous; steps=0, outputs=:none) end @@ -700,10 +774,11 @@ end cells = [Ref(1.0), Ref(2.0), Ref(3.0)] visited = Int[] reference_for(id) = (push!(visited, id.value); cells[id.value]) - @test PSE._input_reference_carrier(One(), ids[1:1], reference_for, Tuple{}) === cells[1] + RT = Tuple{eltype(cells)} + @test PSE._input_reference_carrier(One(), ids[1:1], reference_for, RT) === cells[1] @test visited == [1] empty!(visited) - @test isnothing(PSE._input_reference_carrier(OptionalOne(), ObjectId{Int}[], reference_for, Tuple{})) + @test isnothing(PSE._input_reference_carrier(OptionalOne(), ObjectId{Int}[], reference_for, RT)) @test isempty(visited) homogeneous = PSE._input_reference_carrier(Many(), ids, reference_for, Tuple{Base.RefValue{Float64}}) @test homogeneous isa PSE.RefVector{Float64} @@ -726,14 +801,25 @@ end abstract = Ref{Real}(1.0) @test PSE._input_reference_carrier(Many(), ids[1:1], _ -> abstract, Tuple{Base.RefValue{Real}}) isa PSE.ObjectRefVector @test PSE._input_reference_carrier(Many(), ObjectId{Int}[], reference_for, Tuple{Base.RefValue{Float64}}) isa PSE.RefVector{Float64} - @test isnothing(PSE._input_reference_carrier(One(), ids[1:1], _ -> nothing, Tuple{})) + empty!(visited) + missing_one(id) = (push!(visited, id.value); nothing) + @test isnothing(PSE._input_reference_carrier(One(), ids[1:1], missing_one, RT)) + @test visited == [1] empty!(visited) missing_for(id) = (push!(visited, id.value); id.value == 2 ? nothing : cells[id.value]) @test isnothing(PSE._input_reference_carrier(Many(), ids, missing_for, Tuple{Base.RefValue{Float64}})) @test visited == [1, 2] external = Ref([4.0], 1) - @test_throws ArgumentError PSE._input_reference_carrier(One(), ids[1:1], _ -> external, Tuple{}) - @test_throws ArgumentError PSE._input_reference_carrier(Many(), ids[1:1], _ -> external, Tuple{Base.RefValue{Float64}}) + external_types = Tuple{typeof(external)} + @test PSE._input_reference_carrier(One(), ids[1:1], _ -> external, external_types) === external + external_many = PSE._input_reference_carrier(Many(), ids[1:1], _ -> external, external_types) + @test external_many isa PSE.ObjectRefVector + @test only(parent(external_many)) === external + @test_throws ArgumentError PSE._input_reference_carrier(Many(), ids[1:1], _ -> external, RT) + # A genuinely empty prepared family is distinct from a missing live source. + never_called(id) = error("empty reference family must reject before reading") + @test isnothing(PSE._input_reference_carrier(OptionalOne(), ObjectId{Int}[], never_called, Tuple{})) + @test_throws ArgumentError PSE._input_reference_carrier(One(), ids[1:1], never_called, Tuple{}) end struct OffsetSourceIds{T} <: AbstractVector{T} @@ -784,20 +870,21 @@ end for selector in (One(), OptionalOne()) ids = OffsetSourceIds([ObjectId(1)], 7) cell = Ref(5.0) - @test PSE._input_reference_carrier(selector, ids, _ -> cell, Tuple{}) === cell + @test PSE._input_reference_carrier(selector, ids, _ -> cell, Tuple{typeof(cell)}) === cell @test ids.reads == [7] end end -@noinline function repeat_point_carrier(model, selector, ids, expected, repetitions) +@noinline function repeat_point_carrier(model, selector, ids, expected, + reference_types::Type{RT}, repetitions) where {RT<:Tuple} same = true for _ in 1:repetitions - same &= PSE._input_carrier(model, selector, ids, Val(:x), Tuple{}) === expected + same &= PSE._input_carrier(model, selector, ids, Val(:x), reference_types) === expected end return same end -@noinline point_allocations(model, selector, ids, expected, repetitions) = - @allocated repeat_point_carrier(model, selector, ids, expected, repetitions) +@noinline point_allocations(model, selector, ids, expected, reference_types::Type{RT}, repetitions) where {RT<:Tuple} = + @allocated repeat_point_carrier(model, selector, ids, expected, reference_types, repetitions) @noinline many_allocations(ids, getter) = @allocated PSE._input_reference_carrier(Many(), ids, getter, Tuple{Base.RefValue{Float64}}) @@ -806,10 +893,11 @@ end model = CompositeModel(Object(1; status)) ids = [ObjectId(1)] expected = PSE.refvalue(status, :x) + reference_types = Tuple{typeof(expected)} for selector in (One(), OptionalOne()) - @test repeat_point_carrier(model, selector, ids, expected, 2) - point_allocations(model, selector, ids, expected, 1000) - allocated = minimum(point_allocations(model, selector, ids, expected, 1000) for _ in 1:3) + @test repeat_point_carrier(model, selector, ids, expected, reference_types, 2) + point_allocations(model, selector, ids, expected, reference_types, 1000) + allocated = minimum(point_allocations(model, selector, ids, expected, reference_types, 1000) for _ in 1:3) # A small fixed allowance accommodates instrumentation on the Kaimon # task; the former temporary vector per call exceeds this by far. @test allocated <= 4096 diff --git a/test/test-status-construction.jl b/test/test-status-construction.jl index 09d397bcc..1689a3912 100644 --- a/test/test-status-construction.jl +++ b/test/test-status-construction.jl @@ -181,4 +181,50 @@ PSE.run!(::DistributedDefaults, status, environment, constants, context) = nothi @test model_status(model, :right_leaf).flow == Float32[2] end +# A canonical input reference introduced by one applicable application is also +# visible to another model on that same object. No raw/default TEff cell exists. +struct SharedThermalBinder <: AbstractStatus_Construction_ConsumerModel end +struct SharedThermalObserver <: AbstractStatus_Construction_ConsumerModel end +PSE.inputs_(::SharedThermalBinder) = (TEff=Required(Real),) +PSE.outputs_(::SharedThermalBinder) = NamedTuple() +PSE.run!(::SharedThermalBinder, status, environment, constants, context) = nothing +PSE.inputs_(::SharedThermalObserver) = (TEff=Required(Real),) +PSE.outputs_(::SharedThermalObserver) = (observed_thermal=0.0,) +PSE.run!(::SharedThermalObserver, status, environment, constants, context) = + (status.observed_thermal = status.TEff; nothing) + +@testset "a prepared canonical input serves other same-object Required readers" begin + model = CompositeModel(Object(:source; scale=:Scene); applications=( + ModelSpec(Producer(); name=:producer, on=One(id=:source)), + ModelSpec(SharedThermalBinder(); name=:thermal, on=Many(scale=:Leaf, kind=:wired), + inputs=(TEff=One(SceneScope(); id=:source, application=:producer, var=:value),)), + ModelSpec(SharedThermalObserver(); name=:observer, on=Many(scale=:Leaf)), + ), environment=(duration=Hour(1),)) + @test model.scenario_plan_cache.status_manifest isa PSE.PreparedStatusManifest + simulation = run!(model; steps=0, outputs=:all) + @test isempty(model_objects(model; scale=:Leaf)) + source_reference = PSE.refvalue(model_status(model, :source), :value) + register_object!(model, Object(:new_leaf; scale=:Leaf, kind=:wired)) + continue!(simulation; steps=1) + official = model_status(model, :new_leaf) + @test official.TEff === official.observed_thermal === 7.0 + @test PSE.refvalue(official, :TEff) === source_reference + @test last.(outputs(simulation)[(:observer, ObjectId(:new_leaf), :observed_thermal)]) == [7.0] + + # The observer gains type evidence, not permission to populate that field + # on an object outside the actual binding application's selector. + unauthorized = Status(TEff=9.0) + candidate = Object(:outside; scale=:Leaf, kind=:unwired, status=unauthorized) + records = copy(model.status_conversion_records) + before_count = length(model.registry.objects) + @test_throws ArgumentError register_object!(model, candidate) + @test length(model.registry.objects) == before_count + @test !haskey(model.registry.objects, ObjectId(:outside)) + @test candidate.status === unauthorized + @test model.status_conversion_records == records + @test model_status(model, :new_leaf) === official + @test PSE.refvalue(official, :TEff) === source_reference + @test source_reference[] === 7.0 +end + end From b5ef11dc10dce9d56ec0a6944546c725ae58c30d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 01:18:03 +0100 Subject: [PATCH 144/324] Keep status admission in one boundary and verify official views --- .../prepared_status_manifest.jl | 20 +++---- test/test-initial-status-preparation.jl | 60 ++++++++++++------- test/test-model-canonical-cohorts.jl | 38 +++++++++--- test/test-model-newborn-context-nested.jl | 8 ++- test/test-model-newborn-execution-owner.jl | 9 ++- 5 files changed, 90 insertions(+), 45 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index b2c071dbb..b5f87f891 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -605,27 +605,21 @@ end end end -function _prepared_status_raw_source_allowed(raws::AbstractVector{<:PreparedRawStatusFamily}, - manifest, model, object, source, parent_id) - for raw in raws - _prepared_status_raw_matches(raw, manifest, model, object, parent_id) || continue - Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source, raw) && return true - end - return false -end - # Initial bootstrap supplies the SAME manifest explicitly before the catalog # exists. Runtime delegates through its typed catalog; there is one gather/body. -function _validate_prepared_initial_status(manifest::PreparedStatusManifest, +@inline function _validate_prepared_initial_status(manifest::PreparedStatusManifest, model, object, source_status, parent_id) isnothing(source_status) && return nothing source_status isa Status || throw(ArgumentError("Prepared initial data must be Status or nothing.")) allowed = Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source_status, nothing) - (allowed || _prepared_status_raw_source_allowed(manifest.raw_families, manifest, - model, object, source_status, parent_id)) && return nothing + allowed && return nothing + for raw in manifest.raw_families + _prepared_status_raw_matches(raw, manifest, model, object, parent_id) || continue + Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source_status, raw) && return nothing + end throw(ArgumentError("Status reference classes are incompatible with this prepared object configuration/raw family.")) end -function _validate_prepared_initial_status(model, object, source_status, parent_id) +@inline function _validate_prepared_initial_status(model, object, source_status, parent_id) return _validate_prepared_initial_status(_prepared_status_manifest(model), model, object, source_status, parent_id) end diff --git a/test/test-initial-status-preparation.jl b/test/test-initial-status-preparation.jl index 4977ce285..8dad016ca 100644 --- a/test/test-initial-status-preparation.jl +++ b/test/test-initial-status-preparation.jl @@ -44,7 +44,7 @@ initial_preparation_status(model, id) = only( object.status for object in model_objects(model) if object.id == ObjectId(id) ) -@testset "complete initial statuses retain identity and arbitrary Ref aliases" begin +@testset "official initial statuses retain arbitrary Ref aliases" begin storage = [7.5, 2.25] supplied_reference = Ref(storage, 1) result_reference = Ref(storage, 2) @@ -70,16 +70,24 @@ initial_preparation_status(model, id) = only( ), ) compiled = Advanced.refresh_bindings!(model) - @test initial_preparation_status(model, :leaf) === original + official = model_status(model,:leaf) + @test initial_preparation_status(model,:leaf) === official + @test official !== original + @test_throws ArgumentError object_id(model,original) + @test object_id(model,official) === ObjectId(:leaf) + @test propertynames(official) == (:result,:supplied,:offset,:alias) @test propertynames(original) == (:supplied, :alias, :result, :offset) + @test all(PlantSimEngine.refvalue(official,name) === PlantSimEngine.refvalue(original,name) + for name in propertynames(original)) @test original.offset == 3.0 @test PlantSimEngine.refvalue(original, :supplied) === supplied_reference @test PlantSimEngine.refvalue(original, :alias) === supplied_reference @test PlantSimEngine.refvalue(original, :result) === result_reference for application_id in (:first, :second) view = compiled.status_views_by_target[(application_id, ObjectId(:leaf))] - @test view.status === original - @test view.canonical_status === original + @test view.canonical_status === official + @test all(PlantSimEngine.refvalue(view.status,name) === + PlantSimEngine.refvalue(official,name) for name in propertynames(official)) @test isempty(view.temporal_inputs) @test isempty(view.private_outputs) end @@ -90,7 +98,7 @@ initial_preparation_status(model, id) = only( original.result = 4.5 @test storage[2] == 4.5 simulation = run!(model; steps=1, outputs=:none) - @test initial_preparation_status(model, :leaf) === original + @test initial_preparation_status(model,:leaf) === official @test final_state(simulation).supplied == 9.25 @test storage == [9.25, 4.5] end @@ -105,25 +113,27 @@ end applications=(ModelSpec(probe; name=:empty, on=Many(scale=:Leaf)),), ) compiled = Advanced.refresh_bindings!(model) - @test initial_preparation_status(model, :supplied) === supplied + official = model_status(model,:supplied) + @test initial_preparation_status(model,:supplied) === official + @test official !== supplied + @test_throws ArgumentError object_id(model,supplied) for object in model_objects(model) @test object.status isa Status @test isempty(propertynames(object.status)) @test object_id(model, object.status) == object.id view = compiled.status_views_by_target[(:empty, object.id)] - @test view.status === object.status @test view.canonical_status === object.status + @test isempty(view.status) end @test initial_preparation_status(model, :missing_a) !== initial_preparation_status(model, :missing_b) invalid_status = (sentinel=7.0,) - invalid = CompositeModel( + @test_throws ArgumentError("Initial object status must be a Status or nothing.") CompositeModel( Object(:invalid; scale=:Leaf, status=invalid_status); applications=(ModelSpec(probe; name=:empty, on=One(scale=:Leaf)),), ) - @test_throws "Model object `invalid` uses model applications but its status has type" Advanced.refresh_bindings!(invalid) - @test initial_preparation_status(invalid, :invalid) === invalid_status + @test invalid_status === (sentinel=7.0,) end @testset "initial preparation preserves existing references and first defaults" begin @@ -160,7 +170,7 @@ end @test existing.offset == missing.offset == 2.0 @test existing.extra == missing.extra == 4.0 @test propertynames(existing) == - (:signal, :untouched, :output_buffer, :extra, :offset, :input_buffer) + (:signal, :output_buffer, :extra, :offset, :input_buffer, :untouched) @test propertynames(missing) == (:signal, :output_buffer, :extra, :offset, :input_buffer) @@ -256,8 +266,9 @@ end @test row.status_transform_applied @test row.status_transform_changed view = compiled.status_views_by_target[(:reader, ObjectId(:leaf))] - @test view.status === reader @test view.canonical_status === reader + @test PlantSimEngine.refvalue(view.status,:bound) === + PlantSimEngine.refvalue(reader,:bound) end @testset "initial defaults preserve numeric conversion diagnostics" begin @@ -331,7 +342,7 @@ end end @testset "distributed destination validation precedes initial default preparation" begin - function destination_model(leaf_status) + function destination_model(leaf_status; required_type) return CompositeModel( Object(:scene; scale=:Scene), Object(:leaf; scale=:Leaf, parent=:scene, status=leaf_status); @@ -340,7 +351,7 @@ end InitialStatusPreparationProbe(NamedTuple(), ( local_default=1.0, distributed_buffer=Distributed(Default([1.0])), - required_value=Distributed(Required(Real)), + required_value=Distributed(Required(required_type)), )); name=:distributor, on=One(scale=:Scene), outputs_to=( @@ -353,16 +364,22 @@ end end original = Status(sentinel=7.0) sentinel_reference = PlantSimEngine.refvalue(original, :sentinel) - missing = destination_model(original) + # This case tests missing VALUES before defaults, with a concrete declared + # storage type. Underdetermined Required(Real) is a separate type diagnostic. + missing = destination_model(original; required_type=Float64) + missing_official = model_status(missing,:leaf) + @test missing_official !== original @test_throws "Missing required distributed-output destination" Advanced.refresh_bindings!(missing) @test isnothing(initial_preparation_status(missing, :scene)) - @test initial_preparation_status(missing, :leaf) === original + @test initial_preparation_status(missing,:leaf) === missing_official + @test propertynames(missing_official) == (:sentinel,) + @test PlantSimEngine.refvalue(missing_official,:sentinel) === sentinel_reference @test propertynames(original) == (:sentinel,) @test PlantSimEngine.refvalue(original, :sentinel) === sentinel_reference supplied = Status(required_value=4.0) required_reference = PlantSimEngine.refvalue(supplied, :required_value) - valid = destination_model(supplied) + valid = destination_model(supplied; required_type=Real) Advanced.refresh_bindings!(valid) leaf_status = initial_preparation_status(valid, :leaf) @test PlantSimEngine.refvalue(leaf_status, :required_value) === required_reference @@ -373,13 +390,16 @@ end @testset "runtime output assembly preserves ordered stream and status references" begin object_id = ObjectId(:target) - status = Status(first=7.0, second=Float32[2, 3]) - model = CompositeModel(Object(object_id; status); applications=( + supplied = Status(first=7.0, second=Float32[2, 3]) + model = CompositeModel(Object(object_id; status=supplied); applications=( ModelSpec(InitialStatusPreparationProbe(NamedTuple(), (first=0.0, second=Float32[])); name=:probe, on=One(id=object_id)), )) application = only(Advanced.refresh_bindings!(model).applications) - @test model_status(model, object_id) === status + status = model_status(model,object_id) + @test status !== supplied + @test all(PlantSimEngine.refvalue(status,name) === PlantSimEngine.refvalue(supplied,name) + for name in (:first,:second)) retention = PlantSimEngine.OutputRetentionPlan( false, Set([(:probe, :second)]), diff --git a/test/test-model-canonical-cohorts.jl b/test/test-model-canonical-cohorts.jl index 091567351..c951173e0 100644 --- a/test/test-model-canonical-cohorts.jl +++ b/test/test-model-canonical-cohorts.jl @@ -120,8 +120,17 @@ end @test override_target.model isa ScaledAccumulator{Float64} @test PSE.cohort_location(store, :plant__accumulate, ObjectId(:leaf_default)).cohort !== PSE.cohort_location(store, :plant__accumulate, ObjectId(:leaf_override)).cohort - @test default_target.status_view.canonical_status === default_status - @test override_target.status_view.canonical_status === override_status + default_official = model_status(model,:leaf_default) + override_official = model_status(model,:leaf_override) + @test default_official !== default_status && override_official !== override_status + @test_throws ArgumentError object_id(model,default_status) + @test_throws ArgumentError object_id(model,override_status) + @test default_target.status_view.canonical_status === default_official + @test override_target.status_view.canonical_status === override_official + for (official,supplied) in ((default_official,default_status),(override_official,override_status)) + @test all(PSE.refvalue(official,name) === PSE.refvalue(supplied,name) + for name in (:value,:alias,:visits)) + end continue!(simulation; steps=2) @test assert_canonical_storage(simulation) === store @@ -141,7 +150,7 @@ end @test restarted_store !== store @test restarted_target !== default_target @test restarted_target.context !== default_target.context - @test restarted_target.status_view.canonical_status === default_status + @test restarted_target.status_view.canonical_status === default_official @test current_step(restarted) == 0 step!(restarted) @test default_status.value === 16.0f0 @@ -168,9 +177,13 @@ end @test trace == ObjectId.([1, 2, 3]) @test [model_status(model, id).draw for id in 1:3] == expected @test all(model_status(model, id).visits == 1 for id in 1:3) - @test length(simulation.execution_plan.batches) == 3 - @test first(simulation.execution_plan.batches).targets.cohort === - last(simulation.execution_plan.batches).targets.cohort + # The marker is a canonical extra, not a hot port. Its two payload classes + # share one fixed canonical schema and one unchanged RandomProbe view type. + @test length(simulation.execution_plan.batches) == 1 + @test [target.object_id for target in only(simulation.execution_plan.batches).targets] == ObjectId.([1,2,3]) + @test typeof(model_status(model,1).marker) === Int + @test typeof(model_status(model,2).marker) === Float64 + @test typeof(model_status(model,3).marker) === Int @test rand(copy(rng), UInt64) == rand(copy(reference_rng), UInt64) original_targets = Dict(id => execution_target(simulation, :draw, id) for id in 1:3) original_locations = Dict(id => PSE.cohort_location(store, :draw, ObjectId(id)) for id in 1:3) @@ -292,7 +305,10 @@ end current = collect(call_targets(captured[], :work)) @test object_id.(current) == ObjectId.([:a, :b]) @test model_status(model, :plant_a).total == 3 - @test retained.status === retained_status === model_status(model, :b) + @test retained.status === retained_status + @test retained.canonical_status === model_status(model,:b) + @test all(PSE.refvalue(retained_status,name) === + PSE.refvalue(retained.canonical_status,name) for name in (:value,:alias,:visits)) @test retained.execution_target === retained_execution_target @test retained_status.value == retained_status.visits == 2 @test retained.time == 1.0 @@ -310,7 +326,10 @@ end @test assert_canonical_storage(simulation) === store @test isempty(call_targets(captured[], :work)) @test model_status(model, :plant_a).total == 0 - @test retained.status === model_status(model, :b) + @test retained.status === retained_status + @test retained.canonical_status === model_status(model,:b) + @test all(PSE.refvalue(retained_status,name) === + PSE.refvalue(retained.canonical_status,name) for name in (:value,:alias,:visits)) @test retained_status.value == retained_status.visits == 3 @test retained.time == 1.0 end @@ -366,7 +385,8 @@ end simulation = run!(model; steps=0, outputs=:none) group = only(simulation.execution_plan.groups) original_batches = group.batches - @test length(original_batches) == 3 # Preserve A/B/A execution order. + # value is a hot port: exact Ref32/Ref64 view types still require A/B/A runs. + @test length(original_batches) == 3 assembled = PSE._model_execution_batches(simulation.environment_bindings, group.application, group.membership, simulation.output_retention, group) @test assembled.batches === original_batches diff --git a/test/test-model-newborn-context-nested.jl b/test/test-model-newborn-context-nested.jl index 6af1d5b56..476752441 100644 --- a/test/test-model-newborn-context-nested.jl +++ b/test/test-model-newborn-context-nested.jl @@ -69,7 +69,13 @@ end @test PSE._compiled_call_name(only(data.first.execution_target.call_bindings)) === :child # Independent explicit selections may refresh nested execution owners. # Both views must still expose the same live registry-owned scientific state. - @test data.first.status === data.second.status === model_status(model, :middle) + official = model_status(model,:middle) + @test data.first.canonical_status === data.second.canonical_status === official + for target in (data.first,data.second) + @test target.status === target.execution_target.status_view.status + @test all(PSE.refvalue(target.status,name) === PSE.refvalue(official,name) + for name in (:value,:calls,:seen_time)) + end @test only(middle_contexts) === data.first.context_cache.default @test only(middle_contexts) !== only(leaf_contexts) @test only(middle_contexts) !== data.creator_context diff --git a/test/test-model-newborn-execution-owner.jl b/test/test-model-newborn-execution-owner.jl index 777525d78..53e9ecc2f 100644 --- a/test/test-model-newborn-execution-owner.jl +++ b/test/test-model-newborn-execution-owner.jl @@ -70,8 +70,13 @@ end @test data.first.execution_target isa PSE.CompiledExecutionTarget @test data.second.execution_target isa PSE.CompiledExecutionTarget @test data.first.execution_target !== data.second.execution_target - @test data.first.status === data.second.status === model_status(model, :born) - @test data.first.execution_target.status_view.status === data.first.status + official = model_status(model,:born) + @test data.first.canonical_status === data.second.canonical_status === official + for target in (data.first,data.second) + @test target.status === target.execution_target.status_view.status + @test all(PSE.refvalue(target.status,name) === PSE.refvalue(official,name) + for name in (:driver,:value,:calls)) + end @test data.first.context_cache === data.second.context_cache @test data.first.execution_target.context isa PSE.RunContext @test data.first.context_cache.default === data.first.execution_target.context From d914d9ecaab46e3d1a43ae3feb26c9034cde4306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 02:27:03 +0100 Subject: [PATCH 145/324] Keep status admission independent of environment port configuration --- benchmark/test-status-registry-benchmark.jl | 2 + .../prepared_status_manifest.jl | 25 +++--- src/composite_model/registry_topology.jl | 2 +- test/test-fixed-status-manifest.jl | 88 ++++++++++++++++++- test/test-lifecycle-snapshot-allocations.jl | 19 +++- test/test-model-runtime-stream-extensions.jl | 3 +- 6 files changed, 122 insertions(+), 17 deletions(-) diff --git a/benchmark/test-status-registry-benchmark.jl b/benchmark/test-status-registry-benchmark.jl index b6b9c6a4b..82b5dcf06 100644 --- a/benchmark/test-status-registry-benchmark.jl +++ b/benchmark/test-status-registry-benchmark.jl @@ -11,6 +11,8 @@ function setup_status_registry_benchmark(nobjects::Int) ) for index in 1:nobjects ] model = PlantSimEngine.CompositeModel(objects...) + # Registry lookups use the official headers, which retain the raw cells. + statuses = [PlantSimEngine.model_status(model, index) for index in 1:nobjects] lookup_index = cld(nobjects, 2) return ( model=model, diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index b5f87f891..1bdaf5a12 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -26,16 +26,21 @@ function _same_prepared_raw_family(left::PreparedRawStatusFamily, left.names == right.names && left.reference_types == right.reference_types end -# One typed view of the SAME authored specification and ports. Environment -# hint result types and call plans are irrelevant to status permissions. -struct PreparedStatusApplication{S,M,P} +# Runtime status admission needs only applicability and the effective variant +# slot. Full specifications/ports stay in ScenarioPreparation; environment names +# must not change an otherwise identical canonical registry schema. +struct PreparedStatusApplication{M,O} slot::Int id::Symbol - spec::S target_matcher::M - ports::P + object_slots::O +end +@inline _prepared_status_object_slots(application::PreparedStatusApplication) = + application.object_slots +function _prepared_status_object_slots(application) + owner = _application_model_overrides(application) + return isnothing(owner) ? nothing : owner.object_slots end -_application_ports(application::PreparedStatusApplication) = application.ports function _prepared_raw_status_families(model) catalog = model.registry.objects.catalog @@ -44,8 +49,8 @@ function _prepared_raw_status_families(model) end _prepared_status_variant_slot(application, object_id) = begin - owner = _application_model_overrides(application) - isnothing(owner) ? 1 : get(owner.object_slots, object_id, 1) + slots = _prepared_status_object_slots(application) + isnothing(slots) ? 1 : get(slots, object_id, 1) end function _prepared_status_type_map(names, types) @@ -272,8 +277,8 @@ function _prepare_status_manifest(model, authored, program, raw_basis) physical_refs = map(R -> R === Union{} ? Nothing : R, refs) S = _fixed_status_type(Tuple(names), Tuple{physical_refs...}) applications = map(recipes) do application - PreparedStatusApplication(application.slot, application.id, application.spec, - application.target_matcher, application.ports) + PreparedStatusApplication(application.slot, application.id, + application.target_matcher, _prepared_status_object_slots(application)) end return PreparedStatusManifest(S, applications, permissions, destinations, raw) end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 48752cb54..1ecc645db 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1494,7 +1494,7 @@ end catalog = model.registry.objects.catalog status = if catalog isa ClosedObjectFamilyCatalog manifest = catalog.status_manifest - _validate_prepared_initial_status(manifest, model, object, converted, parent_id) + Base.@inline _validate_prepared_initial_status(manifest, model, object, converted, parent_id) isnothing(converted) ? nothing : _new_prepared_status(manifest.status_type, converted) else converted diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index 85512b05c..321699ba3 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -1,5 +1,5 @@ module FixedStatusManifestChecks -using PlantSimEngine, Test +using Dates, PlantSimEngine, Test const PSE = PlantSimEngine PSE.@process "fixed_status_manifest_source" verbose=false PSE.@process "fixed_status_manifest_reader" verbose=false @@ -116,4 +116,90 @@ end @test official.external === 11f0 end +# Environment variable names are configuration data, not status permissions. +struct EnvironmentNamedSource{T} <: AbstractFixed_Status_Manifest_SourceModel + variable::Symbol + initial::T +end +PSE.inputs_(::EnvironmentNamedSource) = NamedTuple() +PSE.outputs_(model::EnvironmentNamedSource) = (x=model.initial,) +PSE.environment_inputs_(model::EnvironmentNamedSource) = + NamedTuple{(model.variable,)}((model.initial,)) +PSE.run!(model::EnvironmentNamedSource, status, environment, constants, context) = + (status.x = getproperty(environment, model.variable); nothing) + +@testset "environment remapping does not alter the status permission owner schema" begin + spec(variable) = ModelSpec(EnvironmentNamedSource(variable, 0f0); + name=:source, on=One(id=:leaf)) + supplied = Status(x=9f0) + reference = PSE.refvalue(supplied, :x) + model = CompositeModel(Object(:leaf; status=supplied); applications=(spec(:T),), + environment=(duration=Hour(1), T=3f0, U=7f0)) + official = model_status(model, :leaf) + manifest = PSE._prepared_status_manifest(model) + first = Advanced.refresh_bindings!(model) + model.applications[1] = spec(:U) + second = Advanced.refresh_bindings!(model; force=true) + current = PSE._prepared_status_manifest(model) + @test first.model === second.model === model + @test current.status_type === manifest.status_type + @test typeof(current) === typeof(manifest) + @test model.registry.objects.catalog.status_manifest === current + @test model_status(model, :leaf) === official + @test PSE.refvalue(official, :x) === reference + @test official.x === 9f0 + @test fieldnames(typeof(only(current.authored))) == + (:slot, :id, :target_matcher, :object_slots) + run!(model; steps=1, outputs=:none) + @test model_status(model, :leaf) === official + @test PSE.refvalue(official, :x) === reference + @test official.x === 7f0 +end + +@testset "projected admission preserves the real configured override slots" begin + base = Source(1f0, 2.0, Ref(0)) + replacement = Source(1.0, 2f0, Ref(0)) + template = CompositeModelTemplate((ModelSpec(base; name=:source, + on=Many(scale=:Leaf)),)) + instance = ObjectInstance(:stand, template; root=Object(:plant; scale=:Plant), + objects=(Object(:future_override; scale=:Leaf, parent=:plant),), + object_overrides=(Override(object=:future_override, application=:source, + model=replacement),)) + model = CompositeModel(instance) + preparation = model.scenario_plan_cache + manifest = PSE._prepared_status_manifest(model) + authored = only(preparation.authored) + projected = only(manifest.authored) + owner = PSE._application_model_overrides(authored) + counts = (base.calls[], replacement.calls[]) + @test projected.object_slots === owner.object_slots + @test projected.slot == authored.slot + @test projected.id === authored.id + @test projected.target_matcher === authored.target_matcher + for (id, expected) in ((ObjectId(:future_override), 2), (ObjectId(:base), 1)) + @test PSE._prepared_status_variant_slot(projected, id) == expected + @test PSE._prepared_status_variant_slot(projected, id) == + PSE._prepared_status_variant_slot(authored, id) + end + @test (base.calls[], replacement.calls[]) == counts + # Mount the genuine target first, then reuse its vacant identity. Its None + # status contributes no RAW x/y cells; birth rights still come from ports. + @test model_status(model, :future_override) === nothing + remove_object!(model, :future_override) + @test !haskey(model.registry.objects, ObjectId(:future_override)) + @test projected.object_slots === owner.object_slots + @test owner.object_slots[ObjectId(:future_override)] == 2 + @test (base.calls[], replacement.calls[]) == counts + wrong = Object(:future_override; scale=:Leaf, parent=:plant, status=Status(x=3f0, y=4f0)) + @test_throws ArgumentError register_object!(model, wrong) + @test !haskey(model.registry.objects, wrong.id) + supplied = Status(x=3.0, y=4f0) + reference = PSE.refvalue(supplied, :x) + register_object!(model, Object(:future_override; scale=:Leaf, parent=:plant, status=supplied)) + @test PSE.refvalue(model_status(model, :future_override), :x) === reference + register_object!(model, Object(:base; scale=:Leaf, parent=:plant, status=Status(x=5f0, y=6.0))) + @test model_status(model, :base).x === 5f0 + @test (base.calls[], replacement.calls[]) == counts +end + end diff --git a/test/test-lifecycle-snapshot-allocations.jl b/test/test-lifecycle-snapshot-allocations.jl index 98d81cf61..736383170 100644 --- a/test/test-lifecycle-snapshot-allocations.jl +++ b/test/test-lifecycle-snapshot-allocations.jl @@ -116,7 +116,9 @@ end @testset "lifecycle snapshots freeze topology and share geometry" begin geometry = Dict(:position => [1.0, 2.0]) - model = CompositeModel(Object(:root; geometry=geometry)) + # The future branch uses the same genuinely prepared initial-data family. + root_status = Status(signal=big"0.0", payload=Int[]) + model = CompositeModel(Object(:root; geometry=geometry, status=root_status)) root_snapshot = only(model.lifecycle_delta.added) source_status = Status(signal=big"1.25", payload=[1, 2]) branch = register_object!( @@ -125,9 +127,18 @@ end branch_snapshot = last(model.lifecycle_delta.added) leaf = register_object!(model, Object((:leaf, 1); parent=7)) leaf_snapshot = last(model.lifecycle_delta.added) - @test branch.status === source_status - @test model_status(model, source_status) === source_status - @test object_id(model, source_status) == ObjectId(7) + official_status = model_status(model, branch.id) + @test branch.status === official_status + @test official_status !== source_status + @test PlantSimEngine.refvalue(official_status, :signal) === + PlantSimEngine.refvalue(source_status, :signal) + @test PlantSimEngine.refvalue(official_status, :payload) === + PlantSimEngine.refvalue(source_status, :payload) + @test official_status.signal isa BigFloat + @test official_status.signal == big"1.25" + @test official_status.payload == [1, 2] + @test object_id(model, official_status) == ObjectId(7) + @test_throws ArgumentError object_id(model, source_status) @test root_snapshot.children === () @test branch_snapshot.children === () @test branch_snapshot.ancestors == (ObjectId(:root), ObjectId(7)) diff --git a/test/test-model-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl index 69fa014ef..8b0ff4f55 100644 --- a/test/test-model-runtime-stream-extensions.jl +++ b/test/test-model-runtime-stream-extensions.jl @@ -222,7 +222,8 @@ end a_reference = PSE.refvalue(model_status(data.model, 1), :a) register_object!(data.model, Object(2; scale=:Leaf, parent=0, - status=Status(a=0f0, b=0f0, z=0.0))) + status=Status(a=0f0, b=0f0))) + @test !hasproperty(model_status(data.model, 2), :z) step!(data.simulation) grown = check_reconstructed_groups(data, (1, 2)) @test grown !== original From 8a81cd15bdfd553f864aaca70915b55b3170140c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 10:06:22 +0100 Subject: [PATCH 146/324] Capture only application slots while selecting permission plans --- src/composite_model/prepared_status_manifest.jl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 1bdaf5a12..06f410ae5 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -132,8 +132,9 @@ end function _prepared_status_application_permissions(model, recipes, program) return map(recipes) do application + application_slot = application.slot plans = Tuple(plan for plan in program.input_records - if plan isa CompiledModelInputPlan && plan.application_slot == application.slot) + if plan isa CompiledModelInputPlan && plan.application_slot == application_slot) variants = Any[] _foreach_application_variant(application) do _, ports push!(variants, _prepared_status_variant_permission(model, application, ports, plans)) From 824aaa2108a0b0401a9a0601fa83421e22d68091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 10:06:22 +0100 Subject: [PATCH 147/324] Retain configured raw numeric families in materialized scene exports --- .../prepared_status_manifest.jl | 36 +++++++++++++++++++ test/test-fixed-status-manifest.jl | 24 +++++++++++++ test/test-model-graph-editor-extension.jl | 17 +++++++++ 3 files changed, 77 insertions(+) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 06f410ae5..6dbbbb7e3 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -186,6 +186,33 @@ function _prepared_status_raw_signature(model, object, recipes, permissions, des selected=selected, destinations=routes, sources=sources) end +# Materialized source exports preserve the original supplied-data conversion +# records. Their original TYPES still describe the numerical configuration even +# when an unreconstructible callback was intentionally omitted from the export. +function _prepared_status_raw_configured_references(model, object, names, references) + configured = copy(references) + for (index, name) in enumerate(names) + key = _status_conversion_record_key(name; + object_id=object.id, origin=:supplied_status) + record = get(model.status_conversion_records, key, nothing) + record isa StatusConversionRecord || continue + isequal(record.object_id, object.id) && record.variable === name || continue + isnothing(record.application_id) || continue + record.origin === :supplied_status || continue + # Diagnostic metadata from a superseded class is not evidence for the + # actual constructor-owned RAW family being prepared here. + record.effective_type === eltype(references[index]) || continue + R = _prepared_status_declared_reference(model.status_conversion, + name, record.original_type, nothing) + isconcretetype(R) && R <: Ref || continue + # An unchanged VALUE type cannot justify changing the observed Ref + # implementation (RefArray/custom Ref is not RefValue). + eltype(R) === record.effective_type && continue + configured[index] = R + end + return configured +end + function _prepare_status_manifest(model, authored, program, raw_basis) recipes = Tuple(item for item in authored if item isa AuthoredApplicationRecipe) permissions = _prepared_status_application_permissions(model, recipes, program) @@ -213,6 +240,15 @@ function _prepare_status_manifest(model, authored, program, raw_basis) signature.destinations, signature.sources, raw_names, raw_refs) any(previous -> _same_prepared_raw_family(previous, entry), observed) || push!(observed, entry) + configured_refs = _prepared_status_raw_configured_references( + model, object, raw_names, raw_refs) + if configured_refs != raw_refs + configured = PreparedRawStatusFamily{I}(signature.labels, + signature.selected, signature.destinations, signature.sources, + raw_names, configured_refs) + any(previous -> _same_prepared_raw_family(previous, configured), observed) || + push!(observed, configured) + end end observed else diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index 321699ba3..8c087dbb3 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -114,6 +114,30 @@ end @test PSE.refvalue(official,:external) === late_cells[3] late_storage[1] = 11f0 @test official.external === 11f0 + + # A real no-change conversion receipt must not grant RefValue32 when + # the only configured RAW implementation is an external RefArray32. + transform_calls = Ref(0) + preserve_type = (variable, value) -> (transform_calls[] += 1; value) + external_only = Ref(Float32[3], 1) + no_change = CompositeModel(Object(:external; + status=Status((external=external_only,))); status_transform=preserve_type) + same_raw = PSE._prepared_status_manifest(no_change).raw_families + @test only(same_raw).reference_types == [typeof(external_only)] + @test PSE.refvalue(model_status(no_change, :external), :external) === external_only + @test transform_calls[] == 1 + next_external = Ref(Float32[7], 1) + register_object!(no_change, Object(:next_external; + status=Status((external=next_external,)))) + @test PSE.refvalue(model_status(no_change, :next_external), :external) === next_external + @test transform_calls[] == 2 + records_before = copy(no_change.status_conversion_records) + wrong_ref_class = Object(:wrong_ref_class; status=Status(external=9f0)) + @test_throws ArgumentError register_object!(no_change, wrong_ref_class) + @test !haskey(no_change.registry.objects, wrong_ref_class.id) + @test no_change.status_conversion_records == records_before + @test transform_calls[] == 3 # Actual attempts only; preparation did not replay it. + @test only(same_raw).reference_types == [typeof(external_only)] end # Environment variable names are configuration data, not status permissions. diff --git a/test/test-model-graph-editor-extension.jl b/test/test-model-graph-editor-extension.jl index 853cbe8fa..86db57645 100644 --- a/test/test-model-graph-editor-extension.jl +++ b/test/test-model-graph-editor-extension.jl @@ -904,6 +904,23 @@ end @test restored_closure_status.special isa Float16 @test isnothing(restored_closure.status_conversion.transform) + # The serialized per-object supplied-data record already carries the + # original Float64 configuration. Its restored policy prepares future32 + # alongside the preserved effective16, without widening other label scopes. + closure_record = restored_closure.status_conversion_records[ + (:supplied_status, nothing, ObjectId(:closure_leaf), :special)] + @test closure_record.original_type === Float64 + @test closure_record.effective_type === Float16 + retained_special = PlantSimEngine.refvalue(restored_closure_status, :special) + records_before_rejection = copy(restored_closure.status_conversion_records) + wrong_scope = Object(:wrong_closure_scope; scale=:Other, + status=Status(ordinary=7.0, special=8.0)) + @test_throws ArgumentError register_object!(restored_closure, wrong_scope) + @test !haskey(restored_closure.registry.objects, wrong_scope.id) + @test restored_closure.status_conversion_records == records_before_rejection + @test PlantSimEngine.refvalue(model_status(restored_closure, :closure_leaf), :special) === + retained_special + registered_closure = register_object!( restored_closure, Object( From eab67a36ca897f239e285f7c9ea3079082ec5a9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 10:06:22 +0100 Subject: [PATCH 148/324] Diagnose required values from the captured preparation --- src/authoring.jl | 2 +- src/composite_model/compilation.jl | 89 +++++++++-------- src/visualization/model_graph_view.jl | 135 ++++++++++++++++++-------- test/test-authoring-api.jl | 77 ++++++++++++++- test/test-model-api-stabilization.jl | 13 +++ 5 files changed, 231 insertions(+), 85 deletions(-) diff --git a/src/authoring.jl b/src/authoring.jl index c29df4dbf..99f5625e9 100644 --- a/src/authoring.jl +++ b/src/authoring.jl @@ -1112,7 +1112,7 @@ function validate_scenario(model::CompositeModel; strict::Bool=false) if !isnothing(compilation.compiled) initialization = _capture_validation!( - () -> explain_initialization(model), + () -> _explain_initialization(compilation), diagnostics, :initialization_inspection_failed; field=:initialization, diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 5c406b90d..ae06e7893 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5289,13 +5289,13 @@ end function _initialization_effective_value( model::CompositeModel, - compiled::CompiledCompositeModel, + status_views, application_id::Symbol, object_id::ObjectId, variable::Symbol, ) view = get( - compiled.status_views_by_target, + status_views, (application_id, object_id), nothing, ) @@ -5343,7 +5343,7 @@ end function _initialization_conversion_fields( model::CompositeModel, - compiled::CompiledCompositeModel, + status_views, application_id::Symbol, object_id::ObjectId, variable::Symbol; @@ -5359,7 +5359,7 @@ function _initialization_conversion_fields( ) has_effective, effective = _initialization_effective_value( model, - compiled, + status_views, application_id, object_id, variable, @@ -5408,54 +5408,59 @@ required status or environment value is unresolved. Selector, writer, call, and other invalid configuration errors remain errors. """ function explain_initialization(model::CompositeModel) - model = deepcopy(model) - supplied = Dict( - object.id => setdiff( - Set{Symbol}( - object.status isa Status ? Symbol.(propertynames(object.status)) : Symbol[] - ), - get(model.input_default_status_variables, object.id, Set{Symbol}()), - ) - for object in values(model.registry.objects) - ) - compiled = _compile_scene( - model, - _prepare_scenario_plan(model); - validate_required_inputs=false, - ) + # Read captured failures without refreshing/mutating the caller's caches. + preparation = getfield(model, :scenario_plan_cache) + if preparation isa ScenarioPreparation && _authored_specs_match(preparation, model) + _validate_authored_scenario(preparation) + end + report = compile_model_report(model) + _validate_authored_scenario(_scenario_preparation(report.model)) + for diagnostic in report.diagnostics + diagnostic.code in (:unresolved_required_input, :unresolved_environment_input) && continue + diagnostic.severity === :error && error(diagnostic.message) + end + return _explain_initialization(report) +end + +function _initialization_required_input_schema(application) + ports = _application_ports(application) + required = Dict{Symbol,Required}() + for name in ports.input_names + declaration = getproperty(ports.input_declaration_types, name) + declaration <: Required || continue + required[name] = Required(getproperty(ports.input_types, name)) + end + return required +end + +# One row algorithm serves full public explanations and the captured Required +# preflight. The latter reads names/types/bindings only, never declaration values. +function _explain_initialization(model, applications, input_bindings, + status_views, supplied, environment_binding_records; required_only::Bool=false) bindings = Dict( (binding.application_id, binding.consumer_id, binding.input) => binding - for binding in compiled.input_bindings + for binding in input_bindings ) - _, environment_plans_by_id = _compile_environment_application_plans( - model, - compiled.applications, - compiled.applications_by_id; - prepare_runtime=false, - ) environment_bindings = Dict( (binding.application_id, binding.object_id) => binding - for binding in _compile_environment_bindings( - model, - compiled, - environment_plans_by_id, - ) + for binding in environment_binding_records ) rows = NamedTuple[] - for application in compiled.applications - model_outputs = _local_output_schema(application.spec) - environment_model_outputs = _model_environment_output_schema(application) - model_inputs = _model_input_schema(application) - environment_inputs = _model_environment_input_schema(application) + for application in applications + model_outputs = required_only ? NamedTuple() : _local_output_schema(application.spec) + environment_model_outputs = required_only ? NamedTuple() : _model_environment_output_schema(application) + model_inputs = required_only ? _initialization_required_input_schema(application) : + _model_input_schema(application) + environment_inputs = required_only ? NamedTuple() : _model_environment_input_schema(application) generated = Set(Symbol.(keys(model_outputs))) for object_id in application.target_ids for variable in sort!(collect(generated); by=string) default_value = getproperty(model_outputs, variable) conversion = _initialization_conversion_fields( model, - compiled, + status_views, application.id, object_id, variable; @@ -5507,7 +5512,7 @@ function explain_initialization(model::CompositeModel) for variable in sort!(Symbol.(collect(keys(model_inputs))); by=string) key = (application.id, object_id, variable) binding = get(bindings, key, nothing) - declaration = getproperty(model_inputs, variable) + declaration = model_inputs[variable] binding_resolved = !isnothing(binding) && !(binding.carrier_hint == :optional_default && @@ -5538,7 +5543,7 @@ function explain_initialization(model::CompositeModel) end conversion = _initialization_conversion_fields( model, - compiled, + status_views, application.id, object_id, variable; @@ -5589,9 +5594,9 @@ function explain_initialization(model::CompositeModel) Set{Symbol}() : environment_variables(environment_binding.backend) bound = isnothing(available) || Symbol(source) in available - default_value = getproperty(environment_inputs, variable) + default_value = required_only ? nothing : getproperty(environment_inputs, variable) conversion = _no_initialization_conversion_fields( - ; declared_type=typeof(default_value), + ; declared_type=required_only ? nothing : typeof(default_value), ) push!(rows, ( application_id=application.id, @@ -5603,7 +5608,7 @@ function explain_initialization(model::CompositeModel) source_object_ids=Any[], source_variable=Symbol(source), origin=:environment, - expected_type=typeof(default_value), + expected_type=required_only ? nothing : typeof(default_value), default_value=default_value, provided_type=nothing, conversion..., diff --git a/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index f7c64f360..99f5b09c5 100644 --- a/src/visualization/model_graph_view.jl +++ b/src/visualization/model_graph_view.jl @@ -35,6 +35,7 @@ struct CompositeModelCompilationReport cycles::Vector{Vector{Symbol}} diagnostics::Vector{ModelGraphDiagnostic} compiled::Any + environment_bindings::Union{Nothing,Vector{CompiledEnvironmentBinding}} end """ @@ -298,6 +299,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) Vector{Vector{Symbol}}(), ModelGraphDiagnostic[], compiled, + nothing, ) end @@ -316,6 +318,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) Vector{Vector{Symbol}}(), diagnostics, nothing, + CompiledEnvironmentBinding[], ) preparation = _scenario_preparation(model) @@ -331,9 +334,12 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) Vector{Vector{Symbol}}(), diagnostics, nothing, + CompiledEnvironmentBinding[], ) - _model_graph_phase!(diagnostics, :environment_bindings, nothing) do + environment_binding_records = _model_graph_phase!( + diagnostics, :environment_bindings, CompiledEnvironmentBinding[], + ) do _, environment_plans_by_id = _compile_environment_application_plans( model, applications, @@ -345,11 +351,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) applications, environment_plans_by_id, ) - _validate_model_environment_inputs!( - environment_bindings, - Dict(application.id => application for application in applications), - keytype(model.registry.objects), - ) + environment_bindings end distributed_output_plans = _model_graph_phase!( @@ -402,38 +404,74 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) _model_graph_phase!(diagnostics, :call_cadence, nothing) do _validate_model_call_plan_cadences!(applications, call_plans, timeline) end - distributed_outputs = _model_graph_phase!( - diagnostics, - :writers, - NoCompiledDistributedOutputs(), - ) do - _validate_manual_model_output_destination_plans!( - distributed_output_plans, - manual_application_ids, - ) - _compile_model_distributed_outputs( - model, - applications, - _applications_by_id(applications), - manual_application_ids, - distributed_output_plans, - ) - end + manifest_ready = !(preparation.status_manifest isa ScenarioPreparationFailure) + distributed_outputs = NoCompiledDistributedOutputs() + input_bindings = CompiledModelInputBinding[] + if manifest_ready + distributed_outputs = _model_graph_phase!( + diagnostics, + :writers, + NoCompiledDistributedOutputs(), + ) do + _validate_manual_model_output_destination_plans!( + distributed_output_plans, + manual_application_ids, + ) + _compile_model_distributed_outputs( + model, + applications, + _applications_by_id(applications), + manual_application_ids, + distributed_output_plans, + ) + end - input_bindings = _model_graph_phase!(diagnostics, :inputs, CompiledModelInputBinding[]) do - _compile_model_input_bindings( - model, - applications, - manual_application_ids, - _compiled_application_input_recipes( - _plans_by_application(applications, input_plans), - ), - distributed_outputs, - ) - end - _model_graph_phase!(diagnostics, :input_status, nothing) do - _prepare_model_input_statuses_batched!( - model, applications, _applications_by_id(applications), input_bindings) + input_bindings = _model_graph_phase!(diagnostics, :inputs, CompiledModelInputBinding[]) do + _compile_model_input_bindings( + model, + applications, + manual_application_ids, + _compiled_application_input_recipes( + _plans_by_application(applications, input_plans), + ), + distributed_outputs, + ) + end + _model_graph_phase!(diagnostics, :input_status, nothing) do + _prepare_model_input_statuses_batched!( + model, applications, _applications_by_id(applications), input_bindings) + end + else + # These phases require the captured physical schema. Keep their logical + # plan evidence above, and report the original captured cause instead of + # invoking Closed-only status workers on an unprepared registry. + failure = isnothing(preparation.failure) ? + preparation.status_manifest : preparation.failure + diagnostic = _model_graph_diagnostic(failure.error, failure.phase) + any(item -> item.message == diagnostic.message, diagnostics) || + push!(diagnostics, diagnostic) + end + + if manifest_ready && isempty(diagnostics) + # Preserve earlier selector/route/authoring errors as authoritative; + # absent values downstream of those failures add no secondary cause. + # A missing VALUE leaves its real cell absent. Read the captured + # Required declarations before asking for executable port projections. + required_rows = _explain_initialization(model, applications, + input_bindings, Dict{Tuple{Symbol,ObjectId},Any}(), + initial_status_variables, environment_binding_records; required_only=true) + for row in required_rows + row.disposition in (:required, :unresolved) || continue + push!(diagnostics, _model_graph_diagnostic( + ErrorException(something(row.detail, + "`$(row.variable)` is unresolved for application `$(row.application_id)`.")), + :initialization; code=row.role === :environment_input ? + :unresolved_environment_input : :unresolved_required_input, + application_ids=[row.application_id], object_ids=Any[row.object_id], + variable=row.variable, + suggestions=isnothing(row.detail) ? String[] : [String(row.detail)], + )) + end end children = Dict{Symbol,Set{Symbol}}( @@ -471,7 +509,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) end end - compiled = try + compiled = !manifest_ready ? nothing : try _model_graph_compiled( model, preparation, @@ -500,9 +538,27 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) cycles, diagnostics, compiled, + environment_binding_records, ) end +function _explain_initialization(report::CompositeModelCompilationReport) + views = isnothing(report.compiled) ? + Dict{Tuple{Symbol,ObjectId},Any}() : report.compiled.status_views_by_target + bindings = report.environment_bindings + if isnothing(bindings) + # Strict reports have not bound an inspection environment yet. Reuse + # the same application/binding implementation once, without compiling. + _, plans = _compile_environment_application_plans(report.model, + report.applications, _applications_by_id(report.applications); + prepare_runtime=false) + bindings = _compile_environment_bindings_for_applications( + report.model, report.applications, plans) + end + return _explain_initialization(report.model, report.applications, + report.input_bindings, views, report.initial_status_variables, bindings) +end + _model_graph_object_id(value) = value isa ObjectId ? value.value : value _model_graph_application_node_id(id) = string("application:", id) function _model_graph_object_id_key(id) @@ -1702,7 +1758,7 @@ end function _model_graph_add_status_conversion!(rows, report) explanations = try - explain_initialization(report.model) + _explain_initialization(report) catch NamedTuple[] end @@ -1936,6 +1992,7 @@ function compile_model_graph( _model_graph_cycle_components(compiled.applications, children), ModelGraphDiagnostic[], compiled, + nothing, ) return _model_graph_view( report, diff --git a/test/test-authoring-api.jl b/test/test-authoring-api.jl index 2b443a031..e05de1ef7 100644 --- a/test/test-authoring-api.jl +++ b/test/test-authoring-api.jl @@ -118,6 +118,22 @@ const AUTHORING_TEMPERATURE = VariableContract( extent=:intensive, ) +struct AuthoringRequiredInspectionCounter <: AbstractAuthoringLinearModel + input_reads::Base.RefValue{Int} + output_reads::Base.RefValue{Int} +end +function PlantSimEngine.inputs_(model::AuthoringRequiredInspectionCounter) + model.input_reads[] += 1 + return (x=Required(Float64),) +end +function PlantSimEngine.outputs_(model::AuthoringRequiredInspectionCounter) + model.output_reads[] += 1 + return (y=0.0,) +end +PlantSimEngine.variable_contracts_(::AuthoringRequiredInspectionCounter) = + (x=AUTHORING_DIMENSIONLESS, y=AUTHORING_DIMENSIONLESS) +PlantSimEngine.run!(::AuthoringRequiredInspectionCounter, status, environment, constants, context) = nothing + @testset "Distributed model outputs are inspectable without a scenario" begin declarations = ( total=Float32[0, 1], @@ -694,21 +710,76 @@ end @test !isnothing(valid_report.compilation.compiled) @test JSON.parse(to_json(valid_report))["summary"]["compiled"] + # A missing VALUE still admits a complete physical schema when its type + # is configured. The underdetermined Required(Real) case is separate below. unresolved_scenario = CompositeModel( Object(:leaf; scale=:Leaf); applications=( - ModelSpec(model; name=:linear, on=One(scale=:Leaf)), + ModelSpec(AuthoringNarrowInputModel(model.gain, model.offset); + name=:linear, on=One(scale=:Leaf)), ), environment=(T=25.0, duration=3600.0), ) unresolved_report = validate_scenario(unresolved_scenario) @test !unresolved_report.valid - @test unresolved_report.summary.compiled + @test !unresolved_report.summary.compiled @test any( diagnostic -> diagnostic.code == :unresolved_required_input && diagnostic.context["variable"] == "x", unresolved_report.diagnostics, ) + missing_diagnostic = only(unresolved_report.diagnostics) + @test missing_diagnostic.code === :unresolved_required_input + @test missing_diagnostic.context["applicationIds"] == ["linear"] + @test missing_diagnostic.context["objectIds"] == ["leaf"] + @test !occursin("model_bundles", missing_diagnostic.message) + @test model_status(unresolved_scenario, :leaf) === nothing + missing_rows = explain_initialization(unresolved_scenario) + missing_x = only(row for row in missing_rows if row.role === :input) + @test missing_x.variable === :x + @test missing_x.application_id === :linear + @test missing_x.object_id === :leaf + @test missing_x.disposition === :required + @test missing_x.expected_type === Float64 + @test model_status(unresolved_scenario, :leaf) === nothing + + abstract_scenario = CompositeModel( + Object(:leaf; scale=:Leaf); + applications=(ModelSpec(model; name=:linear, on=One(scale=:Leaf)),), + environment=(T=25.0, duration=3600.0), + ) + captured = abstract_scenario.scenario_plan_cache + failure = captured.status_manifest + @test failure isa PlantSimEngine.ScenarioPreparationFailure + @test failure.phase === :status_manifest + abstract_report = PlantSimEngine.compile_model_report(abstract_scenario) + @test isnothing(abstract_report.compiled) + @test length(abstract_report.applications) == 1 + @test only(abstract_report.applications).id === :linear + @test length(abstract_report.diagnostics) == 1 + @test only(abstract_report.diagnostics).phase === :status_manifest + @test only(abstract_report.diagnostics).message == sprint(showerror, failure.error) + @test !occursin("MethodError", only(abstract_report.diagnostics).message) + @test abstract_scenario.scenario_plan_cache === captured + @test captured.status_manifest === failure + @test_throws "Input field `x` has no exact" run!(abstract_scenario; steps=0) + + counted = AuthoringRequiredInspectionCounter(Ref(0), Ref(0)) + counted_scene = CompositeModel(Object(:counted); applications=( + ModelSpec(counted; name=:counted, on=One(id=:counted)),)) + @test (counted.input_reads[], counted.output_reads[]) == (1, 1) + counted_report = PlantSimEngine.compile_model_report(counted_scene) + owned_model = PlantSimEngine._application_default_model(only(counted_report.applications)) + @test (owned_model.input_reads[], owned_model.output_reads[]) == (2, 2) + @test (counted.input_reads[], counted.output_reads[]) == (1, 1) + @test only(counted_report.diagnostics).code === :unresolved_required_input + @test !hasproperty(model_status(counted_report.model, :counted), :x) + @test model_status(counted_scene, :counted) === nothing + PlantSimEngine._explain_initialization(counted_report.model, + counted_report.applications, counted_report.input_bindings, + Dict{Tuple{Symbol,ObjectId},Any}(), counted_report.initial_status_variables, + counted_report.environment_bindings; required_only=true) + @test (owned_model.input_reads[], owned_model.output_reads[]) == (2, 2) invalid_selector = CompositeModel( Object(:leaf; scale=:Leaf, status=Status(x=1.0)); @@ -751,7 +822,7 @@ end unresolved_display = repr(MIME"text/plain"(), unresolved_report) @test occursin(r"\binvalid\b", lowercase(unresolved_display)) - @test occursin("Compilation: complete; cycles: 0", unresolved_display) + @test occursin("Compilation: incomplete; cycles: 0", unresolved_display) @test occursin("unresolved_required_input", unresolved_display) @test occursin("linear", unresolved_display) @test occursin("leaf", unresolved_display) diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index 64851b032..cb2f70b75 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -211,10 +211,16 @@ end @test !isempty(explain_execution_plan(simulation)) unresolved_scene = CompositeModel(StabilizationConsumerModel()) + unresolved_initial = model_status(unresolved_scene, :scene) unresolved = filter( row -> row.role == :input && row.disposition == :required, explain_initialization(unresolved_scene), ) + @test model_status(unresolved_scene, :scene) === unresolved_initial + @test !hasproperty(unresolved_initial, :signal) + @test !hasproperty(unresolved_initial, :supplied) + @test all(row -> row.application_id === :stabilization_consumer, unresolved) + @test all(row -> row.object_id === :scene, unresolved) @test Set(row.variable for row in unresolved) == Set((:signal, :supplied)) @test all(row -> row.origin == :missing, unresolved) @test all(row -> occursin("add `inputs=", row.detail), unresolved) @@ -229,6 +235,13 @@ end if row.role == :environment_input && row.variable == :T ) @test temperature_row.disposition == :environment_bound + missing_environment = CompositeModel(StabilizationEnvironmentModel(); + environment=(duration=3600.0,)) + missing_temperature = only(row for row in explain_initialization(missing_environment) + if row.role === :environment_input) + @test missing_temperature.variable === :T + @test missing_temperature.object_id === :scene + @test missing_temperature.disposition === :unresolved end @testset "public namespace boundary" begin From e6ea2af4b05571f046764e2582a6d9ce6731e794 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 12:56:53 +0100 Subject: [PATCH 149/324] Retain prepared owners across runtime refresh Keep registry and status manifests reference-backed, preserve source identity tokens across conversion, and retain amortized binding storage. Keep key validation inside its concrete callback and preserve captured contract errors during forced refresh. --- src/composite_model/compilation.jl | 44 ++++++++------ src/composite_model/object_families.jl | 8 +-- .../prepared_status_manifest.jl | 21 ++++--- src/composite_model/registry_topology.jl | 22 +++---- test/test-model-authored-port-inventory.jl | 60 +++++++++++++++---- test/test-model-input-plan-output-metadata.jl | 26 ++++++++ test/test-model-object-id.jl | 34 +++++++++++ test/test-object-families.jl | 10 ++++ 8 files changed, 175 insertions(+), 50 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index ae06e7893..9c54b15d9 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1015,6 +1015,18 @@ function _scenario_preparation(model::CompositeModel; force::Bool=false) if force || isnothing(preparation) || !_authored_specs_match(preparation, model) candidate = _prepare_authored_scenario(model, model.applications) + if isnothing(candidate.failure) && + model.registry.objects.catalog isa ClosedObjectFamilyCatalog + # A rejected logical route can remove alias metadata from an + # otherwise valid candidate manifest. Preserve its captured cause + # before comparing that secondary schema with the active registry. + failure = _first_authored_program_failure(candidate.program) + if !isnothing(failure) + candidate = ScenarioPreparation(model, candidate.source_specs, + candidate.authored, failure, candidate.program, + candidate.status_manifest, nothing) + end + end if !isnothing(candidate.failure) || candidate.status_manifest isa ScenarioPreparationFailure # Keep captured authoring failures authoritative, as before. A later # run must not silently fall back to an older compiled preparation. @@ -4024,6 +4036,15 @@ end _status_reference_epoch(view.status) == _status_reference_epoch(canonical) end +# Keep the existing key across the view's dispatch boundary. Read its inline ID +# only after the callback owns the concrete view and key argument types. +Base.@noinline function _status_view_key_epoch_is_current(view, model, key) + objects = model.registry.objects + object_id = _index_object_id(objects, getfield(key, 2)) + haskey(objects, object_id) || return true # removed objects were skipped by this scan + return _status_view_epoch_is_current(view, model, object_id) +end + function _extend_model_status_views( model::CompositeModel, compiled::CompiledCompositeModel, @@ -4060,12 +4081,10 @@ function _extend_model_status_views( end for (key, previous_view) in views - application_id, raw_id = key - object_id = _index_object_id(model.registry.objects, raw_id) - haskey(model.registry.objects, object_id) || continue - current = Base.@inline _with_model_status_view(_status_view_epoch_is_current, - compiled.status_view_schema, application_id, previous_view, model, object_id) - current || push!(affected_keys, (application_id, object_id)) + application_id = getfield(key, 1) + current = Base.@inline _with_model_status_view(_status_view_key_epoch_is_current, + compiled.status_view_schema, application_id, previous_view, model, key) + current || push!(affected_keys, key) end positions = Dict( @@ -4936,18 +4955,9 @@ function _extend_compiled_scene( ) started_at = _runtime_performance_start(performance) - added_input_binding_capacity = 0 - for application in added_applications - input_count = _compiled_application_by_id(compiled, application.id) do current - length(_model_input_names(current)) - end - added_input_binding_capacity += input_count * length(application.target_ids) - end + # Preserve the vector's amortized reserve across lifecycle barriers. + # An exact size hint can shrink and copy unchanged existing bindings. input_bindings = compiled.input_bindings - sizehint!( - input_bindings, - length(compiled.input_bindings) + added_input_binding_capacity, - ) input_bindings_by_target = compiled.input_bindings_by_target many_binding_cache = compiled.many_input_binding_cache changed_bindings = similar(input_bindings, 0) diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 1bfd85533..552414e97 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -51,10 +51,10 @@ end end """Canonical object identities and typed status families behind the object dictionary.""" -struct ObjectFamilyStore{I<:ObjectId,C} <: AbstractDict{I,Object} - catalog::C - locations::Dict{I,ObjectFamilyLocation} - status_owners::IdDict{Base.RefValue{Nothing},I} +mutable struct ObjectFamilyStore{I<:ObjectId,C} <: AbstractDict{I,Object} + const catalog::C + const locations::Dict{I,ObjectFamilyLocation} + const status_owners::IdDict{Base.RefValue{Nothing},I} end ObjectFamilyStore{I}() where {I<:ObjectId} = ObjectFamilyStore( diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 6dbbbb7e3..a1d3e68c1 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -1,11 +1,11 @@ # One constructor-owned manifest. This stores names, exact reference classes, # configured selector owners and raw-family correlations, never default values. -struct PreparedStatusManifest{S,A,P,D,R} - status_type::Type{S} - authored::A - permissions::P - destinations::D - raw_families::R +mutable struct PreparedStatusManifest{S,A,P,D,R} + const status_type::Type{S} + const authored::A + const permissions::P + const destinations::D + const raw_families::R end # RAW membership, labels and reference classes are constructor evidence DATA. @@ -133,8 +133,13 @@ end function _prepared_status_application_permissions(model, recipes, program) return map(recipes) do application application_slot = application.slot - plans = Tuple(plan for plan in program.input_records - if plan isa CompiledModelInputPlan && plan.application_slot == application_slot) + selected_plans = CompiledModelInputPlan[] + for plan in program.input_records + plan isa CompiledModelInputPlan || continue + plan.application_slot == application_slot || continue + push!(selected_plans, plan) + end + plans = Tuple(selected_plans) variants = Any[] _foreach_application_variant(application) do _, ports push!(variants, _prepared_status_variant_permission(model, application, ports, plans)) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 1ecc645db..c61f9c5b7 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1150,13 +1150,13 @@ end @inline function _validate_status_source_identity_available!( model::CompositeModel, - status, + identity::Union{Nothing,Base.RefValue{Nothing}}, object_id::ObjectId, ) - status isa Status || return nothing + isnothing(identity) && return nothing raw_existing = get( model.status_source_owners, - _status_identity(status), + identity, nothing, ) existing = isnothing(raw_existing) ? nothing : @@ -1212,15 +1212,15 @@ function _replace_model_object_status!( object.status === status && return status store = model.registry.objects object_id = object.id::keytype(store) - _validate_status_source_identity_available!(model, status, object_id) + source_identity = isnothing(status) ? nothing : _status_identity(status) + _validate_status_source_identity_available!(model, source_identity, object_id) raw_parent = object.parent parent_id = isnothing(raw_parent) ? nothing : _index_object_id(store, raw_parent) _validate_prepared_initial_status(model, object, status, parent_id) - return Base.@inline _with_prepared_canonical_status_type(model, object, object_id, status) do S, object, object_id, source + return Base.@inline _with_prepared_canonical_status_type(model, object, object_id, status, source_identity) do S, object, object_id, source, identity admitted = isnothing(source) ? nothing : _new_prepared_status(S, source) _store_object_family_row!(store, object, object_id, admitted) setfield!(object, :status, admitted) - identity = isnothing(source) ? nothing : _status_identity(source) _set_status_source_identity!(model, object_id, identity) return admitted end @@ -1476,21 +1476,22 @@ end source_status = object.status source_status isa Union{Nothing,Status} || throw(ArgumentError( "Initial object status must be a Status or nothing.")) - _validate_status_source_identity_available!(model, source_status, id) + source_identity = isnothing(source_status) ? nothing : _status_identity(source_status) + _validate_status_source_identity_available!(model, source_identity, id) if status_values_materialized || _no_status_conversion(model.status_conversion) - return Base.@inline _register_converted_status!(model, object, id, parent_id, source_status, source_status) + return Base.@inline _register_converted_status!(model, object, id, parent_id, source_identity, source_status) end conversion_records = Dict{Any,Any}() converted = _convert_registered_status(model, id, source_status; conversion_records) converted isa Union{Nothing,Status} || throw(ArgumentError( "Converted object status must be a Status or nothing.")) - registered = Base.@inline _register_converted_status!(model, object, id, parent_id, source_status, converted) + registered = Base.@inline _register_converted_status!(model, object, id, parent_id, source_identity, converted) merge!(model.status_conversion_records, conversion_records) return registered end @inline function _register_converted_status!(model, object, id, parent_id, - source_status::Union{Nothing,Status}, converted::Union{Nothing,Status}) + identity::Union{Nothing,Base.RefValue{Nothing}}, converted::Union{Nothing,Status}) catalog = model.registry.objects.catalog status = if catalog isa ClosedObjectFamilyCatalog manifest = catalog.status_manifest @@ -1508,7 +1509,6 @@ end store = registry.objects _store_object_family_row!(store, object, id, status) _index_object!(registry, object) - identity = isnothing(source_status) ? nothing : _status_identity(source_status) _set_status_source_identity!(model, id, identity) ancestors = isnothing(parent_id) ? ObjectId[id] : diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index 4d743f822..8e6ceba9a 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -255,8 +255,9 @@ const broken_input_calls = Ref(0) struct BrokenInput{T} <: AbstractAuthored_Port_Bad_InputModel token::T end -function PSE.inputs_(::BrokenInput) +function PSE.inputs_(model::BrokenInput) broken_input_calls[] += 1 + model.token === :repaired && return NamedTuple() error("captured input declaration failure") end PSE.outputs_(::BrokenInput) = (bad_seen=0f0,) @@ -267,13 +268,18 @@ PSE.run!(::BrokenInput, status, environment, constants, context) = nothing model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( ModelSpec(BrokenInput(:application); name=:broken, on=One(id=:leaf)),)) @test broken_input_calls[] == 1 - @test isnothing(model.scenario_plan_cache.failure) + @test model.scenario_plan_cache.failure isa PSE.ScenarioPreparationFailure @test hasproperty(only(model.scenario_plan_cache.authored), :ports) failed_ports = only(model.scenario_plan_cache.authored).ports @test failed_ports.input_declaration_types === failed_ports.input_types @test failed_ports.input_element_types === failed_ports.input_types @test failed_ports.input_types isa PSE.ScenarioPreparationFailure @test failed_ports.input_types.phase === :input_ports + failure = model.scenario_plan_cache.failure + @test failure === only(model.scenario_plan_cache.program.input_records) + @test failure.error === failed_ports.input_types.error + @test failure.phase === :input_plans + @test failure.application_id === :broken for _ in 1:2 report = PSE.compile_model_report(model) @test [app.id for app in report.applications] == [:broken] @@ -297,20 +303,49 @@ PSE.run!(::BrokenInput, status, environment, constants, context) = nothing @test isnothing(model_status(model, :leaf)) end -@testset "live application Scope is repaired before a saved input failure is delivered" begin +@testset "a repaired input schema retains future Scope resolution" begin broken_input_calls[] = 0 model = CompositeModel(Object(:scene; scale=:Scene); applications=( ModelSpec(BrokenInput(:application); name=:broken, on=One(Scope(ObjectId(:future_root)); scale=:Leaf)),)) @test broken_input_calls[] == 1 - @test isnothing(model.scenario_plan_cache.failure) - @test_throws "No instance or object ID" run!(model; steps=0) - @test broken_input_calls[] == 1 - register_object!(model, Object(:future_root; scale=:Plant)) - register_object!(model, Object(:future_leaf; scale=:Leaf, parent=:future_root)) + failure = model.scenario_plan_cache.failure + @test failure === only(model.scenario_plan_cache.program.input_records) + @test failure isa PSE.ScenarioPreparationFailure + @test failure.error === only(model.scenario_plan_cache.authored).ports.input_types.error + @test failure.phase === :input_plans + @test failure.application_id === :broken @test_throws "captured input declaration failure" run!(model; steps=0) + ids = Set(object_ids(model)) + @test_throws "captured input declaration failure" register_object!(model, + Object(:future_root; scale=:Plant)) + @test Set(object_ids(model)) == ids @test broken_input_calls[] == 1 - @test isnothing(model_status(model, :future_leaf)) + @test isnothing(model_status(model, :scene)) + + # A hook that failed before returning its names/types cannot supply a fixed + # namespace. Repairing authoring requires a new prepared model; the same + # genuine future Scope remains resolvable once its declarations are known. + repaired = CompositeModel(Object(:scene; scale=:Scene); applications=( + ModelSpec(BrokenInput(:repaired); name=:broken, + on=One(Scope(ObjectId(:future_root)); scale=:Leaf)),)) + @test broken_input_calls[] == 2 + @test_throws "No instance or object ID" run!(repaired; steps=0) + @test broken_input_calls[] == 2 + register_object!(repaired, Object(:future_root; scale=:Plant)) + register_object!(repaired, Object(:future_leaf; scale=:Leaf, parent=:future_root)) + @test broken_input_calls[] == 2 + @test isnothing(model_status(repaired, :future_leaf)) + run!(repaired; steps=0) + @test model_status(repaired, :future_leaf).bad_seen === 0f0 + @test isnothing(model_status(repaired, :future_root)) + reads = broken_input_calls[] + preparation = repaired.scenario_plan_cache + for _ in 1:2 + PSE._validate_authored_scenario(PSE._scenario_preparation(repaired)) + end + @test repaired.scenario_plan_cache === preparation + @test broken_input_calls[] == reads end struct Source{UNIT} <: AbstractAuthored_Port_SourceModel end @@ -441,7 +476,12 @@ PSE.run!(::BadShapeBeforeNames, status, environment, constants, context) = nothi model = CompositeModel(Object(:leaf; scale=:Leaf); applications=( ModelSpec(BadShapeBeforeNames(); name=:probe, on=One(id=:leaf)),)) @test shape_input_calls[] == shape_contract_calls[] == 1 - @test isnothing(model.scenario_plan_cache.failure) + failure = model.scenario_plan_cache.failure + @test failure === only(model.scenario_plan_cache.program.input_records) + @test failure isa PSE.ScenarioPreparationFailure + @test failure.error === only(model.scenario_plan_cache.authored).ports.contracts.error + @test failure.phase === :input_plans + @test failure.application_id === :probe @test_throws "must return a NamedTuple" run!(model; steps=0) @test shape_input_calls[] == shape_contract_calls[] == 1 @test isnothing(model_status(model, :leaf)) diff --git a/test/test-model-input-plan-output-metadata.jl b/test/test-model-input-plan-output-metadata.jl index 7de713376..b7b56972d 100644 --- a/test/test-model-input-plan-output-metadata.jl +++ b/test/test-model-input-plan-output-metadata.jl @@ -394,12 +394,38 @@ end # An authored snapshot must not survive an explicit author refresh of the # same model/application instances, including a failed compile. + registry, compiled = data.model.registry, data.model.binding_cache + environment = data.model.environment_binding_cache + preparation = data.model.scenario_plan_cache + official = model_status(data.model, :cell) + reference = PSE.refvalue(official, :signal) + source_owners = copy(data.model.status_source_owners) + source_ids = copy(data.model.status_source_identities) + step = first.current_step + history = copy(outputs(first)[(:reader, ObjectId(:cell), :observed)]) data.source.contracts[] = (signal=VariableContract(unit=:changed_signal),) @test_throws "Incompatible variable contracts" Advanced.refresh_bindings!(data.model; force=true) + rejected = data.model.scenario_plan_cache + @test rejected !== preparation + @test rejected.failure isa PSE.ScenarioPreparationFailure + @test occursin("Incompatible variable contracts", sprint(showerror, rejected.failure.error)) + @test data.model.registry === registry + @test data.model.binding_cache === compiled + @test data.model.environment_binding_cache === environment + @test model_status(data.model, :cell) === official + @test PSE.refvalue(official, :signal) === reference + @test data.model.status_source_owners == source_owners + @test data.model.status_source_identities == source_ids + @test_throws "Incompatible variable contracts" run!(data.model; steps=0, outputs=:none) + @test_throws "Incompatible variable contracts" continue!(first; steps=1) + @test first.current_step == step + @test outputs(first)[(:reader, ObjectId(:cell), :observed)] == history @test data.source.queries[] == data.reader.queries[] == 2 data.reader.contracts[] = (signal=VariableContract(unit=:changed_signal),) Advanced.refresh_bindings!(data.model; force=true) @test data.source.queries[] == data.reader.queries[] == 3 + @test model_status(data.model, :cell) === official + @test PSE.refvalue(official, :signal) === reference repeated = run!(data.model; steps=1, outputs=:all) @test final_state(repeated).observed === T(4) @test data.source.queries[] == data.reader.queries[] == 3 diff --git a/test/test-model-object-id.jl b/test/test-model-object-id.jl index 93cd461e3..dc618f324 100644 --- a/test/test-model-object-id.jl +++ b/test/test-model-object-id.jl @@ -411,6 +411,40 @@ end @test source_node(canonical_mtg, mtg_leaf_b) === mtg_leaf_b end +@testset "newborn source ownership survives official header replacement" begin + model = CompositeModel(Object(:seed; scale=:Leaf, status=Status(signal=1.0))) + source = Status(signal=2.0) + reference = PlantSimEngine.refvalue(source, :signal) + born = Object(:born; scale=:Leaf, status=source) + @test register_object!(model, born) === born + official = model_status(model, :born) + @test official !== source + @test PlantSimEngine.refvalue(official, :signal) === reference + @test object_id(model, official) === ObjectId(:born) + @test_throws ArgumentError object_id(model, source) + + source_owners = copy(model.status_source_owners) + source_identities = copy(model.status_source_identities) + ids = Set(object_ids(model)) + revision = PlantSimEngine.Advanced.model_revision(model) + rejected = Object(:duplicate; scale=:Leaf, status=source) + @test_throws ArgumentError register_object!(model, rejected) + @test Set(object_ids(model)) == ids + @test PlantSimEngine.Advanced.model_revision(model) == revision + @test model.status_source_owners == source_owners + @test model.status_source_identities == source_identities + @test rejected.status === source + @test model_status(model, :born) === official + @test PlantSimEngine.refvalue(official, :signal) === reference + + remove_object!(model, :born) + reborn = Object(:reborn; scale=:Leaf, status=source) + @test register_object!(model, reborn) === reborn + @test object_id(model, model_status(model, :reborn)) === ObjectId(:reborn) + @test PlantSimEngine.refvalue(model_status(model, :reborn), :signal) === reference + @test_throws ArgumentError object_id(model, source) +end + PlantSimEngine.@process "identity_signal" verbose = false struct IdentitySignalModel{T} <: AbstractIdentity_SignalModel diff --git a/test/test-object-families.jl b/test/test-object-families.jl index cac7401b6..74e5cce41 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -291,7 +291,17 @@ end original = Status(value=1f0) object = Object(:leaf; status=original) model = CompositeModel(object) + manifest = model.registry.objects.catalog.status_manifest + @test model.scenario_plan_cache.status_manifest === manifest copied = deepcopy(model) + copied_manifest = copied.registry.objects.catalog.status_manifest + @test copied.scenario_plan_cache.status_manifest === copied_manifest + @test copied_manifest !== manifest + @test copied_manifest.raw_families !== manifest.raw_families + shared = deepcopy((manifest, manifest)) + @test shared[1] === shared[2] + @test shared[1] !== manifest + @test shared[1].raw_families !== manifest.raw_families copied_object = model_object(copied, :leaf) copied_status = model_status(copied, :leaf) @test copied_object !== object From 3124e5a5e1e8b7a6b9c423ddd3ecc369d1640c33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 12:57:06 +0100 Subject: [PATCH 150/324] Align execution fixtures with prepared canonical status Preserve scientific cells and values while using official headers and declared numeric storage. Keep the real Float32-to-Float64 model replacement under its explicit storage policy. The broader prepared-call regression remains incomplete and is retained separately for diagnosis. --- test/test-model-binding-index-identities.jl | 7 ++++-- test/test-model-call-execution-identity.jl | 24 +++++++++++++-------- test/test-model-closed-cohort-schemas.jl | 12 +++++++---- test/test-model-closed-group-refresh.jl | 21 +++++++++++++----- test/test-model-prepared-call-schemas.jl | 6 +++++- test/test-model-status-type-conversion.jl | 16 +++++++++++--- 6 files changed, 62 insertions(+), 24 deletions(-) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index d88930624..ea66cd631 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -83,8 +83,11 @@ end registered = keyword_parent ? register_object!(model, object; parent="root") : register_object!(model, object) @test registered === object - @test model_status(model, id) === status - @test PSE.refvalue(model_status(model, id), :x) === reference + official = model_status(model, id) + @test object.status === official + @test official !== status + @test_throws ArgumentError object_id(model, status) + @test PSE.refvalue(official, :x) === reference @test object.parent === (id === :detached ? nothing : root.id) @test (object.id in root.children) === (id !== :detached) end diff --git a/test/test-model-call-execution-identity.jl b/test/test-model-call-execution-identity.jl index dcdad9d43..a90d8c0a7 100644 --- a/test/test-model-call-execution-identity.jl +++ b/test/test-model-call-execution-identity.jl @@ -43,7 +43,10 @@ function PSE.run!(model::Creator, status, environment, constants, context) status=Status(calls=0, value=0.0))) first = only(call_targets(context, :middle; objects=middle)) second = only(call_targets(context, :middle; objects=middle)) - shared_status = first.status === second.status === model_status(runtime, :middle) + official = model_status(runtime, :middle) + shared_references = first.canonical_status === second.canonical_status === official && + all(name -> PSE.refvalue(first.status, name) === PSE.refvalue(second.status, name) === + PSE.refvalue(official, name), keys(official)) shared_parent_cache = first.context_cache === second.context_cache evaluation = evaluate_call!(first) stamp_count = length(evaluation.frame.executions) @@ -63,7 +66,7 @@ function PSE.run!(model::Creator, status, environment, constants, context) rejection = error isa ArgumentError ? sprint(showerror, error) : string(typeof(error)) stale_rejected = error isa ArgumentError && occursin("stale", rejection) end - model.capture[] = (; shared_status, shared_parent_cache, stamp_count, + model.capture[] = (; shared_references, shared_parent_cache, stamp_count, first_stamp_changed, model_guard_valid, stale_rejected, rejection) status.created = true return nothing @@ -91,7 +94,7 @@ end for call_child in (true, false) result = run_alias_case(call_child) @info "selection evaluation alias diagnostic" call_child diagnostic=result.data - @test result.data.shared_status + @test result.data.shared_references @test result.data.model_guard_valid # no timeline/topology/model mutation between the two runs @test result.middle_calls == 2 @test result.middle_value == 2.0 @@ -118,7 +121,10 @@ PSE.outputs_(::Leaf) = (calls=0,) PSE.run!(::Leaf, status, environment, constants, context) = (status.calls += 1; nothing) function evaluate_then_rerun(first, second) - shared_status = first.status === second.status + official = first.canonical_status + shared_references = second.canonical_status === official && + all(name -> PSE.refvalue(first.status, name) === PSE.refvalue(second.status, name) === + PSE.refvalue(official, name), keys(official)) shared_view = first.execution_target.status_view === second.execution_target.status_view shared_cache = first.context_cache === second.context_cache evaluation = evaluate_call!(first) @@ -136,7 +142,7 @@ function evaluate_then_rerun(first, second) message = error isa ArgumentError ? sprint(showerror, error) : string(typeof(error)) rejected = error isa ArgumentError && occursin("stale", message) end - return (; shared_status, shared_view, shared_cache, model_guard_valid, rejected, message) + return (; shared_references, shared_view, shared_cache, model_guard_valid, rejected, message) end struct Controller{C} <: AbstractStable_Execution_ControllerModel @@ -166,7 +172,7 @@ end simulation = run!(model; outputs=:all) data = capture[] @info "two-binding evaluation identity diagnostic" use_other_binding diagnostic=data - @test data.shared_status + @test data.shared_references @test data.shared_view @test data.model_guard_valid @test data.rejected @@ -207,7 +213,7 @@ end simulation = run!(model; outputs=:all) data = capture[] @info "targeted prebarrier evaluation identity diagnostic" reparent_before_barrier diagnostic=data.before_barrier - @test data.before_barrier.shared_status + @test data.before_barrier.shared_references @test data.before_barrier.model_guard_valid @test data.before_barrier.rejected @test model_status(model, :leaf).calls == 2 @@ -218,7 +224,7 @@ end current = only(call_targets(data.context, :leaf)) after_barrier = evaluate_then_rerun(data.retained, current) @info "retained postbarrier evaluation identity diagnostic" reparent_before_barrier diagnostic=after_barrier - @test after_barrier.shared_status + @test after_barrier.shared_references @test after_barrier.model_guard_valid @test after_barrier.rejected @test model_status(model, :leaf).calls == 4 @@ -230,7 +236,7 @@ end refreshed = only(call_targets(data.context, :leaf)) after_force = evaluate_then_rerun(data.retained, refreshed) @info "retained full-refresh evaluation identity diagnostic" reparent_before_barrier diagnostic=after_force - @test after_force.shared_status + @test after_force.shared_references @test after_force.model_guard_valid @test after_force.rejected @test model_status(model, :leaf).calls == 6 diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl index 4ea2614ce..49ef5b577 100644 --- a/test/test-model-closed-cohort-schemas.jl +++ b/test/test-model-closed-cohort-schemas.jl @@ -152,7 +152,7 @@ end end @testset "an empty future schema creates no target or scientific default" begin - S = Status{(:value,),Tuple{Base.RefValue{Float64}}} + S = Status{(:value,),NamedTuple{(:value,),Tuple{Base.RefValue{Float64}}}} T = Target{ObjectId{Int},S,Base.RefValue{Int}} schema = PSE._closed_execution_cohort_schema(Tuple{T}) store = PSE.ExecutionCohortStore() @@ -253,9 +253,13 @@ PSE.run!(::Leaf, status, environment, constants, context) = (status.leaf_visits batches = capture[].calls[1].execution_batches schema = PSE._execution_cohort_schema(batches) @test schema isa PSE.ClosedExecutionCohortSchema - @test fieldtype(typeof(only(batches).targets), :store) === PSE.ExecutionCohortStore{ObjectId,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,ObjectId}} - @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === PSE.ExecutionCohortStore{ObjectId,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,ObjectId}} - @test typeof(simulation.temporal_streams.cohorts) === PSE.ExecutionCohortStore{ObjectId,Any,Tuple{Any,Symbol,DataType},Tuple{Any,Symbol,ObjectId}} + I = keytype(model.registry.objects) + OwnerT = Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} + Store = PSE.ExecutionCohortStore{I,OwnerT, + PSE.ExecutionCohortKey{OwnerT,DataType},PSE.ExecutionCohortKey{OwnerT,I}} + @test fieldtype(typeof(only(batches).targets), :store) === Store + @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === Store + @test typeof(simulation.temporal_streams.cohorts) === Store owner = PSE._execution_call_owner(capture[].calls[1].binding) location = PSE.cohort_location(simulation.temporal_streams.cohorts,:middle, ObjectId(:plant);owner) diff --git a/test/test-model-closed-group-refresh.jl b/test/test-model-closed-group-refresh.jl index 2b07a034e..55364bffb 100644 --- a/test/test-model-closed-group-refresh.jl +++ b/test/test-model-closed-group-refresh.jl @@ -147,14 +147,18 @@ end status = Status(count=0f0) model = CompositeModel(Object(:leaf; status); applications=(ModelSpec(Counter(1f0, trace, declarations); - name=:counter, on=One(id=:leaf)),)) + name=:counter, on=One(id=:leaf)),), + type_promotion=Dict(Float64 => Float32)) simulation = run!(model; steps=0, outputs=:none) previous = only(simulation.execution_plan.groups) + official = model_status(model, :leaf) + @test PSE.model_(previous.application.spec).increment isa Float32 model.applications[1] = ModelSpec(Counter(2.0, trace, declarations); name=:counter, on=One(id=:leaf)) PSE.Advanced.refresh_bindings!(model; force=true) current = PSE.Advanced.compiled_bindings(model).applications_by_id[:counter] @test typeof(current) !== typeof(previous.application) + @test PSE.model_(current.spec).increment isa Float64 invoked = Ref(false) @test_throws "prepared execution-group schema" PSE._with_previous_execution_group( group -> (invoked[] = true; (0, 0, 0)), (previous,), current, falses(1)) @@ -172,7 +176,10 @@ end @test PSE._execution_groups_in_schema([previous], current_groups) === current_groups step!(current_simulation) @test status.count === 2f0 - @test model_status(model, :leaf) === status + @test model_status(model, :leaf) === official + @test official !== status + @test official.count === 2f0 + @test PSE.refvalue(official, :count) === PSE.refvalue(status, :count) @test trace == [:counter] end @@ -195,8 +202,10 @@ end PSE.Advanced.refresh_bindings!(model; force=true) step!(simulation) @test plain.count === 2f0 && alternate.count === 4.0 - @test model_status(model, :plain) === plain - @test model_status(model, :alternate) === alternate + @test model_status(model, :plain) !== plain + @test model_status(model, :alternate) !== alternate + @test PSE.refvalue(model_status(model, :plain), :count) === PSE.refvalue(plain, :count) + @test PSE.refvalue(model_status(model, :alternate), :count) === PSE.refvalue(alternate, :count) group = only(simulation.execution_plan.groups) @test length(group.batches) == 2 @test trace == fill(:plant__counter, 4) @@ -233,7 +242,9 @@ end @test only(simulation.execution_plan.groups) === future @test only(simulation.execution_plan.groups_by_application_slot) === future @test typeof(simulation.execution_plan) === typeof(plan) - @test only(only(future.batches).targets).status_view.status === newborn.status + view = only(only(future.batches).targets).status_view + @test view.canonical_status === newborn.status + @test PSE.refvalue(view.status, :count) === PSE.refvalue(newborn.status, :count) @test trace == [:counter] end diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl index e3a3408f7..e0bf3c443 100644 --- a/test/test-model-prepared-call-schemas.jl +++ b/test/test-model-prepared-call-schemas.jl @@ -309,7 +309,11 @@ end @test !PSE._compiled_call_membership_is_observed(full.binding) newborn = only(call_targets(data.capture[], :middle; objects=(:middle_new,))) @test newborn.object_id == ObjectId(:middle_new) - @test newborn.status === model_status(data.model, :middle_new) + official = model_status(data.model, :middle_new) + @test newborn.canonical_status === official + @test newborn.status === newborn.execution_target.status_view.status + @test all(name -> PSE.refvalue(newborn.status, name) === PSE.refvalue(official, name), + keys(official)) run_call!(newborn; publish=true) @test data.kernels == Dict(:root => 2, :middle => 1, :leaf => 1) @test model_status(data.model, :middle_a).visits == 0 diff --git a/test/test-model-status-type-conversion.jl b/test/test-model-status-type-conversion.jl index f466f71b0..5c838fc5e 100644 --- a/test/test-model-status-type-conversion.jl +++ b/test/test-model-status-type-conversion.jl @@ -126,8 +126,13 @@ end ), ) - @test object.status === original - @test PlantSimEngine.refvalue(object.status, :supplied) === supplied_reference + official = model_status(model, :scene) + @test object.status === official + @test official !== original + @test_throws ArgumentError object_id(model, original) + @test PlantSimEngine.refvalue(official, :supplied) === supplied_reference + @test PlantSimEngine.refvalue(official, :untouched) === + PlantSimEngine.refvalue(original, :untouched) Advanced.refresh_bindings!(model) @test object.status.supplied isa Float64 @test object.status.offset isa Float64 @@ -169,8 +174,13 @@ end @test status.label_text == "leaf" @test status.date === Date(2026, 8, 26) @test status.cadence === Hour(1) + view = only(values(compiled.status_views_by_target)) + @test view.canonical_status === status + @test keys(view.status) == keys(status) + @test all(name -> PlantSimEngine.refvalue(view.status, name) === + PlantSimEngine.refvalue(status, name), keys(status)) @test only(Diagnostics.explain_execution_plan(model)).status_type == - typeof(status) + typeof(view.status) simulation = run!(model; outputs=:all) @test status.result === Float32(1.75) From e8c2e6b665ac145bc3f62ed177001e100d1e2f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 12:57:17 +0100 Subject: [PATCH 151/324] Clarify explicit initial data for MTG growth --- docs/src/guides/multiscale/import_mtg.md | 20 ++++++++++++++------ docs/src/migration_composite_model.md | 8 +++++--- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/docs/src/guides/multiscale/import_mtg.md b/docs/src/guides/multiscale/import_mtg.md index 71fc337db..1f98b42e3 100644 --- a/docs/src/guides/multiscale/import_mtg.md +++ b/docs/src/guides/multiscale/import_mtg.md @@ -30,8 +30,14 @@ this reduced architecture omits stems and petioles. For an existing MTG file, re PlantSimEngine imports each node's ID and parent automatically. By default, it uses the MTG symbol, such as `:Leaf`, as the object's `scale` label. It does **not** automatically copy numerical attributes into `Status`, -where models read and store their values. To do that, you can supply a function that returns a `Status` for each node. The function can read any attributes you have stored in the MTG, and it can supply default values for missing attributes. The function is called for each node when you create the `CompositeModel` or when you add a new organ with `add_organ!`. The function can return an empty `Status()` if you do not want to import any attributes for a node. -In our example below, this function initializes carbon biomass only for leaves. The plant-scale model reads the leaf areas calculated from that biomass, so it does not need its own carbon biomass value. +where models read and store their values. Supply a function that returns a +`Status` for each node to choose which attributes to import. It can read the +node's attributes, provide missing initial values, or return an empty +`Status()`. This function runs when you create the `CompositeModel`. + +In the example below, it initializes carbon biomass only for leaves. The +plant-scale model reads the leaf areas calculated from that biomass, so it +does not need its own carbon biomass value. ```@example import_mtg initial_status(node) = MultiScaleTreeGraph.symbol(node) == :Leaf ? @@ -69,10 +75,12 @@ plant_area `CompositeModel(root; ...)` keeps the relationship between MTG nodes and simulation objects. Use `object_id(model, leaf_1)` to find the object for a -node. When you create an organ with `add_organ!`, PlantSimEngine reuses your -`initial_status` function to set its initial values. The new node must have -the attributes this function reads, or the function must supply suitable -initial values itself. +node. For a new organ, pass its scientific initial values explicitly, for +example `add_organ!(parent_node, model, :+, :Leaf, 1; +initial_status=(carbon_biomass=0.0,))`. The import function is not called +during growth. The new organ uses the numeric conversion and field types +prepared for its model configuration. MTG attributes remain annotations +and geometry; use `source_node(model, object)` to retrieve its source node. See [Growth within a time step](../../tutorials/growing_plant/part1_growth.md). Use `objects_from_mtg(root; status=initial_status)` when you only want a diff --git a/docs/src/migration_composite_model.md b/docs/src/migration_composite_model.md index 9e7c5d9c6..f2f016858 100644 --- a/docs/src/migration_composite_model.md +++ b/docs/src/migration_composite_model.md @@ -460,9 +460,11 @@ move_object!(model, :leaf_3, new_geometry) ``` For MTG-backed growth, prefer `add_organ!`: it creates the MTG node and its -model object together and, by default, reuses the status initialization policy from -`CompositeModel(mtg; status=...)`. Use `register_object!` when adapting another topology -backend or when a complete `Object` already exists. +model object together. Pass scientific initial values through `initial_status`; +the `status` function used for the initial MTG import is not called again. +The model's numeric conversion and prepared field types apply to these values. +Use `register_object!` when adapting another topology backend or when a +complete `Object` already exists. After the application that adds or removes objects finishes, PlantSimEngine updates which models run, where they get their inputs, and which other models From 7145ac8a4db91b77beb3fa24154647ec188f79cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 13:31:24 +0100 Subject: [PATCH 152/324] Admit native lifecycle operands before dispatch --- src/composite_model/compilation.jl | 2 +- src/composite_model/registry_topology.jl | 5 +++ test/test-model-binding-index-identities.jl | 43 +++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 9c54b15d9..3a3182b31 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4083,7 +4083,7 @@ function _extend_model_status_views( for (key, previous_view) in views application_id = getfield(key, 1) current = Base.@inline _with_model_status_view(_status_view_key_epoch_is_current, - compiled.status_view_schema, application_id, previous_view, model, key) + compiled.status_view_schema, application_id, previous_view, model, key::Key) current || push!(affected_keys, key) end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index c61f9c5b7..03a45b49e 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1473,6 +1473,11 @@ end if !isnothing(parent_id) && !haskey(registry.objects, parent_id) error("No model object with id `$(parent_id.value)`.") end + return _register_object_status!(model, object, id, parent_id, status_values_materialized) +end + +function _register_object_status!(model::CompositeModel, object::Object, + id, parent_id, status_values_materialized::Bool) source_status = object.status source_status isa Union{Nothing,Status} || throw(ArgumentError( "Initial object status must be a Status or nothing.")) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index ea66cd631..c463b2374 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -63,6 +63,19 @@ end revision = model.revision children = copy(root.children) + # A duplicate identity wins before either parent-domain or parent-existence + # rejection, and before any source conversion or ownership publication. + for parent in (1, :missing) + source = Status(x=2.0) + duplicate = Object(:root; status=source) + @test_throws "already contains object id" register_object!(model, duplicate; parent) + @test duplicate.status === source + @test isnothing(duplicate.parent) + @test model.status_conversion_records == records + @test model.revision == revision + @test root.children == children + end + for (id, parent) in ((2, :root), (:wrong_parent, 1)) source = Status(x=2.0) object = Object(id; status=source) @@ -94,6 +107,36 @@ end end +@testset "registration converts a source once after identity and parent admission" begin + for closed in (false, true) + calls = Ref(0) + transform = (variable, value) -> begin + calls[] += 1 + value + end + model = CompositeModel(Object(:seed; status=Status(x=1.0)); + type_promotion=Dict(Float64 => Float32), status_transform=transform) + closed && (model = close_registry(model)) + before = calls[] + source = Status(x=2.0) + @test_throws "already contains object id" register_object!(model, + Object(:seed; status=source); parent=1) + @test_throws "No model object" register_object!(model, + Object(:rejected; status=source); parent=:missing) + @test calls[] == before + @test source.x === 2.0 + @test !haskey(model.registry.objects, ObjectId(:rejected)) + born = Object(:born; parent=:seed, status=source) + @test register_object!(model, born) === born + @test calls[] == before + 1 + @test source.x === 2.0 + @test model_status(model, :born).x === 2f0 + @test born.parent === ObjectId(:seed) + @test ObjectId(:born) in model_object(model, :seed).children + @test_throws ArgumentError object_id(model, source) + end +end + @testset "instance roots retain identity through nested registration and missing lookups" begin for root_value in (:instance_root, 17, (:plant, 2)), form in (:object, :id, :value), closed in (false, true) root = Object(root_value; scale=:Plant, status=Status(x=1f0)) From b40031de21fa8fb50394ad185ebdb18960ebec3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 15:57:53 +0100 Subject: [PATCH 153/324] Reprepare canonical status after graph edits Keep captured authored declarations while rebuilding edited status routes, and avoid admitting data through scopes with no current anchor. Align feature fixtures with the prepared status contract and declare the future publication consumer's temporal default explicitly. Validation: API and graph whole files passed 1275 checks before the final temporal fixture correction; the current temporal whole file passed 240 checks with all source, input and runtime guards. Full cohort/reset and PreparedCall coverage remain pending; this is a feature checkpoint, not merge qualification. --- src/composite_model/compilation.jl | 11 +- src/composite_model/selectors.jl | 11 +- src/visualization/model_graph_editor_api.jl | 101 ++++++------ test/test-input-default-values.jl | 50 +++--- test/test-input-source-matching.jl | 22 ++- test/test-model-api-stabilization.jl | 60 ++++++- test/test-model-call-context-cloning.jl | 9 +- test/test-model-cohort-store-identities.jl | 20 ++- test/test-model-graph-view.jl | 148 ++++++++++++++++++ test/test-model-prepared-call-schemas.jl | 31 +++- ...st-model-prepared-missing-future-schema.jl | 23 +-- test/test-model-reusable-call-targets.jl | 18 ++- test/test-model-scenario-authoring.jl | 8 +- test/test-model-temporal-initial-typing.jl | 36 +++-- test/test-selector-query-scope-append.jl | 20 +++ 15 files changed, 442 insertions(+), 126 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 3a3182b31..1ba314962 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -940,9 +940,14 @@ function _prepare_authored_scenario(model::CompositeModel, raw_specs; recipe.id, err, catch_backtrace()) end end - failure_index = findfirst(record -> record isa ScenarioPreparationFailure, authored) - failure = isnothing(failure_index) ? nothing : authored[failure_index] - authored_records = Tuple(authored) + return _finalize_authored_scenario(model, source_specs, Tuple(authored), raw_families) +end + +# Constructor and transactional edits share the same type/route preparation. +# Captured ports stay unchanged; new initial data can change from_status RT. +function _finalize_authored_scenario(model, source_specs, authored_records, raw_families) + failure_index = findfirst(record -> record isa ScenarioPreparationFailure, authored_records) + failure = isnothing(failure_index) ? nothing : authored_records[failure_index] recipes = Tuple(record for record in authored_records if record isa AuthoredApplicationRecipe) program = _prepare_authored_scenario_program(model, recipes) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 06bcfb5d9..af55e178d 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1692,17 +1692,22 @@ end species=matcher.species, id=matcher.id) end -function _prepared_status_scope_is_current(model, topology, scope) +function _prepared_status_scope_is_current(model, topology, scope, origin) scope isa Scope && return _point_scope_root_exists(topology, first(_named_scope_root_candidate(model, scope))) scope isa CompiledNamedScope && return _point_scope_root_exists(topology, scope.root_id) + if !isnothing(origin) && scope isa Union{SelfPlant,Ancestor} + # No current anchor means no applicable data permission/context. The + # actual input query still owns its missing-anchor diagnostic. + return !isnothing(_scope_anchor(topology, scope, origin)) + end return true end function _prepared_status_application_matches(model, object, parent_id, application) id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) - _prepared_status_scope_is_current(model, topology, application.target_matcher.scope) || return false + _prepared_status_scope_is_current(model, topology, application.target_matcher.scope, nothing) || return false return _selector_matches_object_id(topology, application.target_matcher, id, nothing, false, nothing, false) end @@ -1713,7 +1718,7 @@ function _prepared_status_route_matches(model, object, parent_id, application, # Output destinations and from-status input sources use the same predicate. id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) - _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope) || return false + _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope, execution_id) || return false return _selector_matches_object_id(topology, destination_plan.matcher, id, execution_id, true, _default_dependency_scope(topology, execution_id), false) end diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index e2668935f..f557e7318 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -288,9 +288,10 @@ RemoveModelObjectOverride( Apply one declarative graph edit transactionally. The input model is not modified; a deep-copied, cache-invalidated CompositeModel is returned. Configuration that is temporarily incomplete or cyclic is retained so the editor can display -and repair it. Structural edit errors leave the original model unchanged. Values -listed in `preserve` retain their identity inside the copy; editor sessions use -this for server-side template and environment catalogs. +and repair it. Structural edit errors leave the original model unchanged. Mutable values +listed in `preserve` retain their identity inside the copy. For an immutable +container, list its mutable fields explicitly. Editor sessions use this for +server-side template and environment catalogs. """ function _model_graph_deepcopy(model::CompositeModel, preserve=()) stack = IdDict{Any,Any}() @@ -309,20 +310,15 @@ function apply_model_graph_edit( preparation = candidate.scenario_plan_cache candidate = _apply_model_graph_edit!(candidate, edit) _mark_bindings_dirty!(candidate) - if !isnothing(preparation) && - _authored_specs_match(preparation, candidate) - candidate.scenario_plan_cache = preparation - _model_owned_scenario_preparation(candidate, preparation).resolved = nothing - end final_preparation = if !isnothing(preparation) && _authored_specs_match(preparation, candidate) - _scenario_preparation(candidate) + # The copied state is initial data for this new model. Reuse captured + # declarations, then recompute routes and the namespace without hooks. + _finalize_authored_scenario(candidate, preparation.source_specs, + preparation.authored, nothing) else - # This API already returns a NEW model. Its copied live state is the - # genuine input data for a newly prepared namespace, unlike force in place. - fresh = _prepare_authored_scenario(candidate, candidate.applications; raw_families=nothing) - candidate.scenario_plan_cache = fresh - fresh + _prepare_authored_scenario(candidate, candidate.applications; raw_families=nothing) end + candidate.scenario_plan_cache = final_preparation return _install_prepared_canonical_registry(candidate, final_preparation) end @@ -860,14 +856,16 @@ function _apply_model_graph_edit!(model::CompositeModel, edit::BreakModelCycle) isempty(applications) && error( "Application `$(edit.application.application_id)` could not be resolved after breaking its cycle.", ) + missing = ObjectId[] for application in applications for object_id in application.target_ids object = _model_object(model, object_id) supplied = object.status isa Status && hasproperty(object.status, edit.input) - supplied || _set_model_object_status!(model, object_id, edit.input, edit.initial_value) + supplied || object_id in missing || push!(missing, object_id) end end - return model + return isempty(missing) ? model : + _set_model_object_statuses!(model, missing, edit.input, edit.initial_value) end function _apply_model_graph_edit!(model::CompositeModel, edit::AddModelObject) @@ -904,44 +902,53 @@ function _model_edit_status_values(status) ] end -function _set_model_object_status!(model, object_id, variable, value) - object = _model_object(model, object_id) - effective, _, _ = _materialize_status_value( - model, - Symbol(variable), - value; - object_id=object.id, - origin=:graph_edit_status, - ) - values = _model_edit_status_values(object.status) - index = findfirst(pair -> first(pair) == variable, values) - if isnothing(index) - push!(values, variable => effective) - else - values[index] = variable => effective +function _set_model_object_statuses!(model, object_ids, variable, value) + isempty(object_ids) && error("SetModelObjectStatuses requires at least one object id.") + # Resolve every identity before converting any value. These are facades in + # the transaction's private copy, not objects in the caller's live registry. + selected = [_model_object(model, object_id) for object_id in object_ids] + updates = Dict{ObjectId,Status}() + for object in selected + effective, _, _ = _materialize_status_value(model, variable, value; + object_id=object.id, origin=:graph_edit_status) + references = object.status isa Status ? Pair{Symbol,Any}[ + name => refvalue(object.status, name) for name in propertynames(object.status) + ] : Pair{Symbol,Any}[] + index = findfirst(pair -> first(pair) === variable, references) + reference = variable => Ref(effective) + isnothing(index) ? push!(references, reference) : (references[index] = reference) + updates[object.id] = Status((; references...)) end - _replace_model_object_status!(model, object, Status((; values...))) - delete!( - get!( - model.input_default_status_variables, - object_id, - Set{Symbol}(), - ), - variable, - ) - return model + defaults = Dict{ObjectId,Set{Symbol}}( + id => copy(names) for (id, names) in model.input_default_status_variables) + for (id, status) in updates + setfield!(_model_object(model, id), :status, status) + delete!(get!(defaults, id, Set{Symbol}()), variable) + end + # Assemble the real edited initial data before preparing its canonical S. + # Specs are already mounted; retain the same instance facades and adapter + # maps below instead of mounting templates or converting status values twice. + assembled = _assemble_composite_model(model_objects(model)...; + applications=model.applications, environment=model.environment, + source_adapter=model.source_adapter, _status_conversion=model.status_conversion, + _status_values_materialized=true, + _status_conversion_records=model.status_conversion_records) + fields = map(fieldnames(typeof(model))) do name + name in (:registry, :status_source_owners, :status_source_identities, + :status_conversion_records) && return getfield(assembled, name) + name in (:scenario_plan_cache, :binding_cache, :environment_binding_cache) && return nothing + name === :input_default_status_variables && return defaults + return getfield(model, name) + end + return CompositeModel(fields...) end function _apply_model_graph_edit!(model::CompositeModel, edit::SetModelObjectStatus) - return _set_model_object_status!(model, edit.object_id, edit.variable, edit.value) + return _set_model_object_statuses!(model, (edit.object_id,), edit.variable, edit.value) end function _apply_model_graph_edit!(model::CompositeModel, edit::SetModelObjectStatuses) - isempty(edit.object_ids) && error("SetModelObjectStatuses requires at least one object id.") - for object_id in edit.object_ids - _set_model_object_status!(model, object_id, edit.variable, edit.value) - end - return model + return _set_model_object_statuses!(model, edit.object_ids, edit.variable, edit.value) end function _apply_model_graph_edit!(model::CompositeModel, edit::RemoveModelObjectStatus) diff --git a/test/test-input-default-values.jl b/test/test-input-default-values.jl index e2cf1b5dd..3b1a2cdba 100644 --- a/test/test-input-default-values.jl +++ b/test/test-input-default-values.jl @@ -128,29 +128,33 @@ PSE.outputs_(::MutableInputDefaults) = NamedTuple() PSE.run!(::MutableInputDefaults, status, environment, constants, context) = nothing @testset "canonical callers still copy fresh defaults for every real object" begin - payload = Ref{Any}(Float32[1, 2]) - model = CompositeModel(Object(:first; scale=:Leaf), Object(:second; scale=:Leaf); - applications=(ModelSpec(MutableInputDefaults(payload); name=:defaults, - on=Many(scale=:Leaf)),)) - simulation = run!(model; steps=0, outputs=:none) - first = model_status(model, :first).buffer - second = model_status(model, :second).buffer - @test first == second == Float32[1, 2] - @test first !== second - @test first !== payload[] - payload[] = Float64[7, 8] - register_object!(model, Object(:third; scale=:Leaf)) - step!(simulation) - third = model_status(model, :third).buffer - @test third == [7.0, 8.0] - @test third isa Vector{Float64} - @test third !== payload[] - @test first isa Vector{Float32} - @test second isa Vector{Float32} - first[1] = 9f0 - @test second == Float32[1, 2] - @test third == [7.0, 8.0] - @test model_status(model, :third).optional === 1f0 + # Each CompositeModel prepares one numerical configuration. Exercise both + # Float32 and Float64 without changing that configuration between births. + for T in (Float32, Float64) + payload = Ref{Any}(T[1, 2]) + model = CompositeModel(Object(:first; scale=:Leaf), Object(:second; scale=:Leaf); + applications=(ModelSpec(MutableInputDefaults(payload); name=:defaults, + on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + first = model_status(model, :first).buffer + second = model_status(model, :second).buffer + @test first == second == T[1, 2] + @test first !== second + @test first !== payload[] + payload[] = T[7, 8] + register_object!(model, Object(:third; scale=:Leaf)) + step!(simulation) + third = model_status(model, :third).buffer + @test third == T[7, 8] + @test third isa Vector{T} + @test third !== payload[] + @test first isa Vector{T} + @test second isa Vector{T} + first[1] = T(9) + @test second == T[1, 2] + @test third == T[7, 8] + @test model_status(model, :third).optional === 1f0 + end end end # module InputDefaultValuesChecks diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl index a1794513b..ed6ba99aa 100644 --- a/test/test-input-source-matching.jl +++ b/test/test-input-source-matching.jl @@ -16,13 +16,16 @@ PSE.outputs_(model::Union{Writer,AlternativeWriter}) = (x=zero(model.value),) PSE.run!(model::Union{Writer,AlternativeWriter}, status, environment, constants, context) = (status.x = model.value; nothing) -function matching_fixture() +function matching_fixture(; growing_a=false) names = (:a, :b, :c, :d, :e, :f) models = (Writer(1f0), Writer(2.0), Writer(Int8(3)), Writer(Int16(4)), Writer(Int32(5)), AlternativeWriter(Int64(6))) - objects = ntuple(index -> Object(index; status=Status(x=models[index].value)), 6) + objects = ntuple(index -> Object(index; + kind=growing_a && index == 1 ? :growing_a : nothing, + status=Status(x=models[index].value)), 6) applications = ntuple(index -> ModelSpec(models[index]; - name=names[index], on=One(id=index)), 6) + name=names[index], + on=growing_a && index == 1 ? Many(kind=:growing_a) : One(id=index)), 6) simulation = run!(CompositeModel(objects...; applications); steps=0, outputs=:none) compiled = simulation.compiled owner(name, index) = PSE.CompiledWriterOwner(index, name, ObjectId(index), nothing, :local) @@ -89,10 +92,17 @@ end end @testset "planned singleton matching retains a real newborn partial overlay" begin - simulation, distributed = matching_fixture() + simulation, distributed = matching_fixture(; growing_a=true) compiled = simulation.compiled - newborn = register_object!(simulation.model, Object(7; status=Status(x=7f0))) - reference = PSE.refvalue(newborn.status, :x) + supplied = Status(x=7f0) + reference = PSE.refvalue(supplied, :x) + newborn = register_object!(simulation.model, Object(7; kind=:growing_a, status=supplied)) + @test newborn.status === model_status(simulation.model, 7) + @test PSE.refvalue(newborn.status, :x) === reference + # The authored producer really selects this newborn, while its cached + # pre-barrier target vector intentionally still contains only object 1. + @test ObjectId(7) in resolve_object_ids(simulation.model, + compiled.applications_by_id[:a].spec.on) partial = PSE._partial_model_application(compiled.applications_by_id[:a], ObjectId[ObjectId(7)]) overlay = PSE._ApplicationsByObjectOverlay(compiled.applications_by_object, diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index cb2f70b75..dfbf81b19 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -4,10 +4,16 @@ using Test PlantSimEngine.@process "stabilization_source" verbose = false -struct StabilizationSourceModel <: AbstractStabilization_SourceModel end +struct StabilizationSourceModel{T} <: AbstractStabilization_SourceModel end +StabilizationSourceModel() = StabilizationSourceModel{Float64}() PlantSimEngine.inputs_(::StabilizationSourceModel) = NamedTuple() -PlantSimEngine.outputs_(::StabilizationSourceModel) = (signal=0.0,) +PlantSimEngine.outputs_(::StabilizationSourceModel{T}) where {T} = (signal=zero(T),) +# This real state declaration admits either numerical cell before the first +# step; its owned initial output remains the original Float64 zero. +PlantSimEngine.inputs_(::StabilizationSourceModel{Union{Float32,Float64}}) = + (signal=Required(Union{Float32,Float64}),) +PlantSimEngine.outputs_(::StabilizationSourceModel{Union{Float32,Float64}}) = (signal=0.0,) function PlantSimEngine.run!( ::StabilizationSourceModel, @@ -2038,8 +2044,10 @@ end original_view = simulation.compiled.status_views_by_target[(:source, ObjectId(:leaf_1))] original_status = only(model_objects(model; scale=:Leaf)).status - @test original_view.status === original_status @test original_view.canonical_status === original_status + @test keys(original_view.status) == keys(original_status) + @test all(name -> PlantSimEngine.refvalue(original_view.status, name) === + PlantSimEngine.refvalue(original_status, name), keys(original_status)) @test isempty(original_view.temporal_inputs) @test isempty(original_view.private_outputs) previous_runtime_revision = model.runtime_revision @@ -2185,6 +2193,8 @@ end end @testset "incremental Many source applications use the complete source set" begin + outside_status = Status(signal=10.0) + outside_reference = PlantSimEngine.refvalue(outside_status, :signal) model = CompositeModel( Object(:scene; scale=:Scene), Object(:plant; scale=:Plant, parent=:scene), @@ -2193,6 +2203,15 @@ end scale=:Leaf, kind=:produced, parent=:plant, + ), + # Genuine supplied data outside this consumer's Subtree remains in the + # scene and prepares the same supplied-data role as the newborn below. + Object( + :supplied_elsewhere; + scale=:Leaf, + kind=:supplied, + parent=:scene, + status=outside_status, ); applications=( ModelSpec( @@ -2227,7 +2246,14 @@ end carrier = binding.carrier @test plant.lagged_total == 1.0 @test binding.source_application_ids == [:source] - + @test binding.source_ids == ObjectId.([:leaf_1]) + @test !(ObjectId(:supplied_elsewhere) in binding.source_ids) + @test PlantSimEngine.refvalue(model_status(model, :supplied_elsewhere), :signal) === + outside_reference + @test model_status(model, :supplied_elsewhere).signal === 10.0 + + supplied_status = Status(signal=10.0) + supplied_reference = PlantSimEngine.refvalue(supplied_status, :signal) register_object!( model, Object( @@ -2235,7 +2261,7 @@ end scale=:Leaf, kind=:supplied, parent=:plant, - status=Status(signal=10.0), + status=supplied_status, ), ) continue!(simulation) @@ -2249,6 +2275,8 @@ end @test refreshed_binding.carrier === carrier @test refreshed_binding.source_ids == ObjectId.([:leaf_1, :leaf_2]) @test refreshed_binding.source_application_ids == [:source] + @test PlantSimEngine.refvalue(model_status(model, :leaf_2), :signal) === supplied_reference + @test parent(refreshed_binding.carrier)[2] === supplied_reference @test plant.lagged_total == 12.0 reparent_object!(model, :leaf_2, :scene) @@ -2260,6 +2288,10 @@ end continue!(simulation) @test only(Diagnostics.explain_bindings(model)).source_ids == [:leaf_1, :leaf_2] @test plant.lagged_total == 14.0 + @test !(ObjectId(:supplied_elsewhere) in refreshed_binding.source_ids) + @test PlantSimEngine.refvalue(model_status(model, :supplied_elsewhere), :signal) === + outside_reference + @test model_status(model, :supplied_elsewhere).signal === 10.0 end @testset "new consumers reuse an updated plant-wide Many carrier" begin @@ -2941,15 +2973,20 @@ end end @testset "a newborn payload family preserves unrelated groups and row owners" begin + source_model = StabilizationSourceModel{Union{Float32,Float64}}() model = CompositeModel( Object(:scene; scale=:Scene), Object(:leaf_1; scale=:Leaf, parent=:scene); applications=( - ModelSpec(StabilizationSourceModel(); name=:leaf_source, on=Many(scale=:Leaf)), + ModelSpec(source_model; name=:leaf_source, on=Many(scale=:Leaf)), ModelSpec(StabilizationSourceModel(); name=:scene_source, on=One(scale=:Scene)), ), ) simulation = run!(model; outputs=:none, performance=true) + # No Float32 execution target has been constructed or run in this scene. + @test all(target.status_view.status.signal isa Float64 + for group in simulation.execution_plan.groups for batch in group.batches + for target in batch.targets) old_leaf_group = only(group for group in simulation.execution_plan.groups if group.application.id == :leaf_source) old_scene_group = only(group for group in simulation.execution_plan.groups @@ -2961,8 +2998,10 @@ end old_leaf_location = PlantSimEngine.cohort_location( simulation.execution_plan.cohorts, :leaf_source, ObjectId(:leaf_1), ) + leaf_2_status = Status(signal=0.0f0) + leaf_2_reference = PlantSimEngine.refvalue(leaf_2_status, :signal) register_object!(model, Object( - :leaf_2; scale=:Leaf, parent=:scene, status=Status(signal=0.0f0), + :leaf_2; scale=:Leaf, parent=:scene, status=leaf_2_status, )) continue!(simulation) leaf_group = only(group for group in simulation.execution_plan.groups @@ -2981,6 +3020,7 @@ end ) === old_leaf_location @test model_object(model, :leaf_1).status.signal == 2.0 @test model_object(model, :leaf_2).status.signal === 1.0f0 + @test PlantSimEngine.refvalue(model_status(model, :leaf_2), :signal) === leaf_2_reference @test model_object(model, :scene).status.signal == 2.0 performance = Advanced.runtime_performance(simulation) @test performance.counts[:execution_targets_constructed] == 1 @@ -2991,8 +3031,10 @@ end # Its later view must remain reserved for its existing batch. later_float32_batch = last(leaf_group.batches) later_float32_target = only(later_float32_batch.targets) + leaf_0_status = Status(signal=0.0f0) + leaf_0_reference = PlantSimEngine.refvalue(leaf_0_status, :signal) register_object!(model, Object( - :leaf_0; scale=:Leaf, parent=:scene, status=Status(signal=0.0f0), + :leaf_0; scale=:Leaf, parent=:scene, status=leaf_0_status, )) continue!(simulation) recurring_group = only(group for group in simulation.execution_plan.groups @@ -3008,6 +3050,8 @@ end @test model_object(model, :leaf_0).status.signal === 1.0f0 @test model_object(model, :leaf_1).status.signal == 3.0 @test model_object(model, :leaf_2).status.signal === 2.0f0 + @test PlantSimEngine.refvalue(model_status(model, :leaf_0), :signal) === leaf_0_reference + @test PlantSimEngine.refvalue(model_status(model, :leaf_2), :signal) === leaf_2_reference @test model_object(model, :scene).status.signal == 3.0 performance = Advanced.runtime_performance(simulation) @test performance.counts[:execution_targets_constructed] == 2 diff --git a/test/test-model-call-context-cloning.jl b/test/test-model-call-context-cloning.jl index a9f5e87e9..a47148eb2 100644 --- a/test/test-model-call-context-cloning.jl +++ b/test/test-model-call-context-cloning.jl @@ -222,7 +222,14 @@ end @test inner_parent_capture[].calls !== data.parent.calls @test outer.child.execution_target === inner.child.execution_target @test outer.child.context_cache === inner.child.context_cache - @test outer.child.status === inner.child.status === model_status(data.model, :leaf) + official = model_status(data.model, :leaf) + @test outer.child.canonical_status === inner.child.canonical_status === official + @test outer.child.status === outer.child.execution_target.status_view.status + @test inner.child.status === inner.child.execution_target.status_view.status + @test keys(outer.child.status) == keys(inner.child.status) == keys(official) + @test all(name -> PSE.refvalue(outer.child.status, name) === + PSE.refvalue(inner.child.status, name) === PSE.refvalue(official, name), + keys(official)) @test outer.child.environment === trial @test inner.child.environment === inner_trial @test outer.child.publication_allowed && !inner.child.publication_allowed diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index 1043c3c77..2c9d3da67 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -257,11 +257,21 @@ end location = PSE.cohort_location(store,:controller,ObjectId(:root)) target = location.cohort.rows[location.row] reference = PSE.refvalue(model_status(data.model, 1), :value) - # A changed authored CS needs a fresh Simulation at the outer boundary. - # This host diagnostic exercises the canonical plan-refresh worker only. - deleteat!(data.model.applications, 1) - current = PSE.Advanced.refresh_bindings!(data.model;force=true) - environment = PSE.refresh_environment_bindings!(data.model,current) + # Removing an application prepares a new configuration through the + # existing authoring API. Preserve the genuine scientific cells while + # leaving the original model/header owners intact. This host diagnostic + # still exercises retirement of an UNVISITED owner in the same store. + ticks = PSE.refvalue(model_status(data.model, :root), :ticks) + changed_model = PSE.Authoring.apply_model_graph_edit(data.model, + PSE.Authoring.RemoveModelApplication(PSE.Authoring.GlobalApplicationRef(:controller)); + preserve=(reference, ticks)) + @test changed_model !== data.model + @test length(data.model.applications) == 2 + @test keytype(changed_model.registry.objects) === keytype(data.model.registry.objects) + @test PSE.refvalue(model_status(changed_model, 1), :value) === reference + @test PSE.refvalue(model_status(changed_model, :root), :ticks) === ticks + current = PSE.Advanced.refresh_bindings!(changed_model) + environment = PSE.refresh_environment_bindings!(changed_model,current) refreshed = PSE._refresh_model_execution_plan(previous,current,environment, simulation.temporal_streams,simulation.output_retention,simulation.constants) @test refreshed.plan.cohorts === store diff --git a/test/test-model-graph-view.jl b/test/test-model-graph-view.jl index 29a5bcb79..47a81e10d 100644 --- a/test/test-model-graph-view.jl +++ b/test/test-model-graph-view.jl @@ -1392,3 +1392,151 @@ end @test length(unique(edge["id"] for edge in target_edges)) == 2 @test Set(edge["target"] for edge in target_edges) == Set(object["id"] for object in view.objects) end + + +struct ModelGraphStatusEditObservedModel <: AbstractModelGraphSourceModel + input_reads::Base.RefValue{Int} + output_reads::Base.RefValue{Int} +end +function PlantSimEngine.inputs_(model::ModelGraphStatusEditObservedModel) + model.input_reads[] += 1 + return (driver=Required(Float64),) +end +function PlantSimEngine.outputs_(model::ModelGraphStatusEditObservedModel) + model.output_reads[] += 1 + return (signal=0.0,) +end + +struct ModelGraphStatusEditTransform{R} + calls::Base.RefValue{Int} + untouched_reference::R +end +function (transform::ModelGraphStatusEditTransform)(variable, value) + transform.calls[] += 1 + return value +end + +@testset "graph initial-data edits prepare one new namespace without replaying hooks" begin + process_model = ModelGraphStatusEditObservedModel(Ref(0), Ref(0)) + # Base.deepcopy consults its preservation map for these mutable observables, + # rather than for their immutable model container. + preserved_reads = (process_model.input_reads, process_model.output_reads) + first_status = Status(driver=1f0) + transform = ModelGraphStatusEditTransform(Ref(0), PlantSimEngine.refvalue(first_status, :driver)) + model = CompositeModel( + Object(:first; scale=:Leaf, status=first_status), + Object(:second; scale=:Leaf, status=Status(driver=2f0)); + applications=(ModelSpec(process_model; name=:source, on=Many(scale=:Leaf)),), + type_promotion=Dict(Float64 => Float32), status_transform=transform, + ) + preparation = model.scenario_plan_cache + reads = (process_model.input_reads[], process_model.output_reads[]) + conversions = transform.calls[] + original_statuses = Dict(id => model_status(model, id) for id in (:first, :second)) + original_references = Dict(id => PlantSimEngine.refvalue(status, :driver) + for (id, status) in original_statuses) + edited = apply_model_graph_edit(model, + SetModelObjectStatuses([:first, :second], :shared_value, 5.0); + preserve=preserved_reads) + @test edited !== model + @test model.scenario_plan_cache === preparation + @test (process_model.input_reads[], process_model.output_reads[]) == reads + @test transform.calls[] == conversions + @test edited.status_conversion.transform.calls[] == conversions + 2 + @test edited.scenario_plan_cache.owner === edited + @test PlantSimEngine.model_(only(edited.scenario_plan_cache.authored).spec) === process_model + @test PlantSimEngine.model_(only(edited.scenario_plan_cache.authored).spec).input_reads === + process_model.input_reads + @test PlantSimEngine.model_(only(edited.scenario_plan_cache.authored).spec).output_reads === + process_model.output_reads + @test PlantSimEngine.refvalue(model_status(edited, :first), :driver) === + edited.status_conversion.transform.untouched_reference + @test edited.registry.objects.catalog.status_manifest === edited.scenario_plan_cache.status_manifest + @test :shared_value in PlantSimEngine._status_schema_names( + edited.scenario_plan_cache.status_manifest.status_type) + @test !(:shared_value in PlantSimEngine._status_schema_names(preparation.status_manifest.status_type)) + for id in (:first, :second) + official = model_status(edited, id) + @test official.shared_value === 5f0 + @test official.driver === original_statuses[id].driver + @test PlantSimEngine.refvalue(official, :driver) !== original_references[id] + @test model_status(model, id) === original_statuses[id] + @test PlantSimEngine.refvalue(model_status(model, id), :driver) === original_references[id] + @test !hasproperty(model_status(model, id), :shared_value) + end + # Resolve the whole edit before conversion: a missing second target neither + # publishes a first replacement nor invokes an explicitly shared callback. + @test_throws ErrorException apply_model_graph_edit(model, + SetModelObjectStatuses([:first, :missing], :shared_value, 5.0); + preserve=(preserved_reads..., transform.calls)) + @test transform.calls[] == conversions + @test (process_model.input_reads[], process_model.output_reads[]) == reads + @test model.scenario_plan_cache === preparation + @test all(model_status(model, id) === original_statuses[id] && + PlantSimEngine.refvalue(model_status(model, id), :driver) === original_references[id] && + !hasproperty(model_status(model, id), :shared_value) for id in (:first, :second)) + + single = apply_model_graph_edit(model, SetModelObjectStatus(:first, :shared_value, 7.0); + preserve=preserved_reads) + @test model_status(single, :first).shared_value === 7f0 + @test !hasproperty(model_status(single, :second), :shared_value) + @test single.status_conversion.transform.calls[] == conversions + 1 + @test (process_model.input_reads[], process_model.output_reads[]) == reads +end + +@testset "graph initial-data reconstruction retains already mounted instance owners" begin + model = model_graph_override_fixture() + edited = apply_model_graph_edit(model, + SetModelObjectStatuses([:leaf_a, :leaf_b], :shared_value, 5)) + @test length(edited.instances) == length(model.instances) == 2 + @test length(edited.applications) == length(model.applications) == 2 + @test getproperty.(edited.instances, :name) == [:plant_a, :plant_b] + @test map(PlantSimEngine._model_edit_application_id, edited.applications) == + map(PlantSimEngine._model_edit_application_id, model.applications) + @test edited.instances[1].template === edited.instances[2].template + for instance in edited.instances + if instance.root isa Object + @test instance.root === PlantSimEngine._model_object(edited, instance.root.id) + end + end + @test all(model_status(edited, id).shared_value == 5 for id in (:leaf_a, :leaf_b)) + @test all(!hasproperty(model_status(model, id), :shared_value) for id in (:leaf_a, :leaf_b)) +end + + +import MultiScaleTreeGraph as ModelGraphMTG + +@testset "graph initial-data edits retain source-node round trips without reimport" begin + root = ModelGraphMTG.Node(1, ModelGraphMTG.NodeMTG(:/, :Scene, 1, 0), (note="scene",)) + leaf = ModelGraphMTG.Node(2, root, ModelGraphMTG.NodeMTG(:+, :Leaf, 1, 1), (note="leaf",)) + imports = Ref(0) + import_status = node -> begin + imports[] += 1 + ModelGraphMTG.symbol(node) === :Leaf ? Status(driver=1.0) : nothing + end + model = CompositeModel(root; status=import_status, + applications=(ModelSpec(ModelGraphSourceModel(); name=:source, on=Many(scale=:Leaf)),)) + before = imports[] + official = model_status(model, leaf) + reference = PlantSimEngine.refvalue(official, :driver) + edited = apply_model_graph_edit(model, SetModelObjectStatus(2, :shared_value, 5); + preserve=(import_status,)) + @test imports[] == before + @test edited.source_adapter !== model.source_adapter + @test length(edited.source_adapter.nodes_by_object_id) == 2 + @test length(edited.source_adapter.object_ids_by_node) == 2 + edited_leaf = source_node(edited, 2) + @test edited_leaf !== leaf + @test source_node(edited, model_status(edited, 2)) === edited_leaf + @test object_id(edited, edited_leaf) == ObjectId(2) + @test model_status(edited, edited_leaf) === model_status(edited, 2) + @test edited.source_adapter.root === source_node(edited, 1) + @test ModelGraphMTG.parent(edited_leaf) === source_node(edited, 1) + @test model_status(edited, edited_leaf).shared_value == 5 + @test edited_leaf[:note] == "leaf" + @test_throws ArgumentError object_id(edited, leaf) + @test source_node(model, 2) === leaf + @test model_status(model, leaf) === official + @test PlantSimEngine.refvalue(official, :driver) === reference + @test !hasproperty(official, :shared_value) +end diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl index e0bf3c443..e2f8122f6 100644 --- a/test/test-model-prepared-call-schemas.jl +++ b/test/test-model-prepared-call-schemas.jl @@ -52,7 +52,7 @@ end # All statuses below belong to real scenario objects. No kernel or callback is # executed to manufacture a status, a future organ, or an execution batch type. -function fixture(; leaves=true) +function fixture(; leaves=true, unselected_numeric=false) capture = Ref{Any}(nothing) contexts = Dict{Symbol,Any}() kernels = Dict(:root => 0, :middle => 0, :leaf => 0) @@ -64,6 +64,12 @@ function fixture(; leaves=true) Object(:middle_b; scale=:Branch, parent=:root, status=Status(visits=0, total=0.0)), ] + if unselected_numeric + # Real supplied numeric state, outside the root's call Subtree. It + # prepares the same Branch RAW role without teaching a call batch. + push!(objects, Object(:middle_outside; scale=:Branch, + status=Status(visits=0, total=0f0))) + end if leaves append!(objects, ( Object(:leaf_a; scale=:Leaf, parent=:middle_a, @@ -334,14 +340,22 @@ end @test history(ordinary.simulation) == history(prepared) end -@testset "pending prepared Many does not admit an unselected Status variant" begin - witness = fixture() +@testset "pending prepared Many rejects an unlearned prepared numeric view" begin + witness = fixture(; unselected_numeric=true) learned = observed_schemas(witness.simulation) - data = fixture() - # A real registered object, never a fabricated Type witness. The existing - # Middle kernel is unchanged; its extra canonical field is outside learned. + data = fixture(; unselected_numeric=true) + outside = model_status(data.model, :middle_outside) + @test outside.total === 0f0 + pending_before_birth = call_targets(root_target(data.simulation).context, :middle) + @test !(ObjectId(:middle_outside) in pending_before_birth.binding.callee_object_ids) + @test !PSE._call_execution_batches_materialized(pending_before_birth) + # Same namespace, same supplied Branch role, and a real Ref32 already + # prepared outside the root. Its kernel view was not in learned Middle64. + supplied = Status(visits=0, total=0f0) + supplied_reference = PSE.refvalue(supplied, :total) register_object!(data.model, Object(:middle_z_extra; scale=:Branch, parent=:root, - status=Status(visits=0, total=0.0, unselected_marker=0))) + status=supplied)) + @test PSE.refvalue(model_status(data.model, :middle_z_extra), :total) === supplied_reference fresh = run!(data.model; steps=0, outputs=:all) # Check owner compatibility before activation: only the real Status variant # is outside the learned target schema, not another owner/ABI fixture. @@ -362,6 +376,8 @@ end run_call!(selected; publish=false) @test data.kernels == Dict(:root => 1, :middle => 1, :leaf => 1) @test model_status(data.model, :middle_z_extra).visits == 0 + @test model_status(data.model, :middle_z_extra).total === 0f0 + @test outside.visits == 0 && outside.total === 0f0 @test !PSE._call_execution_batches_materialized(full) @test PSE._cached_call_execution_batches(full) === nothing state, random_state, cells = scientific_state(data.model), rng_probe(data.rng), status_cells(data.model) @@ -370,6 +386,7 @@ end @test PSE._cached_call_execution_batches(full) === nothing @test isempty(full.execution_batches) # No partial vector is published on rejection. @test scientific_state(data.model) == state + @test PSE.refvalue(model_status(data.model, :middle_z_extra), :total) === supplied_reference @test rng_probe(data.rng) == random_state assert_same_cells(data.model, cells) end diff --git a/test/test-model-prepared-missing-future-schema.jl b/test/test-model-prepared-missing-future-schema.jl index a2c6e0e94..10a2fb383 100644 --- a/test/test-model-prepared-missing-future-schema.jl +++ b/test/test-model-prepared-missing-future-schema.jl @@ -37,25 +37,30 @@ end cells = Fixtures.status_cells(data.model) science = Fixtures.scientific_state(data.model) random_state = Fixtures.rng_probe(data.rng) - # An output declaration is not a supplied-reference storage constraint. - # This is a real registered organ with a Float32 Ref, not a dummy witness. - newborn = register_object!(data.model,Object(:leaf_bad;scale=:Leaf, - parent=:middle_a,status=Status(visits=0,value=0f0,payload=zeros(2)))) + # The configured output and observed raw statuses prepare Ref64. A new + # organ carrying an unprepared Ref32 must be rejected before registration. + newborn = Object(:leaf_bad;scale=:Leaf, + parent=:middle_a,status=Status(visits=0,value=0f0,payload=zeros(2))) @test newborn.status.value isa Float32 selected = call_targets(data.capture[],:middle;objects=(:middle_a,)) @test selected.batch_schema isa PSE.PreparedExecutionBatchSchema middle = only(only(PSE._materialize_call_execution_batches!(selected)).targets) - # Selecting Middle does not demand its Leaf Many. Reject the Float32 Ref - # only when this test explicitly requests that descendant membership. + # Save the real descendant metadata as well as the selected parent view. leaves = call_targets(middle.context,:leaf) @test leaves.batch_schema isa PSE.PreparedExecutionBatchSchema - # Parent selection is now legal. Save the cohort baseline immediately before - # the descendant demand that must reject, including its live selected views. + # Save the cohort baseline before the rejected registration, including all + # live selected views. No registry, cohort, state or RNG may partly change. store = simulation.execution_plan.cohorts locations = copy(store.locations) payloads = Dict(key=>PSE._execution_cohort_target(location) for (key,location) in locations) views = recorded_views(simulation, selected) - @test_throws "prepared execution schema" PSE._materialize_call_execution_batches!(leaves) + revision = PSE.Advanced.model_revision(data.model) + step = current_step(simulation) + @test_throws "prepared object configuration/raw family" register_object!(data.model, newborn) + @test !haskey(data.model.registry.objects, ObjectId(:leaf_bad)) + @test PSE.Advanced.model_revision(data.model) == revision + @test current_step(simulation) == step + @test leaves.batch_schema isa PSE.PreparedExecutionBatchSchema @test Set(keys(store.locations)) == Set(keys(locations)) @test all(store.locations[key] === location for (key,location) in locations) @test all(PSE._execution_cohort_target(store.locations[key]) === target for (key,target) in payloads) diff --git a/test/test-model-reusable-call-targets.jl b/test/test-model-reusable-call-targets.jl index 19f8a1ba9..470a308c3 100644 --- a/test/test-model-reusable-call-targets.jl +++ b/test/test-model-reusable-call-targets.jl @@ -82,6 +82,16 @@ ids(targets) = getproperty.(targets, :object_id) rows(simulation, object=:leaf_a) = sort!( collect_outputs(simulation, object, :seen; sink=nothing); by=row -> row.timestep) +function check_status_references(target, official) + @test target.canonical_status === official + @test target.status === target.execution_target.status_view.status + @test keys(target.status) == keys(official) + for name in keys(official) + @test PSE.refvalue(target.status, name) === PSE.refvalue(official, name) + end + return nothing +end + @testset "borrowed target vectors preserve concrete types and shared status" begin for S in (Float32, Float64), heterogeneous in (false, true) fixture = scene(S; heterogeneous) @@ -105,7 +115,7 @@ rows(simulation, object=:leaf_a) = sort!( end escaped[] = first(targets) for target in targets - @test target.status === model_status(fixture.model, target.object_id) + check_status_references(target, model_status(fixture.model, target.object_id)) @test target.status.driver === S(2.5) @test PSE.refvalue(target.status, :driver) === PSE.refvalue(model_status(fixture.model, :owner), :shared_driver) @@ -332,7 +342,7 @@ end @test isconcretetype(eltype(targets)) newborn = only(targets) @test newborn.object_id == ObjectId(:newborn) - @test newborn.status === model_status(fixture.model, :newborn) + check_status_references(newborn, model_status(fixture.model, :newborn)) @test eltype(newborn.status.coefficients) === S run_call!(newborn; sampled_environment=(T=30.0,)) @test newborn.status.seen === S(45.5) @@ -367,7 +377,7 @@ end with_call_targets(fixture.capture[], :empty) do targets @test isempty(targets) end - @test middle.status === model_status(fixture.model, :middle) + check_status_references(middle, model_status(fixture.model, :middle)) end end @@ -396,7 +406,7 @@ end @test targets[1].model isa Leaf @test targets[2].model isa AlternateLeaf for target in targets - @test target.status === model_status(model, target.object_id) + check_status_references(target, model_status(model, target.object_id)) @test target.status.driver isa S run_call!(target; publish=true) end diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl index 9e2f14d17..cd18c3019 100644 --- a/test/test-model-scenario-authoring.jl +++ b/test/test-model-scenario-authoring.jl @@ -277,8 +277,14 @@ PSE.run!(::BrokenDeclarations, status, environment, constants, context) = (statu # The failed output hook supplied no schema at construction. Fixing it # requires an actual prepared model, not in-place discovery of a new S. original_preparation = model.scenario_plan_cache + original_status = model_status(model, :root) @test_throws ArgumentError PSE.Advanced.refresh_bindings!(model; force=true) - @test model.scenario_plan_cache === original_preparation + rejected = model.scenario_plan_cache + @test rejected !== original_preparation + @test rejected.status_manifest isa PSE.ScenarioPreparationFailure + @test rejected.status_manifest.phase === :status_manifest + @test model.bindings_dirty + @test model_status(model, :root) === original_status model = CompositeModel(Object(:root; scale=:Scene); applications=Tuple(model.applications), environment=model.environment) @test isnothing(model.scenario_plan_cache.failure) diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 03f63b111..c0e02197f 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -266,10 +266,20 @@ end end history = copy(outputs(simulation)[(:paired_consumer, ObjectId(:scene), :total)]) # The first input's Ref32 is admitted. The second has neither the configured - # Ref32 nor Ref64 type, so no existing private snapshot may be extended. - register_object!(model, Object(:b; scale=:Leaf, parent=:scene, - status=Status(a=10f0, b=big"20.0"))) - @test_throws "outside its prepared Many family" step!(simulation) + # Ref32 nor Ref64 type, so admission must reject the whole object before + # registration or extension of any existing private snapshot. + revision = PSE.Advanced.model_revision(model) + bindings = simulation.compiled + step = current_step(simulation) + newborn = Object(:b; scale=:Leaf, parent=:scene, + status=Status(a=10f0, b=big"20.0")) + @test_throws "prepared object configuration/raw family" register_object!(model, newborn) + @test !haskey(model.registry.objects, ObjectId(:b)) + @test PSE.Advanced.model_revision(model) == revision + @test simulation.compiled === bindings + @test current_step(simulation) == step + @test newborn.status.a === 10f0 + @test newborn.status.b == big"20.0" for (temporal, saved) in zip(temporal_inputs, before) @test temporal.initial == saved.initial @test collect(temporal.reference[]) == saved.values @@ -284,7 +294,7 @@ end module PreparedPublicationChecks using Dates, Random, Test, PlantSimEngine const PSE = PlantSimEngine -import ..TemporalInitialTypingChecks: AbstractTyped_Initial_SourceModel, Consumer +import ..TemporalInitialTypingChecks: AbstractTyped_Initial_SourceModel, AbstractTyped_Initial_ConsumerModel, Consumer struct PublicationSource{T,R} <: AbstractTyped_Initial_SourceModel initial::T rng::R @@ -296,16 +306,24 @@ function PSE.run!(model::PublicationSource, status, environment, constants, cont return nothing end +# This fixture declares the future Leaf's temporal seed even before any Leaf +# exists. Raw values observed on Scene alone do not declare a Leaf family. +struct PublicationConsumer <: AbstractTyped_Initial_ConsumerModel end +PSE.inputs_(::PublicationConsumer) = (signals=Default(Float64[]),) +PSE.outputs_(::PublicationConsumer) = PSE.outputs_(Consumer{Float64}()) +PSE.run!(::PublicationConsumer, status, environment, constants, context) = + PSE.run!(Consumer{Float64}(), status, environment, constants, context) + # A model-owned RNG and an unconsumed output distinguish the :none and :all # publication shapes while keeping both future applications initially empty. function scene(; leaf=false, outputs=:none) rng = Xoshiro(917) objects = Object[Object(:scene; scale=:Scene, status=Status(signals=Float64[]))] leaf && push!(objects, Object(:leaf; scale=:Leaf, parent=:scene, - status=Status(signal=2.0, visits=0, signals=Float64[]))) + status=Status(signal=2.0, visits=0))) model = CompositeModel(objects...; applications=( ModelSpec(PublicationSource(0.0, rng); name=:source, on=Many(scale=:Leaf)), - ModelSpec(Consumer{Float64}(); name=:consumer, on=Many(scale=:Leaf), + ModelSpec(PublicationConsumer(); name=:consumer, on=Many(scale=:Leaf), inputs=(PreviousTimeStep(:signals) => Many(scale=:Leaf, within=SceneScope(), application=:source, var=:signal),)), ), environment=(duration=Hour(1),)) @@ -372,7 +390,7 @@ function check_initially_empty_publication() assert_parity(ordinary, candidate) for data in (ordinary, candidate) register_object!(data.model, Object(:newborn; scale=:Leaf, parent=:scene, - status=Status(signal=7.0, visits=0, signals=Float64[]))) + status=Status(signal=7.0, visits=0))) end for _ in 1:3 step!(ordinary.simulation) @@ -409,7 +427,7 @@ function check_initially_empty_publication() for (data, old_history) in zip((ordinary, candidate), retained_histories) @test all(history(data)[key] == values for (key, values) in old_history) register_object!(data.model, Object(:regrown; scale=:Leaf, parent=:scene, - status=Status(signal=11.0, visits=0, signals=Float64[]))) + status=Status(signal=11.0, visits=0))) step!(data.simulation) end assert_parity(ordinary, candidate) diff --git a/test/test-selector-query-scope-append.jl b/test/test-selector-query-scope-append.jl index 4f42280ab..38298e0b4 100644 --- a/test/test-selector-query-scope-append.jl +++ b/test/test-selector-query-scope-append.jl @@ -84,12 +84,32 @@ end data = append_scene(SelfPlant()) reparent_object!(data.model, :consumer, :scene) # no current Plant anchor register_object!(data.model, Object(30; scale=:Branch, parent=:scene)) + # A missing consumer anchor grants no data rights. The real Leaf outside + # its original Plant supplies the matching no-route RAW family for Ref32, + # while a new Ref64 remains rejected before any registration is published. + rejected = Object(31; scale=:Leaf, parent=:scene, status=Status(x=31.0)) + supplied = rejected.status + children = copy(model_object(data.model, :scene).children) + source_owners = copy(data.model.status_source_owners) + source_ids = copy(data.model.status_source_identities) + object_count = length(data.model.registry.objects) + carrier = input_carrier(data.binding) + references = Tuple(parent(carrier)) + @test_throws ArgumentError register_object!(data.model, rejected) + @test length(data.model.registry.objects) == object_count + @test !haskey(data.model.registry.objects, ObjectId(31)) + @test rejected.status === supplied + @test model_object(data.model, :scene).children == children + @test data.model.status_source_owners == source_owners + @test data.model.status_source_identities == source_ids @test append_selected!(data, Int[]) @test append_selected!(data, [30]) # a rejected label must not resolve scope @test data.binding.source_ids == ObjectId.([1, 2]) add_leaf!(data.model, 31, :scene) @test_throws "No `scale=:Plant` ancestor" append_selected!(data, [31]) @test data.binding.source_ids == ObjectId.([1, 2]) + @test input_carrier(data.binding) === carrier + @test all(current === previous for (current, previous) in zip(parent(carrier), references)) related = append_scene(SelfPlant(); relation=:descendants) reparent_object!(related.model, :consumer, :scene) From eeb829a4e4aba7168e9945d439627a42eeb31435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 16:53:49 +0100 Subject: [PATCH 154/324] Compile the configuration authored by CompositeModel Remove compile/refresh overloads that accept another ModelSpec set, and remove their parallel private preparation helpers. Keep fresh explicit compilation snapshots and compatible force refreshes owned by the same model. Configure alternate scenarios through independent CompositeModel constructors and document the single configuration entry point. Targeted validation: whole unified API passed 735 checks; environment-index passed 558 after correcting its full-discovery oracle; global-environment/authored plans passed 785; distributed routes/scenario authoring passed 195. Owner (71) and environment binding (739) completed without errors inside the earlier mixed run, whose two environment-index assertion failures remain recorded separately. Qualification remains incomplete: the helpers run was cancelled at 1203.7 seconds with 1073 terminal passes and only binding-index completed. The first ten input-plan metadata testsets completed, but its final 36-application cold compilation stress case did not. Preserve that cancellation and missing finally maps; this checkpoint is not a globally green suite, full native/scientific parity or 4160-day performance qualification. --- docs/src/API/API_public.md | 9 +- src/composite_model/compilation.jl | 94 ++--------- src/visualization/model_graph_editor_api.jl | 2 +- test/test-model-authored-call-plans.jl | 19 ++- test/test-model-authored-port-inventory.jl | 4 +- test/test-model-binding-index-identities.jl | 4 +- .../test-model-distributed-route-ownership.jl | 2 +- ...test-model-environment-binding-identity.jl | 101 +++++++---- ...test-model-environment-index-identities.jl | 124 +++++++++++--- ...-model-global-environment-sample-schema.jl | 31 ++-- test/test-model-input-plan-output-metadata.jl | 6 +- test/test-model-prepared-authoring-owner.jl | 21 ++- test/test-model-scenario-authoring.jl | 4 +- test/test-unified-model-object-api.jl | 159 ++++++++---------- 14 files changed, 314 insertions(+), 266 deletions(-) diff --git a/docs/src/API/API_public.md b/docs/src/API/API_public.md index 954b98a59..69569b281 100644 --- a/docs/src/API/API_public.md +++ b/docs/src/API/API_public.md @@ -437,8 +437,13 @@ ordinary simulations, use `Diagnostics.explain_*` with a `CompositeModel` to inspect the setup. Examples include `Advanced.compile_composite_model`, `Advanced.refresh_bindings!`, and -the `Advanced.CompiledCompositeModel` family. These qualified APIs may evolve more -quickly than the default modeling interface. +the `Advanced.CompiledCompositeModel` family. Configure applications and their +connections in the `CompositeModel` constructor, then call +`Advanced.compile_composite_model(model)` or `Advanced.refresh_bindings!(model)`. +`force=true` refreshes declarations of the configuration already held by the +model, subject to its prepared Status schema. Construct another `CompositeModel` +for a different prepared schema. These qualified APIs may evolve more quickly +than the default modeling interface. ## Index diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1ba314962..476e6bcb3 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -856,9 +856,9 @@ function _first_authored_program_failure(program::AuthoredScenarioProgram) return nothing end -function _prepare_authored_scenario(model::CompositeModel, raw_specs; +function _prepare_authored_scenario(model::CompositeModel; raw_families=_prepared_raw_status_families(model)) - source_specs = Tuple(raw_specs) + source_specs = Tuple(model.applications) # Capture one declaration result per application. Invalid authoring does # not hide later valid applications from a read-only diagnostic report. counts = Dict{Symbol,Int}() @@ -1019,7 +1019,7 @@ function _scenario_preparation(model::CompositeModel; force::Bool=false) preparation = model.scenario_plan_cache if force || isnothing(preparation) || !_authored_specs_match(preparation, model) - candidate = _prepare_authored_scenario(model, model.applications) + candidate = _prepare_authored_scenario(model) if isnothing(candidate.failure) && model.registry.objects.catalog isa ClosedObjectFamilyCatalog # A rejected logical route can remove alias metadata from an @@ -1075,13 +1075,6 @@ function _authored_application_recipes(preparation::ScenarioPreparation) return preparation.authored end -function _scenario_preparation(model::CompositeModel, raw_specs) - if _authored_specs_match(model.applications, raw_specs) - return _scenario_preparation(model) - end - return _prepare_authored_scenario(model, raw_specs) -end - # The snapshot owns its target lists. Runtime application membership can # change during growth, so each binding compilation takes a private copy. struct PreparedScenario{P,I<:ObjectId} @@ -2140,17 +2133,15 @@ end # genuine preparation, then gives the shared worker a resolved snapshot only # when the existing lifecycle metadata cannot be extended. function refresh_bindings!( - model::CompositeModel, - specs=model.applications; + model::CompositeModel; force::Bool=false, performance=nothing, ) - return _refresh_bindings!(model, specs; force, performance) + return _refresh_bindings!(model; force, performance) end function _refresh_bindings!( - model::CompositeModel, - specs=model.applications; + model::CompositeModel; force::Bool=false, performance=nothing, input_binding_storage=nothing, @@ -2160,10 +2151,6 @@ function _refresh_bindings!( throw(ArgumentError("This model has no prepared canonical Status registry. " * "Fix the authoring declarations and construct a new CompositeModel.")) end - if specs !== model.applications - raw_specs = specs isa Tuple ? specs : specs isa AbstractVector ? Tuple(specs) : (specs,) - return _compile_scene(model, raw_specs; performance, input_binding_storage, status_view_schema) - end rebuild = force || !isnothing(input_binding_storage) || !isnothing(status_view_schema) preparation = _scenario_preparation(model; force) _validate_authored_scenario(preparation) @@ -2608,42 +2595,18 @@ function _index_model_call_bindings(bindings::AbstractVector{B}, plans_by_applic end """ - compile_composite_model(model[, applications...]) + compile_composite_model(model::CompositeModel) -Compile model applications, selectors, value bindings, hard calls, writer -ordering, and schedules into the single Composite Model/Object runtime representation. -Most callers can use [`run!`](@ref) directly, which compiles as needed. +Compile the applications configured on `model`, including selectors, value +bindings, hard calls, writer ordering and schedules. Configure applications +in the `CompositeModel` constructor. Most callers can use `run!` directly, +which uses the same prepared scenario. """ function compile_composite_model(model::CompositeModel; performance=nothing) - return compile_composite_model( - model, - model.applications; - performance=performance, - ) -end - -function compile_composite_model( - model::CompositeModel, - specs::Tuple; - performance=nothing, -) - return _compile_scene(model, specs; performance=performance) -end - -function compile_composite_model( - model::CompositeModel, - specs::AbstractVector; - performance=nothing, -) - return _compile_scene(model, Tuple(specs); performance=performance) -end - -function compile_composite_model( - model::CompositeModel, - specs...; - performance=nothing, -) - return _compile_scene(model, specs; performance=performance) + timeline = _model_timeline(model) + preparation = _scenario_preparation(model) + plan, applications = _resolve_prepared_scenario(model, preparation, timeline; performance) + return _compile_scene(model, plan, applications; performance) end function _model_timeline(model::CompositeModel) @@ -2671,16 +2634,6 @@ function _compile_resolved_scenario_plan( ) end -function _build_scenario_plan( - model::CompositeModel, - raw_specs, - timeline; - performance=nothing, -) - preparation = _scenario_preparation(model, raw_specs) - return _resolve_prepared_scenario(model, preparation, timeline; performance) -end - function _resolve_prepared_scenario( model::CompositeModel, preparation::ScenarioPreparation, timeline; performance=nothing, @@ -2746,19 +2699,6 @@ function _prepare_scenario_plan( return prepared end -function _compile_scene( - model::CompositeModel, - raw_specs; - validate_required_inputs::Bool=true, - performance=nothing, - input_binding_storage=nothing, - status_view_schema=nothing, -) - scenario_plan, applications = _build_scenario_plan(model, raw_specs, _model_timeline(model); performance) - return _compile_scene(model, scenario_plan, applications; - validate_required_inputs, performance, input_binding_storage, status_view_schema) -end - function _compile_scene(model::CompositeModel, prepared::PreparedScenario; kwargs...) applications = _scenario_applications(prepared, keytype(model.registry.objects)) return _compile_scene(model, prepared.plan, applications; kwargs...) @@ -5642,8 +5582,8 @@ function _explain_initialization(model, applications, input_bindings, return rows end -function _compile_model_applications(model::CompositeModel, raw_specs, timeline) - recipes = _authored_application_recipes(_scenario_preparation(model, raw_specs)) +function _compile_model_applications(model::CompositeModel, timeline) + recipes = _authored_application_recipes(_scenario_preparation(model)) return _resolve_application_recipes(model, recipes, timeline) end diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index f557e7318..2ffca5fab 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -316,7 +316,7 @@ function apply_model_graph_edit( _finalize_authored_scenario(candidate, preparation.source_specs, preparation.authored, nothing) else - _prepare_authored_scenario(candidate, candidate.applications; raw_families=nothing) + _prepare_authored_scenario(candidate; raw_families=nothing) end candidate.scenario_plan_cache = final_preparation return _install_prepared_canonical_registry(candidate, final_preparation) diff --git a/test/test-model-authored-call-plans.jl b/test/test-model-authored-call-plans.jl index b8d8986c5..f2f89427c 100644 --- a/test/test-model-authored-call-plans.jl +++ b/test/test-model-authored-call-plans.jl @@ -66,8 +66,7 @@ end @test authored.potential_callee_application_ids == (:leaf,) @test isempty(preparation.authored[2].call_plans) @test isnothing(preparation.failure) - applications = PSE._compile_model_applications(data.model, Tuple(data.model.applications), - PSE._model_timeline(data.model)) + applications = PSE._compile_model_applications(data.model, PSE._model_timeline(data.model)) @test applications[1].call_plans === recipe.call_plans @test_throws "No instance or object ID" PSE._compile_model_call_plans(data.model, applications) @test data.dependencies[] == data.normalized_count @@ -107,14 +106,24 @@ end PSE._compile_model_call_plans(data.model, simulation.compiled.applications) @test data.dependencies[] == data.normalized_count - # A compiler call with another explicit spec set must use that set's - # prepared declarations, never the model's default preparation cache. + # A different authored configuration belongs to a fresh CompositeModel; + # compiling it must not replay declarations or replace this model's cache. alternate_driver = ModelSpec(Driver(data.dependencies); name=:alternate_driver, on=One(id=:scene), calls=(leaf=One(Scope(ObjectId(:future_root)); scale=:Leaf, application=:alternate_leaf),)) alternate_leaf = ModelSpec(Leaf(); name=:alternate_leaf, on=Many(scale=:Leaf)) before_compile = data.dependencies[] - alternate = PSE.compile_composite_model(data.model, (alternate_driver, alternate_leaf)) + alternate_model = CompositeModel( + Object(:scene; scale=:Scene, status=Status(seen=0f0, drivers=0)), + Object(:future_root; scale=:Plant, parent=:scene), + Object(:leaf; scale=:Leaf, parent=:future_root, status=Status(value=3f0, calls=0)); + applications=(alternate_driver, alternate_leaf), environment=data.model.environment) + @test data.dependencies[] == before_compile + alternate = PSE.compile_composite_model(alternate_model) + @test alternate.model === alternate_model + @test alternate_model !== data.model + @test all(model_object(alternate_model, id) !== model_object(data.model, id) + for id in (:scene, :future_root, :leaf)) @test only(alternate.scenario_plan.call_plans).application_id === :alternate_driver @test only(alternate.scenario_plan.call_plans).potential_callee_application_ids == (:alternate_leaf,) @test data.dependencies[] == before_compile diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index 8e6ceba9a..c05d8c310 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -192,7 +192,7 @@ end end # Compiler-only preparation must not replay any metadata getter. before_a, before_b = a.counter[], b.counter[] - applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) PSE._resolve_model_input_plans(model, PSE._scenario_preparation(model), applications, destinations) PSE._compile_environment_application_plans(model, applications, @@ -440,7 +440,7 @@ end environment=Environment(sources=NamedTuple())),)) @test counter[] == 1 @test isnothing(model.scenario_plan_cache.failure) - applications = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) @test counter[] == 1 # empty remap must not demand failed names early destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) @test_throws message PSE._resolve_model_input_plans(model, PSE._scenario_preparation(model), applications, destinations) diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index c463b2374..a0860173f 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -586,7 +586,7 @@ end prepared = PSE._prepare_scenario_plan(model) copied = PSE._scenario_applications(prepared, I) @test eltype(copied) === eltype(simulation.compiled.applications) - authored = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + authored = PSE._compile_model_applications(model, PSE._model_timeline(model)) @test eltype(authored) === eltype(copied) for application in simulation.compiled.applications ids = application.target_ids @@ -636,7 +636,7 @@ end applications=()) closed && (model = close_registry(model)) I = keytype(model.registry.objects) - authored = PSE._compile_model_applications(model, model.applications, PSE._model_timeline(model)) + authored = PSE._compile_model_applications(model, PSE._model_timeline(model)) prepared = PSE._prepare_scenario_plan(model) copied = PSE._scenario_applications(prepared, I) @test isempty(authored) && isempty(copied) diff --git a/test/test-model-distributed-route-ownership.jl b/test/test-model-distributed-route-ownership.jl index 053615e1d..3a68748a7 100644 --- a/test/test-model-distributed-route-ownership.jl +++ b/test/test-model-distributed-route-ownership.jl @@ -103,7 +103,7 @@ end @test layout.coverage === :exact model = CompositeModel(Object(:scene; scale=:Scene), Object(:leaf; scale=:Leaf); applications=(spec,)) - applications = PSE._compile_model_applications(model, model.applications, + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) destinations = PSE._resolve_model_output_destination_plans(model, PSE._scenario_preparation(model), applications) plan = only(destinations.plans) diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index be0058970..436e1472b 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -54,22 +54,33 @@ function PSE.run!(::Leaf, status, environment, constants, context) return nothing end -function fixture(::Type{T}; steps=1, environment_schema=PSE.EnvironmentBindingSchema()) where {T} +function fixture(::Type{T}; steps=1, environment_schema=PSE.EnvironmentBindingSchema(), + only_application=nothing, backend=nothing, moved_cell=:a) where {T} capture = Ref{Any}() - backend = Backend(Dict(:a => T(10), :b => T(20)), 0) + backend = isnothing(backend) ? Backend(Dict(:a => T(10), :b => T(20)), 0) : backend + specs = ( + ModelSpec(Owner(capture); name=:owner, on=One(id=:scene), + calls=(leaves=Many(kind=:manual, within=Subtree(), application=:manual_probe),)), + ModelSpec(Leaf(zero(T)); name=:scheduled_probe, on=Many(kind=:scheduled), + environment=Environment(provider=:shell_probe)), + ModelSpec(Leaf(zero(T)); name=:manual_probe, on=Many(kind=:manual), + environment=Environment(provider=:shell_probe)), + ) + selected_specs = if isnothing(only_application) + specs + elseif only_application === :scheduled_probe + (specs[2],) + elseif only_application === :manual_probe + (specs[3],) + else + throw(ArgumentError("Unknown fixture application.")) + end model = CompositeModel( Object(:scene; scale=:Scene), Object(:scheduled_keep; scale=:Leaf, kind=:scheduled, parent=:scene, geometry=(cell=:a,)), - Object(:scheduled_move; scale=:Leaf, kind=:scheduled, parent=:scene, geometry=(cell=:a,)), + Object(:scheduled_move; scale=:Leaf, kind=:scheduled, parent=:scene, geometry=(cell=moved_cell,)), Object(:manual; scale=:Leaf, kind=:manual, parent=:scene, geometry=(cell=:a,)); - applications=( - ModelSpec(Owner(capture); name=:owner, on=One(id=:scene), - calls=(leaves=Many(kind=:manual, within=Subtree(), application=:manual_probe),)), - ModelSpec(Leaf(zero(T)); name=:scheduled_probe, on=Many(kind=:scheduled), - environment=Environment(provider=:shell_probe)), - ModelSpec(Leaf(zero(T)); name=:manual_probe, on=Many(kind=:manual), - environment=Environment(provider=:shell_probe)), - ), environment=backend) + applications=selected_specs, environment=backend) simulation = if PSE._is_open_environment_schema(environment_schema) run!(model; steps, outputs=:all) else @@ -77,9 +88,11 @@ function fixture(::Type{T}; steps=1, environment_schema=PSE.EnvironmentBindingSc constants=PSE.Constants(), environment_schema) PSE._continue_scene!(prepared, steps) end - batch = only(batch for batch in simulation.execution_plan.batches - if batch.application.id == :scheduled_probe) - kept = only(target for target in batch.targets if target.object_id == ObjectId(:scheduled_keep)) + batch = only_application === :manual_probe ? nothing : + only(batch for batch in simulation.execution_plan.batches + if batch.application.id == :scheduled_probe) + kept = isnothing(batch) ? nothing : + only(target for target in batch.targets if target.object_id == ObjectId(:scheduled_keep)) return (; model, simulation, capture, backend, batch, kept) end @@ -316,22 +329,25 @@ end @test same_schema @test current.by_target[(:scheduled_probe, ObjectId(:scheduled_move))].handle.cell === :b - # Advanced compilation may replace model metadata before this Simulation - # resumes. The current cache remains authoritative even for another set of - # applications; the common refresh algorithm reconciles it when requested. - alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( - ModelSpec(Leaf(0.0f0); name=:scheduled_probe, on=Many(kind=:scheduled), - environment=Environment(provider=:shell_probe)), - )) - alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) - current = PSE._current_environment_binding_owner(data.model, prepared) + # A subset is a separate constructor-owned configuration. Preparing it + # with the same backend cannot publish a cache into this full model. + subset = fixture(Float32; steps=0, environment_schema=schema, + only_application=:scheduled_probe, backend=data.backend, moved_cell=:b) + alternate_compiled = subset.simulation.compiled + alternate = subset.simulation.environment_bindings + current = PSE._current_environment_binding_owner(subset.model, alternate) + @test alternate_compiled.model === subset.model + @test subset.model !== data.model + @test data.model.environment_binding_cache === full + @test all(model_object(subset.model, id) !== model_object(data.model, id) + for id in (:scene, :scheduled_keep, :scheduled_move, :manual)) is_current_alternate = current === alternate && current !== full @test is_current_alternate @test length(current.bindings) == 2 @test current.compiled_applications === alternate_compiled.applications @test current.environment_schema === schema samples = data.backend.samples - restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, current) + restored = PSE._refresh_environment_bindings!(data.model, simulation.compiled, full) is_restored = restored === PSE.compiled_environment_bindings(data.model) @test is_restored @test restored.compiled_applications === simulation.compiled.applications @@ -404,15 +420,19 @@ end [(1.0, 10.0f0), (2.0, 20.0f0)] end -@testset "a pending move reconciles an authoritative Advanced subset cache" begin +@testset "a pending move stays correct beside an independent subset configuration" begin for schema in (PSE.EnvironmentBindingSchema(), fixture_environment_schema(Float32)) data = fixture(Float32; environment_schema=schema) simulation = data.simulation - alternate_compiled = PSE.Advanced.compile_composite_model(data.model, ( - ModelSpec(Leaf(0.0f0); name=:manual_probe, on=Many(kind=:manual), - environment=Environment(provider=:shell_probe)), - )) - alternate = PSE.Advanced.refresh_environment_bindings!(data.model, alternate_compiled) + subset = fixture(Float32; steps=0, environment_schema=schema, + only_application=:manual_probe, backend=data.backend) + alternate_compiled = subset.simulation.compiled + alternate = subset.simulation.environment_bindings + @test alternate_compiled.model === subset.model + @test data.model.environment_binding_cache === simulation.environment_bindings + @test subset.model.environment_binding_cache === alternate + @test all(model_object(subset.model, id) !== model_object(data.model, id) + for id in (:scene, :scheduled_keep, :scheduled_move, :manual)) @test alternate.environment_schema === schema @test length(alternate.bindings) == 1 @test !haskey(alternate.application_plans_by_id, :scheduled_probe) @@ -669,7 +689,8 @@ end simulation = prepare_policy(a; schema=PSE._collecting_environment_binding_schema()) first_types = policy_types(simulation) first_schema = PSE._freeze_environment_binding_schema(simulation.environment_bindings.environment_schema) - alternate = PSE.Advanced.compile_composite_model(a.model, (policy_spec(:U; active=false),)) + a.model.applications[1] = policy_spec(:U; active=false) + alternate = PSE.Advanced.refresh_bindings!(a.model; force=true) future = PSE.Advanced.refresh_environment_bindings!(a.model, alternate; force=true) @test isempty(future.bindings) @test PSE._is_collecting_environment_schema(future.environment_schema) @@ -677,14 +698,16 @@ end @test first_types != future_types b = policy_model(:T; active=false) fixed = prepare_policy(b; schema=first_schema) - alternate_b = PSE.Advanced.compile_composite_model(b.model, (policy_spec(:U; active=false),)) + b.model.applications[1] = policy_spec(:U; active=false) + alternate_b = PSE.Advanced.refresh_bindings!(b.model; force=true) @test_throws "policy_probe` is outside its prepared family schema" PSE.Advanced.refresh_environment_bindings!(b.model, alternate_b) @test b.backend.binds == 0 union_schema = PSE._freeze_environment_binding_schema(simulation.environment_bindings.environment_schema) c = policy_model(:T; active=false) admitted = prepare_policy(c; schema=union_schema) E = typeof(admitted.environment_bindings) - alternate_c = PSE.Advanced.compile_composite_model(c.model, (policy_spec(:U; active=false),)) + c.model.applications[1] = policy_spec(:U; active=false) + alternate_c = PSE.Advanced.refresh_bindings!(c.model; force=true) current = PSE.Advanced.refresh_environment_bindings!(c.model, alternate_c; force=true) @test typeof(current) === E @test current.environment_schema === union_schema @@ -725,7 +748,8 @@ end dirty && mark_environment_binding_dirty!(data.model) collected = prepare_policy(data; schema=PSE._collecting_environment_binding_schema()) @test PSE._is_collecting_environment_schema(collected.environment_bindings.environment_schema) - alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) + data.model.applications[1] = policy_spec(:U) + alternate = PSE.Advanced.refresh_bindings!(data.model; force=true) refreshed = PSE.Advanced.refresh_environment_bindings!(data.model, alternate) @test PSE._is_collecting_environment_schema(refreshed.environment_schema) @test only(refreshed.application_plans).compiled_sampling_rules != @@ -761,7 +785,8 @@ end control = policy_model(:T) observed = prepare_policy(control; schema=evidence) old_plan = only(observed.environment_bindings.application_plans) - alternate = PSE.Advanced.compile_composite_model(control.model, (policy_spec(:U),)) + control.model.applications[1] = policy_spec(:U) + alternate = PSE.Advanced.refresh_bindings!(control.model; force=true) future = PSE.Advanced.refresh_environment_bindings!(control.model, alternate; force=true) new_plan = only(future.application_plans) @test typeof(new_plan) !== typeof(old_plan) @@ -775,7 +800,8 @@ end data = policy_model(:T) simulation = prepare_policy(data; schema=policy) owner = simulation.environment_bindings - alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) + data.model.applications[1] = policy_spec(:U) + alternate = PSE.Advanced.refresh_bindings!(data.model; force=true) before = policy_counts(data) refreshed = PSE.Advanced.refresh_environment_bindings!(data.model, alternate) @test refreshed !== owner @@ -869,7 +895,8 @@ end evidence = PSE._collecting_environment_binding_schema() simulation = prepare_policy(data; schema=evidence) owner = simulation.environment_bindings - alternate = PSE.Advanced.compile_composite_model(data.model, (policy_spec(:U),)) + data.model.applications[1] = policy_spec(:U) + alternate = PSE.Advanced.refresh_bindings!(data.model; force=true) ids = only(alternate.applications).target_ids first_id, later_id = first(ids), last(ids) # A stale later context makes the metadata fast path give up, after the diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index a4156d358..a3ef4f161 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -84,10 +84,17 @@ function fixture(closed::Bool; environment_schema=PSE.EnvironmentBindingSchema() return (; model, simulation, backend) end -function index_discovery_fixture(closed::Bool; extra_applications::Int=0) - events = Any[] - backend_a = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, events, nothing) - backend_b = Backend(copy(backend_a.values), 0, events, nothing) +function index_discovery_fixture(closed::Bool; extra_applications::Int=0, + application_slots=nothing, backends=nothing) + if isnothing(backends) + events = Any[] + backend_a = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, events, nothing) + backend_b = Backend(copy(backend_a.values), 0, events, nothing) + else + backend_a, backend_b = backends + events = backend_a.index_updates + @assert backend_b.index_updates === events + end extra_objects = ntuple(extra_applications) do index Object(Symbol(:extra_, index); scale=:Leaf, parent=:root, geometry=(cell=:a,), status=Status(seen=0.0f0, visits=0)) @@ -97,24 +104,28 @@ function index_discovery_fixture(closed::Bool; extra_applications::Int=0) ModelSpec(Probe(); name, on=One(id=name), environment=Environment(backend=IndexDiscoverySource(backend_a, name))) end + specs = ( + ModelSpec(Probe(); name=:first, on=One(id=1), + environment=Environment(backend=IndexDiscoverySource(backend_a, :first))), + ModelSpec(Probe(); name=:shared, on=One(id=:leaf), + environment=Environment(backend=IndexDiscoverySource(backend_a, :shared), provider=:shared)), + ModelSpec(Probe(); name=:other, on=One(id=:other), + environment=Environment(backend=IndexDiscoverySource(backend_b, :other))), + ModelSpec(Probe(); name=:global, on=One(id=:global), + environment=Environment(backend=EA.GlobalConstant((T=30.0f0,)))), + extra_specs..., + ) + applications = isnothing(application_slots) ? specs : + Tuple(specs[slot] for slot in application_slots) model = CompositeModel( - Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), + Object(:root; scale=:Scene, geometry=(cell=:a,), + status=Status(seen=0.0f0, visits=0)), Object(1; scale=:Leaf, parent=:root, geometry=(cell=:a,), status=Status(seen=0.0f0, visits=0)), Object(:leaf; scale=:Leaf, parent=:root, geometry=(cell=:b,), status=Status(seen=0.0f0, visits=0)), Object(:other; scale=:Leaf, parent=:root, geometry=(cell=:a,), status=Status(seen=0.0f0, visits=0)), Object(:global; scale=:Leaf, parent=:root, geometry=(cell=:b,), status=Status(seen=0.0f0, visits=0)), extra_objects...; - applications=( - ModelSpec(Probe(); name=:first, on=One(id=1), - environment=Environment(backend=IndexDiscoverySource(backend_a, :first))), - ModelSpec(Probe(); name=:shared, on=One(id=:leaf), - environment=Environment(backend=IndexDiscoverySource(backend_a, :shared), provider=:shared)), - ModelSpec(Probe(); name=:other, on=One(id=:other), - environment=Environment(backend=IndexDiscoverySource(backend_b, :other))), - ModelSpec(Probe(); name=:global, on=One(id=:global), - environment=Environment(backend=EA.GlobalConstant((T=30.0f0,)))), - extra_specs..., - ), + applications=applications, environment=backend_a) closed && (model = close_registry(model)) return (; model, backend_a, backend_b, events) @@ -180,19 +191,53 @@ end @test owner.environment_schema === active_schema @test index_trace(events) == vcat(discoveries, indexed, discoveries) - # A different current geometry owner must preserve its schema and the - # newly discovered backend order, rather than the witness-table order. - alternate = PSE.Advanced.compile_composite_model(model, - (model.applications[3], model.applications[2], model.applications[1], model.applications[4])) + # Reordering mixed-ID selectors changes the prepared configuration. + # A fresh model owns that configuration and discovers the same backend + # values in its authored order, independently of this model's cache. + reordered = index_discovery_fixture(fixed; + application_slots=(3, 2, 1, 4), backends=(data.backend_a, data.backend_b)) + alternate = PSE.Advanced.compile_composite_model(reordered.model) + kept_handles = Dict(id => owner.by_target[(id, object)].handle + for (id, object) in ((:shared, ObjectId(:leaf)), + (:other, ObjectId(:other)), (:global, ObjectId(:global)))) empty!(events) - PSE.Advanced.refresh_environment_bindings!(model, alternate; force=true) + alternate_owner = PSE._refresh_environment_bindings!(reordered.model, + alternate, nothing; force=true, environment_schema=active_schema) alternate_discoveries = [(:discover, :other), (:discover, :shared), (:discover, :first)] @test index_trace(events) == vcat(alternate_discoveries, reverse(indexed), alternate_discoveries) + @test alternate.model === reordered.model + @test reordered.model !== model + @test reordered.model.environment_binding_cache === alternate_owner + @test alternate_owner.environment_schema === active_schema + @test model.environment_binding_cache === owner + @test all(model_object(reordered.model, id) !== model_object(model, id) + for id in (:root, 1, :leaf, :other, :global)) + + # Its preparation cannot force provider discovery or replace untouched + # handles in this model's real targeted geometry refresh. empty!(events) + before_partial = (data.backend_a.binds, data.backend_b.binds) update_geometry!(model, 1, (cell=:b,)) restored = PSE.Advanced.refresh_environment_bindings!(model, compiled) @test restored.environment_schema === active_schema - @test index_trace(events) == vcat(discoveries, [(:index, objectid(data.backend_a))]) + @test index_trace(events) == [(:index, objectid(data.backend_a))] + @test (data.backend_a.binds, data.backend_b.binds) == + (before_partial[1] + 1, before_partial[2]) + @test all(restored.by_target[(id, object)].handle === kept_handles[id] + for (id, object) in ((:shared, ObjectId(:leaf)), + (:other, ObjectId(:other)), (:global, ObjectId(:global)))) + @test only(last(events).entities).geometry == (cell=:b,) + + # The explicit discovery/index worker visits all discovered backends; + # its dirty subset filters the entity list, not the backend list. + empty!(events) + before_explicit = (data.backend_a.binds, data.backend_b.binds) + PSE._update_model_environment_indices!(model, compiled, [ObjectId(1)]) + @test index_trace(events) == vcat(discoveries, indexed) + explicit_updates = filter(event -> event.phase === :index, events) + @test all([entity.id for entity in update.entities] == [1] + for update in explicit_updates) + @test (data.backend_a.binds, data.backend_b.binds) == before_explicit @test only(last(events).entities).geometry == (cell=:b,) empty!(events) @@ -247,12 +292,37 @@ end constants=PSE.Constants(), environment_schema=fixed ? schema : PSE.EnvironmentBindingSchema()) compiled, owner = simulation.compiled, simulation.environment_bindings - # A previous target remains relevant even when the supplied compiled - # application set no longer contains that application ID. - subset = PSE.Advanced.compile_composite_model(model, (model.applications[1],)) + # A genuine selector-value edit removes this object's current + # membership while the previous environment owner still remembers it. + # The replacement has the same declared family and uses the same model. + original_spec = model.applications[3] + replacement = PSE._replace_model_spec(original_spec; on=One(id=:root)) + @test typeof(replacement) === typeof(original_spec) + model.applications[3] = replacement + retargeted = PSE.Advanced.refresh_bindings!(model; force=true) + @test retargeted.model === model + @test model.environment_binding_cache === owner + @test only(retargeted.applications_by_id[:other].target_ids) === ObjectId(:root) + current_ids = Symbol[] + PSE._foreach_object_application(retargeted, ObjectId(:other)) do application + push!(current_ids, application.id) + end + @test isempty(current_ids) + @test any(target -> target[1] === :other, + owner.targets_by_object[ObjectId(:other)]) empty!(events) - PSE._update_model_environment_indices_for_objects!(model, subset, owner, [ObjectId(:other)]) + PSE._update_model_environment_indices_for_objects!(model, retargeted, owner, + [ObjectId(:other)]) @test index_trace(events) == [(:index, objectid(data.backend_b))] + @test only(only(events).entities).id === :other + + model.applications[3] = original_spec + restored = PSE.Advanced.refresh_bindings!(model; force=true) + @test restored.model === model + @test only(restored.applications_by_id[:other].target_ids) === ObjectId(:other) + # Reconfiguration must not mutate either previous metadata snapshot. + @test only(retargeted.applications_by_id[:other].target_ids) === ObjectId(:root) + @test only(compiled.applications_by_id[:other].target_ids) === ObjectId(:other) # Preserve the Set's actual order. The first callback replaces a later # dictionary entry; its already-selected immutable plan must still run. @@ -276,7 +346,7 @@ end owner.application_plans_by_id[second_id] = second_plan remove_object!(model, :other) empty!(events) - PSE._update_model_environment_indices_for_objects!(model, subset, owner, [ObjectId(:other)]) + PSE._update_model_environment_indices_for_objects!(model, retargeted, owner, [ObjectId(:other)]) @test index_trace(events) == [(:index, objectid(data.backend_b))] @test isempty(only(events).entities) @test only(events).removed_object_ids == [ObjectId(:other)] diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index 488350d94..ee5c2627f 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -447,12 +447,13 @@ PSE._prepare_environment_sampler(source::MemoPreparationSource) = PSE._prepare_global_environment(source::MemoPreparationSource) = (source.source_preparations += 1; source) -function memo_source_model(source) +function memo_source_model(source; mapped_only=false) + mapped = ModelSpec(Probe(0f0); name=:mapped, on=One(id=:b), + environment=Environment(sources=(T=:U,))) + specs = mapped_only ? (mapped,) : + (ModelSpec(Probe(0f0); name=:raw, on=One(id=:a)), mapped) return CompositeModel(Object(:a; scale=:Leaf), Object(:b; scale=:Leaf); - applications=( - ModelSpec(Probe(0f0); name=:raw, on=One(id=:a)), - ModelSpec(Probe(0f0); name=:mapped, on=One(id=:b), - environment=Environment(sources=(T=:U,)))), environment=source) + applications=specs, environment=source) end memo_preparations(source) = (source.sampler_preparations, source.source_preparations) @@ -515,13 +516,18 @@ memo_preparations(source) = (source.sampler_preparations, source.source_preparat @test_throws "raw` is outside its prepared family schema" PSE._refresh_environment_bindings!( model, compiled, owner; environment_schema=mapped_schema) @test model.environment_binding_cache === owner - alternate = PSE.Advanced.compile_composite_model(model, (model.applications[2],)) - replacement = PSE._refresh_environment_bindings!(model, alternate, owner; + mapped_model = memo_source_model(source; mapped_only=true) + alternate = PSE.Advanced.compile_composite_model(mapped_model) + replacement = PSE._refresh_environment_bindings!(mapped_model, alternate, nothing; environment_schema=mapped_schema) + @test alternate.model === mapped_model + @test mapped_model.environment_binding_cache === replacement + @test model.environment_binding_cache === owner + @test model_object(mapped_model, :b) !== model_object(model, :b) @test replacement.environment_schema === mapped_schema @test only(replacement.application_plans).application_id === :mapped @test memo_preparations(source) == (2, 2) - again, _ = PSE._compile_environment_application_plans(model, + again, _ = PSE._compile_environment_application_plans(mapped_model, alternate.applications, alternate.applications_by_id; previous_plans_by_id=replacement.application_plans_by_id, environment_schema=replacement.environment_schema) @@ -671,7 +677,8 @@ end @test PSE._sample_compiled_global_environment(old, 3).T === 25.0 replacement = recipe_window_spec(width, offset) @test typeof(replacement) === typeof(initial_spec) - compiled = PSE.Advanced.compile_composite_model(model, (replacement,)) + model.applications[1] = replacement + compiled = PSE.Advanced.refresh_bindings!(model; force=true) refreshed = PSE._refresh_environment_bindings!(model, compiled, owner) current = refreshed.by_target[(:probe, ObjectId(:a))] @test model.environment_binding_cache === refreshed @@ -743,7 +750,8 @@ end binding = owner.by_target[(:probe, ObjectId(:a))] @test PSE._model_environment_for_binding(owner, application, binding, 1.0).T === 10f0 - compiled = PSE.Advanced.compile_composite_model(model, (specs[2],)) + model.applications[1] = specs[2] + compiled = PSE.Advanced.refresh_bindings!(model; force=true) refreshed = PSE._refresh_environment_bindings!(model, compiled, owner) binding = refreshed.by_target[(:probe, ObjectId(:a))] @test model.environment_binding_cache === refreshed @@ -756,7 +764,8 @@ end compiled.applications_by_id[:probe], binding, 1.0).T === 20f0 admitted_application = compiled.applications_by_id[:probe] - unadmitted = PSE.Advanced.compile_composite_model(model, (specs[3],)) + model.applications[1] = specs[3] + unadmitted = PSE.Advanced.refresh_bindings!(model; force=true) @test_throws "probe` is outside its prepared family schema" PSE._refresh_environment_bindings!( model, unadmitted, refreshed) @test model.environment_binding_cache === refreshed diff --git a/test/test-model-input-plan-output-metadata.jl b/test/test-model-input-plan-output-metadata.jl index b7b56972d..b6bb1aa30 100644 --- a/test/test-model-input-plan-output-metadata.jl +++ b/test/test-model-input-plan-output-metadata.jl @@ -99,7 +99,7 @@ plan_signature(plans) = [(plan.application_id, plan.input, plan.origin, @testset "one input-plan pass bounds output declaration queries as consumers grow" begin for T in (Float32, Float64), explicit in (false, true), count in (1, 8, 32) data = query_scene(T, count; explicit) - applications = PSE._compile_model_applications(data.model, data.model.applications, + applications = PSE._compile_model_applications(data.model, PSE._model_timeline(data.model)) destinations = PSE._resolve_model_output_destination_plans(data.model, PSE._scenario_preparation(data.model), applications) plans, queries = planner_pass(data, applications, destinations) @@ -132,7 +132,7 @@ end @testset "planner metadata supports filtered applications with non-dense slots" begin data = query_scene(Float64, 8) - applications = PSE._compile_model_applications(data.model, data.model.applications, + applications = PSE._compile_model_applications(data.model, PSE._model_timeline(data.model)) selected = applications[[1, length(applications)]] @test getproperty.(selected, :slot) == [1, 9] @@ -463,7 +463,7 @@ end ModelSpec(Reader(Float64; port=:sent); name=:reader, on=Many(scale=(:LocalFirst, :Destination, :LocalLast))), ), environment=(duration=Hour(1),)) - applications = PSE._compile_model_applications(model, model.applications, + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) preparation = PSE._scenario_preparation(model) authored = PSE._project_authored_applications(preparation, applications) diff --git a/test/test-model-prepared-authoring-owner.jl b/test/test-model-prepared-authoring-owner.jl index 3363cd50a..05d04289f 100644 --- a/test/test-model-prepared-authoring-owner.jl +++ b/test/test-model-prepared-authoring-owner.jl @@ -88,17 +88,32 @@ end @test model_status(data.model, :born).visits == 1 end -@testset "alternate compilation has its own owner without taking over the live cache" begin +@testset "independently configured models keep their genuine preparation owners" begin data = fixture() simulation = run!(data.model; steps=0, outputs=:none) canonical = simulation.compiled preparation = data.model.scenario_plan_cache alternate_specs = (ModelSpec(Probe(Ref(0), Ref(false)); name=:alternate, on=One(id=:leaf)),) - alternate = Advanced.refresh_bindings!(data.model, alternate_specs) + before = data.hint_calls[] + @test_throws MethodError Advanced.compile_composite_model(data.model, alternate_specs) + @test_throws MethodError Advanced.compile_composite_model(data.model, collect(alternate_specs)) + @test_throws MethodError Advanced.compile_composite_model(data.model, only(alternate_specs)) + @test_throws MethodError Advanced.refresh_bindings!(data.model, alternate_specs) + @test data.hint_calls[] == before + alternate_model = CompositeModel( + Object(:root; scale=:Scene), + Object(:leaf; scale=:Leaf, parent=:root); + applications=alternate_specs, + ) + alternate = Advanced.refresh_bindings!(alternate_model) + @test alternate_model.binding_cache === alternate + @test alternate_model.scenario_plan_cache.owner === alternate_model + @test PSE.refvalue(model_status(alternate_model, :leaf), :visits) !== + PSE.refvalue(model_status(data.model, :leaf), :visits) @test data.model.binding_cache === canonical @test data.model.scenario_plan_cache === preparation @test alternate.scenario_plan.authoring.preparation !== preparation - @test alternate.scenario_plan.authoring.preparation.owner === data.model + @test alternate.scenario_plan.authoring.preparation.owner === alternate_model @test alternate.scenario_plan.authoring.preparation.source_specs === alternate_specs @test PSE._refresh_runtime_bindings!(data.model, canonical) === canonical step!(simulation) diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl index cd18c3019..69fb6c102 100644 --- a/test/test-model-scenario-authoring.jl +++ b/test/test-model-scenario-authoring.jl @@ -64,7 +64,7 @@ end # Resolve the existing recipe against real membership and time without # invoking its moved port/hint declarations a second time. - resolved = PSE._compile_model_applications(model, Tuple(model.applications), PSE._model_timeline(model)) + resolved = PSE._compile_model_applications(model, PSE._model_timeline(model)) @test only(resolved).target_ids == [ObjectId(1)] @test declarations[] == hints[] == 1 @test conversions == [:seed] @@ -185,7 +185,7 @@ end # Pure application resolution reuses both moved declaration hooks. Real # status/default and contract preparation may still read outputs_ later. declaration_count, hint_count = declarations[], hints[] - applications = PSE._compile_model_applications(model, Tuple(model.applications), + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) @test only(applications).target_ids == [ObjectId(1), ObjectId(2)] @test only(applications).clock.dt == 1.0 diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index f24701699..223725fff 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -1172,7 +1172,7 @@ end @test any(row -> row.id == :leaf_1 && row.has_geometry, object_rows) @test any(row -> row.id == :plant_1 && row.children == [ObjectId(:leaf_1).value], object_rows) - selector_scene = CompositeModel( + make_selector_scene(applications) = CompositeModel( Object(:scene; scale=:Scene, kind=:scene), Object(:plant_1; scale=:Plant, kind=:plant, species=:oil_palm, name=:palm_1, parent=:scene), Object(:axis_1; scale=:Axis, kind=:plant, species=:oil_palm, parent=:plant_1), @@ -1180,8 +1180,10 @@ end Object(:leaf_2; scale=:Leaf, kind=:plant, species=:oil_palm, parent=:axis_1, status=Status(leaf_area=2.0)), Object(:plant_2; scale=:Plant, kind=:plant, species=:oil_palm, name=:palm_2, parent=:scene), Object(:leaf_3; scale=:Leaf, kind=:plant, species=:oil_palm, parent=:plant_2, status=Status(leaf_area=3.0)), - Object(:soil; scale=:Soil, kind=:soil, parent=:scene), + Object(:soil; scale=:Soil, kind=:soil, parent=:scene); + applications=applications, ) + selector_scene = make_selector_scene(()) scope_rows = explain_scopes(selector_scene) scene_scope = only(row for row in scope_rows if row.scope_type == :scene) @@ -1691,7 +1693,7 @@ end @test PlantSimEngine.input_origins(override_input_spec).leaf_carbon == :model_spec - default_input_origin_scene = CompositeModel( + make_default_input_origin_scene(applications) = CompositeModel( Object(:scene; scale=:Scene, kind=:scene), Object(:plant_1; scale=:Plant, kind=:plant, parent=:scene), Object( @@ -1700,22 +1702,18 @@ end kind=:plant, parent=:plant_1, status=Status(leaf_carbon=2.0, carbon_override=3.0), - ), + ); + applications=applications, ) - default_input_origin_compiled = Advanced.compile_composite_model( - default_input_origin_scene, - ( + default_input_origin_compiled = Advanced.compile_composite_model(make_default_input_origin_scene(( ModelSpec( ModelObjectDefaultInputConsumerModel(); on=One(scale=:Plant), ), - ), - ) + ))) @test only(explain_bindings(default_input_origin_compiled)).origin == :model_default - override_input_origin_compiled = Advanced.compile_composite_model( - default_input_origin_scene, - ( + override_input_origin_compiled = Advanced.compile_composite_model(make_default_input_origin_scene(( ModelSpec( ModelObjectDefaultInputConsumerModel(); on=One(scale=:Plant), @@ -1724,8 +1722,7 @@ end Many(scale=:Leaf, var=:carbon_override), ), ), - ), - ) + ))) @test only(explain_bindings(override_input_origin_compiled)).origin == :model_spec @@ -1784,7 +1781,8 @@ end ModelSpec(ModelObjectStomataModel(); name=:stomata, on=Many(scale=:Leaf)), ModelSpec(ModelObjectLeafEnergyModel(); name=:leaf_energy, on=Many(scale=:Leaf), inputs=(:leaf_areas => Many(scale=:Leaf, within=SelfPlant(), var=:leaf_area, policy=Integrate(), window=Day(1)))), ) - compiled = Advanced.compile_composite_model(selector_scene, compiled_specs) + compiled_selector_scene = make_selector_scene(compiled_specs) + compiled = Advanced.compile_composite_model(compiled_selector_scene) application_rows = explain_applications(compiled) @test length(application_rows) == 2 @test only(row for row in application_rows if row.application_id == :stomata).target_ids == @@ -1817,7 +1815,7 @@ end @test !leaf_2_call.default_publish @test leaf_2_call.accepted_publish - compiled_environment = Advanced.compile_environment_bindings(selector_scene, compiled) + compiled_environment = Advanced.compile_environment_bindings(compiled_selector_scene, compiled) execution_plan = PlantSimEngine.compile_model_execution_plan(compiled, compiled_environment) execution_rows = explain_execution_plan(execution_plan) @@ -1959,14 +1957,14 @@ end ModelSpec(ModelObjectStomataModel(); name=:shaded_stomata, on=Many(scale=:Leaf)), ModelSpec(ModelObjectLeafEnergyModel(); name=:leaf_energy, on=Many(scale=:Leaf)), ) - @test_throws ErrorException Advanced.compile_composite_model(selector_scene, ambiguous_call_specs) + @test_throws ErrorException Advanced.compile_composite_model(make_selector_scene(ambiguous_call_specs)) disambiguated_call_specs = ( ModelSpec(ModelObjectStomataModel(); name=:sunlit_stomata, on=Many(scale=:Leaf)), ModelSpec(ModelObjectStomataModel(); name=:shaded_stomata, on=Many(scale=:Leaf), updates=Updates(:gs; after=:sunlit_stomata)), ModelSpec(ModelObjectLeafEnergyModel(); name=:leaf_energy, on=Many(scale=:Leaf), inputs=(:leaf_areas => Many(scale=:Leaf, within=SelfPlant(), var=:leaf_area)), calls=(:stomata => One(application=:sunlit_stomata))), ) - disambiguated = Advanced.compile_composite_model(selector_scene, disambiguated_call_specs) + disambiguated = Advanced.compile_composite_model(make_selector_scene(disambiguated_call_specs)) disambiguated_call = only(row for row in explain_calls(disambiguated) if row.consumer_id == :leaf_2) @test disambiguated_call.origin == :model_spec @test disambiguated_call.callee_application_ids == [:sunlit_stomata] @@ -2049,41 +2047,38 @@ end run!(renamed_input_scene) @test renamed_status.observed_renamed_signal == 12.5 - default_scope_scene = CompositeModel( + make_default_scope_scene(applications) = CompositeModel( Object(:scene; scale=:Scene, kind=:scene, status=Status(signal_sum=0.0, temporal_total=0.0)), Object(:plant_1; scale=:Plant, kind=:plant, parent=:scene, status=Status(signal_sum=0.0, temporal_total=0.0)), Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:plant_1, status=Status(leaf_area=1.0)), Object(:leaf_2; scale=:Leaf, kind=:plant, parent=:plant_1, status=Status(leaf_area=2.0)), Object(:plant_2; scale=:Plant, kind=:plant, parent=:scene, status=Status(signal_sum=0.0, temporal_total=0.0)), - Object(:leaf_3; scale=:Leaf, kind=:plant, parent=:plant_2, status=Status(leaf_area=3.0)), + Object(:leaf_3; scale=:Leaf, kind=:plant, parent=:plant_2, status=Status(leaf_area=3.0)); + applications=applications, ) - plant_default_scope = Advanced.compile_composite_model( - default_scope_scene, - ( + plant_default_scope = Advanced.compile_composite_model(make_default_scope_scene(( ModelSpec(ModelObjectTemporalSumModel(); name=:plant_leaf_sum, on=Many(scale=:Plant), inputs=(:signal_sum => Many(scale=:Leaf, within=Subtree(), var=:leaf_area))), - ), - ) + ))) @test only(row for row in explain_bindings(plant_default_scope) if row.consumer_id == :plant_1).source_ids == [:leaf_1, :leaf_2] @test only(row for row in explain_bindings(plant_default_scope) if row.consumer_id == :plant_2).source_ids == [:leaf_3] - scene_default_scope = Advanced.compile_composite_model( - default_scope_scene, - ( + scene_default_scope = Advanced.compile_composite_model(make_default_scope_scene(( ModelSpec(ModelObjectTemporalSumModel(); name=:scene_leaf_sum, on=One(scale=:Scene), inputs=(:signal_sum => Many(scale=:Leaf, var=:leaf_area))), - ), - ) + ))) @test only(explain_bindings(scene_default_scope)).source_ids == [:leaf_1, :leaf_2, :leaf_3] - inferred_input_scene = CompositeModel( + make_inferred_input_scene(applications) = CompositeModel( Object(:scene; scale=:Scene, kind=:scene), - Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene, status=Status(signal=0.0, observed_signal=0.0)), + Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene, status=Status(signal=0.0, observed_signal=0.0)); + applications=applications, ) inferred_input_specs = ( ModelSpec(ModelObjectSignalSourceModel(); name=:signal_source, on=One(scale=:Leaf)), ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf)), ) - inferred_compiled = Advanced.compile_composite_model(inferred_input_scene, inferred_input_specs) + inferred_input_scene = make_inferred_input_scene(inferred_input_specs) + inferred_compiled = Advanced.compile_composite_model(inferred_input_scene) inferred_binding = only(explain_bindings(inferred_compiled)) @test inferred_binding.application_id == :signal_consumer @test inferred_binding.input == :signal @@ -2173,16 +2168,14 @@ end @test previous_value_status.observed_signal == 2.0 @test previous_value_status.signal == 3.0 - @test_throws ErrorException Advanced.compile_composite_model( - CompositeModel( + @test_throws ErrorException Advanced.compile_composite_model(CompositeModel( Object(:scene; scale=:Scene, kind=:scene), - Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene, status=Status(cycle_a=0.0, cycle_b=0.0)), - ), - ( + Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene, status=Status(cycle_a=0.0, cycle_b=0.0)); + applications=( ModelSpec(ModelObjectCycleAModel(); name=:cycle_a, on=One(scale=:Leaf)), ModelSpec(ModelObjectCycleBModel(); name=:cycle_b, on=One(scale=:Leaf)), ), - ) + )) zero_target_cycle_scene = CompositeModel( Object(:scene; scale=:Scene, kind=:scene); @@ -2311,68 +2304,56 @@ end ) @test_throws "PreviousTimeStep marker for input `cycle_b`" Advanced.refresh_bindings!(mismatched_lag_scene) - @test_throws ErrorException Advanced.compile_composite_model( - CompositeModel( + @test_throws ErrorException Advanced.compile_composite_model(CompositeModel( Object(:scene; scale=:Scene, kind=:scene), - Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene), - ), - ( + Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene); + applications=( ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf)), ), - ) - @test_throws ErrorException Advanced.compile_composite_model( - inferred_input_scene, - ( + )) + @test_throws ErrorException Advanced.compile_composite_model(make_inferred_input_scene(( ModelSpec(ModelObjectSignalSourceModel(); name=:sunlit_signal, on=One(scale=:Leaf)), ModelSpec(ModelObjectSignalSourceModel(); name=:shaded_signal, on=One(scale=:Leaf), updates=Updates(:signal; after=:sunlit_signal)), ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf)), - ), - ) + ))) filtered_input_specs = ( ModelSpec(ModelObjectSignalSourceModel(); name=:signal_source, on=One(scale=:Leaf)), ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf), inputs=(:signal => One(scale=:Leaf, var=:signal, application=:signal_source))), ) - filtered_binding = only(explain_bindings(Advanced.compile_composite_model(inferred_input_scene, filtered_input_specs))) + filtered_binding = only(explain_bindings(Advanced.compile_composite_model(make_inferred_input_scene(filtered_input_specs)))) @test filtered_binding.origin == :model_spec @test filtered_binding.source_application_ids == [:signal_source] @test isnothing(filtered_binding.process) @test filtered_binding.application == :signal_source - @test_throws ErrorException Advanced.compile_composite_model( - inferred_input_scene, - ( + @test_throws ErrorException Advanced.compile_composite_model(make_inferred_input_scene(( filtered_input_specs[1], ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf), inputs=(:signal => One(scale=:Leaf, var=:signal, application=:missing_source))), - ), - ) - @test_throws ErrorException Advanced.compile_composite_model( - inferred_input_scene, - ( + ))) + @test_throws ErrorException Advanced.compile_composite_model(make_inferred_input_scene(( filtered_input_specs[1], ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf), inputs=(:siggnal => One(scale=:Leaf, var=:signal, application=:signal_source))), - ), - ) - @test_throws ErrorException Advanced.compile_composite_model( - inferred_input_scene, - ( + ))) + @test_throws ErrorException Advanced.compile_composite_model(make_inferred_input_scene(( filtered_input_specs[1], ModelSpec(ModelObjectSignalConsumerModel(); name=:signal_consumer, on=One(scale=:Leaf), inputs=(:signal => One(scale=:Leaf, var=:missing_signal))), - ), - ) + ))) - carrier_scene = CompositeModel( + make_carrier_scene(applications) = CompositeModel( Object(:scene; scale=:Scene, kind=:scene), Object(:plant_1; scale=:Plant, kind=:plant, species=:oil_palm, parent=:scene), Object(:leaf_1; scale=:Leaf, kind=:plant, species=:oil_palm, parent=:plant_1, status=Status(leaf_area=1.0, leaf_token=ModelObjectTaggedValue(1), aPPFD=100.0)), Object(:leaf_2; scale=:Leaf, kind=:plant, species=:oil_palm, parent=:plant_1, status=Status(leaf_area=2.0, leaf_token=2, aPPFD=100.0)), - Object(:soil; scale=:Soil, kind=:soil, parent=:scene, status=Status(soil_water_content=0.31)), + Object(:soil; scale=:Soil, kind=:soil, parent=:scene, status=Status(soil_water_content=0.31)); + applications=applications, ) carrier_specs = ( ModelSpec(ModelObjectCarrierConsumerModel(); name=:carrier_consumer, on=Many(scale=:Leaf), inputs=(:leaf_areas => Many(scale=:Leaf, within=SelfPlant(), var=:leaf_area), :leaf_tokens => Many(scale=:Leaf, within=SelfPlant(), var=:leaf_token),)), ModelSpec(ToyAssimModel(); name=:assim, on=Many(scale=:Leaf), inputs=(:soil_water_content => One(scale=:Soil, within=SceneScope(), var=:soil_water_content))), ) - carrier_compiled = Advanced.compile_composite_model(carrier_scene, carrier_specs) + carrier_scene = make_carrier_scene(carrier_specs) + carrier_compiled = Advanced.compile_composite_model(carrier_scene) carrier_rows = explain_bindings(carrier_compiled) leaf_1_carrier_bindings = carrier_compiled.input_bindings_by_target[(:carrier_consumer, ObjectId(:leaf_1))] @test length(leaf_1_carrier_bindings) == 2 @@ -2860,12 +2841,12 @@ end @test length(contract_backend.binds) == 1 @test length(contract_backend.index_updates) == 1 - revised_contract_compiled = Advanced.compile_composite_model( - contract_scene, - ( - ModelSpec(ModelObjectTemperatureOnlyProbeModel(); name=:probe, on=One(scale=:Leaf), environment=Environment(provider=:grid)), - ), + contract_scene.applications[1] = ModelSpec( + ModelObjectTemperatureOnlyProbeModel(); name=:probe, on=One(scale=:Leaf), + environment=Environment(provider=:grid), ) + revised_contract_compiled = + Advanced.refresh_bindings!(contract_scene; force=true) revised_contract_bindings = Advanced.refresh_environment_bindings!(contract_scene, revised_contract_compiled) revised_contract_binding = @@ -3931,19 +3912,18 @@ end process=:model_object_signal_source, ) - writer_scene = CompositeModel( + make_writer_scene(applications) = CompositeModel( Object(:scene; scale=:Scene, kind=:scene), - Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene, status=Status(biomass=-1.0)), + Object(:leaf_1; scale=:Leaf, kind=:plant, parent=:scene, status=Status(biomass=-1.0)); + applications=applications, ) biomass_source = ModelSpec(ModelObjectBiomassSourceModel(); name=:carbon_allocation, on=One(scale=:Leaf)) biomass_pruner = ModelSpec(ModelObjectBiomassPrunerModel(); name=:leaf_pruning, on=One(scale=:Leaf)) - @test_throws ErrorException Advanced.compile_composite_model(writer_scene, (biomass_source, biomass_pruner)) - @test_throws ErrorException Advanced.compile_composite_model( - writer_scene, - ( + @test_throws ErrorException Advanced.compile_composite_model(make_writer_scene((biomass_source, biomass_pruner))) + @test_throws ErrorException Advanced.compile_composite_model(make_writer_scene(( biomass_source, ModelSpec( ModelObjectBiomassPrunerModel(); @@ -3951,11 +3931,8 @@ end on=One(scale=:Leaf), updates=Updates(:biomass; after=:water_status), ), - ), - ) - @test_throws ErrorException Advanced.compile_composite_model( - writer_scene, - ( + ))) + @test_throws ErrorException Advanced.compile_composite_model(make_writer_scene(( biomass_source, ModelSpec( ModelObjectBiomassPrunerModel(); @@ -3963,11 +3940,8 @@ end on=One(scale=:Leaf), updates=Updates(:biomass; after=:model_object_biomass_source), ), - ), - ) - @test_throws ErrorException Advanced.compile_composite_model( - writer_scene, - ( + ))) + @test_throws ErrorException Advanced.compile_composite_model(make_writer_scene(( ModelSpec( ModelObjectBiomassPrunerModel(); name=:leaf_pruning, @@ -3975,8 +3949,7 @@ end updates=Updates(:biomass; after=:carbon_allocation), ), biomass_source, - ), - ) + ))) ordered_pruner = ModelSpec( ModelObjectBiomassPrunerModel(); @@ -3984,7 +3957,7 @@ end on=One(scale=:Leaf), updates=Updates(:biomass; after=:carbon_allocation), ) - writer_compiled = Advanced.compile_composite_model(writer_scene, (biomass_source, ordered_pruner)) + writer_compiled = Advanced.compile_composite_model(make_writer_scene((biomass_source, ordered_pruner))) writer_row = only(row for row in explain_writers(writer_compiled) if row.variable == :biomass) @test writer_row.object_id == :leaf_1 @test writer_row.duplicate From 31966da76f291526a0cb7e429198059d52a5fdea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 17:46:03 +0100 Subject: [PATCH 155/324] Bound compilation of configured status admission Disable constant propagation on the generated admission method and keep its emitted body behind a noinline boundary. Reference classes, permissions, error paths and operation ordering are unchanged; the boundary shares typed admission work across status fields. Validation: the unchanged isolated 36-application case passed all 22 assertions plus 17 guards; the real whole metadata file passed 870 checks within its fixed 1200-second bound. The original strict allocation probe passed 19 checks with unchanged five slope allowances at sizes 8 and 2048. Method.constprop and emitted CodeInfo noinline flags were checked directly before execution. This establishes bounded cold-compilation progress and targeted parity, not a warm speedup. Narrow stock JuliaC safe, full XPalm safe, remaining feature qualification and matched 4160-day performance remain pending. Keep the PR in draft. --- src/composite_model/prepared_status_manifest.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index a1d3e68c1..01d70b258 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -497,7 +497,7 @@ function _prepared_status_sources_admission(applications::Tuple, permissions::Tu return (declared | next_declared, allowed & next_allowed, compatible) end -@generated function _prepared_status_configured_reference_admission( +Base.@constprop :none @generated function _prepared_status_configured_reference_admission( manifest::PreparedStatusManifest{S}, model, object, parent_id, name, reference, ) where {S} # The sparse CSR keeps Ref instances erased; admit them through the SAME @@ -519,7 +519,7 @@ end end end for R in references] return quote - $(Expr(:meta, :inline)) + Base.@noinline $(branches...) return (false, false) end From 6ff126343e940919f48cec63fd2e63a8b87c2377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 18:34:33 +0100 Subject: [PATCH 156/324] Type admission before its shared worker and stabilize compiled snapshots Keep the prepared Ref classifier inline and pass each concrete reference class to one noinline, constprop-disabled permission worker. Preserve the admission algorithm and its order while restoring a concrete call boundary for safe compilation. Retain the cold compilation barrier instead of restoring per-field permission expansion. Build the compiled program's private status view from the same official references in dense named storage. Its existing final_state snapshot becomes inferable without changing its API, the official status, execution engine or values. Validation: whole native-compilation file passed 84 checks including 13 alias/inference/snapshot/copy/parity checks. The unchanged 36-application stress case passed its 22 assertions plus 19 guards, with classifier/worker flags inspected directly; original strict allocation probe passed all 19 checks and five unchanged slope allowances. Native compilation is pending on this checkpoint: prior31966da Mac safe was cancelled after observed Ref/Any errors, and its Linux safe failed separately on runtime NamedTuple construction. Full feature/downstream qualification and matched4160-day performance remain pending; PR stays draft. --- .../prepared_status_manifest.jl | 36 +++++++++++-------- src/native_compilation.jl | 2 ++ test/test-native-compilation.jl | 33 +++++++++++++++++ 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 01d70b258..612ab67e7 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -497,34 +497,42 @@ function _prepared_status_sources_admission(applications::Tuple, permissions::Tu return (declared | next_declared, allowed & next_allowed, compatible) end -Base.@constprop :none @generated function _prepared_status_configured_reference_admission( +# Keep erased cells behind the prepared physical bounds before crossing the +# permission worker's function boundary. The worker shares its typed body across +# field names; no caller needs to inline an application scan for every slot. +@generated function _prepared_status_configured_reference_admission( manifest::PreparedStatusManifest{S}, model, object, parent_id, name, reference, ) where {S} - # The sparse CSR keeps Ref instances erased; admit them through the SAME - # prepared physical bounds before visiting the active configuration. references = unique(R for slot in fieldtypes(_status_schema_references(S)) for R in Base.uniontypes(slot) if R <: Ref) branches = [quote if reference isa $R - declared, source_allowed, compatible = _prepared_status_sources_admission( - manifest.authored, manifest.permissions, model, object, parent_id, - name, reference::$R) - compatible || return (false, false) - allowed = (declared && source_allowed) || - _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, - model, object, parent_id, name, reference::$R) || - _prepared_status_destinations_allow(manifest.destinations, manifest, - model, object, parent_id, name, reference::$R) - return (allowed, true) + return _prepared_status_reference_admission( + manifest, model, object, parent_id, name, reference::$R) end end for R in references] return quote - Base.@noinline + $(Expr(:meta, :inline)) $(branches...) return (false, false) end end +Base.@constprop :none Base.@noinline function _prepared_status_reference_admission( + manifest, model, object, parent_id, name, reference::R, +) where {R<:Ref} + declared, source_allowed, compatible = _prepared_status_sources_admission( + manifest.authored, manifest.permissions, model, object, parent_id, + name, reference::R) + compatible || return (false, false) + allowed = (declared && source_allowed) || + _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, + model, object, parent_id, name, reference::R) || + _prepared_status_destinations_allow(manifest.destinations, manifest, + model, object, parent_id, name, reference::R) + return (allowed, true) +end + function _prepared_status_raw_variant(raw, slot) for entry in raw.selected first(entry) == slot && return last(entry) diff --git a/src/native_compilation.jl b/src/native_compilation.jl index faf445c30..5c64d1fa9 100644 --- a/src/native_compilation.jl +++ b/src/native_compilation.jl @@ -114,6 +114,8 @@ function prepare(model::PSE.CompositeModel; constants=PSE.Constants()) status = only(PSE.model_objects(owned)).status _has_scalar_status(status) || throw(ArgumentError("Compilation requires concrete scalar numeric object status values.")) + # Fix the present-field schema at build time while sharing the live cells. + status = PSE.Status(NamedTuple{keys(status)}(PSE.refvalues(status))) plan = PSE._fixed_execution_plan(simulation.execution_plan) return PreparedSimulation(PSE._simulation_with_execution_plan(simulation, plan), status) end diff --git a/test/test-native-compilation.jl b/test/test-native-compilation.jl index 9965c07e8..7a6041f6e 100644 --- a/test/test-native-compilation.jl +++ b/test/test-native-compilation.jl @@ -118,6 +118,39 @@ end @test NamedTuple(model_status(authored, :sample)) == before end +@testset "Prepared native state shares canonical cells with a fixed schema" begin + constants = (scale=3.0f0,) + program = Compilation.prepare(native_compilation_scene(); constants) + official = model_status(program.simulation.model, :sample) + initial = @inferred final_state(program) + + @test keys(program.status) == keys(official) + @test all(name -> PlantSimEngine.refvalue(program.status, name) === + PlantSimEngine.refvalue(official, name), keys(official)) + @test PlantSimEngine.refvalue(program.status, :incoming) === + PlantSimEngine.refvalue(official, :total) + @test initial isa NamedTuple + @test initial == NamedTuple(official) + + official.total = 5.0f0 + @test final_state(program).total === 5.0f0 + program.status.total = 7.0f0 + @test official.total === 7.0f0 + @test initial.total === 2.0f0 + + expected_model = native_compilation_scene() + model_status(expected_model, :sample).total = 7.0f0 + expected = run!(expected_model; steps=2, constants) + continue!(program; steps=2) + + @test current_step(program) == current_step(expected) == 2 + @test (@inferred final_state(program)) == final_state(expected) == NamedTuple(official) + @test final_state(program).observed === 35.0f0 + @test model_status(program.simulation.model, :sample) === official + @test all(name -> PlantSimEngine.refvalue(program.status, name) === + PlantSimEngine.refvalue(official, name), keys(official)) +end + @testset "Fixed environment rows use ordinary PSE bindings" begin function weather_scene(global_environment) on = One(id=:sample) From 2f13d4db28a827ca020afb4551a61979352409ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 23:02:26 +0100 Subject: [PATCH 157/324] Update CI fixtures for prepared status admission --- test/test-input-source-matching.jl | 2 +- ...t-model-output-destination-declarations.jl | 57 +++++++++++-------- 2 files changed, 34 insertions(+), 25 deletions(-) diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl index ed6ba99aa..d263a9c26 100644 --- a/test/test-input-source-matching.jl +++ b/test/test-input-source-matching.jl @@ -102,7 +102,7 @@ end # The authored producer really selects this newborn, while its cached # pre-barrier target vector intentionally still contains only object 1. @test ObjectId(7) in resolve_object_ids(simulation.model, - compiled.applications_by_id[:a].spec.on) + compiled.applications_by_id[:a].spec.applies_to) partial = PSE._partial_model_application(compiled.applications_by_id[:a], ObjectId[ObjectId(7)]) overlay = PSE._ApplicationsByObjectOverlay(compiled.applications_by_object, diff --git a/test/test-model-output-destination-declarations.jl b/test/test-model-output-destination-declarations.jl index cfee30128..b5e6235a9 100644 --- a/test/test-model-output-destination-declarations.jl +++ b/test/test-model-output-destination-declarations.jl @@ -165,41 +165,50 @@ end ) @test isnothing(leaf.status) - invalid_status = CompositeModel( + initial_status = Status(existing=1.0) + initial_ref = PlantSimEngine.refvalue(initial_status, :existing) + @test_throws "Initial object status must be a Status or nothing" CompositeModel( Object(:scene; scale=:Scene), - Object( - :leaf_a; - scale=:Leaf, - parent=:scene, - status=Status(existing=1.0), - ), - Object( - :leaf_z; - scale=:Leaf, - parent=:scene, - status=(invalid=1.0,), - ); + Object(:leaf_a; scale=:Leaf, parent=:scene, status=initial_status), + Object(:leaf_z; scale=:Leaf, parent=:scene, status=(invalid=1.0,)), + ) + @test propertynames(initial_status) == (:existing,) + @test PlantSimEngine.refvalue(initial_status, :existing) === initial_ref + @test initial_status.existing == 1.0 + + missing_status = CompositeModel( + Object(:scene; scale=:Scene), + Object(:leaf_a; scale=:Leaf, parent=:scene, + status=Status(existing=1.0, absorbed_par=2.0)), + Object(:leaf_z; scale=:Leaf, parent=:scene, status=Status(existing=3.0)); applications=( ModelSpec( - OutputDestinationProbeModel(); + OutputDestinationProbeModel(( + incident_par=Distributed(Default(0.0)), + absorbed_par=Distributed(Required(Float64)), + )); name=:scene_probe, on=One(scale=:Scene), outputs_to=( - OutputTo( - Many(scale=:Leaf, within=SceneScope()); - vars=(:incident_par,), - ), + OutputTo(Many(scale=:Leaf, within=SceneScope()); + vars=(:incident_par, :absorbed_par)), ), ), ), ) - leaf_a = only( - object for object in model_objects(invalid_status; scale=:Leaf) - if object.id == ObjectId(:leaf_a) + leaves = model_objects(missing_status; scale=:Leaf) + statuses = [object.status for object in leaves] + references = [PlantSimEngine.refvalue(status, :existing) for status in statuses] + @test all(status -> !(:incident_par in propertynames(status)), statuses) + @test_throws "Missing required distributed-output destination" Advanced.refresh_bindings!( + missing_status, ) - @test !(:incident_par in propertynames(leaf_a.status)) - @test_throws "with status type" Advanced.refresh_bindings!(invalid_status) - @test !(:incident_par in propertynames(leaf_a.status)) + @test all(object.status === status for (object, status) in zip(leaves, statuses)) + @test all(PlantSimEngine.refvalue(status, :existing) === reference + for (status, reference) in zip(statuses, references)) + @test all(status -> !(:incident_par in propertynames(status)), statuses) + @test sort([status.existing for status in statuses]) == [1.0, 3.0] + end @testset "empty and lifecycle-refreshed output destinations" begin From 27570d6078a78a168f92586ebb656e594c3a9759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Mon, 16 Nov 2026 23:56:17 +0100 Subject: [PATCH 158/324] Measure runtime input allocations in a typed helper Keep the zero-allocation gate and reference/state checks unchanged. Both whole-file validation runs passed 729 checks, on Julia 1.10.12 and Julia 1.13.3. The direct testset scope accounts for 32 bytes on Julia 1.10. --- test/test-unified-model-object-api.jl | 31 ++++++++++++++++++++------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index 223725fff..ba461785c 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -932,6 +932,23 @@ function PlantSimEngine.EnvironmentAPI.commit_environment!( return nothing end +function _model_object_input_materialization_allocations( + compiled, + application, + object_id, + streams, + time, +) + # Measure the typed operation outside the enclosing testset's local scope. + return @allocated PlantSimEngine._materialize_model_inputs!( + compiled, + application, + object_id, + streams, + time, + ) +end + @testset "Unified model/object API" begin mtg_root = Node(MultiScaleTreeGraph.NodeMTG("/", :Scene, 1, 0)) mtg_plant = Node(mtg_root, MultiScaleTreeGraph.NodeMTG("+", :Plant, 1, 1)) @@ -3049,14 +3066,12 @@ end ) runtime_leaf_2.status.leaf_area = 7.0 @test runtime_status.leaf_areas[2] == 7.0 - @test @allocated( - PlantSimEngine._materialize_model_inputs!( - runtime_compiled, - runtime_application, - runtime_object_id, - nothing, - 1, - ) + @test _model_object_input_materialization_allocations( + runtime_compiled, + runtime_application, + runtime_object_id, + nothing, + 1, ) == 0 unrelated_call_counter = Ref(0) From 26a92416bcded76389509a3c92b83795b8d60be8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 00:24:23 +0100 Subject: [PATCH 159/324] Allow time for the compound graph editor scenario Give this compound E2E scenario 120 seconds. Keep the existing assertions and polling limits. Type checking and Playwright collection pass; actual browser execution is still pending remote CI. --- frontend/e2e/graph-editor.spec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/e2e/graph-editor.spec.ts b/frontend/e2e/graph-editor.spec.ts index 44ef57718..7428dffb8 100644 --- a/frontend/e2e/graph-editor.spec.ts +++ b/frontend/e2e/graph-editor.spec.ts @@ -128,6 +128,7 @@ test.describe.serial("PlantSimEngine model graph editor", () => { }); test("connects another consumer and supports undo, redo, remove, and save", async ({ page, request }, testInfo) => { + test.setTimeout(120_000); await page.goto(server.url); await page.getByTestId("configure-environment").click(); await page.getByTestId("scene-environment").selectOption("environment:weather"); From b6f9fdd3ff068b5ec49e760d4c00240093d87c4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 01:34:15 +0100 Subject: [PATCH 160/324] Allow preview startup time and keep backend diagnostics Give template instance preview up to 20 seconds on slower runners. Forward backend output after startup so failures include Julia diagnostics. Keep other assertions and global budgets unchanged. Type checking, Playwright collection and three helper tests pass; remote browser execution still requires verification. --- frontend/e2e/graph-editor.spec.ts | 2 +- frontend/e2e/graphEditorServer.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/frontend/e2e/graph-editor.spec.ts b/frontend/e2e/graph-editor.spec.ts index 7428dffb8..9a34a2c71 100644 --- a/frontend/e2e/graph-editor.spec.ts +++ b/frontend/e2e/graph-editor.spec.ts @@ -195,7 +195,7 @@ test.describe.serial("PlantSimEngine model graph editor", () => { await page.getByTestId("instance-name").fill(plant); await page.getByTestId("instance-root").selectOption(JSON.stringify(plant)); await page.getByTestId("instance-preview-button").click(); - await expect(page.getByTestId("instance-preview")).toContainText("1 claimed object"); + await expect(page.getByTestId("instance-preview")).toContainText("1 claimed object", { timeout: 20_000 }); await page.getByTestId("instance-submit").click(); await waitForState(request, server.url, (value) => value.graph.instances.some((instance) => instance.name === plant)); } diff --git a/frontend/e2e/graphEditorServer.ts b/frontend/e2e/graphEditorServer.ts index af645da99..c01b5a108 100644 --- a/frontend/e2e/graphEditorServer.ts +++ b/frontend/e2e/graphEditorServer.ts @@ -40,7 +40,10 @@ export async function startGraphEditorServer(): Promise { let timeout: ReturnType; const consume = (chunk: Buffer) => { - if (settled) return; + if (settled) { + process.stderr.write(chunk); + return; + } log += chunk.toString(); const match = log.match(/PSE_GRAPH_EDITOR_URL=(http:\/\/127\.0\.0\.1:\d+[^\s]*)/); if (match) { From 158a70d771aee2f10e434e00c73e867a649b0dab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 08:14:55 +0100 Subject: [PATCH 161/324] test: use canonical GraphEditor namespace for cohort retirement --- test/test-model-cohort-store-identities.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index 2c9d3da67..d62756c5c 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -262,8 +262,8 @@ end # leaving the original model/header owners intact. This host diagnostic # still exercises retirement of an UNVISITED owner in the same store. ticks = PSE.refvalue(model_status(data.model, :root), :ticks) - changed_model = PSE.Authoring.apply_model_graph_edit(data.model, - PSE.Authoring.RemoveModelApplication(PSE.Authoring.GlobalApplicationRef(:controller)); + changed_model = PSE.GraphEditor.apply_model_graph_edit(data.model, + PSE.GraphEditor.RemoveModelApplication(PSE.GraphEditor.GlobalApplicationRef(:controller)); preserve=(reference, ticks)) @test changed_model !== data.model @test length(data.model.applications) == 2 From 74fff8f954f5df7c5b3592f2dc6c09d643432dcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 14:01:12 +0100 Subject: [PATCH 162/324] Bound scenario metadata and destination admission compilation --- src/composite_model/compilation.jl | 59 +++----- .../prepared_status_manifest.jl | 139 ++++++++++-------- src/visualization/model_graph_editor_api.jl | 4 +- test/test-model-prepared-authoring-owner.jl | 13 +- 4 files changed, 110 insertions(+), 105 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 476e6bcb3..10e71410a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -796,9 +796,9 @@ mutable struct ScenarioPreparation{M,S,A,F,P,SM} resolved::Any end -# Preserve the genuine owner, without copying its source tuple or encoding the -# result types of declaration hooks in every runtime plan. Lifecycle refresh -# needs only the owner identity and the immutable source-declaration schema. +# Preserve the genuine owner, without copying its source snapshot or encoding +# declaration-hook result types in every runtime plan. Lifecycle refresh needs +# only the owner identity and its captured source declarations. struct CompiledScenarioAuthoring{M,S} preparation::ScenarioPreparation{M,S} @@ -832,9 +832,15 @@ struct CompiledScenarioPlan{SA,AP,AI,ATI,IP,IPI,IR,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS end -function _authored_specs_match(source_specs, specs) - length(source_specs) == length(specs) || return false - return all(pair -> pair[1] === pair[2], zip(source_specs, specs)) +# Compare the copied source cells without reading model parameters. +function _authored_specs_match(preparation::ScenarioPreparation, model::CompositeModel) + source_specs = getfield(preparation, :source_specs) + live_specs = getfield(model, :applications) + length(source_specs) == length(live_specs) || return false + for index in eachindex(source_specs) + source_specs[index] === live_specs[index] || return false + end + return true end # Select an existing captured cause in the same order as scene resolution. @@ -858,7 +864,9 @@ end function _prepare_authored_scenario(model::CompositeModel; raw_families=_prepared_raw_status_families(model)) - source_specs = Tuple(model.applications) + # Capture declarations before any hook can change applications. This local + # snapshot is read-only after publication and shares the same source values. + source_specs = collect(Any, model.applications) # Capture one declaration result per application. Invalid authoring does # not hide later valid applications from a read-only diagnostic report. counts = Dict{Symbol,Int}() @@ -940,7 +948,7 @@ function _prepare_authored_scenario(model::CompositeModel; recipe.id, err, catch_backtrace()) end end - return _finalize_authored_scenario(model, source_specs, Tuple(authored), raw_families) + return _finalize_authored_scenario(model, source_specs, authored, raw_families) end # Constructor and transactional edits share the same type/route preparation. @@ -948,8 +956,8 @@ end function _finalize_authored_scenario(model, source_specs, authored_records, raw_families) failure_index = findfirst(record -> record isa ScenarioPreparationFailure, authored_records) failure = isnothing(failure_index) ? nothing : authored_records[failure_index] - recipes = Tuple(record for record in authored_records - if record isa AuthoredApplicationRecipe) + recipes = _graph_record_vector(AuthoredApplicationRecipe, + (record for record in authored_records if record isa AuthoredApplicationRecipe)) program = _prepare_authored_scenario_program(model, recipes) status_manifest = _capture_authored_metadata(:status_manifest, nothing) do _prepare_status_manifest(model, authored_records, program, raw_families) @@ -961,7 +969,7 @@ function _finalize_authored_scenario(model, source_specs, authored_records, raw_ # available to the partial diagnostic compiler. failure = _first_authored_program_failure(program) end - return ScenarioPreparation(model, source_specs, authored_records, failure, + return ScenarioPreparation(model, source_specs, Tuple(authored_records), failure, program, status_manifest, nothing) end @@ -976,35 +984,6 @@ function _model_owned_scenario_preparation(model::CompositeModel, preparation::S return owned end -# Read each immutable source declaration inside its exact owner schema. Live -# applications are iterated in order; no source tuple or model value escapes. -@generated function _authored_specs_match( - preparation::ScenarioPreparation{M,S}, - model::CompositeModel, -) where {M,S<:Tuple} - count = fieldcount(S) - comparisons = Expr[] - for index in 1:count - next = index == 1 ? :(iterate(live_specs)) : - :(iterate(live_specs, getfield(current, 2))) - push!(comparisons, :(current = $next)) - push!(comparisons, :(isnothing(current) && return false)) - expected_type = fieldtype(S, index) - push!(comparisons, :(candidate = getfield(current, 1))) - push!(comparisons, :(candidate isa $expected_type || return false)) - push!(comparisons, :( - getfield(getfield(preparation, :source_specs), $index) === - (candidate::$expected_type) || return false - )) - end - return quote - live_specs = getfield(model, :applications) - length(live_specs) == $count || return false - $(comparisons...) - return true - end -end - function _publish_failed_scenario_preparation!(model::CompositeModel, preparation) previous = getfield(model, :scenario_plan_cache) model.scenario_plan_cache = preparation diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 612ab67e7..c54a558ad 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -219,7 +219,10 @@ function _prepared_status_raw_configured_references(model, object, names, refere end function _prepare_status_manifest(model, authored, program, raw_basis) - recipes = Tuple(item for item in authored if item isa AuthoredApplicationRecipe) + # Host traversal uses scalar records; freeze exact owner tuples only once + # the namespace and all RAW permissions have been prepared. + recipes = _graph_record_vector(AuthoredApplicationRecipe, + (item for item in authored if item isa AuthoredApplicationRecipe)) permissions = _prepared_status_application_permissions(model, recipes, program) outputs = _authored_distributed_output_plans( _graph_record_vector(AuthoredApplicationRecipe, recipes), program.output_records) @@ -322,7 +325,7 @@ function _prepare_status_manifest(model, authored, program, raw_basis) PreparedStatusApplication(application.slot, application.id, application.target_matcher, _prepared_status_object_slots(application)) end - return PreparedStatusManifest(S, applications, permissions, destinations, raw) + return PreparedStatusManifest(S, Tuple(applications), Tuple(permissions), destinations, raw) end # The catalog references the SAME prepared manifest; runtime never finds a @@ -380,48 +383,70 @@ function _prepared_status_application_reference_allowed(applications::Tuple, Base.tail(permissions), model, object, parent_id, name, reference) end -_prepared_status_destination_reference_allowed(::Tuple{}, ::Tuple{}, plan, - model, object, parent_id, name, reference) = false -function _prepared_status_destination_reference_allowed(applications::Tuple, - permissions::Tuple, plan, model, object, parent_id, name, reference) - application, permission = first(applications), first(permissions) - if application.slot == plan.application_slot && name in plan.variable_names - # Visit registered producer identities in place. No candidate vector or - # synthetic producer is allocated by this admission path. - has_producer = false - for (execution_id, producer) in model.registry.objects - _prepared_status_application_matches(model, producer, producer.parent, application) || continue - has_producer = true - _prepared_status_route_matches(model, object, parent_id, - application, plan, execution_id) || continue - variant = _prepared_status_variant_slot(application, execution_id) - _with_metadata_entry(_prepared_status_output_reference_allowed, - permission.variants, variant, name, reference) && return true - end - # Explicit SceneScope without a relation is independent of a producer - # context. With zero real producers, its base declaration already gives - # a prospective permission; no RAW family or override is substituted. - matcher = plan.matcher - if !has_producer && matcher.scope isa SceneScope && isnothing(matcher.relation) - id = _index_object_id(model.registry.objects, object.id) - topology = _prepared_status_topology(model, object, id, parent_id) - if _selector_matches_object_id(topology, matcher, id, - nothing, false, nothing, false) - return _prepared_status_output_reference_allowed( - first(permission.variants), name, reference) - end +# One exact application/permission pair enters the producer/route worker. +Base.@constprop :none Base.@noinline function _prepared_status_destination_entry_allowed( + application, permission, plan, model, object, parent_id, name, reference, +) + # Visit registered producer identities in place. No candidate vector or + # synthetic producer is allocated by this admission path. + has_producer = false + for (execution_id, producer) in model.registry.objects + _prepared_status_application_matches(model, producer, producer.parent, application) || continue + has_producer = true + _prepared_status_route_matches(model, object, parent_id, + application, plan, execution_id) || continue + variant = _prepared_status_variant_slot(application, execution_id) + _with_metadata_entry(_prepared_status_output_reference_allowed, + permission.variants, variant, name, reference) && return true + end + # Explicit SceneScope without a relation is independent of a producer + # context. With zero real producers, its base declaration already gives + # a prospective permission; no RAW family or override is substituted. + matcher = plan.matcher + if !has_producer && matcher.scope isa SceneScope && isnothing(matcher.relation) + id = _index_object_id(model.registry.objects, object.id) + topology = _prepared_status_topology(model, object, id, parent_id) + if _selector_matches_object_id(topology, matcher, id, + nothing, false, nothing, false) + return _prepared_status_output_reference_allowed( + first(permission.variants), name, reference) end + end + return false +end + +# Slots are authored identities, not tuple positions: partial preparation can +# retain gaps. Select the correlated entries inside the same finite branch. +@generated function _prepared_status_destination_application_allowed(applications::A, + permissions::P, application_slot::Int, plan, model, object, parent_id, name, reference, +) where {A<:Tuple,P<:Tuple} + fieldcount(A) == fieldcount(P) || return :(throw(DimensionMismatch( + "Prepared application and permission tuple lengths must match."))) + branches = [:(getfield(applications, $index).slot == application_slot && + return _prepared_status_destination_entry_allowed( + getfield(applications, $index), getfield(permissions, $index), + plan, model, object, parent_id, name, reference)) + for index in 1:fieldcount(A)] + return quote + $(branches...) return false end - return _prepared_status_destination_reference_allowed(Base.tail(applications), - Base.tail(permissions), plan, model, object, parent_id, name, reference) end -_prepared_status_destinations_allow(::Tuple{}, manifest, model, object, parent_id, name, reference) = false + +Base.@constprop :none Base.@noinline function _prepared_status_destination_plan_allowed( + plan, manifest, model, object, parent_id, name, reference, +) + name in plan.variable_names || return false + return _prepared_status_destination_application_allowed(manifest.authored, + manifest.permissions, plan.application_slot, plan, model, object, parent_id, name, reference) +end + function _prepared_status_destinations_allow(plans::Tuple, manifest, model, object, parent_id, name, reference) - _prepared_status_destination_reference_allowed(manifest.authored, manifest.permissions, - first(plans), model, object, parent_id, name, reference) && return true - return _prepared_status_destinations_allow(Base.tail(plans), manifest, - model, object, parent_id, name, reference) + for slot in eachindex(plans) + _with_metadata_entry(_prepared_status_destination_plan_allowed, plans, + slot, manifest, model, object, parent_id, name, reference) && return true + end + return false end _prepared_status_source_input_admission(variant, input, reference) = hasproperty(variant.source_inputs, input) ? @@ -634,30 +659,22 @@ function _prepared_status_raw_reference_allowed(raw::PreparedRawStatusFamily, return typeof(reference) === raw.reference_types[index] end -# Each slot visit is emitted from the MANIFEST owner's target schema. Fixed storage has -# nullable exact Ref slots; no variable-length propertynames/ref tuple is built. -@generated function _prepared_status_source_allowed(manifest::PreparedStatusManifest{S}, +# Visit the prepared namespace in order without building a per-field method body. +# The existing finite classifier admits each exact Ref before the shared worker. +function _prepared_status_source_allowed(manifest::PreparedStatusManifest{S}, model, object, parent_id, source::Status, raw) where {S} - names = _status_schema_names(S) - checks = Expr[] - for name in names - push!(checks, quote - reference = _initial_status_reference(source, $(QuoteNode(name))) - if reference !== nothing - present += 1 - allowed, compatible = _prepared_status_configured_reference_admission(manifest, model, - object, parent_id, $(QuoteNode(name)), reference) - compatible && (allowed || - _prepared_status_raw_reference_allowed(raw, $(QuoteNode(name)), reference)) || return false - end - end) - end - return quote - $(Expr(:meta, :inline)) - present = 0 - $(checks...) - return present == _initial_status_reference_count(source) + present = 0 + for name in _status_schema_names(S) + reference = _initial_status_reference(source, name) + if reference !== nothing + present += 1 + allowed, compatible = _prepared_status_configured_reference_admission(manifest, model, + object, parent_id, name, reference) + compatible && (allowed || + _prepared_status_raw_reference_allowed(raw, name, reference)) || return false + end end + return present == _initial_status_reference_count(source) end # Initial bootstrap supplies the SAME manifest explicitly before the catalog diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index 2ffca5fab..d4435189a 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -313,8 +313,8 @@ function apply_model_graph_edit( final_preparation = if !isnothing(preparation) && _authored_specs_match(preparation, candidate) # The copied state is initial data for this new model. Reuse captured # declarations, then recompute routes and the namespace without hooks. - _finalize_authored_scenario(candidate, preparation.source_specs, - preparation.authored, nothing) + _finalize_authored_scenario(candidate, collect(Any, preparation.source_specs), + collect(Any, preparation.authored), nothing) else _prepare_authored_scenario(candidate; raw_families=nothing) end diff --git a/test/test-model-prepared-authoring-owner.jl b/test/test-model-prepared-authoring-owner.jl index 05d04289f..c1263a668 100644 --- a/test/test-model-prepared-authoring-owner.jl +++ b/test/test-model-prepared-authoring-owner.jl @@ -31,7 +31,11 @@ end preparation = data.model.scenario_plan_cache @test plan.authoring.preparation === preparation @test preparation.owner === data.model - @test preparation.source_specs === Tuple(data.model.applications) + @test preparation.source_specs isa Vector{Any} + @test preparation.source_specs !== data.model.applications + @test length(preparation.source_specs) == length(data.model.applications) + @test all(preparation.source_specs[index] === data.model.applications[index] + for index in eachindex(data.model.applications)) @test data.hint_calls[] == 1 original_ref = PSE.refvalue(model_status(data.model, :leaf), :visits) @@ -114,7 +118,12 @@ end @test data.model.scenario_plan_cache === preparation @test alternate.scenario_plan.authoring.preparation !== preparation @test alternate.scenario_plan.authoring.preparation.owner === alternate_model - @test alternate.scenario_plan.authoring.preparation.source_specs === alternate_specs + alternate_sources = alternate.scenario_plan.authoring.preparation.source_specs + @test alternate_sources isa Vector{Any} + @test alternate_sources !== alternate_model.applications + @test length(alternate_sources) == length(alternate_specs) + @test all(alternate_sources[index] === alternate_specs[index] + for index in eachindex(alternate_sources)) @test PSE._refresh_runtime_bindings!(data.model, canonical) === canonical step!(simulation) @test simulation.compiled === canonical From 991a8b5ffe1a83e626aa96b1b1e0387f2b524549 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 15:27:05 +0100 Subject: [PATCH 163/324] Keep lifecycle refresh operations inside typed owners Validate admission with 383 assertions across four whole files and distributed output/retention with 346 assertions across two whole files on the exact V7 source. Native distributed JuliaC safe validation remains incomplete: run3 reported verifier errors. Full XPalm, 4160-day parity and performance qualification remain pending. --- src/composite_model/compilation.jl | 172 +++++++++++------- .../prepared_status_manifest.jl | 20 +- src/composite_model/runtime_outputs.jl | 99 +++++++--- 3 files changed, 202 insertions(+), 89 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 10e71410a..fb30eb201 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3969,6 +3969,43 @@ Base.@noinline function _status_view_key_epoch_is_current(view, model, key) return _status_view_epoch_is_current(view, model, object_id) end +# Keep the real application inside its finite metadata branch. Transient +# views are read only after admission, never captured by a metadata callback. +function _refresh_model_status_view_for_target!( + application, model, compiled, views, previous_views, key, + input_bindings_by_target, applications_by_id, positions, + distributed_outputs, previous_temporal_sources, +) + application_id, object_id = key + previous_view = get(previous_views, key, nothing) + if !isnothing(previous_view) + Base.@inline _with_model_status_view(_record_previous_temporal_sources!, + compiled.status_view_schema, application_id, previous_view, + previous_temporal_sources, key) + end + current_view = _compile_model_status_view( + model, + application, + object_id, + get(input_bindings_by_target, key, ()), + applications_by_id, + positions, + distributed_outputs, + _status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema), + compiled.status_view_schema, + compiled.input_bindings, + ) + views[key] = isnothing(previous_view) ? + current_view : + Base.@inline _preserve_model_status_view_temporal_state!( + compiled.status_view_schema, application_id, current_view, + previous_view, + previous_temporal_sources, + key, + ) + return nothing +end + function _extend_model_status_views( model::CompositeModel, compiled::CompiledCompositeModel, @@ -4031,33 +4068,12 @@ function _extend_model_status_views( end end for key in affected_keys - application_id, object_id = key - application = applications_by_id[application_id] - previous_view = get(previous_views, key, nothing) - if !isnothing(previous_view) - Base.@inline _with_model_status_view(_record_previous_temporal_sources!, - compiled.status_view_schema, application_id, previous_view, - previous_temporal_sources, key) - end - current_view = _compile_model_status_view( - model, - application, - object_id, - get(input_bindings_by_target, key, ()), - applications_by_id, - positions, - distributed_outputs, - _status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema), - compiled.status_view_schema, - compiled.input_bindings, - ) - views[key] = isnothing(previous_view) ? - current_view : - Base.@inline _preserve_model_status_view_temporal_state!( - compiled.status_view_schema, application_id, current_view, - previous_view, - previous_temporal_sources, - key, + application_id = getfield(key, 1) + _with_metadata_entry( + _refresh_model_status_view_for_target!, applications_by_id, + application_id, model, compiled, views, previous_views, key, + input_bindings_by_target, applications_by_id, positions, + distributed_outputs, previous_temporal_sources, ) end return views @@ -4601,7 +4617,7 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S model, input_bindings, input_bindings_by_target, many_binding_cache, changed_bindings, rewired_consumer_ids, affected_temporal_keys, previous_temporal_sources, processed_many_sources, previous_shared_many_sources, forced_input_binding_keys, pure_addition, - writer_rebind_keys, structural_dirty_ids, applications_by_object, applications_by_id, + writer_rebind_keys, has_writer_rebinds, structural_dirty_ids, applications_by_object, applications_by_id, distributed_outputs, added_ids, performance, queued_binding_indices, pending_binding_indices, ) = state @@ -4631,7 +4647,7 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S (previous_shared_many_sources[binding.source_ids] = copy(source_ids)) default_scope = _default_dependency_scope(model, consumer_id) if !pure_addition && - (isnothing(writer_rebind_keys) || !(binding_key in writer_rebind_keys)) + (!has_writer_rebinds || !(binding_key in writer_rebind_keys)) structural_update = _update_structural_many_sources!( model, binding, @@ -4892,9 +4908,11 @@ function _extend_compiled_scene( previous_shared_many_sources = IdDict{Any,Vector{I}}() rebuild_dynamic_input_index = !pure_addition candidate_binding_indices = Set{Int}() - writer_rebind_keys = nothing + # Keep one key schema; the inactive alias is never queried as writer evidence. + writer_rebind_keys = forced_input_binding_keys + has_writer_rebinds = false if !isnothing(changed_writers_by_variable) - rebinds = pure_addition ? forced_input_binding_keys : Set{Tuple{Symbol,ObjectId,Symbol}}() + rebinds = pure_addition ? forced_input_binding_keys : empty(forced_input_binding_keys) _force_distributed_producer_rebinds!( rebinds, model, @@ -4904,6 +4922,7 @@ function _extend_compiled_scene( if !pure_addition union!(forced_input_binding_keys, rebinds) writer_rebind_keys = rebinds + has_writer_rebinds = true end end if !isempty(forced_input_binding_keys) @@ -4935,7 +4954,7 @@ function _extend_compiled_scene( model, input_bindings, input_bindings_by_target, many_binding_cache, changed_bindings, rewired_consumer_ids, affected_temporal_keys, previous_temporal_sources, processed_many_sources, previous_shared_many_sources, forced_input_binding_keys, pure_addition, - writer_rebind_keys, structural_dirty_ids, applications_by_object, applications_by_id, + writer_rebind_keys, has_writer_rebinds, structural_dirty_ids, applications_by_object, applications_by_id, distributed_outputs, added_ids, performance, queued_binding_indices, pending_binding_indices, ) @@ -6369,15 +6388,42 @@ function _input_carrier( return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end +_has_stream_only_output(application, source_var::Symbol) = + _publish_mode_for_output(application.spec, source_var) == :stream_only + +_source_application_targets_object(application, source_id::ObjectId) = + source_id in application.target_ids + function _has_stream_only_input_source( source_application_ids, source_var::Symbol, applications_by_id, ) return any(source_application_ids) do application_id - application = applications_by_id[application_id] - _publish_mode_for_output(application.spec, source_var) == - :stream_only + Base.@inline _with_metadata_entry(_has_stream_only_output, + applications_by_id, application_id, source_var) + end +end + +function _stream_only_initial_reference( + application::CompiledModelApplication, + model::CompositeModel, + source_id::ObjectId, + source_var::Symbol, +) + _has_stream_only_output(application, source_var) || return nothing + return Base.@inline _with_application_variant(application, source_id) do effective_model, ports + initial, _, _ = _materialize_status_value( + model, + source_var, + getproperty(_local_output_schema(effective_model), source_var); + object_id=source_id, + application_id=application.id, + origin=:stream_only_source_default, + private_copy=true, + reuse=true, + ) + return Ref(initial) end end @@ -6388,29 +6434,15 @@ function _stream_only_initial_reference( source_var::Symbol, applications_by_id, ) - matching_applications = CompiledModelApplication[ - applications_by_id[application_id] - for application_id in source_application_ids - if source_id in applications_by_id[application_id].target_ids + matching_application_ids = Symbol[ + application_id for application_id in source_application_ids + if Base.@inline _with_metadata_entry(_source_application_targets_object, + applications_by_id, application_id, source_id) ] - if length(matching_applications) == 1 - application = only(matching_applications) - if _publish_mode_for_output(application.spec, source_var) == - :stream_only - return Base.@inline _with_application_variant(application, source_id) do effective_model, ports - initial, _, _ = _materialize_status_value( - model, - source_var, - getproperty(_local_output_schema(effective_model), source_var); - object_id=source_id, - application_id=application.id, - origin=:stream_only_source_default, - private_copy=true, - reuse=true, - ) - return Ref(initial) - end - end + if length(matching_application_ids) == 1 + reference = Base.@inline _with_metadata_entry(_stream_only_initial_reference, + applications_by_id, only(matching_application_ids), model, source_id, source_var) + isnothing(reference) || return reference end return _status_ref_or_nothing( _model_object(model, source_id).status, @@ -7649,6 +7681,10 @@ function _private_temporal_value(value) return _private_initial_value(value) end +# Test source ownership inside the existing finite application metadata branch. +_temporal_source_application_matches(application, distributed_outputs, source_id, source_var) = + _application_writes_object_variable(distributed_outputs, application, source_id, source_var) + function _temporal_source_application( binding::CompiledModelInputBinding, source_id::ObjectId, @@ -7661,11 +7697,9 @@ function _temporal_source_application( return only(binding.source_application_ids) matches = Symbol[ application_id for application_id in binding.source_application_ids - if _application_writes_object_variable( - distributed_outputs, - applications_by_id[application_id], - source_id, - binding.source_var, + if Base.@inline _with_metadata_entry( + _temporal_source_application_matches, applications_by_id, application_id, + distributed_outputs, source_id, binding.source_var, ) ] canonical_application = _distributed_temporal_source_application( @@ -9181,6 +9215,20 @@ end end end +# Some prepared indexes already own immutable named tuples. Select their +# scalar entry directly, without allocating a second metadata-table wrapper. +@generated function _with_metadata_entry(f::F, entries::T, key::Symbol, + args::Vararg{Any,N}, +) where {F,T<:NamedTuple,N} + branches = [:(key === $(QuoteNode(name)) && + return f(getfield(entries, $index), args...)) + for (index, name) in enumerate(fieldnames(T))] + return quote + $(branches...) + throw(KeyError(key)) + end +end + # Execution plans already have a typed tuple boundary; its callback uses the # same scalar-entry operation as fixed metadata owners. Never unwrap an owner # into a tuple to enter this method. diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index c54a558ad..b6d9e26f0 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -391,7 +391,10 @@ Base.@constprop :none Base.@noinline function _prepared_status_destination_entry # synthetic producer is allocated by this admission path. has_producer = false for (execution_id, producer) in model.registry.objects - _prepared_status_application_matches(model, producer, producer.parent, application) || continue + producer_parent = producer.parent + producer_parent_id = isnothing(producer_parent) ? nothing : + _index_object_id(model.registry.objects, producer_parent) + _prepared_status_application_matches(model, producer, producer_parent_id, application) || continue has_producer = true _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue @@ -466,7 +469,10 @@ function _prepared_status_source_routes_admission(sources::Tuple, application, p if source.plan.source_var === name has_consumer = false for (consumer_id, consumer) in model.registry.objects - _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue + consumer_parent = consumer.parent + consumer_parent_id = isnothing(consumer_parent) ? nothing : + _index_object_id(model.registry.objects, consumer_parent) + _prepared_status_application_matches(model, consumer, consumer_parent_id, application) || continue has_consumer = true _prepared_status_route_matches(model, object, parent_id, application, source.plan, consumer_id) || continue @@ -591,7 +597,10 @@ function _prepared_status_raw_destination_count(applications::Tuple, plan, raw, Base.tail(applications), plan, raw, model, object, parent_id) count = 0 for (execution_id, producer) in model.registry.objects - _prepared_status_application_matches(model, producer, producer.parent, application) || continue + producer_parent = producer.parent + producer_parent_id = isnothing(producer_parent) ? nothing : + _index_object_id(model.registry.objects, producer_parent) + _prepared_status_application_matches(model, producer, producer_parent_id, application) || continue _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue variant = _prepared_status_variant_slot(application, execution_id) @@ -613,7 +622,10 @@ function _prepared_status_raw_source_count(sources::Tuple, application, raw, mod source = first(sources) count = 0 for (consumer_id, consumer) in model.registry.objects - _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue + consumer_parent = consumer.parent + consumer_parent_id = isnothing(consumer_parent) ? nothing : + _index_object_id(model.registry.objects, consumer_parent) + _prepared_status_application_matches(model, consumer, consumer_parent_id, application) || continue _prepared_status_route_matches(model, object, parent_id, application, source.plan, consumer_id) || continue variant = _prepared_status_variant_slot(application, consumer_id) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index d7ead6110..29a1f098c 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1925,6 +1925,77 @@ function _initialize_model_output_stream!( sizehint_steps, application.clock.dt) end +# Lifecycle groups keep their open cache shell; this operation needs only the +# existing plan and membership, never the columns' changing carrier types. +@inline function _with_model_output_destination_membership(f::F, + plan::CompiledModelOutputDestinationPlan{GROUP}, groups::NamedTuple, + application::CompiledModelApplication{P,I}, args::Vararg{Any,N}, +) where {F,GROUP,P,I,N} + plan.application_id === application.id || return nothing + isdefined(groups, GROUP) || return nothing + binding = getfield(groups, GROUP)::CompiledModelOutputDestinationBinding + destination_ids = getfield(binding, :destination_ids)::Vector{I} + return f(plan, destination_ids, args...) +end + +function _initialize_changed_model_output_destination_streams!( + plan, destination_ids, streams, compiled, retention, application, variables, + sizehint_steps, +) + for variable_ in plan.variable_names + variable = Symbol(variable_) + variable in variables || continue + for destination_id in destination_ids + id = _index_object_id(compiled.model.registry.objects, destination_id) + _initialize_model_output_stream!( + streams, + compiled, + retention, + application, + id, + variable, + sizehint_steps, + ) + end + end + return nothing +end + +function _initialize_changed_model_output_plan_streams!( + plan, object_id, streams, compiled, retention, application, variables, + sizehint_steps, +) + # Admit the finite plan before reading the lifecycle cache's open shell. + groups = get( + compiled.distributed_outputs.by_execution_target, + (application.id, object_id), + nothing, + ) + isnothing(groups) && return nothing + groups isa NamedTuple || throw(ArgumentError( + "Compiled output destination groups must be a named tuple.", + )) + return _with_model_output_destination_membership( + _initialize_changed_model_output_destination_streams!, plan, groups, + application, streams, compiled, retention, application, variables, + sizehint_steps, + ) +end + +function _initialize_changed_model_output_application_streams!( + application_plans, object_id, streams, compiled, retention, application, + variables, sizehint_steps, +) + for slot in 1:length(application_plans) + _with_metadata_entry( + _initialize_changed_model_output_plan_streams!, application_plans, + slot, object_id, streams, compiled, retention, application, variables, + sizehint_steps, + ) + end + return nothing +end + function _initialize_changed_model_output_streams!( streams, compiled::CompiledCompositeModel, @@ -1957,30 +2028,12 @@ function _initialize_changed_model_output_streams!( end end compiled.distributed_outputs isa CompiledDistributedOutputs || return nothing - groups = get( - compiled.distributed_outputs.by_execution_target, - (application_id, object_id), - nothing, + plans = compiled.scenario_plan.distributed_output_plans::CompiledDistributedOutputPlans + _with_metadata_entry( + _initialize_changed_model_output_application_streams!, + plans.by_application, application_id, object_id, streams, compiled, + retention, application, variables, sizehint_steps, ) - isnothing(groups) && return nothing - for binding in values(groups) - for variable_ in binding.plan.variable_names - variable = Symbol(variable_) - variable in variables || continue - for destination_id in binding.destination_ids - id = _index_object_id(compiled.model.registry.objects, destination_id) - _initialize_model_output_stream!( - streams, - compiled, - retention, - application, - id, - variable, - sizehint_steps, - ) - end - end - end end end return streams From fc3482a632b4568047fbc9c9a78ca2f37bf4e5ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 16:42:07 +0100 Subject: [PATCH 164/324] Keep source selection and rebind keys concrete Validate the V9 source with 639 assertions across three whole files. The V8 distributed/retention 346-assertion block and source/multirate 149-assertion block remain separate results. Native V9 run9 was cancelled after three real JuliaC safe verifier errors; owned processes were drained. Complete native parity, full XPalm qualification and performance validation remain pending. --- src/composite_model/compilation.jl | 70 +++++++++++++++++------------- 1 file changed, 39 insertions(+), 31 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index fb30eb201..c7283359a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4246,6 +4246,10 @@ function _sorted_object_ids_intersect_set(sorted_ids, ids::AbstractSet) return false end +# Rebind keys use the same prepared identity family as the registry index. +_input_binding_key_set(::AbstractDict{I}) where {I<:ObjectId} = + Set{Tuple{Symbol,I,Symbol}}() + function _prepare_structural_compiled_delta( model::CompositeModel, compiled::CompiledCompositeModel, @@ -4288,12 +4292,13 @@ function _prepare_structural_compiled_delta( end push!(input_bindings, binding) end - forced_input_binding_keys = Set{Tuple{Symbol,ObjectId,Symbol}}() + forced_input_binding_keys = _input_binding_key_set(model.registry.objects) previous_temporal_sources = _previous_temporal_source_storage(model) for binding in input_bindings _sorted_object_ids_intersect_set(binding.source_ids, dirty) || continue - key = (binding.application_id, binding.consumer_id, binding.input) + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + key = (binding.application_id, consumer_id, binding.input) push!(forced_input_binding_keys, key) if binding.carrier_hint == :temporal_stream previous_temporal_sources[key] = copy(binding.source_ids) @@ -4761,7 +4766,7 @@ function _extend_compiled_scene( model::CompositeModel, compiled::CompiledCompositeModel, added_objects; - forced_input_binding_keys=Set{Tuple{Symbol,ObjectId,Symbol}}(), + forced_input_binding_keys=_input_binding_key_set(model.registry.objects), forced_call_target_keys=Set{Tuple{Symbol,ObjectId}}(), previous_views=compiled.status_views_by_target, previous_temporal_sources_seed=_previous_temporal_source_storage(model), @@ -7421,19 +7426,21 @@ function _force_distributed_producer_rebinds!(forced, model, bindings, by_variab continue candidates = get(by_variable, binding.source_var, ()) isempty(candidates) && continue - default_scope = _default_dependency_scope(model, binding.consumer_id) - for (destination, producer) in candidates + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + default_scope = _default_dependency_scope(model, consumer_id) + for (raw_destination, producer) in candidates producer in binding.plan.potential_source_application_ids || continue + destination = _index_object_id(model.registry.objects, raw_destination) _selector_matches_object_id( model, binding.matcher, destination, - binding.consumer_id, + consumer_id, true, default_scope, false, ) || continue - push!(forced, (binding.application_id, binding.consumer_id, binding.input)) + push!(forced, (binding.application_id, consumer_id, binding.input)) break end end @@ -7682,7 +7689,7 @@ function _private_temporal_value(value) end # Test source ownership inside the existing finite application metadata branch. -_temporal_source_application_matches(application, distributed_outputs, source_id, source_var) = +_application_writes_source_variable(application, distributed_outputs, source_id, source_var) = _application_writes_object_variable(distributed_outputs, application, source_id, source_var) function _temporal_source_application( @@ -7698,7 +7705,7 @@ function _temporal_source_application( matches = Symbol[ application_id for application_id in binding.source_application_ids if Base.@inline _with_metadata_entry( - _temporal_source_application_matches, applications_by_id, application_id, + _application_writes_source_variable, applications_by_id, application_id, distributed_outputs, source_id, binding.source_var, ) ] @@ -8610,32 +8617,37 @@ end _application_plans(plans_by_application, application_id::Symbol) = plans_by_application[application_id] +function _append_potential_input_source_application!( + application, matches, source_var::Symbol, process_filter, application_filter, +) + if _application_declares_output_name(application, source_var) && + (isnothing(process_filter) || application.process == process_filter) && + (isnothing(application_filter) || application.id == application_filter) + push!(matches, application.id) + end + return nothing +end + function _potential_input_source_applications( applications_by_id, source_var::Symbol, process_filter, application_filter, ) - matches = Symbol[ - application.id - for application in values(applications_by_id) - if _application_declares_output_name(application, source_var) && - (isnothing(process_filter) || application.process == process_filter) && - (isnothing(application_filter) || application.id == application_filter) - ] + matches = Symbol[] + for application_id in keys(applications_by_id) + Base.@inline _with_metadata_entry( + _append_potential_input_source_application!, applications_by_id, + application_id, matches, source_var, process_filter, application_filter, + ) + end sort!(matches) return matches end function _application_declares_output_name(application, variable::Symbol) - variable in _model_output_names(application) && return true - destinations = _output_destination_layout( - application.spec, _model_distributed_output_names(application), - ) - return any( - destination -> variable in destination.variable_names, - values(destinations), - ) + # Destination layouts are validated before input bindings resolve. + return variable in _application_ports(application).outputs.all_names end function _final_canonical_source_application( @@ -8944,14 +8956,10 @@ function _final_many_source_applications( final_owner = isnothing(writer) ? nothing : writer.application_id if isnothing(final_owner) for application_id in source_application_ids - application = applications_by_id[application_id] - first( - _sorted_object_id_position( - application.target_ids, - source_id, - ), + Base.@inline _with_metadata_entry( + _application_writes_source_variable, applications_by_id, + application_id, NoCompiledDistributedOutputs(), source_id, source_var, ) || continue - source_var in _model_output_names(application) || continue application_id in canonical_ids || push!(canonical_ids, application_id) end From f54e1c3aad28804c5a0880fae15aab74b86d7c5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 18:45:34 +0100 Subject: [PATCH 165/324] Use prepared memberships for distributed refresh Validate V13 with 346 assertions across the distributed-runtime and retention-owner whole files on this exact source. Results from other source versions remain separate. Native run18 was cancelled after four real JuliaC safe verifier diagnostics and all owned processes were drained. The public XPalm control run16 reached its 300-second bound before CompositeModel returned. Complete native parity, full XPalm and performance qualification remain pending. --- src/composite_model/compilation.jl | 216 ++++++++++++++++++++++------- 1 file changed, 164 insertions(+), 52 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index c7283359a..993297d60 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5972,7 +5972,7 @@ function _resolve_model_output_destinations( ) end end - return Tuple(resolved) + return resolved end function _push_compiled_writer_owner!( @@ -7116,22 +7116,27 @@ function _compile_model_distributed_outputs( ) end -_distributed_output_binding_key(binding) = ( - binding.application_id, - binding.execution_object_id, - binding.group, -) +function _distributed_output_target_membership( + objects::AbstractDict{I}, outputs::CompiledDistributedOutputs, +) where {I<:ObjectId} + membership = Dict{Tuple{Symbol,I,Symbol},Vector{I}}() + for raw_binding in outputs.bindings + binding = raw_binding::CompiledModelOutputDestinationBinding + plan = getfield(binding, :plan)::CompiledModelOutputDestinationPlan + object_id = _index_object_id(objects, getfield(binding, :execution_object_id)) + destination_ids = getfield(binding, :destination_ids)::Vector{I} + key = (getfield(plan, :application_id), object_id, getfield(plan, :group)) + membership[key] = destination_ids + end + return membership +end -function _changed_distributed_output_target_ids(previous, current) - previous_membership = Dict( - _distributed_output_binding_key(binding) => binding.destination_ids - for binding in previous.bindings - ) - current_membership = Dict( - _distributed_output_binding_key(binding) => binding.destination_ids - for binding in current.bindings - ) - changed = Set{Tuple{Symbol,ObjectId}}() +function _changed_distributed_output_target_ids( + objects::AbstractDict{I}, previous, current, +) where {I<:ObjectId} + previous_membership = _distributed_output_target_membership(objects, previous) + current_membership = _distributed_output_target_membership(objects, current) + changed = Set{Tuple{Symbol,I}}() for key in union(keys(previous_membership), keys(current_membership)) get(previous_membership, key, nothing) == get(current_membership, key, nothing) && continue @@ -7362,58 +7367,165 @@ function _refresh_model_distributed_outputs( manual_application_ids, plans, ) - changed_targets = _changed_distributed_output_target_ids(previous, current) + changed_targets = _changed_distributed_output_target_ids( + model.registry.objects, previous, current, + ) changed_writers_by_variable = if pure_addition # A new origin may write to a destination already in the registry. - _new_writers_on_existing_destinations(current, new_targets, added_ids) + _new_writers_on_existing_destinations( + model, current, new_targets, added_ids, applications_by_id, plans, + ) else - _changed_writers_on_surviving_destinations(model, previous, current, changed_targets) + _changed_writers_on_surviving_destinations( + model, previous, current, changed_targets, applications_by_id, plans, + ) end return current, changed_targets, changed_writers_by_variable end -function _new_writers_on_existing_destinations(outputs, new_targets, added_ids) +function _append_output_destination_writer!(plan, destination, by_variable) + if isnothing(by_variable) + by_variable = Dict{Symbol,Vector{Tuple{ObjectId,Symbol}}}() + end + for variable in plan.variable_names + push!(get!(Vector{Tuple{ObjectId,Symbol}}, by_variable, variable), + (destination, plan.application_id)) + end + return by_variable +end + +function _append_existing_destination_writers!( + plan, destination_ids, added, by_variable, +) + for destination in destination_ids + destination in added && continue + by_variable = _append_output_destination_writer!(plan, destination, by_variable) + end + return by_variable +end + +function _new_output_plan_writers( + plan, object_id, outputs, added, application, by_variable, +) + key = (application.id, object_id) + groups = get(outputs.by_execution_target, key, NamedTuple())::NamedTuple + isdefined(groups, plan.group) || return by_variable + return _with_model_output_destination_membership( + _append_existing_destination_writers!, plan, groups, application, + added, by_variable, + ) +end + +function _new_output_application_writers( + application_plans, object_id, outputs, added, application, by_variable, +) + for slot in 1:length(application_plans) + by_variable = _with_metadata_entry( + _new_output_plan_writers, application_plans, slot, + object_id, outputs, added, application, by_variable, + ) + end + return by_variable +end + +function _new_output_application_writers( + application::CompiledModelApplication, object_id, outputs, added, + plans::CompiledDistributedOutputPlans, by_variable, +) + return _with_metadata_entry( + _new_output_application_writers, plans.by_application, application.id, + object_id, outputs, added, application, by_variable, + ) +end + +function _new_writers_on_existing_destinations( + model, outputs, new_targets, added_ids, applications_by_id, + plans::CompiledDistributedOutputPlans, +) added = Set(added_ids) by_variable = nothing for (application_id, origins) in new_targets, origin in origins - groups = get(outputs.by_execution_target, (application_id, origin), ()) - for group in groups, destination in group.destination_ids - destination in added && continue - if isnothing(by_variable) - by_variable = Dict{Symbol,Vector{Tuple{ObjectId,Symbol}}}() - end - for variable in group.plan.variable_names - push!( - get!(Vector{Tuple{ObjectId,Symbol}}, by_variable, variable), - (destination, application_id), - ) - end + object_id = _index_object_id(model.registry.objects, origin) + by_variable = _with_metadata_entry( + _new_output_application_writers, applications_by_id, + application_id, object_id, outputs, added, plans, by_variable, + ) + end + return by_variable +end + +function _append_changed_destination_writers!( + plan, other_ids, model, destination_ids, by_variable, +) + for destination in destination_ids + haskey(model.registry.objects, destination) || continue + first(_sorted_object_id_position(other_ids, destination)) && continue + by_variable = _append_output_destination_writer!(plan, destination, by_variable) + end + return by_variable +end + +function _compare_changed_destination_writers!( + plan, destination_ids, model, other, application, by_variable, +) + isdefined(other, plan.group) || return _append_changed_destination_writers!( + plan, (), model, destination_ids, by_variable, + ) + return _with_model_output_destination_membership( + _append_changed_destination_writers!, plan, other, application, + model, destination_ids, by_variable, + ) +end + +function _changed_output_plan_writers( + plan, object_id, model, outputs, other_outputs, application, by_variable, +) + key = (application.id, object_id) + groups = get(outputs.by_execution_target, key, NamedTuple())::NamedTuple + isdefined(groups, plan.group) || return by_variable + other = get(other_outputs.by_execution_target, key, NamedTuple())::NamedTuple + return _with_model_output_destination_membership( + _compare_changed_destination_writers!, plan, groups, application, + model, other, application, by_variable, + ) +end + +function _changed_output_application_writers( + application_plans, object_id, model, previous, current, application, + by_variable, +) + for (outputs, other_outputs) in ((previous, current), (current, previous)) + for slot in 1:length(application_plans) + by_variable = _with_metadata_entry( + _changed_output_plan_writers, application_plans, slot, + object_id, model, outputs, other_outputs, application, by_variable, + ) end end return by_variable end -function _changed_writers_on_surviving_destinations(model, previous, current, changed_targets) +function _changed_output_application_writers( + application::CompiledModelApplication, object_id, model, previous, current, + plans::CompiledDistributedOutputPlans, by_variable, +) + return _with_metadata_entry( + _changed_output_application_writers, plans.by_application, application.id, + object_id, model, previous, current, application, by_variable, + ) +end + +function _changed_writers_on_surviving_destinations( + model, previous, current, changed_targets, applications_by_id, + plans::CompiledDistributedOutputPlans, +) by_variable = nothing - for key in changed_targets - before = get(previous.by_execution_target, key, NamedTuple()) - after = get(current.by_execution_target, key, NamedTuple()) - for (groups, other) in ((before, after), (after, before)) - for (name, group) in pairs(groups) - other_ids = haskey(other, name) ? other[name].destination_ids : () - for destination in group.destination_ids - haskey(model.registry.objects, destination) || continue - first(_sorted_object_id_position(other_ids, destination)) && continue - if isnothing(by_variable) - by_variable = Dict{Symbol,Vector{Tuple{ObjectId,Symbol}}}() - end - for variable in group.plan.variable_names - push!(get!(Vector{Tuple{ObjectId,Symbol}}, by_variable, variable), - (destination, group.application_id)) - end - end - end - end + for (application_id, raw_object_id) in changed_targets + object_id = _index_object_id(model.registry.objects, raw_object_id) + by_variable = _with_metadata_entry( + _changed_output_application_writers, applications_by_id, + application_id, object_id, model, previous, current, plans, by_variable, + ) end return by_variable end From 1930c0b4df8c53b247244e68ff6cb5c051822684 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 21:27:23 +0100 Subject: [PATCH 166/324] Build distributed bindings from prepared plan groups Keep destination column construction, execution groups and target indexes within their prepared metadata owners. Preserve destination order, shared Ref cells, and existing merge behavior. Validation: V16 passed 346 assertions in two complete distributed-runtime/retention files. A separate carrier control passed 18 checks plus 16 guards. Source/input guards and owned-process drains were exact. Native D run31 was cancelled after three real safe-verifier errors; no executable or complete native parity is qualified. The XPalm141 birth control reached its 1200-second bound without a scientific verdict. Full XPalm, reference and performance qualification remain pending. --- src/composite_model/compilation.jl | 212 +++++++++++++++++++---------- 1 file changed, 138 insertions(+), 74 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 993297d60..b803d8067 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6470,8 +6470,17 @@ function _stream_only_initial_carrier( return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end -function _ref_vector_carrier(refs) - T = typeof(refs[1][]) +_ref_vector_carrier(refs) = _ref_vector_carrier(first(refs), refs) + +function _ref_vector_carrier(first_ref::Ref, refs) + first_ref[] + return ObjectRefVector(refs) +end + +function _ref_vector_carrier(first_ref::Base.RefValue{T}, refs) where {T} + # Retain the original first-value read, including uninitialized-Ref errors. + first_ref[] + isconcretetype(T) || return ObjectRefVector(refs) typed_refs = Base.RefValue{T}[] sizehint!(typed_refs, length(refs) + 1) for source_ref in refs @@ -6957,23 +6966,24 @@ function _prepare_model_output_destination_statuses!( end end -function _model_output_destination_columns( +function _model_output_destination_column( + model::CompositeModel, destination_ids, ::Val{VARIABLE}, +) where {VARIABLE} + refs = [refvalue(model_status(model, destination_id), VARIABLE) + for destination_id in destination_ids] + return isempty(refs) ? RefVector{Any}() : _ref_vector_carrier(refs) +end + +@generated function _model_output_destination_columns( model::CompositeModel, - resolved::ResolvedModelOutputDestination, -) - declarations = resolved.declarations - names = Tuple(Symbol.(keys(declarations))) - columns = map(names) do variable - refs = Base.RefValue[ - refvalue( - _model_object(model, destination_id).status, - variable, - ) - for destination_id in resolved.destination_ids - ] - isempty(refs) ? RefVector{Any}() : _ref_vector_carrier(refs) - end - return NamedTuple{names}(Tuple(columns)) + ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, + destination_ids, +) where {GROUP,NAMES} + columns = Expr(:tuple, [:( + _model_output_destination_column(model, destination_ids, + Val{$(QuoteNode(name))}()) + ) for name in NAMES]...) + return :(NamedTuple{$(QuoteNode(NAMES))}($columns)) end function _model_output_destination_index(destination_ids::AbstractVector{I}) where {I<:ObjectId} @@ -6989,73 +6999,125 @@ function _model_output_destination_index(destination_ids::AbstractVector{I}) whe return index end +function _append_model_output_destination_binding!(plan, model, resolved, bindings) + I = keytype(model.registry.objects) + execution_object_id = _index_object_id( + model.registry.objects, getfield(resolved, :execution_object_id), + ) + destination_ids = getfield(resolved, :destination_ids)::Vector{I} + binding = CompiledModelOutputDestinationBinding( + plan, + execution_object_id, + destination_ids, + _model_output_destination_columns(model, plan, destination_ids), + _model_output_destination_index(destination_ids), + UInt64(model.revision), + ) + push!(bindings, binding) + return binding +end + +function _model_output_plan_binding_rows(plan, model, resolved_by_plan, bindings) + resolved = get!(Vector{ResolvedModelOutputDestination}, resolved_by_plan, plan.slot) + return [_append_model_output_destination_binding!(plan, model, row, bindings) + for row in resolved] +end + +# The tuple follows authored groups; only the vectors' lengths depend on organs. +# Every row reuses the exact binding already appended in plan/origin order. +@generated function _publish_model_output_binding_groups!( + plans::P, rows, objects::AbstractDict{I}, by_execution_target, +) where {P<:Tuple,I<:ObjectId} + isempty(fieldtypes(P)) && return :(nothing) + names = Tuple(Plan.parameters[1] for Plan in fieldtypes(P)) + values = Expr(:tuple, [:(getfield(rows, $slot)[row]) + for slot in 1:fieldcount(P)]...) + return quote + first_rows = getfield(rows, 1) + for row in eachindex(first_rows) + execution_object_id = _index_object_id( + objects, getfield(first_rows[row], :execution_object_id), + ) + groups = NamedTuple{$(QuoteNode(names))}($values) + by_execution_target[(getfield(getfield(plans, 1), :application_id), + execution_object_id)] = groups + end + return nothing + end +end + +function _compile_model_output_application_bindings!( + plans, model, resolved_by_plan, bindings, by_execution_target, +) + rows = map(plans) do plan + _model_output_plan_binding_rows(plan, model, resolved_by_plan, bindings) + end + return _publish_model_output_binding_groups!( + plans, rows, model.registry.objects, by_execution_target, + ) +end + function _compile_model_output_destination_bindings( model::CompositeModel, resolved_destinations, + plans::CompiledDistributedOutputPlans, ) bindings = Any[] sizehint!(bindings, length(resolved_destinations)) - by_execution_pairs = Dict{ - Tuple{Symbol,ObjectId}, - Vector{Pair{Symbol,Any}}, - }() + resolved_by_plan = Dict{Int,Vector{ResolvedModelOutputDestination}}() for resolved in resolved_destinations - binding = CompiledModelOutputDestinationBinding( - resolved.plan, - resolved.execution_object_id, - resolved.destination_ids, - _model_output_destination_columns(model, resolved), - _model_output_destination_index(resolved.destination_ids), - UInt64(model.revision), - ) - push!(bindings, binding) - push!( - get!( - by_execution_pairs, - ( - resolved.plan.application_id, - resolved.execution_object_id, - ), - Pair{Symbol,Any}[], - ), - resolved.plan.group => binding, - ) + plan = getfield(resolved, :plan)::CompiledModelOutputDestinationPlan + push!(get!(Vector{ResolvedModelOutputDestination}, resolved_by_plan, + getfield(plan, :slot)), resolved) end by_execution_target = Dict{Tuple{Symbol,ObjectId},Any}() - for (key, group_bindings) in by_execution_pairs - names = Tuple(first(pair) for pair in group_bindings) - values = Tuple(last(pair) for pair in group_bindings) - by_execution_target[key] = NamedTuple{names}(values) - end - # Keep the cache shell type stable across lifecycle refreshes. Membership - # can change both the number of bindings and an initially empty column's - # concrete carrier type. Concrete bindings are installed on execution - # targets later; the scene-wide lifecycle cache deliberately stays widened. + for application_id in keys(plans.by_application) + _with_metadata_entry( + _compile_model_output_application_bindings!, plans.by_application, + application_id, model, resolved_by_plan, bindings, by_execution_target, + ) + end + # Keep the same lifecycle cache shell; its values are built from the finite + # authored groups instead of recovering their schema from erased bindings. return bindings, by_execution_target end -function _index_model_output_destination_ids(model::CompositeModel, bindings) - I = keytype(model.registry.objects) +function _index_model_output_destination_membership!( + plan, binding_ids, index, merged_keys, +) + for variable_ in plan.variable_names + variable = Symbol(variable_) + key = (plan.application_id, variable) + destination_ids = get(index, key, nothing) + if isnothing(destination_ids) + # Destination IDs are already sorted by the compiled selector. + # Share that immutable membership in the common one-binding case. + index[key] = binding_ids + continue + end + if !(key in merged_keys) + destination_ids = copy(destination_ids) + index[key] = destination_ids + push!(merged_keys, key) + end + append!(destination_ids, binding_ids) + end + return nothing +end + +function _index_model_output_destination_ids( + objects::AbstractDict{I}, bindings, plans::CompiledDistributedOutputPlans, +) where {I<:ObjectId} index = Dict{Tuple{Symbol,Symbol},Vector{I}}() merged_keys = Set{Tuple{Symbol,Symbol}}() - for binding in bindings - for variable_ in binding.plan.variable_names - variable = Symbol(variable_) - key = (binding.application_id, variable) - destination_ids = get(index, key, nothing) - if isnothing(destination_ids) - # Destination IDs are already sorted by the compiled selector. - # Share that immutable membership in the common one-binding case. - index[key] = binding.destination_ids - continue - end - if !(key in merged_keys) - destination_ids = copy(destination_ids) - index[key] = destination_ids - push!(merged_keys, key) - end - append!(destination_ids, binding.destination_ids) - end + for raw_binding in bindings + binding = raw_binding::CompiledModelOutputDestinationBinding + plan = getfield(binding, :plan)::CompiledModelOutputDestinationPlan + destination_ids = getfield(binding, :destination_ids)::Vector{I} + _with_metadata_entry( + _index_model_output_destination_membership!, plans.plans, + getfield(plan, :slot), destination_ids, index, merged_keys, + ) end for key in merged_keys destination_ids = index[key] @@ -7107,12 +7169,12 @@ function _compile_model_distributed_outputs( _prepare_model_output_statuses!(model, applications, applications_by_id) _prepare_model_output_destination_statuses!(model, resolved) bindings, by_execution_target = - _compile_model_output_destination_bindings(model, resolved) + _compile_model_output_destination_bindings(model, resolved, plans) return CompiledDistributedOutputs( bindings, by_execution_target, ownership, - _index_model_output_destination_ids(model, bindings), + _index_model_output_destination_ids(model.registry.objects, bindings, plans), ) end @@ -7291,7 +7353,9 @@ function _incremental_distributed_output_addition!( key = (resolved.plan.application_id, resolved.execution_object_id) groups = previous.by_execution_target[key] binding = getproperty(groups, resolved.plan.group) - columns = _model_output_destination_columns(model, resolved) + columns = _model_output_destination_columns( + model, resolved.plan, resolved.destination_ids, + ) for variable in binding.plan.variable_names existing_references = parent(getproperty(binding.columns, variable)) added_references = parent(getproperty(columns, variable)) From 58e896f522ed3d574d7529f53e11dfaa2ce685da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 22:06:51 +0100 Subject: [PATCH 167/324] Log individual test file boundaries Report the group index and file before each normal test include, then log elapsed time in a finally block. Keep include order, focused routes and exception propagation unchanged. Validation: cached diff check and static review passed. No assertions, models or scientific test files changed. The next CI run must qualify the updated runner; earlier green checks do not qualify this new logging. --- test/runtests.jl | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/runtests.jl b/test/runtests.jl index 211569a33..eb3672493 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -54,7 +54,13 @@ else try @testset "$name" begin for file in files - include(file) + @info "Test file start" group_index file + file_started_at = time_ns() + try + include(file) + finally + @info "Test file end" group_index file elapsed_seconds=(time_ns() - file_started_at) / 1.0e9 + end end end finally From fd0e2646a1ee996b9cae90f9c6f8cdad7fe98ee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Tue, 17 Nov 2026 23:55:18 +0100 Subject: [PATCH 168/324] Keep distributed output column views concrete Build output bindings from typed group columns and pass concrete views into execution batches. Preserve output cells and the order of user Ref reads. Validation: 346 existing distributed/retention assertions, 34 carrier checks, parent/candidate Ref protocol checks, and 150 assertions in the updated retention-owner file passed. Native D remains incomplete: its attempt was cancelled after six verifier errors in separate staging paths. No native parity or performance claim. --- src/composite_model/compilation.jl | 240 ++++++++++++------ .../execution_batch_schemas.jl | 25 +- src/composite_model/output_targets.jl | 25 +- src/composite_model/runtime_outputs.jl | 25 +- test/test-model-output-retention-owners.jl | 62 +++++ 5 files changed, 286 insertions(+), 91 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b803d8067..943a1a80a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6320,10 +6320,10 @@ function _status_ref_or_nothing(status::S, variable) where {S} return refvalue(status, name) end -@inline function _checked_input_reference(reference) +@inline function _checked_reference(reference) isnothing(reference) && return nothing reference isa Ref || throw(ArgumentError( - "Input reference carriers require Ref storage; got `$(typeof(reference))`.", + "Reference carriers require Ref storage; got `$(typeof(reference))`.", )) return reference end @@ -6353,34 +6353,45 @@ end R = Union{types...} return quote isempty(source_ids) && return nothing - reference = _checked_input_reference(reference_for(only(source_ids))) + reference = _checked_reference(reference_for(only(source_ids))) isnothing(reference) && return nothing reference isa $R || throw(ArgumentError("An input source reference is outside its prepared family.")) return reference::$R end end -@generated function _input_reference_carrier( - ::Many, source_ids, reference_for::F, ::Type{RT}, +# Input and output preparation collect the same exact Ref family. Carrier +# selection remains the policy of the caller; no cell is converted or copied. +@generated function _collect_reference_family(source_ids, reference_for::F, + ::Type{RT}, ) where {F,RT<:Tuple} - types = fieldtypes(RT) - isempty(types) && return :(throw(ArgumentError("A Many input requires a prepared reference family."))) - all(R -> R <: Ref && isconcretetype(R), types) || - return :(throw(ArgumentError("A Many input requires exact prepared reference types."))) - R = Union{types...} - C = _many_input_carrier_type(RT) - result = :($C(references)) + R = Union{fieldtypes(RT)...} return quote references = $R[] sizehint!(references, length(source_ids) + 1) for source_id in source_ids - reference = _checked_input_reference(reference_for(source_id)) + reference = _checked_reference(reference_for(source_id)) isnothing(reference) && return nothing reference isa $R || throw(ArgumentError( - "An input source reference is outside its prepared Many family.")) + "A reference is outside its prepared collection family.")) push!(references, reference::$R) end - return $result + return references + end +end + +@generated function _input_reference_carrier( + ::Many, source_ids, reference_for::F, ::Type{RT}, +) where {F,RT<:Tuple} + types = fieldtypes(RT) + isempty(types) && return :(throw(ArgumentError("A Many input requires a prepared reference family."))) + all(R -> R <: Ref && isconcretetype(R), types) || + return :(throw(ArgumentError("A Many input requires exact prepared reference types."))) + C = _many_input_carrier_type(RT) + return quote + references = _collect_reference_family(source_ids, reference_for, $RT) + isnothing(references) && return nothing + return $C(references) end end @@ -6917,46 +6928,86 @@ function _validate_model_output_destination_statuses!( return nothing end +function _stage_model_output_destination_statuses!(plan, model, records, index, + applications_by_id, recipes, recipe_order, +) + return _with_metadata_entry(_stage_model_output_destination_statuses!, + applications_by_id, plan.application_id, plan, model, records, index, + recipes, recipe_order) +end +function _stage_model_output_destination_statuses!(application::CompiledModelApplication, + plan, model, records, index, recipes, recipe_order, +) + execution_id = _index_object_id(model.registry.objects, + getfield(records[index], :execution_object_id)) + return _with_application_variant(_stage_model_output_destination_statuses!, + application, execution_id, plan, model, records, index, recipes, recipe_order) +end + +# The existing port inventory admits the declarations captured by this event. +# In particular, no output/default hook is called to recover their lost type. +@generated function _stage_model_output_destination_statuses!(producer, ports::P, + plan::CompiledModelOutputDestinationPlan{GROUP,NAMES}, model, records, index, + recipes::AbstractDict{I}, recipe_order, +) where {P,GROUP,NAMES,I<:ObjectId} + Types = fieldtype(P, :output_declaration_types) + declarations = Tuple(fieldtype(Types, name).parameters[1].parameters[1] for name in NAMES) + D = NamedTuple{NAMES,Tuple{declarations...}} + return quote + record = records[index] + destination_ids = getfield(record, :destination_ids)::Vector{$I} + captured = getfield(record, :declarations) + captured isa $D || throw(ArgumentError( + "A distributed output declaration schema changed after preparation.")) + declarations = captured::$D + for destination_id in destination_ids + preparation = _status_preparation_for_object!( + recipes, + recipe_order, + model, + destination_id, + ) + for (variable_, declaration) in pairs(declarations) + declaration isa Default || continue + variable = Symbol(variable_) + if preparation isa Status + hasproperty(preparation, variable) && continue + preparation = _status_recipe_for_object!( + recipes, + recipe_order, + model, + destination_id, + ) + end + _status_recipe_add_default!( + model, + preparation, + destination_id, + variable, + _input_default(declaration); + application_id=plan.application_id, + origin=:distributed_output_default, + ) + end + end + return nothing + end +end + function _prepare_model_output_destination_statuses!( - model::CompositeModel, - resolved_destinations, + model::CompositeModel, resolved_destinations, applications_by_id, + plans::CompiledDistributedOutputPlans, ) I = keytype(model.registry.objects) recipes = _canonical_status_recipe_storage(model, I) recipe_order = I[] records_before = copy(model.status_conversion_records) try - for resolved in resolved_destinations - for destination_id in resolved.destination_ids - preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - destination_id, - ) - for (variable_, declaration) in pairs(resolved.declarations) - declaration isa Default || continue - variable = Symbol(variable_) - if preparation isa Status - hasproperty(preparation, variable) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, - model, - destination_id, - ) - end - _status_recipe_add_default!( - model, - preparation, - destination_id, - variable, - _input_default(declaration); - application_id=resolved.plan.application_id, - origin=:distributed_output_default, - ) - end - end + for index in eachindex(resolved_destinations) + plan = getfield(resolved_destinations[index], :plan)::CompiledModelOutputDestinationPlan + _with_metadata_entry(_stage_model_output_destination_statuses!, + plans.plans, getfield(plan, :slot), model, resolved_destinations, + index, applications_by_id, recipes, recipe_order) end return _apply_status_recipes!(model, recipes, recipe_order) catch @@ -6966,24 +7017,53 @@ function _prepare_model_output_destination_statuses!( end end -function _model_output_destination_column( - model::CompositeModel, destination_ids, ::Val{VARIABLE}, -) where {VARIABLE} - refs = [refvalue(model_status(model, destination_id), VARIABLE) - for destination_id in destination_ids] - return isempty(refs) ? RefVector{Any}() : _ref_vector_carrier(refs) -end - -@generated function _model_output_destination_columns( - model::CompositeModel, - ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, - destination_ids, -) where {GROUP,NAMES} +function _model_output_destination_column(model, destination_ids, ::Val{VARIABLE}, + ::Type{RT}, +) where {VARIABLE,RT<:Tuple} + reference_for = id -> refvalue(model_status(model, id), VARIABLE) + refs = _collect_reference_family(destination_ids, reference_for, RT) + isnothing(refs) && throw(ArgumentError("A distributed output lost its prepared reference.")) + return _ref_vector_carrier(refs) +end + +# Physical bounds come from the sole canonical Status manifest. Public carrier +# kinds stay exact; this union fixes only the preparation header representation. +function _output_column_carrier_type(::Type{RT}) where {RT<:Tuple} + references = fieldtypes(RT) + R = Union{references...} + carriers = Type[RefVector{Any}] + for T in references + T <: Base.RefValue && isconcretetype(eltype(T)) || continue + push!(carriers, RefVector{eltype(T)}) + end + if length(references) != 1 || !(only(references) <: Base.RefValue) || + !isconcretetype(eltype(only(references))) + push!(carriers, ObjectRefVector{Vector{R}}) + end + return Union{carriers...} +end + +_model_output_destination_columns(model::CompositeModel, plan, destination_ids) = + _with_prepared_canonical_status_type(_model_output_destination_columns, + model, model, plan, destination_ids) +@generated function _model_output_destination_columns(::Type{S}, model, + ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, destination_ids, +) where {S<:Status,GROUP,NAMES} + names, references = _status_schema_names(S), _status_schema_references(S) + families = Tuple(Tuple{Base.uniontypes(fieldtype(references, + findfirst(isequal(name), names)))...} for name in NAMES) + all(R -> all(T -> T <: Ref && isconcretetype(T), fieldtypes(R)), families) || + return :(throw(ArgumentError("An output column requires exact prepared reference classes."))) + C = NamedTuple{NAMES,Tuple{map(_output_column_carrier_type, families)...}} columns = Expr(:tuple, [:( _model_output_destination_column(model, destination_ids, - Val{$(QuoteNode(name))}()) - ) for name in NAMES]...) - return :(NamedTuple{$(QuoteNode(NAMES))}($columns)) + Val{$(QuoteNode(name))}(), $(families[index])) + ) for (index,name) in enumerate(NAMES)]...) + empty_columns = Expr(:tuple, [:(RefVector{Any}()) for _ in NAMES]...) + return quote + isempty(destination_ids) && return $C($empty_columns) + return $C($columns) + end end function _model_output_destination_index(destination_ids::AbstractVector{I}) where {I<:ObjectId} @@ -6999,12 +7079,9 @@ function _model_output_destination_index(destination_ids::AbstractVector{I}) whe return index end -function _append_model_output_destination_binding!(plan, model, resolved, bindings) - I = keytype(model.registry.objects) - execution_object_id = _index_object_id( - model.registry.objects, getfield(resolved, :execution_object_id), - ) - destination_ids = getfield(resolved, :destination_ids)::Vector{I} +function _append_model_output_destination_binding!( + plan, model, execution_object_id::I, destination_ids::Vector{I}, bindings, +) where {I<:ObjectId} binding = CompiledModelOutputDestinationBinding( plan, execution_object_id, @@ -7018,9 +7095,10 @@ function _append_model_output_destination_binding!(plan, model, resolved, bindin end function _model_output_plan_binding_rows(plan, model, resolved_by_plan, bindings) - resolved = get!(Vector{ResolvedModelOutputDestination}, resolved_by_plan, plan.slot) - return [_append_model_output_destination_binding!(plan, model, row, bindings) - for row in resolved] + membership = get!(valtype(resolved_by_plan), resolved_by_plan, plan.slot) + return [_append_model_output_destination_binding!( + plan, model, execution_object_id, destination_ids, bindings, + ) for (execution_object_id, destination_ids) in membership] end # The tuple follows authored groups; only the vectors' lengths depend on organs. @@ -7064,11 +7142,16 @@ function _compile_model_output_destination_bindings( ) bindings = Any[] sizehint!(bindings, length(resolved_destinations)) - resolved_by_plan = Dict{Int,Vector{ResolvedModelOutputDestination}}() + I = keytype(model.registry.objects) + resolved_by_plan = Dict{Int,Vector{Tuple{I,Vector{I}}}}() for resolved in resolved_destinations plan = getfield(resolved, :plan)::CompiledModelOutputDestinationPlan - push!(get!(Vector{ResolvedModelOutputDestination}, resolved_by_plan, - getfield(plan, :slot)), resolved) + execution_object_id = _index_object_id( + model.registry.objects, getfield(resolved, :execution_object_id), + ) + destination_ids = getfield(resolved, :destination_ids)::Vector{I} + push!(get!(valtype(resolved_by_plan), resolved_by_plan, + getfield(plan, :slot)), (execution_object_id, destination_ids)) end by_execution_target = Dict{Tuple{Symbol,ObjectId},Any}() for application_id in keys(plans.by_application) @@ -7167,7 +7250,7 @@ function _compile_model_distributed_outputs( _validate_model_output_destination_statuses!(model, resolved) _validate_required_model_output_destinations!(model, resolved) _prepare_model_output_statuses!(model, applications, applications_by_id) - _prepare_model_output_destination_statuses!(model, resolved) + _prepare_model_output_destination_statuses!(model, resolved, applications_by_id, plans) bindings, by_execution_target = _compile_model_output_destination_bindings(model, resolved, plans) return CompiledDistributedOutputs( @@ -7346,7 +7429,7 @@ function _incremental_distributed_output_addition!( end end _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) - _prepare_model_output_destination_statuses!(model, resolved_additions) + _prepare_model_output_destination_statuses!(model, resolved_additions, applications_by_id, plans) column_additions = Any[] for resolved in resolved_additions @@ -7360,6 +7443,7 @@ function _incremental_distributed_output_addition!( existing_references = parent(getproperty(binding.columns, variable)) added_references = parent(getproperty(columns, variable)) eltype(added_references) <: eltype(existing_references) || + all(reference -> reference isa eltype(existing_references), added_references) || return nothing end push!(column_additions, (binding=binding, resolved=resolved, columns=columns)) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index fbe56ce8b..ea69e4822 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -137,7 +137,7 @@ function _output_target_binding_groups_type(::Type{T}) where {T<:NamedTuple} for View in fieldtypes(T) View <: OutputTargets && isconcretetype(View) || throw(ArgumentError("Prepared output destinations require concrete OutputTargets views.")) - Binding = fieldtype(View, :binding) + Binding = _output_target_binding_type(View) Plan = fieldtype(Binding, :plan) group, variables = Plan.parameters[1], Plan.parameters[2] if group in groups @@ -155,6 +155,20 @@ function _output_target_binding_groups_type(::Type{T}) where {T<:NamedTuple} return NamedTuple{Tuple(groups),Tuple{bindings...}} end +# A fixed preparation binding can contain empty or populated carriers. Admit +# their actual classes before choosing the concrete batch view, once per target. +@generated function _output_group_columns_match(groups::G, ::Type{Views}) where {G<:NamedTuple,Views<:NamedTuple} + checks = Expr[] + for (index, Binding) in enumerate(fieldtypes(G)) + names = fieldtype(Binding, :plan).parameters[2] + C = _output_target_columns_type(fieldtype(Views, first(names))) + for (slot,name) in enumerate(names) + push!(checks, :(getfield(getfield(getfield(groups, $index), :columns), $(QuoteNode(name))) isa $(fieldtype(C,slot)))) + end + end + return isempty(checks) ? :(true) : foldl((a,b) -> :($a && $b), checks) +end + # Admit the real status view before reading its parameterized fields. The # ordinary function barrier specializes its actual V; prepared execution uses # the same existing finite target schema before assembling the same fields. @@ -190,13 +204,14 @@ end Views = fieldtype(Target, :output_targets) Groups = _output_target_binding_groups_type(Views) checks = Expr[:(application isa $(fieldtype(Context, :application))), - :(output_groups isa $Groups)] + :(output_groups isa $Groups), + :(_output_group_columns_match(output_groups::$Groups, $Views))] values = Expr[] for name in names value = if name === :status_view :status_view elseif name === :output_targets - :(_runtime_model_output_targets(output_groups::$Groups)::$Views) + :(_runtime_model_output_targets(output_groups::$Groups, $Views)::$Views) elseif name === :bound_inputs # The earlier status_view check short-circuits before this read. :((status_view::$V).bound_inputs) @@ -465,9 +480,9 @@ function _prepared_distributed_runtime_output(::Type{O}, output_targets, applica streams, retention, ) where {V,B,S,R,O<:RuntimeDistributedOutputStream{V,B,S,R}} target = getproperty(output_targets,V) - binding = target.binding + binding = _output_target_binding(target) binding isa B || throw(ArgumentError("A distributed output owner is outside its prepared schema.")) - references = getproperty(binding.columns,V) + references = getproperty(target.columns,V) references isa R || throw(ArgumentError("A distributed output column is outside its prepared schema.")) sources = _prepared_distributed_output_sources(S, streams, binding, application.id, V) return O(binding::B, sources::S, references::R, diff --git a/src/composite_model/output_targets.jl b/src/composite_model/output_targets.jl index ff576227a..dd02aa618 100644 --- a/src/composite_model/output_targets.jl +++ b/src/composite_model/output_targets.jl @@ -30,9 +30,12 @@ struct OutputTargets{B,C} end function OutputTargets(binding::CompiledModelOutputDestinationBinding, alignment_id::Int) + return _output_targets(binding, _output_target_columns(binding), alignment_id) +end +function _output_targets(binding, columns, alignment_id::Int) count = length(binding.destination_ids) return OutputTargets( - binding, + OutputTargetColumns(binding, columns), OutputAssignmentCache( nothing, Vector{Int}(undef, count), @@ -52,6 +55,26 @@ struct OutputTargetColumns{B,C} columns::C end +# Snapshot only the carrier header; source, carriers, IDs and cells are borrowed. +_output_target_binding(targets::OutputTargets) = getfield(getfield(targets, :binding), :source) +_output_target_binding_type(::Type{T}) where {T<:OutputTargets} = + fieldtype(fieldtype(T, :binding), :source) +_output_target_columns_type(::Type{T}) where {T<:OutputTargets} = + fieldtype(fieldtype(T, :binding), :columns) + +@generated function _output_target_columns(binding::B) where {B<:CompiledModelOutputDestinationBinding} + names = fieldtype(B, :plan).parameters[2] + values = Expr(:tuple, [:(getfield(getfield(binding, :columns), $(QuoteNode(name)))) for name in names]...) + return :(NamedTuple{$(QuoteNode(names))}($values)) +end +@generated function _output_target_columns(binding::B, ::Type{C}) where {B<:CompiledModelOutputDestinationBinding,C<:NamedTuple} + names = fieldtype(B, :plan).parameters[2] + names === fieldnames(C) || return :(throw(ArgumentError("Prepared output column names changed."))) + values = Expr(:tuple, [:(getfield(getfield(binding, :columns), $(QuoteNode(name)))::$(fieldtype(C,index))) + for (index,name) in enumerate(names)]...) + return :($C($values)) +end + @inline function Base.getproperty(view::OutputTargetColumns, name::Symbol) name === :columns && return getfield(view, :columns) name === :source && return getfield(view, :source) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 29a1f098c..2f40ab1c5 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -499,7 +499,7 @@ end first_target = getproperty(context.output_targets, $first_name) $(alignment_checks...) columns = NamedTuple{$(QuoteNode(variables))}($columns) - binding = OutputTargetColumns(first_target.binding, columns) + binding = OutputTargetColumns(_output_target_binding(first_target), columns) OutputTargets(binding, first_target.assignment_cache, first_target.alignment_id) end end @@ -3472,7 +3472,9 @@ end _runtime_model_output_groups(compiled, application, object_id) = _runtime_model_output_groups(application, object_id, compiled.distributed_outputs) -@generated function _runtime_model_output_targets(groups::G) where {G<:NamedTuple} +@generated function _runtime_model_output_targets(groups::G, + ::Type{Views}=Nothing, +) where {G<:NamedTuple,Views} names, targets, statements = Symbol[], Symbol[], Expr[] binding_vars, target_vars = Symbol[], Symbol[] for (index, Binding) in enumerate(fieldtypes(G)) @@ -3486,7 +3488,13 @@ _runtime_model_output_groups(compiled, application, object_id) = $(target_vars[previous]).alignment_id : $alignment ) end push!(statements, :($binding = getfield(groups, $index))) - push!(statements, :($target = OutputTargets($binding, $alignment))) + factory = if Views === Nothing + :(OutputTargets($binding, $alignment)) + else + C = _output_target_columns_type(fieldtype(Views, first(variables))) + :(_output_targets($binding, _output_target_columns($binding, $C), $alignment)) + end + push!(statements, :($target = $factory)) push!(statements, :(alignment_count = max(alignment_count, $target.alignment_id))) append!(names, variables) append!(targets, fill(target, length(variables))) @@ -3496,7 +3504,7 @@ _runtime_model_output_groups(compiled, application, object_id) = return quote alignment_count = 0 $(statements...) - return NamedTuple{$(QuoteNode(Tuple(names)))}($(Expr(:tuple, targets...))) + return $(Views === Nothing ? :(NamedTuple{$(QuoteNode(Tuple(names)))}) : Views)($(Expr(:tuple, targets...))) end end @@ -3932,14 +3940,15 @@ function _model_execution_outputs_match( for variable in keys(output_targets) variable in variables || continue isnothing(temporal_streams) && return false - binding = getproperty(output_targets, variable).binding + target = getproperty(output_targets, variable) + binding = _output_target_binding(target) output_index += 1 output_index <= length(runtime_outputs) || return false output = runtime_outputs[output_index] output isa RuntimeDistributedOutputStream || return false _runtime_output_variable(output) == variable || return false output.binding === binding || return false - output.references === getproperty(binding.columns, variable) || return false + output.references === getproperty(target.columns, variable) || return false expected_horizon = isnothing(dependency_horizons) ? 0.0 : get(dependency_horizons, (application.id, variable), 0.0) @@ -3999,7 +4008,9 @@ end binding = :(getfield(bindings, $index)) current = :(getproperty(targets, $(QuoteNode(first(variables))))) for name in variables - push!(checks, :(getproperty(targets, $(QuoteNode(name))).binding === $binding || return false)) + push!(checks, :(_output_target_binding(getproperty(targets, $(QuoteNode(name)))) === $binding || return false)) + push!(checks, :(getproperty(getproperty(targets, $(QuoteNode(name))).columns, $(QuoteNode(name))) === + getproperty($binding.columns, $(QuoteNode(name))) || return false)) end # In-place growth preserves the view only while group alignments agree. for previous in 1:(index - 1) diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl index fb689e1ce..6f969635b 100644 --- a/test/test-model-output-retention-owners.jl +++ b/test/test-model-output-retention-owners.jl @@ -249,6 +249,68 @@ end @test stream(simulation, :writer, 2, :private) isa PSE.TemporalDependencyBuffer{Float32} end +# Reading a user Ref is observable. Preparing separate output groups must keep +# the same group/origin order and borrow the original cells. +mutable struct ObservedRef{T} <: Ref{T} + value::T + label::Symbol + reads::Vector{Symbol} +end +Base.getindex(cell::ObservedRef) = (push!(cell.reads, cell.label); cell.value) +Base.setindex!(cell::ObservedRef{T}, value) where {T} = (cell.value = convert(T, value)) + +struct RefOrderDistributor <: AbstractRetention_Owner_DistributorModel end +PSE.inputs_(::RefOrderDistributor) = NamedTuple() +PSE.outputs_(::RefOrderDistributor) = ( + incident_par=Distributed(Default(0.0)), absorbed_par=Distributed(Default(0.0)), +) +PSE.run!(::RefOrderDistributor, status, environment, constants, context) = nothing + +@testset "distributed preparation preserves custom Ref read order and identity" begin + reads = Symbol[] + cells = Dict((leaf, variable) => ObservedRef(0.0, + Symbol(leaf, "__", variable), reads) + for leaf in (:leaf_a, :leaf_b) for variable in (:incident_par, :absorbed_par)) + model = CompositeModel( + Object(:scene_a; scale=:Scene), + Object(:scene_b; scale=:Scene), + Object(:leaf_a; scale=:Leaf, parent=:scene_a, + status=Status((incident_par=cells[(:leaf_a, :incident_par)], + absorbed_par=cells[(:leaf_a, :absorbed_par)]))), + Object(:leaf_b; scale=:Leaf, parent=:scene_b, + status=Status((incident_par=cells[(:leaf_b, :incident_par)], + absorbed_par=cells[(:leaf_b, :absorbed_par)]))); + applications=(ModelSpec(RefOrderDistributor(); name=:ref_order_probe, + on=Many(scale=:Scene), outputs_to=( + OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:incident_par,)), + OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:absorbed_par,)))),)) + @test isempty(reads) + compiled = Advanced.refresh_bindings!(model) + expected_reads = [:leaf_a__incident_par, :leaf_b__incident_par, + :leaf_a__absorbed_par, :leaf_b__absorbed_par] + @test reads == expected_reads + bindings = compiled.distributed_outputs.bindings + @test length(bindings) == 4 + @test [(binding.execution_object_id.value, only(binding.destination_ids).value, + only(binding.plan.variable_names)) for binding in bindings] == [ + (:scene_a, :leaf_a, :incident_par), (:scene_b, :leaf_b, :incident_par), + (:scene_a, :leaf_a, :absorbed_par), (:scene_b, :leaf_b, :absorbed_par), + ] + for binding in bindings + variable = only(binding.plan.variable_names) + destination = only(binding.destination_ids) + cell = cells[(destination.value, variable)] + carrier = getproperty(binding.columns, variable) + @test carrier isa PSE.ObjectRefVector + @test eltype(carrier) === Any + @test only(parent(carrier)) === cell + @test PSE.refvalue(model_status(model, destination), variable) === cell + @test getfield(cell, :value) === 0.0 + end + # The identity/type inspection above must itself cause no value reads. + @test reads == expected_reads +end + struct Distributor <: AbstractRetention_Owner_DistributorModel end PSE.inputs_(::Distributor) = NamedTuple() PSE.outputs_(::Distributor) = (delivered=Distributed(Default(0f0)),) From ae54c8fe88b0953e9e4a523683af5c397ece43f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 00:27:29 +0100 Subject: [PATCH 169/324] Store status admission routes as data Keep the authored projection small and place aligned admission permissions in concrete vectors. Preserve typed status cells, selectors and Ref identity while avoiding recursive descriptor tuples in model types. Validation on the combined source: 387 assertions across four admission files and 150 retention-owner assertions passed. Four new assertions cover rejected/admitted shadow cells and manifest type reuse. A bounded public XPalm control returned from CompositeModel and entered run!. This is a cold diagnostic observation, without a warm timing or ratio claim. Native qualification remains incomplete. --- .../prepared_status_manifest.jl | 343 +++++++++--------- test/test-fixed-status-manifest.jl | 19 + 2 files changed, 197 insertions(+), 165 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index b6d9e26f0..903cf06e6 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -29,12 +29,39 @@ end # Runtime status admission needs only applicability and the effective variant # slot. Full specifications/ports stay in ScenarioPreparation; environment names # must not change an otherwise identical canonical registry schema. +struct PreparedStatusSource{M} + slot::Int + input::Symbol + source_var::Symbol + matcher::M + references::Vector{Pair{Symbol,DataType}} +end + +struct PreparedStatusDestination{M} + slot::Int + application_slot::Int + variable_names::Vector{Symbol} + matcher::M +end + +struct PreparedStatusVariant + canonical::Vector{Pair{Symbol,DataType}} + outputs::Vector{Pair{Symbol,DataType}} + source_inputs::Vector{Pair{Symbol,DataType}} +end + struct PreparedStatusApplication{M,O} slot::Int id::Symbol target_matcher::M object_slots::O end + +struct PreparedStatusPermission{R} + variants::Vector{PreparedStatusVariant} + aliases::Vector{Pair{Symbol,DataType}} + sources::Vector{R} +end @inline _prepared_status_object_slots(application::PreparedStatusApplication) = application.object_slots function _prepared_status_object_slots(application) @@ -53,8 +80,11 @@ _prepared_status_variant_slot(application, object_id) = begin isnothing(slots) ? 1 : get(slots, object_id, 1) end -function _prepared_status_type_map(names, types) - return _authored_port_types(identity, NamedTuple{Tuple(names)}(Tuple(types))) +# These permissions are data consulted at admission. The fixed Status schema +# still owns the field layout and its exact reference types. +function _prepared_status_reference_classes(names, types) + return Pair{Symbol,DataType}[name => R for (name, family) in zip(names, types) + for R in Base.uniontypes(family) if R !== Union{}] end function _prepared_status_add_type!(names, types, name::Symbol, R) @@ -114,9 +144,9 @@ function _prepared_status_variant_permission(model, application, ports, plans) isempty(classes) && continue _prepared_status_add_type!(source_names, source_refs, plan.input, Union{classes...}) end - return (canonical=_prepared_status_type_map(names, refs), - outputs=_prepared_status_type_map(output_names, output_refs), - source_inputs=_prepared_status_type_map(source_names, source_refs)) + return PreparedStatusVariant(_prepared_status_reference_classes(names, refs), + _prepared_status_reference_classes(output_names, output_refs), + _prepared_status_reference_classes(source_names, source_refs)) end # Project the SAME prepared source-reference family used by the runtime carrier @@ -130,17 +160,25 @@ function _prepared_status_input_reference(plan) return Base.RefValue{_many_input_carrier_type(plan.reference_types)} end -function _prepared_status_application_permissions(model, recipes, program) - return map(recipes) do application +# Matcher and override values keep their authored types and identities. The type +# of the collection depends on the supported matcher families, never on the +# number of applications, the input name, or the number of routes. +_prepared_status_field_type(values) = foldl((T, value) -> Union{T,typeof(value)}, + values; init=Union{}) + +function _prepared_status_applications(model, recipes, program) + inputs = [plan for plan in program.input_records if plan isa CompiledModelInputPlan] + M = _prepared_status_field_type(application.target_matcher for application in recipes) + O = _prepared_status_field_type(_prepared_status_object_slots(application) for application in recipes) + R = PreparedStatusSource{_prepared_status_field_type(plan.matcher for plan in inputs if + _input_route_from_status(plan.route))} + A = PreparedStatusApplication{M,O} + applications = A[] + permissions = PreparedStatusPermission{R}[] + for application in recipes application_slot = application.slot - selected_plans = CompiledModelInputPlan[] - for plan in program.input_records - plan isa CompiledModelInputPlan || continue - plan.application_slot == application_slot || continue - push!(selected_plans, plan) - end - plans = Tuple(selected_plans) - variants = Any[] + plans = filter(plan -> plan.application_slot == application_slot, inputs) + variants = PreparedStatusVariant[] _foreach_application_variant(application) do _, ports push!(variants, _prepared_status_variant_permission(model, application, ports, plans)) end @@ -151,23 +189,33 @@ function _prepared_status_application_permissions(model, recipes, program) _prepared_status_add_type!(alias_names, alias_refs, plan.input, _prepared_status_input_reference(plan)) end - aliases = _prepared_status_type_map(alias_names, alias_refs) - sources = Tuple((plan=plan, references=_prepared_status_type_map( - (plan.source_var,), (Union{fieldtypes(plan.reference_types)...},))) - for plan in plans if _input_route_from_status(plan.route)) - (slot=application.slot, id=application.id, variants=Tuple(variants), - aliases=aliases, sources=sources) + aliases = _prepared_status_reference_classes(alias_names, alias_refs) + sources = R[R(plan.slot, plan.input, plan.source_var, plan.matcher, + _prepared_status_reference_classes((plan.source_var,), + (Union{fieldtypes(plan.reference_types)...},))) + for plan in plans if _input_route_from_status(plan.route)] + push!(applications, A(application.slot, application.id, application.target_matcher, + _prepared_status_object_slots(application))) + push!(permissions, PreparedStatusPermission(variants, aliases, sources)) end + return applications, permissions +end + +function _prepared_status_destinations(plans) + M = _prepared_status_field_type(plan.matcher for plan in plans) + return PreparedStatusDestination{M}[PreparedStatusDestination{M}( + plan.slot, plan.application_slot, collect(Symbol, plan.variable_names), plan.matcher) + for plan in plans] end -function _prepared_status_raw_signature(model, object, recipes, permissions, destinations) +function _prepared_status_raw_signature(model, object, applications, permissions, destinations) I = keytype(model.registry.objects) selected = Tuple{Int,Int}[(application.slot, _prepared_status_variant_slot(application, object.id)) - for application in recipes + for application in applications if _prepared_status_application_matches(model, object, object.parent, application)] routes = Tuple{Int,I,Int}[] for plan in destinations - application = only(a for a in recipes if a.slot == plan.application_slot) + application = only(a for a in applications if a.slot == plan.application_slot) for (execution_id, producer) in model.registry.objects _prepared_status_application_matches(model, producer, producer.parent, application) || continue _prepared_status_route_matches(model, object, object.parent, @@ -177,12 +225,12 @@ function _prepared_status_raw_signature(model, object, recipes, permissions, des end end sources = Tuple{Int,I,Int}[] - for (application, permission) in zip(recipes, permissions), source in permission.sources + for (application, permission) in zip(applications, permissions), source in permission.sources for (consumer_id, consumer) in model.registry.objects _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue _prepared_status_route_matches(model, object, object.parent, - application, source.plan, consumer_id) || continue - push!(sources, (source.plan.slot, consumer_id, + application, source, consumer_id) || continue + push!(sources, (source.slot, consumer_id, _prepared_status_variant_slot(application, consumer_id))) end end @@ -223,10 +271,10 @@ function _prepare_status_manifest(model, authored, program, raw_basis) # the namespace and all RAW permissions have been prepared. recipes = _graph_record_vector(AuthoredApplicationRecipe, (item for item in authored if item isa AuthoredApplicationRecipe)) - permissions = _prepared_status_application_permissions(model, recipes, program) + applications, permissions = _prepared_status_applications(model, recipes, program) outputs = _authored_distributed_output_plans( _graph_record_vector(AuthoredApplicationRecipe, recipes), program.output_records) - destinations = outputs isa NoCompiledDistributedOutputPlans ? () : Tuple(outputs.plans) + destinations = _prepared_status_destinations(outputs isa NoCompiledDistributedOutputPlans ? () : outputs.plans) names = Symbol[]; refs = Any[] # Stable authoring order, captured once; physical absence never creates data. for application in recipes @@ -243,7 +291,7 @@ function _prepare_status_manifest(model, authored, program, raw_basis) source isa Status || continue raw_names = Symbol[name for name in propertynames(source)] raw_refs = DataType[typeof(refvalue(source, name)) for name in raw_names] - signature = _prepared_status_raw_signature(model, object, recipes, permissions, destinations) + signature = _prepared_status_raw_signature(model, object, applications, permissions, destinations) entry = PreparedRawStatusFamily{I}(signature.labels, signature.selected, signature.destinations, signature.sources, raw_names, raw_refs) any(previous -> _same_prepared_raw_family(previous, entry), observed) || @@ -268,17 +316,17 @@ function _prepare_status_manifest(model, authored, program, raw_basis) _prepared_status_add_type!(names, refs, name, R) end for permission in permissions - for variant in permission.variants, (name, R) in pairs(variant.canonical) + for variant in permission.variants, (name, R) in variant.canonical _prepared_status_add_type!(names, refs, name, R) end - for (name, R) in pairs(permission.aliases) + for (name, R) in permission.aliases _prepared_status_add_type!(names, refs, name, R) end for source in permission.sources, variant in permission.variants - input = source.plan.input - hasproperty(variant.source_inputs, input) || continue - _prepared_status_add_type!(names, refs, source.plan.source_var, - getproperty(variant.source_inputs, input)) + input = source.input + for (name, R) in variant.source_inputs + name === input && _prepared_status_add_type!(names, refs, source.source_var, R) + end end end # Distributed default types use the corresponding producer variant owner. @@ -321,11 +369,7 @@ function _prepare_status_manifest(model, authored, program, raw_basis) # no biological Ref is created for that slot. physical_refs = map(R -> R === Union{} ? Nothing : R, refs) S = _fixed_status_type(Tuple(names), Tuple{physical_refs...}) - applications = map(recipes) do application - PreparedStatusApplication(application.slot, application.id, - application.target_matcher, _prepared_status_object_slots(application)) - end - return PreparedStatusManifest(S, Tuple(applications), Tuple(permissions), destinations, raw) + return PreparedStatusManifest(S, applications, permissions, destinations, raw) end # The catalog references the SAME prepared manifest; runtime never finds a @@ -349,38 +393,27 @@ end end end -# Runtime admission is Boolean over the EXISTING typed metadata. It never -# assembles a runtime NamedTuple schema, a type, or a membership-sized tuple. -@generated function _prepared_status_reference_allowed(schema::NamedTuple{Names,T}, - name::Symbol, reference) where {Names,T} - checks = Expr[] - for index in eachindex(Names) - R = fieldtype(T, index).parameters[1] - push!(checks, :(name === $(QuoteNode(Names[index])) && reference isa $R && return true)) - end - return quote - $(checks...) - return false +# All recorded classes are concrete. Comparing the class keeps custom Refs +# and abstract-valued Refs distinct without reading their contents. +function _prepared_status_reference_allowed(classes, name::Symbol, reference) + for (field, R) in classes + field === name && R === typeof(reference) && return true end + return false end _prepared_status_variant_reference_allowed(variant, name, reference) = _prepared_status_reference_allowed(variant.canonical, name, reference) _prepared_status_output_reference_allowed(variant, name, reference) = _prepared_status_reference_allowed(variant.outputs, name, reference) -_prepared_status_application_reference_allowed(::Tuple{}, ::Tuple{}, model, - object, parent_id, name, reference) = false -function _prepared_status_application_reference_allowed(applications::Tuple, - permissions::Tuple, model, object, parent_id, name, reference) - application, permission = first(applications), first(permissions) - if _prepared_status_application_matches(model, object, parent_id, application) +function _prepared_status_application_reference_allowed(manifest, model, object, parent_id, name, reference) + for (application, permission) in zip(manifest.authored, manifest.permissions) + _prepared_status_application_matches(model, object, parent_id, application) || continue variant = _prepared_status_variant_slot(application, object.id) - _with_metadata_entry(_prepared_status_variant_reference_allowed, - permission.variants, variant, name, reference) && return true + _prepared_status_variant_reference_allowed(permission.variants[variant], name, reference) && return true _prepared_status_reference_allowed(permission.aliases, name, reference) && return true end - return _prepared_status_application_reference_allowed(Base.tail(applications), - Base.tail(permissions), model, object, parent_id, name, reference) + return false end # One exact application/permission pair enters the producer/route worker. @@ -418,55 +451,37 @@ Base.@constprop :none Base.@noinline function _prepared_status_destination_entry return false end -# Slots are authored identities, not tuple positions: partial preparation can -# retain gaps. Select the correlated entries inside the same finite branch. -@generated function _prepared_status_destination_application_allowed(applications::A, - permissions::P, application_slot::Int, plan, model, object, parent_id, name, reference, -) where {A<:Tuple,P<:Tuple} - fieldcount(A) == fieldcount(P) || return :(throw(DimensionMismatch( - "Prepared application and permission tuple lengths must match."))) - branches = [:(getfield(applications, $index).slot == application_slot && - return _prepared_status_destination_entry_allowed( - getfield(applications, $index), getfield(permissions, $index), - plan, model, object, parent_id, name, reference)) - for index in 1:fieldcount(A)] - return quote - $(branches...) - return false +function _prepared_status_destinations_allow(plans, manifest, model, object, parent_id, name, reference) + for plan in plans + name in plan.variable_names || continue + for (application, permission) in zip(manifest.authored, manifest.permissions) + application.slot == plan.application_slot || continue + _prepared_status_destination_entry_allowed(application, permission, plan, model, object, + parent_id, name, reference) && return true + break + end end + return false end -Base.@constprop :none Base.@noinline function _prepared_status_destination_plan_allowed( - plan, manifest, model, object, parent_id, name, reference, -) - name in plan.variable_names || return false - return _prepared_status_destination_application_allowed(manifest.authored, - manifest.permissions, plan.application_slot, plan, model, object, parent_id, name, reference) -end - -function _prepared_status_destinations_allow(plans::Tuple, manifest, model, object, parent_id, name, reference) - for slot in eachindex(plans) - _with_metadata_entry(_prepared_status_destination_plan_allowed, plans, - slot, manifest, model, object, parent_id, name, reference) && return true +function _prepared_status_source_input_admission(variant, input, reference) + declared = false + for (name, R) in variant.source_inputs + name === input || continue + declared = true + R === typeof(reference) && return (true, true) end - return false + return (declared, !declared) end -_prepared_status_source_input_admission(variant, input, reference) = - hasproperty(variant.source_inputs, input) ? - (true, _prepared_status_reference_allowed(variant.source_inputs, input, reference)) : - (false, true) # Return whether a declaration contributes a right, all declarations agree, # and every applicable route reference family admits the actual class. # Observed extra RT classes support existing references/reparenting; they do not # create new initial-data permissions in a different configured source context. -_prepared_status_source_routes_admission(::Tuple{}, application, permission, - model, object, parent_id, name, reference) = (false, true, true) -function _prepared_status_source_routes_admission(sources::Tuple, application, permission, +function _prepared_status_source_route_admission(source, application, permission, model, object, parent_id, name, reference) - source = first(sources) declared, allowed = false, true - if source.plan.source_var === name + if source.source_var === name has_consumer = false for (consumer_id, consumer) in model.registry.objects consumer_parent = consumer.parent @@ -475,12 +490,12 @@ function _prepared_status_source_routes_admission(sources::Tuple, application, p _prepared_status_application_matches(model, consumer, consumer_parent_id, application) || continue has_consumer = true _prepared_status_route_matches(model, object, parent_id, - application, source.plan, consumer_id) || continue + application, source, consumer_id) || continue _prepared_status_reference_allowed(source.references, name, reference) || return (false, false, false) has_type, matches = _with_metadata_entry(_prepared_status_source_input_admission, permission.variants, _prepared_status_variant_slot(application, consumer_id), - source.plan.input, reference) + source.input, reference) declared |= has_type allowed &= matches end @@ -488,17 +503,17 @@ function _prepared_status_source_routes_admission(sources::Tuple, application, p if !isnothing(pending_id) has_consumer = true if _prepared_status_route_matches(model, object, parent_id, - application, source.plan, pending_id) + application, source, pending_id) _prepared_status_reference_allowed(source.references, name, reference) || return (false, false, false) has_type, matches = _with_metadata_entry(_prepared_status_source_input_admission, permission.variants, _prepared_status_variant_slot(application, pending_id), - source.plan.input, reference) + source.input, reference) declared |= has_type allowed &= matches end end - matcher = source.plan.matcher + matcher = source.matcher if !has_consumer && matcher.scope isa SceneScope && isnothing(matcher.relation) id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) @@ -507,25 +522,23 @@ function _prepared_status_source_routes_admission(sources::Tuple, application, p _prepared_status_reference_allowed(source.references, name, reference) || return (false, false, false) declared, allowed = _prepared_status_source_input_admission( - first(permission.variants), source.plan.input, reference) + first(permission.variants), source.input, reference) end end end - next_declared, next_allowed, compatible = _prepared_status_source_routes_admission( - Base.tail(sources), application, permission, model, object, parent_id, name, reference) - return (declared | next_declared, allowed & next_allowed, compatible) + return (declared, allowed, true) end -_prepared_status_sources_admission(::Tuple{}, ::Tuple{}, model, object, - parent_id, name, reference) = (false, true, true) -function _prepared_status_sources_admission(applications::Tuple, permissions::Tuple, - model, object, parent_id, name, reference) - declared, allowed, compatible = _prepared_status_source_routes_admission( - first(permissions).sources, first(applications), first(permissions), - model, object, parent_id, name, reference) - compatible || return (false, false, false) - next_declared, next_allowed, compatible = _prepared_status_sources_admission( - Base.tail(applications), Base.tail(permissions), model, object, parent_id, name, reference) - return (declared | next_declared, allowed & next_allowed, compatible) + +function _prepared_status_sources_admission(manifest, model, object, parent_id, name, reference) + declared, allowed = false, true + for (application, permission) in zip(manifest.authored, manifest.permissions), source in permission.sources + has_type, matches, compatible = _prepared_status_source_route_admission(source, + application, permission, model, object, parent_id, name, reference) + compatible || return (false, false, false) + declared |= has_type + allowed &= matches + end + return (declared, allowed, true) end # Keep erased cells behind the prepared physical bounds before crossing the @@ -553,11 +566,11 @@ Base.@constprop :none Base.@noinline function _prepared_status_reference_admissi manifest, model, object, parent_id, name, reference::R, ) where {R<:Ref} declared, source_allowed, compatible = _prepared_status_sources_admission( - manifest.authored, manifest.permissions, model, object, parent_id, + manifest, model, object, parent_id, name, reference::R) compatible || return (false, false) allowed = (declared && source_allowed) || - _prepared_status_application_reference_allowed(manifest.authored, manifest.permissions, + _prepared_status_application_reference_allowed(manifest, model, object, parent_id, name, reference::R) || _prepared_status_destinations_allow(manifest.destinations, manifest, model, object, parent_id, name, reference::R) @@ -570,18 +583,19 @@ function _prepared_status_raw_variant(raw, slot) end return 0 end -_prepared_status_raw_membership_matches(::Tuple{}, raw, model, object, parent_id) = true -function _prepared_status_raw_membership_matches(applications::Tuple, raw, model, object, parent_id) - application = first(applications) - expected = _prepared_status_raw_variant(raw, application.slot) - matches = _prepared_status_application_matches(model, object, parent_id, application) - if matches - expected == _prepared_status_variant_slot(application, object.id) || return false - else - iszero(expected) || return false +function _prepared_status_raw_membership_matches(applications, raw, model, object, parent_id) + for application in applications + expected = _prepared_status_raw_variant(raw, application.slot) + matches = _prepared_status_application_matches(model, object, parent_id, application) + if matches + expected == _prepared_status_variant_slot(application, object.id) || return false + elseif !iszero(expected) + return false + end end - return _prepared_status_raw_membership_matches(Base.tail(applications), raw, model, object, parent_id) + return true end + function _prepared_status_raw_has_context(contexts, plan, origin_id, variant) for entry in contexts # ObjectId uses identity equality; this also avoids dispatch through @@ -590,11 +604,7 @@ function _prepared_status_raw_has_context(contexts, plan, origin_id, variant) end return false end -_prepared_status_raw_destination_count(::Tuple{}, plan, raw, model, object, parent_id) = 0 -function _prepared_status_raw_destination_count(applications::Tuple, plan, raw, model, object, parent_id) - application = first(applications) - application.slot == plan.application_slot || return _prepared_status_raw_destination_count( - Base.tail(applications), plan, raw, model, object, parent_id) +function _prepared_status_raw_destination_count(application, plan, raw, model, object, parent_id) count = 0 for (execution_id, producer) in model.registry.objects producer_parent = producer.parent @@ -609,17 +619,21 @@ function _prepared_status_raw_destination_count(applications::Tuple, plan, raw, end return count end -_prepared_status_raw_destination_total(::Tuple{}, manifest, raw, model, object, parent_id) = 0 -function _prepared_status_raw_destination_total(plans::Tuple, manifest, raw, model, object, parent_id) - count = _prepared_status_raw_destination_count(manifest.authored, - first(plans), raw, model, object, parent_id) - count < 0 && return -1 - rest = _prepared_status_raw_destination_total(Base.tail(plans), manifest, raw, model, object, parent_id) - return rest < 0 ? -1 : count + rest -end -_prepared_status_raw_source_count(::Tuple{}, application, raw, model, object, parent_id) = 0 -function _prepared_status_raw_source_count(sources::Tuple, application, raw, model, object, parent_id) - source = first(sources) +function _prepared_status_raw_destination_total(plans, manifest, raw, model, object, parent_id) + total = 0 + for plan in plans + for application in manifest.authored + application.slot == plan.application_slot || continue + count = _prepared_status_raw_destination_count(application, plan, raw, model, object, parent_id) + count < 0 && return -1 + total += count + break + end + end + return total +end + +function _prepared_status_raw_source_count(source, application, raw, model, object, parent_id) count = 0 for (consumer_id, consumer) in model.registry.objects consumer_parent = consumer.parent @@ -627,40 +641,39 @@ function _prepared_status_raw_source_count(sources::Tuple, application, raw, mod _index_object_id(model.registry.objects, consumer_parent) _prepared_status_application_matches(model, consumer, consumer_parent_id, application) || continue _prepared_status_route_matches(model, object, parent_id, - application, source.plan, consumer_id) || continue + application, source, consumer_id) || continue variant = _prepared_status_variant_slot(application, consumer_id) - _prepared_status_raw_has_context(raw.sources, source.plan, + _prepared_status_raw_has_context(raw.sources, source, consumer_id, variant) || return -1 count += 1 end pending_id = _prepared_status_pending_consumer_id(model, object, parent_id, application) if !isnothing(pending_id) && _prepared_status_route_matches(model, object, parent_id, - application, source.plan, pending_id) + application, source, pending_id) variant = _prepared_status_variant_slot(application, pending_id) - _prepared_status_raw_has_context(raw.sources, source.plan, pending_id, variant) || return -1 + _prepared_status_raw_has_context(raw.sources, source, pending_id, variant) || return -1 count += 1 end - rest = _prepared_status_raw_source_count(Base.tail(sources), application, - raw, model, object, parent_id) - return rest < 0 ? -1 : count + rest + return count end -_prepared_status_raw_source_total(::Tuple{}, ::Tuple{}, raw, model, object, parent_id) = 0 -function _prepared_status_raw_source_total(applications::Tuple, permissions::Tuple, - raw, model, object, parent_id) - count = _prepared_status_raw_source_count(first(permissions).sources, - first(applications), raw, model, object, parent_id) - count < 0 && return -1 - rest = _prepared_status_raw_source_total(Base.tail(applications), Base.tail(permissions), - raw, model, object, parent_id) - return rest < 0 ? -1 : count + rest + +function _prepared_status_raw_source_total(manifest, raw, model, object, parent_id) + total = 0 + for (application, permission) in zip(manifest.authored, manifest.permissions), source in permission.sources + count = _prepared_status_raw_source_count(source, application, raw, model, object, parent_id) + count < 0 && return -1 + total += count + end + return total end + function _prepared_status_raw_matches(raw, manifest, model, object, parent_id) labels = _prepared_status_object_labels(model, object, parent_id) raw.labels === (labels.scale, labels.kind, labels.species) || return false _prepared_status_raw_membership_matches(manifest.authored, raw, model, object, parent_id) || return false _prepared_status_raw_destination_total(manifest.destinations, manifest, raw, model, object, parent_id) == length(raw.destinations) || return false - return _prepared_status_raw_source_total(manifest.authored, manifest.permissions, + return _prepared_status_raw_source_total(manifest, raw, model, object, parent_id) == length(raw.sources) end _prepared_status_raw_reference_allowed(::Nothing, name, reference) = false diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index 8c087dbb3..0fe686ca7 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -67,6 +67,25 @@ end @test PSE.refvalue(model_status(model, :scene), :x) === x @test source.calls[] == 2 # ordinary fresh staging read, no manifest replay end +@testset "repeated applications share the prepared admission schema" begin + function scene(kinds) + applications = [ModelSpec(Source(1.0, 2.0, Ref(0)); name=kind, + on=Many(scale=:Leaf, kind=kind)) for kind in kinds] + return CompositeModel(Object(:scene; scale=:Scene); applications) + end + + small = scene((:sun,)) + large = scene((:sun, :shade)) + @test typeof(PSE._prepared_status_manifest(small)) === typeof(PSE._prepared_status_manifest(large)) + + leaf = Object(:leaf; scale=:Leaf, kind=:shade, status=Status(x=3.0)) + reference = PSE.refvalue(leaf.status, :x) + @test_throws ArgumentError register_object!(small, leaf) + @test !haskey(small.registry.objects, leaf.id) + register_object!(large, leaf) + @test PSE.refvalue(model_status(large, :leaf), :x) === reference +end + @testset "RAW evidence cardinality does not alter an otherwise equal prepared owner" begin make = function (leaves) source = Source(1.0,2.0,Ref(0)) From 481a1cb7f59e71e3828183544f33ec0bca181d60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 01:12:03 +0100 Subject: [PATCH 170/324] Keep distributed output declarations with their effective producer --- src/composite_model/compilation.jl | 225 +++++++++--------- ...t-model-output-destination-declarations.jl | 58 +++++ 2 files changed, 167 insertions(+), 116 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 943a1a80a..49b38b5e8 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -271,7 +271,7 @@ Base.propertynames(plan::CompiledModelOutputDestinationPlan) = struct ResolvedModelOutputDestination{P,D,I<:ObjectId} plan::P declarations::D - execution_object_id::ObjectId + execution_object_id::I destination_ids::Vector{I} end @@ -5931,12 +5931,65 @@ _resolve_model_output_destinations( # Port names are authored metadata; defaults belong to the actual initial or # newborn destination event, never a previous binding's cached declaration. function _model_output_destination_declarations( - application, execution_object_id, + application, execution_object_id, plan::CompiledModelOutputDestinationPlan, +) + return _with_application_variant(_read_model_output_destination_declarations, + application, execution_object_id, plan) +end + +function _read_model_output_destination_declarations(producer, ports, ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, ) where {GROUP,NAMES} - effective_model = _application_model(application, execution_object_id) - selected = NamedTuple{NAMES}(_output_schema(effective_model)) - return map(output -> output.declaration, selected) + outputs = NamedTuple{NAMES}(_output_schema(producer)) + types = NamedTuple{NAMES}(ports.output_declaration_types) + return map(outputs, types) do output, declared_type + typeof(output) === declared_type || throw(ArgumentError( + "A distributed output declaration schema changed after preparation.")) + output.declaration + end +end + +# Allocate one row family for the routes and object overrides in this scenario. +# The type inventory is fixed by CompositeModel; default values are still read +# from the effective producer when each destination event is resolved. +@generated function _model_output_destination_rows( + ::Type{I}, ::CompiledMetadataTable{A}, ::CompiledDistributedOutputPlans{P,G}, +) where {I<:ObjectId,A,P,G} + rows = Union{} + for id in fieldnames(G) + routes = fieldtypes(fieldtype(G, id)) + isempty(routes) && continue + application = fieldtype(fieldtype(A, id), :plan) + model = fieldtype(fieldtype(application, :spec), :model) + ports = if model <: ObjectModelOverrides + entries = fieldtype(fieldtype(model, :variants), :entries) + map(entry -> fieldtype(entry, :ports), fieldtypes(entries)) + else + (fieldtype(application, :ports),) + end + for route in routes, port in ports + names = route.parameters[2] + types = fieldtype(port, :output_declaration_types) + types <: NamedTuple || continue + all(name -> name in fieldnames(types) && + fieldtype(types, name) <: Type{<:Distributed}, names) || continue + declarations = map(name -> fieldtype(types, name).parameters[1].parameters[1], names) + record = ResolvedModelOutputDestination{route,NamedTuple{names,Tuple{declarations...}},I} + rows = Union{rows,record} + end + end + return :(Vector{$rows}()) +end + +function _record_model_output_destination!(rows::Vector{R}, plan, declarations, + execution_id, destination_ids::Vector{I}, +) where {R,I} + record = ResolvedModelOutputDestination{typeof(plan),typeof(declarations),I}( + plan, declarations, execution_id, destination_ids) + record isa R || throw(ArgumentError( + "A distributed output declaration schema changed after preparation.")) + push!(rows, record) + return nothing end function _resolve_model_output_destinations( @@ -5944,7 +5997,7 @@ function _resolve_model_output_destinations( applications_by_id, compiled_plans::CompiledDistributedOutputPlans, ) - resolved = ResolvedModelOutputDestination[] + resolved = _model_output_destination_rows(keytype(model.registry.objects), applications_by_id, compiled_plans) for plan in compiled_plans.plans application = applications_by_id[plan.application_id] for execution_object_id in application.target_ids @@ -5961,14 +6014,8 @@ function _resolve_model_output_destinations( ), ) sizehint!(destination_ids, length(destination_ids) + 1) - push!( - resolved, - ResolvedModelOutputDestination( - plan, - declarations, - execution_object_id, - destination_ids, - ), + _record_model_output_destination!( + resolved, plan, declarations, execution_object_id, destination_ids, ) end end @@ -6864,7 +6911,7 @@ function _validate_required_model_output_destinations!( model::CompositeModel, resolved_destinations, ) - missing = NamedTuple[] + missing = String[] for resolved in resolved_destinations for destination_id in resolved.destination_ids for (variable_, declaration) in pairs(resolved.declarations) @@ -6880,28 +6927,14 @@ function _validate_required_model_output_destinations!( )) continue end - push!( - missing, - ( - application_id=resolved.plan.application_id, - execution_object_id=resolved.execution_object_id.value, - group=resolved.plan.group, - destination_id=destination_id.value, - variable=variable, - ), - ) + push!(missing, + "`$(resolved.plan.application_id).$(resolved.plan.group)` requires " * + "`$(variable)` on destination object `$(destination_id.value)`") end end end isempty(missing) && return nothing - details = join( - [ - "`$(row.application_id).$(row.group)` requires `$(row.variable)` on " * - "destination object `$(row.destination_id)`" - for row in missing - ], - "; ", - ) + details = join(missing, "; ") error( "Missing required distributed-output destination variable(s): ", details, @@ -6928,91 +6961,58 @@ function _validate_model_output_destination_statuses!( return nothing end -function _stage_model_output_destination_statuses!(plan, model, records, index, - applications_by_id, recipes, recipe_order, -) - return _with_metadata_entry(_stage_model_output_destination_statuses!, - applications_by_id, plan.application_id, plan, model, records, index, - recipes, recipe_order) -end -function _stage_model_output_destination_statuses!(application::CompiledModelApplication, - plan, model, records, index, recipes, recipe_order, -) - execution_id = _index_object_id(model.registry.objects, - getfield(records[index], :execution_object_id)) - return _with_application_variant(_stage_model_output_destination_statuses!, - application, execution_id, plan, model, records, index, recipes, recipe_order) -end - -# The existing port inventory admits the declarations captured by this event. -# In particular, no output/default hook is called to recover their lost type. -@generated function _stage_model_output_destination_statuses!(producer, ports::P, - plan::CompiledModelOutputDestinationPlan{GROUP,NAMES}, model, records, index, - recipes::AbstractDict{I}, recipe_order, -) where {P,GROUP,NAMES,I<:ObjectId} - Types = fieldtype(P, :output_declaration_types) - declarations = Tuple(fieldtype(Types, name).parameters[1].parameters[1] for name in NAMES) - D = NamedTuple{NAMES,Tuple{declarations...}} - return quote - record = records[index] - destination_ids = getfield(record, :destination_ids)::Vector{$I} - captured = getfield(record, :declarations) - captured isa $D || throw(ArgumentError( - "A distributed output declaration schema changed after preparation.")) - declarations = captured::$D - for destination_id in destination_ids - preparation = _status_preparation_for_object!( - recipes, - recipe_order, - model, - destination_id, - ) - for (variable_, declaration) in pairs(declarations) - declaration isa Default || continue - variable = Symbol(variable_) - if preparation isa Status - hasproperty(preparation, variable) && continue - preparation = _status_recipe_for_object!( - recipes, - recipe_order, - model, - destination_id, - ) - end - _status_recipe_add_default!( +function _stage_model_output_destination_statuses!(model, record, recipes, recipe_order) + for destination_id in record.destination_ids + preparation = _status_preparation_for_object!( + recipes, + recipe_order, + model, + destination_id, + ) + for (variable_, declaration) in pairs(record.declarations) + declaration isa Default || continue + variable = Symbol(variable_) + if preparation isa Status + hasproperty(preparation, variable) && continue + preparation = _status_recipe_for_object!( + recipes, + recipe_order, model, - preparation, destination_id, - variable, - _input_default(declaration); - application_id=plan.application_id, - origin=:distributed_output_default, ) end + _status_recipe_add_default!( + model, + preparation, + destination_id, + variable, + _input_default(declaration); + application_id=record.plan.application_id, + origin=:distributed_output_default, + ) end - return nothing end + return nothing end function _prepare_model_output_destination_statuses!( - model::CompositeModel, resolved_destinations, applications_by_id, - plans::CompiledDistributedOutputPlans, + model::CompositeModel, resolved_destinations, ) I = keytype(model.registry.objects) recipes = _canonical_status_recipe_storage(model, I) recipe_order = I[] - records_before = copy(model.status_conversion_records) + record_conversions = !_no_status_conversion(model.status_conversion) + records_before = record_conversions ? copy(model.status_conversion_records) : nothing try - for index in eachindex(resolved_destinations) - plan = getfield(resolved_destinations[index], :plan)::CompiledModelOutputDestinationPlan - _with_metadata_entry(_stage_model_output_destination_statuses!, - plans.plans, getfield(plan, :slot), model, resolved_destinations, - index, applications_by_id, recipes, recipe_order) + for record in resolved_destinations + _stage_model_output_destination_statuses!(model, record, recipes, recipe_order) end return _apply_status_recipes!(model, recipes, recipe_order) catch - empty!(model.status_conversion_records) - merge!(model.status_conversion_records, records_before) + if record_conversions + empty!(model.status_conversion_records) + merge!(model.status_conversion_records, records_before) + end rethrow() end end @@ -7250,7 +7250,7 @@ function _compile_model_distributed_outputs( _validate_model_output_destination_statuses!(model, resolved) _validate_required_model_output_destinations!(model, resolved) _prepare_model_output_statuses!(model, applications, applications_by_id) - _prepare_model_output_destination_statuses!(model, resolved, applications_by_id, plans) + _prepare_model_output_destination_statuses!(model, resolved) bindings, by_execution_target = _compile_model_output_destination_bindings(model, resolved, plans) return CompiledDistributedOutputs( @@ -7336,7 +7336,7 @@ function _incremental_distributed_output_addition!( return nothing end - resolved_additions = ResolvedModelOutputDestination[] + resolved_additions = _model_output_destination_rows(keytype(model.registry.objects), applications_by_id, plans) for binding in previous.bindings default_scope = _default_dependency_scope( model, @@ -7365,18 +7365,11 @@ function _incremental_distributed_output_addition!( !_object_id_isless(last(binding.destination_ids), first(destination_ids)) return nothing end - push!( - resolved_additions, - ResolvedModelOutputDestination( - binding.plan, - _model_output_destination_declarations( - applications_by_id[binding.application_id], - binding.execution_object_id, - binding.plan, - ), - binding.execution_object_id, - destination_ids, - ), + declarations = _model_output_destination_declarations( + applications_by_id[binding.application_id], binding.execution_object_id, binding.plan, + ) + _record_model_output_destination!( + resolved_additions, binding.plan, declarations, binding.execution_object_id, destination_ids, ) end @@ -7429,7 +7422,7 @@ function _incremental_distributed_output_addition!( end end _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) - _prepare_model_output_destination_statuses!(model, resolved_additions, applications_by_id, plans) + _prepare_model_output_destination_statuses!(model, resolved_additions) column_additions = Any[] for resolved in resolved_additions diff --git a/test/test-model-output-destination-declarations.jl b/test/test-model-output-destination-declarations.jl index b5e6235a9..db6844f26 100644 --- a/test/test-model-output-destination-declarations.jl +++ b/test/test-model-output-destination-declarations.jl @@ -668,3 +668,61 @@ end @test model_object(scenario, :leaf).status.existing == 2.0 end end + +struct OutputDestinationChangingProbe{R,C} <: AbstractOutput_Destination_ProbeModel + seed::R + reads::C +end +PlantSimEngine.inputs_(::OutputDestinationChangingProbe) = NamedTuple() +function PlantSimEngine.outputs_(model::OutputDestinationChangingProbe) + model.reads[] += 1 + return (incident_par=Distributed(Default(model.seed[])),) +end +PlantSimEngine.run!(::OutputDestinationChangingProbe, status, environment, constants, context) = nothing + +@testset "distributed declaration types belong to their effective producer" begin + narrow = OutputDestinationChangingProbe(Ref{Any}(1f0), Ref(0)) + wide = OutputDestinationChangingProbe(Ref{Any}(2.0), Ref(0)) + first_cell, second_cell = Ref(3f0), Ref(4.0) + model = CompositeModel( + Object(:plant_a; scale=:Plant), Object(:plant_b; scale=:Plant), + Object(:leaf_a; scale=:Leaf, parent=:plant_a, + status=Status((incident_par=first_cell,))), + Object(:leaf_b; scale=:Leaf, parent=:plant_b, + status=Status((incident_par=second_cell,))); + applications=( + ModelSpec(narrow; name=:narrow, on=One(id=:plant_a), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:incident_par,)),)), + ModelSpec(wide; name=:wide, on=One(id=:plant_b), + outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:incident_par,)),)), + )) + compiled = Advanced.refresh_bindings!(model) + bindings = compiled.distributed_outputs.bindings + @test length(bindings) == 2 + # The global row union contains both declarations for the SAME route type. + @test typeof(first(bindings).plan) === typeof(last(bindings).plan) + @test model_status(model, :leaf_a).incident_par === 3f0 + @test model_status(model, :leaf_b).incident_par === 4.0 + + # The other producer's Float64 witness must not authorize this change. + # A supplied newborn field also makes the default value unnecessary, so + # validation must happen before deciding whether initialization is needed. + narrow.seed[] = 9.0 + newborn_cell = Ref(5f0) + register_object!(model, Object(:leaf_z; scale=:Leaf, parent=:plant_a, + status=Status((incident_par=newborn_cell,)))) + before = model.binding_cache + original_ids = map(binding -> copy(binding.destination_ids), bindings) + reads = (narrow.reads[], wide.reads[]) + @test_throws "schema changed after preparation" Advanced.refresh_bindings!(model) + @test narrow.reads[] == reads[1] + 1 + @test wide.reads[] == reads[2] + @test model.binding_cache === before + @test map(binding -> binding.destination_ids, bindings) == original_ids + @test PlantSimEngine.refvalue(model_status(model, :leaf_a), :incident_par) === first_cell + @test PlantSimEngine.refvalue(model_status(model, :leaf_b), :incident_par) === second_cell + @test PlantSimEngine.refvalue(model_status(model, :leaf_z), :incident_par) === newborn_cell + @test first_cell[] === 3f0 + @test second_cell[] === 4.0 + @test newborn_cell[] === 5f0 +end From 9b1c467e5cdb6f41e122887f5fc02a5055e91f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 01:21:29 +0100 Subject: [PATCH 171/324] Prepare retained output target types before the first organ appears --- src/composite_model/runtime_outputs.jl | 47 ++++++++++++++++++++---- test/test-model-empty-output-requests.jl | 20 ++++++++++ 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 2f40ab1c5..50062cea9 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7941,10 +7941,44 @@ function _compile_output_request(model, compiled, request) end end +# Memberships for requested outputs are retained in append-only streams. Use +# the same reference classes that the fixed Status and its private ports admit, +# including families with no current objects. This inspects no live value. +function _output_request_types(model, application, variable) + manifest = _prepared_status_manifest(model) + open_types = (references=Tuple{Any}, values=Tuple{Any}, streams=Tuple{Any}) + if _publish_mode_for_output(application.spec, variable) === :stream_only + variants = manifest.permissions[application.slot].variants + all(v -> any(p -> first(p) === variable, v.outputs), variants) || return open_types + refs = unique(R for variant in variants for (name, R) in variant.outputs if name === variable) + else + storage = fieldtype(manifest.status_type, :vars) + slot = findfirst(isequal(variable), fieldnames(fieldtype(storage, :refs))) + refs = isnothing(slot) ? DataType[] : + filter(R -> R <: Ref, Base.uniontypes(fieldtype(_status_storage_reference_types(storage), slot))) + end + values = unique(V for R in refs for V in Base.uniontypes(eltype(R))) + if isempty(values) || !all(isconcretetype, values) + # A user-defined reference such as Ref{Real} can hold a previously + # unseen concrete value. Keep its open membership semantics. + return open_types + end + return (references=Tuple{refs...}, values=Tuple{values...}, + streams=Tuple{(Vector{Tuple{Float64,V}} for V in values)...}) +end + +function _output_request_record(request, matcher, application_id, ::Type{I}, types) where {I} + values = fieldtypes(types.values) + Target = values === (Any,) ? Any : Union{(OutputRequestTarget{T} for T in values)...} + return CompiledOutputRequest(request, matcher, application_id, Dict{I,Target}(), + types.references, types.values, types.streams) +end + function _compile_output_request_targets(model, compiled, request, matcher, application) I = keytype(typeof(model.registry.objects)) - targets = Dict{I,Any}() - record = CompiledOutputRequest(request, matcher, application.id, targets, Tuple{Any}, Tuple{Any}, Tuple{Any}) + types = _output_request_types(model, application, request.var) + record = _output_request_record(request, matcher, application.id, I, types) + targets = record.targets owned_ids = Set{I}(_index_object_id(model.registry.objects, id) for id in _model_output_object_ids(compiled, application, request.var)) for raw_id in _resolve_object_ids(model, request.selector, matcher; context=request.context) @@ -7968,13 +8002,10 @@ end function _prepare_output_request_record(record, schemas) schema = getproperty(schemas, record.application_id) types = _prepared_output_request_types(schema, record.request.var) - Target = Union{(OutputRequestTarget{T} for T in fieldtypes(types.values))...} - I = keytype(typeof(record.targets)) - targets = Dict{I,Target}() - prepared = CompiledOutputRequest(record.request, record.matcher, record.application_id, - targets, types.references, types.values, types.streams) + prepared = _output_request_record(record.request, record.matcher, record.application_id, + keytype(record.targets), types) for (id, target) in record.targets - targets[id] = _with_output_request_target(identity, prepared, target) + prepared.targets[id] = _with_output_request_target(identity, prepared, target) end return prepared end diff --git a/test/test-model-empty-output-requests.jl b/test/test-model-empty-output-requests.jl index 2be73a6e0..b6e57e475 100644 --- a/test/test-model-empty-output-requests.jl +++ b/test/test-model-empty-output-requests.jl @@ -39,6 +39,20 @@ end @test_throws ErrorException PSE._model_output_selection(:unsupported) end +@testset "retained output type before the first matching leaf is born" begin + model = CompositeModel(Object(0; scale=:Plant); + applications=(ModelSpec(Counter(); name=:counter, on=Many(scale=:Leaf)),)) + request = OutputRequest(Many(scale=:Leaf), :counter; application=:counter) + simulation = run!(model; steps=0, outputs=request) + record = only(simulation.output_requests) + @test isempty(record.targets) + @test valtype(record.targets) === PSE.OutputRequestTarget{Int} + register_object!(model, Object(1; scale=:Leaf, parent=0)) + step!(simulation) + @test only(values(record.targets)) isa PSE.OutputRequestTarget{Int} + @test outputs(simulation)[(:counter, ObjectId(1), :counter)] == [(1.0, 1)] +end + @testset "typed requests share one owner through output membership changes" begin model = CompositeModel( Object(1; scale=:Plant), @@ -53,6 +67,12 @@ end @test Tuple(entry.request for entry in simulation.output_requests) === (first_request, plant_request) record = simulation.output_requests[:plant] + # A normal run already owns the output families before any optional + # batch preparation. Existing target objects survive the batch preparation. + @test record.reference_types === Tuple{Base.RefValue{Int}} + @test record.value_types === Tuple{Int} + @test record.stream_types === Tuple{Vector{Tuple{Float64,Int}}} + @test valtype(record.targets) === PSE.OutputRequestTarget{Int} original_target = record.targets[ObjectId(2)] original_memberships = original_target.memberships batch = only(simulation.execution_plan.batches) From 9b88910342b74b37585c34f650f8473e19719dcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 02:00:20 +0100 Subject: [PATCH 172/324] Share writer ownership validation between preparation and growth --- src/composite_model/compilation.jl | 196 +++++++++-------------------- 1 file changed, 60 insertions(+), 136 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 49b38b5e8..ab58df0e1 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5973,7 +5973,10 @@ end types <: NamedTuple || continue all(name -> name in fieldnames(types) && fieldtype(types, name) <: Type{<:Distributed}, names) || continue - declarations = map(name -> fieldtype(types, name).parameters[1].parameters[1], names) + declarations = map(names) do name + wrapper = only(fieldtype(types, name).parameters) + fieldtype(wrapper, :declaration) + end record = ResolvedModelOutputDestination{route,NamedTuple{names,Tuple{declarations...}},I} rows = Union{rows,record} end @@ -5997,7 +6000,8 @@ function _resolve_model_output_destinations( applications_by_id, compiled_plans::CompiledDistributedOutputPlans, ) - resolved = _model_output_destination_rows(keytype(model.registry.objects), applications_by_id, compiled_plans) + resolved = _model_output_destination_rows( + keytype(model.registry.objects), applications_by_id, compiled_plans) for plan in compiled_plans.plans application = applications_by_id[plan.application_id] for execution_object_id in application.target_ids @@ -6022,103 +6026,75 @@ function _resolve_model_output_destinations( return resolved end -function _push_compiled_writer_owner!( - ownership, - object_id::ObjectId, - variable::Symbol, - owner::CompiledWriterOwner, -) - push!( - get!( - ownership, - (object_id, variable), - CompiledWriterOwner[], - ), - owner, - ) - return ownership +# During growth only touched keys are copied. Validation can therefore reject +# the whole edit without changing any existing writer list. +function _record_writer_owner!(ownership, previous, object_id, variable, owner) + key = (object_id, variable) + owners = get!(ownership, key) do + isnothing(previous) && return CompiledWriterOwner[] + existing = get(previous.writer_ownership, key, nothing) + return isnothing(existing) ? CompiledWriterOwner[] : copy(existing) + end + push!(owners, owner) + return nothing +end + +function _record_application_writers!(application, ownership, previous, object_ids) + for object_id in object_ids, variable in _model_canonical_output_names(application) + owner = CompiledWriterOwner(application.slot, application.id, object_id, nothing, + :application_target) + _record_writer_owner!(ownership, previous, object_id, variable, owner) + end + return nothing +end + +function _record_destination_writers!(ownership, previous, resolved_destinations) + for record in resolved_destinations + plan = record.plan + owner = CompiledWriterOwner(plan.application_slot, plan.application_id, + record.execution_object_id, plan.group, :output_destination) + for destination_id in record.destination_ids, variable in plan.variable_names + _record_writer_owner!(ownership, previous, destination_id, variable, owner) + end + end + return nothing end function _validate_compiled_writer_ownership!(ownership, applications_by_id) - groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Symbol}}}() + groups = Dict{keytype(ownership),Vector{Tuple{Int,Symbol}}}() for ((object_id, variable), owners) in ownership + length(owners) > 1 || continue sort!(owners; by=owner -> owner.application_slot) - seen_application_slots = Set{Int}() - for owner in owners - if owner.application_slot in seen_application_slots + for index in 2:length(owners) + owner = owners[index] + if owner.application_slot == owners[index - 1].application_slot error( "Application `$(owner.application_id)` declares more than one canonical " * "writer for `$(variable)` on object `$(object_id.value)`. Ensure its " * "`on=...` targets and `outputs_to` destinations do not overlap.", ) end - push!(seen_application_slots, owner.application_slot) - push!( - get!( - groups, - (object_id, variable), - Tuple{Int,Symbol}[], - ), - ( - owner.application_slot, - owner.application_id, - ), - ) end + groups[(object_id, variable)] = [(owner.application_slot, owner.application_id) for owner in owners] end _validate_model_writer_groups!(groups, applications_by_id) return ownership end function _compile_model_writer_ownership( + ::Type{I}, applications, applications_by_id, manual_application_ids, resolved_destinations, -) - ownership = Dict{ - Tuple{ObjectId,Symbol}, - Vector{CompiledWriterOwner}, - }() - for application in applications - application.id in manual_application_ids && continue - for object_id in application.target_ids - for variable in _model_canonical_output_names(application) - _push_compiled_writer_owner!( - ownership, - object_id, - variable, - CompiledWriterOwner( - application.plan.slot, - application.id, - object_id, - nothing, - :application_target, - ), - ) - end - end - end - for resolved in resolved_destinations - plan = resolved.plan - for destination_id in resolved.destination_ids - for variable_ in plan.variable_names - variable = Symbol(variable_) - _push_compiled_writer_owner!( - ownership, - destination_id, - variable, - CompiledWriterOwner( - plan.application_slot, - plan.application_id, - resolved.execution_object_id, - plan.group, - :output_destination, - ), - ) - end - end +) where {I<:ObjectId} + ownership = Dict{Tuple{I,Symbol},Vector{CompiledWriterOwner}}() + for partial in applications + getfield(getfield(partial, :plan), :id) in manual_application_ids && continue + _with_model_application(_record_application_writers!, applications_by_id, partial, + ownership, nothing, partial.target_ids) end + _record_destination_writers!(ownership, nothing, resolved_destinations) return _validate_compiled_writer_ownership!(ownership, applications_by_id) end @@ -7239,6 +7215,7 @@ function _compile_model_distributed_outputs( plans, ) ownership = _compile_model_writer_ownership( + keytype(model.registry.objects), applications, applications_by_id, manual_application_ids, @@ -7304,21 +7281,6 @@ function _refresh_model_distributed_outputs( return previous, Set{Tuple{Symbol,ObjectId}}(), nothing end -function _stage_distributed_writer_owner!( - staged, - previous, - object_id::ObjectId, - variable::Symbol, - owner::CompiledWriterOwner, -) - key = (object_id, variable) - owners = get!(staged, key) do - copy(get(previous.writer_ownership, key, CompiledWriterOwner[])) - end - push!(owners, owner) - return staged -end - function _incremental_distributed_output_addition!( model::CompositeModel, previous::CompiledDistributedOutputs, @@ -7336,7 +7298,8 @@ function _incremental_distributed_output_addition!( return nothing end - resolved_additions = _model_output_destination_rows(keytype(model.registry.objects), applications_by_id, plans) + resolved_additions = _model_output_destination_rows( + keytype(model.registry.objects), applications_by_id, plans) for binding in previous.bindings default_scope = _default_dependency_scope( model, @@ -7375,52 +7338,13 @@ function _incremental_distributed_output_addition!( _validate_model_output_destination_statuses!(model, resolved_additions) _validate_required_model_output_destinations!(model, resolved_additions) - staged_ownership = Dict{ - Tuple{ObjectId,Symbol}, - Vector{CompiledWriterOwner}, - }() + staged_ownership = empty(previous.writer_ownership) for (application_id, object_ids) in new_targets - application = applications_by_id[application_id] - application.id in manual_application_ids && continue - for object_id in object_ids - for variable in _model_canonical_output_names(application) - _stage_distributed_writer_owner!( - staged_ownership, - previous, - object_id, - variable, - CompiledWriterOwner( - application.plan.slot, - application.id, - object_id, - nothing, - :application_target, - ), - ) - end - end - end - for resolved in resolved_additions - plan = resolved.plan - for destination_id in resolved.destination_ids - for variable_ in plan.variable_names - variable = Symbol(variable_) - _stage_distributed_writer_owner!( - staged_ownership, - previous, - destination_id, - variable, - CompiledWriterOwner( - plan.application_slot, - plan.application_id, - resolved.execution_object_id, - plan.group, - :output_destination, - ), - ) - end - end + application_id in manual_application_ids && continue + _with_metadata_entry(_record_application_writers!, applications_by_id, application_id, + staged_ownership, previous, object_ids) end + _record_destination_writers!(staged_ownership, previous, resolved_additions) _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) _prepare_model_output_destination_statuses!(model, resolved_additions) From b04cb66bcbcf6bb459e3e56ac06004fcfc085b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 02:02:24 +0100 Subject: [PATCH 173/324] Commit prepared status references without capturing the model --- src/composite_model/compilation.jl | 14 +++++++------- test/test-status-fixed-storage.jl | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index ab58df0e1..1345dc0ef 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6647,9 +6647,9 @@ end # One prepared physical schema handles every presence pattern. Slot construction # validates ALL edits before its single metadata assignment; no runtime type/name # discovery, terminal-layout enumeration or alternate Open algorithm remains. -@generated function _finish_canonical_status_recipe(f::F, +@generated function _finish_canonical_status_recipe!( recipe::_CanonicalStatusRecipe{S}, -) where {F,N,R,T,S<:Status{N,_FixedStatusStorage{N,R,T}}} +) where {N,R,T,S<:Status{N,_FixedStatusStorage{N,R,T}}} cells = [gensym(:cell) for _ in N] reads = [quote position = findfirst(isequal($(QuoteNode(name))), recipe.edit_names) @@ -6659,7 +6659,8 @@ end end for (i,name) in enumerate(N)] values = Expr(:tuple, [:( $(cells[i])::$(fieldtype(T,i)) ) for i in eachindex(N)]...) return quote - recipe.changed || return f(recipe.original) + $(Expr(:meta, :noinline)) + recipe.changed || return recipe.original for name in recipe.edit_names name in $(QuoteNode(N)) || throw(KeyError(name)) end @@ -6670,7 +6671,7 @@ end storage.refs = references storage.reference_epoch += UInt(1) end - return f(recipe.original) + return recipe.original end end @@ -6743,9 +6744,8 @@ function _apply_status_recipes!( for object_id in recipe_order recipe = recipes[object_id] recipe.changed || continue - _finish_canonical_status_recipe(recipe) do status - _replace_model_object_status!(model, object_id, status) - end + status = _finish_canonical_status_recipe!(recipe) + _replace_model_object_status!(model, object_id, status) _runtime_performance_count!( performance, :lifecycle_binding_refresh_status_recipe_materializations, diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 0deb10d11..8c00f042b 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -98,10 +98,10 @@ end replacement = Ref(2.0) @test PSE._status_recipe_set_reference!(recipe,:x,replacement) @test PSE.refvalue(state,:x) !== replacement - @test PSE._finish_canonical_status_recipe(identity,recipe) === original + @test PSE._finish_canonical_status_recipe!(recipe) === original @test PSE.refvalue(state,:x) === replacement @test PSE._status_reference_epoch(state) == epoch+1 - @test PSE._finish_canonical_status_recipe(identity,recipe) === original + @test PSE._finish_canonical_status_recipe!(recipe) === original @test PSE._status_reference_epoch(state) == epoch+1 @test_throws ArgumentError PSE._status_recipe_set_reference!(recipe,:x,Ref("bad")) @test PSE.refvalue(state,:x) === replacement From 1db4619a69d4009b04bb4496a98a8ae4b29ec31f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 02:19:13 +0100 Subject: [PATCH 174/324] Match the XPalm benchmark to its versioned scientific reference --- benchmark/test-xpalm.jl | 63 ++++++++++++++++++++++++++++++++++---- benchmark/test/runtests.jl | 46 +++++++++++++++++++++++----- 2 files changed, 95 insertions(+), 14 deletions(-) diff --git a/benchmark/test-xpalm.jl b/benchmark/test-xpalm.jl index eea02dd5e..e8c8be16e 100644 --- a/benchmark/test-xpalm.jl +++ b/benchmark/test-xpalm.jl @@ -7,8 +7,43 @@ using SHA using TOML using XPalm -const XPALM_REFERENCE_BASELINE = "v0.7.0" -const XPALM_REFERENCE_SOURCE_COMMIT = "d4ded8891d03f85bb5691b89572a4e003ac6eb7a" +# This versioned reference was introduced with standard bunch-growth recovery +# in XPalm 4f825f7. Older checkouts retain the published reference unchanged. +function _xpalm_reference_baseline(xpalm_root) + candidate = "v0.7.0-catchup-dev" + return isdir(joinpath(xpalm_root, "test", "references", "regression", candidate)) ? + candidate : "v0.7.0" +end + +function _xpalm_reference_identity(baseline) + if baseline == "v0.7.0" + return ( + source_commit="d4ded8891d03f85bb5691b89572a4e003ac6eb7a", + scientific_change=nothing, + predecessor=nothing, + csv_sha256=( + "trajectory_checkpoints.csv" => "5b4b6cdd2bddcf63393810a5bfb825c8081b221517ad8f97decfb3a8edad0b95", + "harvest_events.csv" => "c887048a8530f5c7834964ace71e2660b8b1a189b275787172da348116522b77", + "summary.csv" => "ea1d0e929b13f379e9924f35d058bd7f895695268004b6603ec1101255df50e0", + ), + ) + elseif baseline == "v0.7.0-catchup-dev" + return ( + source_commit="7650eccf039a7d2b9cf3263d2d77292bbaea876a", + scientific_change="reproductive-lifecycle-rooted-recharge-and-bunch-growth-recovery", + predecessor="v0.7.0", + csv_sha256=( + "trajectory_checkpoints.csv" => "f742f74f7db90cc7b6f119f2301cc47638be7604b3aeaeffcba994cd03ad06f7", + "harvest_events.csv" => "3ca7c853d248dede8fba4dc849ac9b5e3c9358c7c5442a27ee454b74cfc2a90f", + "summary.csv" => "4e02b8f5c285240df00f08796bde5a6cd5091b975383552ae1b6700563d2b99e", + ), + ) + end + error("Unsupported XPalm numerical reference: $(baseline).") +end + +const XPALM_REFERENCE_BASELINE = + _xpalm_reference_baseline(dirname(dirname(pathof(XPalm)))) const XPALM_REFERENCE_BENCHMARK_VARIABLES = Dict{Symbol,Any}( :Scene => (:lai, :leaf_area, :aPPFD), @@ -190,17 +225,33 @@ end function xpalm_reference_full_cycle_expected_state(; xpalm_root=dirname(dirname(pathof(XPalm))), + baseline=_xpalm_reference_baseline(xpalm_root), ) + identity = _xpalm_reference_identity(baseline) reference_dir = joinpath( - xpalm_root, "test", "references", "regression", XPALM_REFERENCE_BASELINE, + xpalm_root, "test", "references", "regression", baseline, ) metadata = TOML.parsefile(joinpath(reference_dir, "metadata.toml")) source = metadata["source"] inputs = metadata["inputs"] - source["baseline_id"] == XPALM_REFERENCE_BASELINE || - error("XPalm benchmark reference baseline does not match $(XPALM_REFERENCE_BASELINE).") - source["xpalm_commit"] == XPALM_REFERENCE_SOURCE_COMMIT || + source["baseline_id"] == baseline || + error("XPalm benchmark reference baseline does not match $(baseline).") + source["xpalm_commit"] == identity.source_commit || error("XPalm benchmark reference source commit has changed; review its provenance.") + isequal(get(source, "scientific_change_id", nothing), identity.scientific_change) && + isequal(get(source, "predecessor_baseline", nothing), identity.predecessor) || + error("XPalm benchmark reference identifies a different scientific change.") + seeds = metadata["stochastic_configuration"] + seeds["sex_determination_seed"] == 1 && seeds["abortion_seed"] == 1 || + error("XPalm benchmark reference uses different stochastic seeds.") + for (file, expected) in identity.csv_sha256 + bytes2hex(SHA.sha256(read(joinpath(reference_dir, file)))) == expected || + error("XPalm benchmark reference data changed: $(file).") + end + if identity.scientific_change !== nothing + metadata["fixture"]["csv_sha256"] == Dict(identity.csv_sha256) || + error("XPalm benchmark reference data provenance has changed.") + end source["parameter_source"] == "XPalm.default_parameters()" || error("XPalm benchmark reference uses a different parameter scenario.") inputs["meteo_file"] == "0-data/meteo.csv" || diff --git a/benchmark/test/runtests.jl b/benchmark/test/runtests.jl index 266c3eb9f..53dc40eb0 100644 --- a/benchmark/test/runtests.jl +++ b/benchmark/test/runtests.jl @@ -1134,22 +1134,43 @@ if benchmark_test_enabled("XPalm reference oracle smoke") ) mktempdir() do fixture_root - for relative_path in ( - joinpath("0-data", "meteo.csv"), - joinpath(reference_relpath, "metadata.toml"), - joinpath(reference_relpath, "summary.csv"), - ) - target = joinpath(fixture_root, relative_path) - mkpath(dirname(target)) - cp(joinpath(xpalm_root, relative_path), target) + mkpath(joinpath(fixture_root, "0-data")) + cp(joinpath(xpalm_root, "0-data", "meteo.csv"), + joinpath(fixture_root, "0-data", "meteo.csv")) + for baseline in ("v0.7.0", "v0.7.0-catchup-dev") + relative = joinpath("test", "references", "regression", baseline) + isdir(joinpath(xpalm_root, relative)) || continue + mkpath(joinpath(fixture_root, relative)) + for file in ("metadata.toml", "summary.csv", "trajectory_checkpoints.csv", "harvest_events.csv") + cp(joinpath(xpalm_root, relative, file), joinpath(fixture_root, relative, file)) + end end + @test _xpalm_reference_baseline(fixture_root) == XPALM_REFERENCE_BASELINE @test xpalm_reference_full_cycle_expected_state(; xpalm_root=fixture_root) == expected + historical = xpalm_reference_full_cycle_expected_state(; + xpalm_root=fixture_root, baseline="v0.7.0") + @test historical.current_step == expected.current_step == 4160 + @test_throws ErrorException xpalm_reference_full_cycle_expected_state(; + xpalm_root=fixture_root, baseline="unreviewed") + candidate_dir = joinpath(fixture_root, "test", "references", "regression", "v0.7.0-catchup-dev") + if isdir(candidate_dir) + @test !xpalm_reference_state_matches(historical, expected) + # Simulate an older checkout containing only the published data. + inactive = joinpath(fixture_root, "inactive-reference") + mv(candidate_dir, inactive) + @test _xpalm_reference_baseline(fixture_root) == "v0.7.0" + @test xpalm_reference_full_cycle_expected_state(; xpalm_root=fixture_root) == historical + mv(inactive, candidate_dir) + end metadata_path = joinpath(fixture_root, reference_relpath, "metadata.toml") metadata = TOML.parsefile(metadata_path) for (section, key, wrong_value) in ( ("source", "baseline_id", "v0.6.1"), ("source", "xpalm_commit", "unknown"), ("source", "parameter_source", "historical_parameters()"), + ("source", "scientific_change_id", "unreviewed-change"), + ("source", "predecessor_baseline", "unreviewed-predecessor"), + ("stochastic_configuration", "sex_determination_seed", 2), ("inputs", "nsteps", 1000), ("inputs", "meteo_sha256", repeat("0", 64)), ) @@ -1165,6 +1186,15 @@ if benchmark_test_enabled("XPalm reference oracle smoke") open(metadata_path, "w") do io TOML.print(io, metadata) end + for file in ("trajectory_checkpoints.csv", "harvest_events.csv", "summary.csv") + path = joinpath(fixture_root, reference_relpath, file) + original = read(path) + write(path, [original; UInt8(0x0a)]) + @test_throws ErrorException xpalm_reference_full_cycle_expected_state(; + xpalm_root=fixture_root, + ) + write(path, original) + end summary_path = joinpath(fixture_root, reference_relpath, "summary.csv") changed_summary = CSV.read(summary_path, DataFrame) changed_summary.nsteps[1] -= 1 From 8b62ec993a04248bc39c686658c9d83af3b5e378 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 08:25:35 +0100 Subject: [PATCH 175/324] Reuse projected status types across organs with the same kernel ports --- src/composite_model/status_construction.jl | 9 +++++++++ src/composite_model/status_view_construction.jl | 2 +- test/test-status-fixed-storage.jl | 10 ++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl index 998cab76d..c1e164fe4 100644 --- a/src/composite_model/status_construction.jl +++ b/src/composite_model/status_construction.jl @@ -23,6 +23,15 @@ _status_schema_names(::Type{Nothing}) = () _status_schema_names(::Type{Status{Names,T}}) where {Names,T} = Names _status_schema_references(::Type{Status{Names,T}}) where {Names,T} = _status_storage_reference_types(T) + +# These witnesses contain only the prepared namespace and exact reference +# classes, so identical views share one schema calculation across objects. +@generated function _projected_status_type( + ::Type{C}, ::Val{NAMES}, ::Type{R}, +) where {C<:Status,NAMES,R<:Tuple} + return QuoteNode(_projected_status_type(C, NAMES, R)) +end + _status_schema_values(::Nothing) = () _status_schema_values(status::Status{N,<:NamedTuple}) where {N} = refvalues(status) _status_schema_values(status::Status{N,<:Union{_FixedStatusStorage,_ProjectedStatusStorage}}) where {N} = diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index 3c98d11a9..860b9ce67 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -539,7 +539,7 @@ function _open_status_view_type(parts) hasproperty(parts.canonical_status,name) || throw(ArgumentError("A declared kernel port has no initialized value.")) typeof(refvalue(parts.canonical_status,name)) end - S = _projected_status_type(C, parts.hot_names, Tuple{hot_references...}) + S = _projected_status_type(C, Val(parts.hot_names), Tuple{hot_references...}) bound_types = map(parts.many_names, parts.many_ids) do name, ids Value = if (index = findfirst(recipe -> recipe.input === name, parts.temporal)) !== nothing _open_status_view_storage_type(parts.temporal[index]) diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 8c00f042b..b6a7e4c51 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -66,7 +66,11 @@ end @testset "dense hot and full namespace snapshot use identical private overrides" begin owner = PSE._new_prepared_status(SCHEMA,Status(x=3f0,q=1//2,seed=Float32[2])) private = Ref(100.0) - Projected = PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF64,RR}) + Projected = @inferred PSE._projected_status_type(SCHEMA,Val((:x,:q)),Tuple{RF64,RR}) + @test Projected === PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF64,RR}) + @test PSE._projected_status_type(SCHEMA,Val(()),Tuple{}) === + PSE._projected_status_type(SCHEMA,(),Tuple{}) + @test_throws ArgumentError PSE._projected_status_type(SCHEMA,Val((:unprepared,)),Tuple{RF32}) factory = PSE.ExactReferenceFactory(SCHEMA,Tuple{RF64},Projected,(:x,)) old = PSE._construct_status(factory,owner,(private,)) @test old.x === 100.0 && first(Tuple(old)) === 100.0 @@ -78,7 +82,9 @@ end PSE._set_status_reference!(owner,:literal,Ref(nothing)) @test keys(old) === (:x,:q,:seed) && !hasproperty(old,:literal) @test old.x === 100.0 && PSE.refvalue(old,:x) === private - Fresh = PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF32,RR}) + Fresh = @inferred PSE._projected_status_type(SCHEMA,Val((:x,:q)),Tuple{RF32,RR}) + @test Fresh === PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF32,RR}) + @test Fresh !== Projected current = PSE._construct_status(PSE.ExactReferenceFactory(SCHEMA,Tuple{},Fresh,()),owner,()) @test PSE.refvalue(current,:x) === replacement @test current.x === first(Tuple(current)) === 4f0 From 717b152167495419cffeb4f42eb03064223c54af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 09:09:13 +0100 Subject: [PATCH 176/324] Resolve distributed routes with their owning producers at preparation and birth --- src/composite_model/compilation.jl | 155 ++++++++++-------- test/fixtures/distributed_growth.jl | 86 ++++++++++ test/test-model-distributed-output-runtime.jl | 69 +++++++- .../test-model-distributed-route-ownership.jl | 5 +- 4 files changed, 244 insertions(+), 71 deletions(-) create mode 100644 test/fixtures/distributed_growth.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1345dc0ef..20ade90da 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5930,13 +5930,6 @@ _resolve_model_output_destinations( # Port names are authored metadata; defaults belong to the actual initial or # newborn destination event, never a previous binding's cached declaration. -function _model_output_destination_declarations( - application, execution_object_id, plan::CompiledModelOutputDestinationPlan, -) - return _with_application_variant(_read_model_output_destination_declarations, - application, execution_object_id, plan) -end - function _read_model_output_destination_declarations(producer, ports, ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, ) where {GROUP,NAMES} @@ -5996,34 +5989,54 @@ function _record_model_output_destination!(rows::Vector{R}, plan, declarations, end function _resolve_model_output_destinations( - model::CompositeModel, - applications_by_id, - compiled_plans::CompiledDistributedOutputPlans, -) - resolved = _model_output_destination_rows( - keytype(model.registry.objects), applications_by_id, compiled_plans) - for plan in compiled_plans.plans - application = applications_by_id[plan.application_id] - for execution_object_id in application.target_ids - declarations = _model_output_destination_declarations( - application, execution_object_id, plan, - ) - destination_ids = _application_target_ids( - model, - _dependency_object_ids( - model, - plan.selector, - plan.matcher, - execution_object_id, - ), - ) - sizehint!(destination_ids, length(destination_ids) + 1) - _record_model_output_destination!( - resolved, plan, declarations, execution_object_id, destination_ids, - ) - end + model::CompositeModel, applications_by_id, plans::CompiledDistributedOutputPlans, +) + rows = _model_output_destination_rows(keytype(model.registry.objects), applications_by_id, plans) + _visit_model_output_routes(_resolve_producer_destinations!, applications_by_id, + plans.by_application, nothing, model, rows, nothing, nothing) + return rows +end + +# Grouped routes and applications have the same authored keys. Visit each route +# with its owning producer so unrelated model schemas never enter inference. +# Growth supplies the slot of the one route whose membership just changed. +@generated function _visit_model_output_routes(f::F, applications::CompiledMetadataTable, + groups::G, slot::S, args::Vararg{Any,N}, +) where {F,G<:NamedTuple,S<:Union{Int,Nothing},N} + visits = Expr[] + for owner in fieldnames(G), i in 1:fieldcount(fieldtype(G, owner)) + route = :(getfield(getfield(groups, $(QuoteNode(owner))), $i)) + application = :(getfield(getfield(applications, :entries), $(QuoteNode(owner)))) + visit = :(f($application, $route, args...)) + push!(visits, S === Nothing ? visit : :(getfield($route, :slot) == slot && return $visit)) + end + return quote + $(visits...) + $(S === Nothing ? :(return nothing) : :(throw(BoundsError(groups, slot)))) + end +end + +function _resolve_producer_destinations!(application, plan, model, rows, execution_id, destination_ids) + origins = isnothing(execution_id) ? application.target_ids : (execution_id,) + for origin in origins + _with_application_variant(_capture_model_output_destination!, application, + origin, plan, model, rows, origin, destination_ids) end - return resolved + return nothing +end + +# Read defaults from the effective producer before resolving the initial +# destination query. On growth the caller already knows the additional IDs. +function _capture_model_output_destination!(producer, ports, plan, model, rows, + execution_id, destination_ids, +) + declarations = _read_model_output_destination_declarations(producer, ports, plan) + if isnothing(destination_ids) + destination_ids = _application_target_ids(model, + _dependency_object_ids(model, plan.selector, plan.matcher, execution_id)) + sizehint!(destination_ids, length(destination_ids) + 1) + end + return _record_model_output_destination!(rows, plan, declarations, execution_id, destination_ids) end # During growth only touched keys are copied. Validation can therefore reject @@ -7281,6 +7294,40 @@ function _refresh_model_distributed_outputs( return previous, Set{Tuple{Symbol,ObjectId}}(), nothing end +# Admit the old route through the existing finite plan owner before selecting +# new destinations. A changed route family uses the complete refresh below. +function _resolve_incremental_model_output_addition!( + application, plan::P, binding::CompiledModelOutputDestinationBinding, + objects::AbstractDict{I}, model, resolved_additions, added_ids, +) where {P<:CompiledModelOutputDestinationPlan,I<:ObjectId} + previous_plan = getfield(binding, :plan)::CompiledModelOutputDestinationPlan + previous_plan isa P || return false + execution_id = _index_object_id(objects, getfield(binding, :execution_object_id)) + previous_ids = getfield(binding, :destination_ids)::Vector{I} + default_scope = _default_dependency_scope(model, execution_id) + destination_ids = I[ + object_id for object_id in added_ids + if _selector_matches_object_id( + model, + previous_plan.matcher, + object_id, + execution_id, + true, + default_scope, + false, + ) && !first(_sorted_object_id_position(previous_ids, object_id)) + ] + isempty(destination_ids) && return true + _sort_object_ids!(destination_ids) + if !isempty(previous_ids) && + !_object_id_isless(last(previous_ids), first(destination_ids)) + return false + end + _resolve_producer_destinations!(application, plan, model, + resolved_additions, execution_id, destination_ids) + return true +end + function _incremental_distributed_output_addition!( model::CompositeModel, previous::CompiledDistributedOutputs, @@ -7300,40 +7347,12 @@ function _incremental_distributed_output_addition!( resolved_additions = _model_output_destination_rows( keytype(model.registry.objects), applications_by_id, plans) - for binding in previous.bindings - default_scope = _default_dependency_scope( - model, - binding.execution_object_id, - ) - destination_ids = keytype(model.registry.objects)[ - object_id for object_id in added_ids - if _selector_matches_object_id( - model, - binding.matcher, - object_id, - binding.execution_object_id, - true, - default_scope, - false, - ) && !first( - _sorted_object_id_position( - binding.destination_ids, - object_id, - ), - ) - ] - isempty(destination_ids) && continue - _sort_object_ids!(destination_ids) - if !isempty(binding.destination_ids) && - !_object_id_isless(last(binding.destination_ids), first(destination_ids)) - return nothing - end - declarations = _model_output_destination_declarations( - applications_by_id[binding.application_id], binding.execution_object_id, binding.plan, - ) - _record_model_output_destination!( - resolved_additions, binding.plan, declarations, binding.execution_object_id, destination_ids, - ) + for raw_binding in previous.bindings + binding = raw_binding::CompiledModelOutputDestinationBinding + previous_plan = getfield(binding, :plan)::CompiledModelOutputDestinationPlan + _visit_model_output_routes(_resolve_incremental_model_output_addition!, + applications_by_id, plans.by_application, getfield(previous_plan, :slot), + binding, model.registry.objects, model, resolved_additions, added_ids) || return nothing end _validate_model_output_destination_statuses!(model, resolved_additions) diff --git a/test/fixtures/distributed_growth.jl b/test/fixtures/distributed_growth.jl new file mode 100644 index 000000000..020921740 --- /dev/null +++ b/test/fixtures/distributed_growth.jl @@ -0,0 +1,86 @@ +module DistributedGrowthFixture + +import PlantSimEngine as PSE + +PSE.@process "mini_weather_grower" verbose=false +PSE.@process "mini_weather_leaf_source" verbose=false +PSE.@process "mini_weather_lag_reader" verbose=false +PSE.@process "mini_weather_distributor" verbose=false +struct Grower <: AbstractMini_Weather_GrowerModel end +struct LeafSource <: AbstractMini_Weather_Leaf_SourceModel end +struct LagReader <: AbstractMini_Weather_Lag_ReaderModel end +struct Distributor{VARIABLE} <: AbstractMini_Weather_DistributorModel + factor::Float32 +end +PSE.inputs_(::Grower) = NamedTuple() +PSE.outputs_(::Grower) = (visits=0, seen=0.0, dose=0.0) +PSE.environment_inputs_(::Grower) = (T=0.0,) +PSE.inputs_(::LeafSource) = (tick=PSE.Default(0),) +PSE.outputs_(::LeafSource) = (x=0f0,) +PSE.inputs_(::LagReader) = (tick=PSE.Default(0), lag=PSE.Default(Float32[])) +PSE.outputs_(::LagReader) = (lagtotal=0f0,) +PSE.inputs_(::Distributor) = (tick=PSE.Default(0),) +PSE.outputs_(::Distributor{VARIABLE}) where {VARIABLE} = + NamedTuple{(VARIABLE,)}((PSE.Distributed(PSE.Default(0f0)),)) +PSE.environment_inputs_(::Distributor) = (T=0.0,) +leaf_status(value::Float32) = PSE.Status(x=value, tick=0) +function PSE.run!(::Grower, status, environment, constants, context) + status.visits += 1 + status.seen = environment.T + status.dose += environment.T + if status.visits == 2 + model = PSE.runtime_model(context) + # Both signals are first supplied at birth. The root distributor is + # already running, and the emitter distributor becomes active below. + supplied = PSE.Status(x=10f0, tick=0, delivered=-7f0, prospective=-11f0) + PSE.register_object!(model, PSE.Object(:leaf_b; + scale=:Leaf, parent=:root, status=supplied)) + PSE.register_object!(model, PSE.Object(:emitter; + scale=:Emitter, parent=:root, status=PSE.Status(tick=0))) + end + return nothing +end +PSE.run!(::LeafSource, status, environment, constants, context) = + (status.x += 1f0; nothing) +PSE.run!(::LagReader, status, environment, constants, context) = + (status.lagtotal = sum(PSE.bound_input(context, :lag); init=0f0); nothing) +function PSE.run!(model::Distributor{VARIABLE}, status, environment, constants, context) where {VARIABLE} + destinations = PSE.output_targets(context, (VARIABLE,)) + column = getproperty(destinations.columns, VARIABLE) + for index in eachindex(PSE.object_ids(destinations)) + column[index] = model.factor * Float32(environment.T) + end + return nothing +end + +function make_model(; reader_every=PSE.Dates.Hour(1), distributor_every=PSE.Dates.Hour(1)) + weather = PSE.PlantMeteo.Weather([ + PSE.PlantMeteo.Atmosphere(date=PSE.Dates.DateTime(2025, 1, 1) + PSE.Dates.Hour(index - 1), + T=temperature, Wind=1.0, Rh=0.5, duration=PSE.Dates.Hour(1)) + for (index, temperature) in enumerate((10.0, 20.0, 30.0, 40.0)) + ]) + root = PSE.Object(:root; scale=:Scene, + status=PSE.Status(visits=0, seen=0.0, dose=0.0, tick=0, lag=Float32[], lagtotal=0f0)) + leaf = PSE.Object(:leaf_a; scale=:Leaf, parent=:root, status=leaf_status(1f0)) + model = PSE.CompositeModel(root, leaf; environment=weather, applications=( + PSE.ModelSpec(Grower(); name=:grower, on=PSE.One(id=:root), every=PSE.Dates.Hour(1)), + # This genuine One input orders growth before sources so B runs on its birth step. + PSE.ModelSpec(LeafSource(); name=:source, on=PSE.Many(scale=:Leaf), every=PSE.Dates.Hour(1), + inputs=(:tick => PSE.One(id=:root, within=PSE.SceneScope(), application=:grower, var=:visits),)), + PSE.ModelSpec(LagReader(); name=:reader, on=PSE.One(id=:root), every=reader_every, + inputs=(:tick => PSE.One(id=:root, within=PSE.SceneScope(), application=:grower, var=:visits), + PSE.PreviousTimeStep(:lag) => PSE.Many(PSE.SceneScope(); scale=:Leaf, + application=:source, var=:x))), + PSE.ModelSpec(Distributor{:delivered}(1f0); name=:distributed, + on=PSE.One(id=:root), every=distributor_every, + inputs=(:tick => PSE.One(id=:root, within=PSE.SceneScope(), application=:grower, var=:visits),), + outputs_to=(PSE.OutputTo(PSE.Many(PSE.SceneScope(); scale=:Leaf); vars=(:delivered,)),)), + PSE.ModelSpec(Distributor{:prospective}(2f0); name=:prospective_distributor, + on=PSE.Many(scale=:Emitter), every=PSE.Dates.Hour(1), + inputs=(:tick => PSE.One(id=:root, within=PSE.SceneScope(), application=:grower, var=:visits),), + outputs_to=(PSE.OutputTo(PSE.Many(PSE.SceneScope(); scale=:Leaf); vars=(:prospective,)),)), + )) + return model +end + +end diff --git a/test/test-model-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index fb58af6d4..bec93d319 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1269,7 +1269,8 @@ end @test index[(:closed_destination_writer, :incident_par)] === ids @test object_ids(PSE.OutputTargets(binding, 1)).ids === ids application = simulation.compiled.applications_by_id[:closed_destination_writer] - declarations = PSE._model_output_destination_declarations(application, binding.execution_object_id, binding.plan) + declarations = PSE._with_application_variant(PSE._read_model_output_destination_declarations, + application, binding.execution_object_id, binding.plan) resolved = PSE.ResolvedModelOutputDestination(binding.plan, declarations, binding.execution_object_id, ids) @test resolved.destination_ids === ids @test fieldtype(typeof(resolved), :destination_ids) === typeof(ids) @@ -1368,3 +1369,69 @@ end @test all(combined !== binding.destination_ids for binding in bindings) @test model_status(merged_model, 30).incident_par == 101.0 end + + +include("fixtures/distributed_growth.jl") + +@testset "same-step leaf and producer growth preserves weather, lagged Many and history" begin + # Growth, leaf sources and the newborn producer run hourly. The other + # producer and reader can run every two hours across the birth at tick 2. + # PreviousTimeStep uses global t-1, not the reader's preceding invocation. + for cadence in (Hour(1), Hour(2)) + model = DistributedGrowthFixture.make_model(; reader_every=cadence, distributor_every=cadence) + simulation = run!(model; steps=0, outputs=:all) + lag_key = (:reader, ObjectId(:root), :lagtotal) + lag_stream = outputs(simulation)[lag_key] + @test isempty(lag_stream) + @test Set(object_ids(model)) == Set(ObjectId.((:root, :leaf_a))) + + expected_lag = cadence == Hour(1) ? + [(1.0, 1f0), (2.0, 12f0), (3.0, 14f0), (4.0, 16f0)] : + [(1.0, 1f0), (3.0, 14f0)] + expected_delivery = cadence == Hour(1) ? + [(1.0, 10f0), (2.0, 20f0), (3.0, 30f0), (4.0, 40f0)] : + [(1.0, 10f0), (3.0, (20f0 + 30f0) / 2)] + for hour in 1:4 + step!(simulation) + streams = outputs(simulation) + @test current_step(simulation) == hour + @test streams[lag_key] === lag_stream + @test lag_stream == filter(sample -> first(sample) <= hour, expected_lag) + @test final_state(simulation, :root).lagtotal === last(last(lag_stream)) + @test streams[(:grower, ObjectId(:root), :seen)] == + [(Float64(t), (10.0, 20.0, 30.0, 40.0)[t]) for t in 1:hour] + @test streams[(:grower, ObjectId(:root), :dose)] == + [(Float64(t), (10.0, 30.0, 60.0, 100.0)[t]) for t in 1:hour] + @test streams[(:source, ObjectId(:leaf_a), :x)] == + [(Float64(t), Float32(t + 1)) for t in 1:hour] + @test streams[(:distributed, ObjectId(:leaf_a), :delivered)] == + filter(sample -> first(sample) <= hour, expected_delivery) + if hour < 2 + @test Set(object_ids(model)) == Set(ObjectId.((:root, :leaf_a))) + @test !haskey(streams, (:prospective_distributor, ObjectId(:leaf_a), :prospective)) + else + @test Set(object_ids(model)) == Set(ObjectId.((:root, :leaf_a, :leaf_b, :emitter))) + # B and its previously absent producer BOTH execute on birth tick 2. + @test streams[(:source, ObjectId(:leaf_b), :x)] == + [(Float64(t), Float32(t + 9)) for t in 2:hour] + @test get(streams, (:distributed, ObjectId(:leaf_b), :delivered), + Tuple{Float64,Float32}[]) == + filter(sample -> 2 <= first(sample) <= hour, expected_delivery) + if cadence == Hour(2) && hour == 2 + # The old producer is not due: supplied data survives until + # its next tick, which averages temperature over hours 2 and 3. + @test final_state(simulation, :leaf_b).delivered === -7f0 + end + for leaf in (:leaf_a, :leaf_b) + @test streams[(:prospective_distributor, ObjectId(leaf), :prospective)] == + [(Float64(t), 20f0 * t) for t in 2:hour] + end + end + end + # At global tick 3 the reader uses the actual tick-2 source publications: + # A=3 and newborn B=11. Both are newer than the reader's preceding tick 1. + @test outputs(simulation)[(:source, ObjectId(:leaf_a), :x)][2] == (2.0, 3f0) + @test first(outputs(simulation)[(:source, ObjectId(:leaf_b), :x)]) == (2.0, 11f0) + @test only(sample for sample in lag_stream if first(sample) == 3.0) == (3.0, 14f0) + end +end diff --git a/test/test-model-distributed-route-ownership.jl b/test/test-model-distributed-route-ownership.jl index 3a68748a7..cc5f5c561 100644 --- a/test/test-model-distributed-route-ownership.jl +++ b/test/test-model-distributed-route-ownership.jl @@ -113,8 +113,9 @@ end @test plan.variable_names === (:payload,) seed[] = 8f0 before_actual = queries[] - declarations = @inferred PSE._model_output_destination_declarations( - only(applications), ObjectId(:scene), plan) + rows = @inferred PSE._resolve_model_output_destinations( + model, PSE._applications_by_id(applications), destinations) + declarations = only(rows).declarations @test queries[] == before_actual + 1 @test declarations.payload.value == Float32[8, 8] resolved = only(PSE._resolve_model_output_destinations(model, PSE._applications_by_id(applications), destinations)) From a747150a07807ad3a79997500ac335362d0c4b5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 09:10:07 +0100 Subject: [PATCH 177/324] Use registered scale candidates to admit status at organ birth --- src/composite_model/object_families.jl | 1 + .../prepared_status_manifest.jl | 45 ++++++++++--------- src/composite_model/selectors.jl | 9 ++-- test/test-fixed-status-manifest.jl | 19 ++++++++ ...st-fixed-status-prospective-distributed.jl | 20 +++++++++ 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 552414e97..acde4c3e0 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -65,6 +65,7 @@ ObjectFamilyStore() = ObjectFamilyStore{ObjectId}() Base.length(store::ObjectFamilyStore) = length(store.locations) Base.haskey(store::ObjectFamilyStore, id) = haskey(store.locations, id) +_prepared_status_context_ids(store::ObjectFamilyStore) = keys(store.locations) Base.getindex(store::ObjectFamilyStore, id) = store.locations[id].object function Base.get(store::ObjectFamilyStore, id, default) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 903cf06e6..71f8e2dbe 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -416,6 +416,15 @@ function _prepared_status_application_reference_allowed(manifest, model, object, return false end +# Registered producers and consumers already belong to the registry's scale +# index. A pending object's inherited labels and route still use the full matcher. +_prepared_status_context_ids(objects::AbstractDict) = keys(objects) +function _prepared_status_context_ids(model, application) + scale = application.target_matcher.scale + scale isa Symbol && return get(model.registry.by_scale, scale, ()) + return _prepared_status_context_ids(model.registry.objects) +end + # One exact application/permission pair enters the producer/route worker. Base.@constprop :none Base.@noinline function _prepared_status_destination_entry_allowed( application, permission, plan, model, object, parent_id, name, reference, @@ -423,11 +432,10 @@ Base.@constprop :none Base.@noinline function _prepared_status_destination_entry # Visit registered producer identities in place. No candidate vector or # synthetic producer is allocated by this admission path. has_producer = false - for (execution_id, producer) in model.registry.objects - producer_parent = producer.parent - producer_parent_id = isnothing(producer_parent) ? nothing : - _index_object_id(model.registry.objects, producer_parent) - _prepared_status_application_matches(model, producer, producer_parent_id, application) || continue + for candidate_id in _prepared_status_context_ids(model, application) + execution_id = _index_object_id(model.registry.objects, candidate_id) + _prepared_status_application_matches_id(model, model, + application.target_matcher, execution_id) || continue has_producer = true _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue @@ -483,11 +491,10 @@ function _prepared_status_source_route_admission(source, application, permission declared, allowed = false, true if source.source_var === name has_consumer = false - for (consumer_id, consumer) in model.registry.objects - consumer_parent = consumer.parent - consumer_parent_id = isnothing(consumer_parent) ? nothing : - _index_object_id(model.registry.objects, consumer_parent) - _prepared_status_application_matches(model, consumer, consumer_parent_id, application) || continue + for candidate_id in _prepared_status_context_ids(model, application) + consumer_id = _index_object_id(model.registry.objects, candidate_id) + _prepared_status_application_matches_id(model, model, + application.target_matcher, consumer_id) || continue has_consumer = true _prepared_status_route_matches(model, object, parent_id, application, source, consumer_id) || continue @@ -606,11 +613,10 @@ function _prepared_status_raw_has_context(contexts, plan, origin_id, variant) end function _prepared_status_raw_destination_count(application, plan, raw, model, object, parent_id) count = 0 - for (execution_id, producer) in model.registry.objects - producer_parent = producer.parent - producer_parent_id = isnothing(producer_parent) ? nothing : - _index_object_id(model.registry.objects, producer_parent) - _prepared_status_application_matches(model, producer, producer_parent_id, application) || continue + for candidate_id in _prepared_status_context_ids(model, application) + execution_id = _index_object_id(model.registry.objects, candidate_id) + _prepared_status_application_matches_id(model, model, + application.target_matcher, execution_id) || continue _prepared_status_route_matches(model, object, parent_id, application, plan, execution_id) || continue variant = _prepared_status_variant_slot(application, execution_id) @@ -635,11 +641,10 @@ end function _prepared_status_raw_source_count(source, application, raw, model, object, parent_id) count = 0 - for (consumer_id, consumer) in model.registry.objects - consumer_parent = consumer.parent - consumer_parent_id = isnothing(consumer_parent) ? nothing : - _index_object_id(model.registry.objects, consumer_parent) - _prepared_status_application_matches(model, consumer, consumer_parent_id, application) || continue + for candidate_id in _prepared_status_context_ids(model, application) + consumer_id = _index_object_id(model.registry.objects, candidate_id) + _prepared_status_application_matches_id(model, model, + application.target_matcher, consumer_id) || continue _prepared_status_route_matches(model, object, parent_id, application, source, consumer_id) || continue variant = _prepared_status_variant_slot(application, consumer_id) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index af55e178d..5f2e35d3e 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1707,9 +1707,12 @@ end function _prepared_status_application_matches(model, object, parent_id, application) id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) - _prepared_status_scope_is_current(model, topology, application.target_matcher.scope, nothing) || return false - return _selector_matches_object_id(topology, application.target_matcher, - id, nothing, false, nothing, false) + return _prepared_status_application_matches_id(model, topology, application.target_matcher, id) +end + +function _prepared_status_application_matches_id(model, topology, matcher, id) + _prepared_status_scope_is_current(model, topology, matcher.scope, nothing) || return false + return _selector_matches_object_id(topology, matcher, id, nothing, false, nothing, false) end function _prepared_status_route_matches(model, object, parent_id, application, diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index 0fe686ca7..9fb64a401 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -245,4 +245,23 @@ end @test (base.calls[], replacement.calls[]) == counts end + +@testset "pending consumers admit their own from-status source before registration" begin + model = CompositeModel(Object(:scene; scale=:Scene); applications=( + ModelSpec(Reader(); name=:reader, on=Many(scale=:Leaf), + inputs=(x=One(Self(); var=:seed, from_status=true),)),)) + supplied = Status(seed=3f0) + reference = PSE.refvalue(supplied, :seed) + wrong = Object(:wrong; scale=:Leaf, parent=:scene, status=Status(seed=3.0)) + @test_throws ArgumentError register_object!(model, wrong) + @test Set(keys(model.registry.objects)) == Set([ObjectId(:scene)]) + leaf = Object(:pending; scale=:Leaf, parent=:scene, status=supplied) + @test register_object!(model, leaf) === leaf + @test PSE.refvalue(model_status(model, leaf), :seed) === reference + @test Set(keys(model.registry.objects)) == Set([ObjectId(:scene), ObjectId(:pending)]) + run!(model; steps=1, outputs=:none) + @test PSE.refvalue(model_status(model, leaf), :x) === reference + @test model_status(model, leaf).x === 3f0 +end + end diff --git a/test/test-fixed-status-prospective-distributed.jl b/test/test-fixed-status-prospective-distributed.jl index bf010ad5f..464f611fc 100644 --- a/test/test-fixed-status-prospective-distributed.jl +++ b/test/test-fixed-status-prospective-distributed.jl @@ -39,4 +39,24 @@ end @test canonical.x === 7.0 @test reference[] === 7.0 end + +@testset "public metadata edits update registered producer scale candidates" begin + model = CompositeModel(Object(:plant; scale=:Plant), + Object(:producer; scale=:Dormant, parent=:plant); applications=( + ModelSpec(Source(7.0); name=:source, on=Many(scale=:Scene), + outputs_to=(OutputTo(Many(SceneScope(), scale=:Leaf)),)),)) + edited = PSE.GraphEditor.apply_model_graph_edit(model, + PSE.GraphEditor.SetModelObjectMetadata(:producer; scale=:Scene, name="Active producer")) + @test model_object(model, :producer).scale === :Dormant + @test model_object(edited, :producer).scale === :Scene + @test model_object(edited, :producer).name == "Active producer" + @test resolve_object_ids(edited, Many(scale=:Scene)) == [ObjectId(:producer)] + supplied = Status(x=4.0) + reference = PSE.refvalue(supplied, :x) + register_object!(edited, Object(:leaf; scale=:Leaf, parent=:plant, status=supplied)) + run!(edited; steps=1, outputs=:none) + @test PSE.refvalue(model_status(edited, :leaf), :x) === reference + @test reference[] === 7.0 +end + end From 340e3f4e41f483dc1dade7119c3e90ba91115538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 09:21:30 +0100 Subject: [PATCH 178/324] Refresh execution targets that still reference rebuilt status views --- src/composite_model/compilation.jl | 74 ++++++++++++------- .../test-model-status-view-cache-admission.jl | 49 ++++++++++++ 2 files changed, 97 insertions(+), 26 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 20ade90da..9447491e9 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1793,12 +1793,28 @@ mutable struct CompiledModelStatusView{S,C,T,P,BI} # One logical application/object execution identity, shared by all context # leases and by rebuilt views of the same live scientific state. const execution_stamp::Base.RefValue{UInt64} + # Scalar evidence belongs to this immutable projection, not to a later + # canonical header. Keep it before the parameterized component fields. + const canonical_identity::Base.RefValue{Nothing} + const reference_epoch::UInt const status::S const canonical_status::C const temporal_inputs::T const private_outputs::P const bound_inputs::BI + + function CompiledModelStatusView{S,C,T,P,BI}(execution_stamp, status, + canonical_status, temporal_inputs, private_outputs, bound_inputs, + ) where {S,C,T,P,BI} + return new{S,C,T,P,BI}(execution_stamp, _status_identity(canonical_status), + _status_reference_epoch(status), status, canonical_status, + temporal_inputs, private_outputs, bound_inputs) + end end +CompiledModelStatusView(execution_stamp, status::S, canonical_status::C, + temporal_inputs::T, private_outputs::P, bound_inputs::BI, +) where {S,C,T,P,BI} = CompiledModelStatusView{S,C,T,P,BI}(execution_stamp, + status, canonical_status, temporal_inputs, private_outputs, bound_inputs) # Per-application view families are metadata only. A host-owned tracing schema # may extend this narrow callback operation; no unknown schema falls back open. @@ -3954,20 +3970,36 @@ function _extend_temporal_many_inputs_in_place!(view::CompiledModelStatusView, return _apply_temporal_many_extensions!(staged) end -@inline function _status_view_epoch_is_current(view, model, object_id) +@inline function _status_view_epoch_is_current(canonical_identity::Base.RefValue{Nothing}, + reference_epoch::UInt, model, object_id, +) canonical = model_status(model, object_id) - return view.canonical_status === canonical && - _status_reference_epoch(view.status) == _status_reference_epoch(canonical) + return canonical isa Status && canonical_identity === _status_identity(canonical) && + reference_epoch == _status_reference_epoch(canonical) end +@inline _status_view_epoch_is_current(view::CompiledModelStatusView, model, object_id) = + _status_view_epoch_is_current(view.canonical_identity, view.reference_epoch, model, object_id) -# Keep the existing key across the view's dispatch boundary. Read its inline ID -# only after the callback owns the concrete view and key argument types. -Base.@noinline function _status_view_key_epoch_is_current(view, model, key) +@inline function _status_view_key_epoch_is_current(canonical_identity::Base.RefValue{Nothing}, + reference_epoch::UInt, model, key, +) objects = model.registry.objects object_id = _index_object_id(objects, getfield(key, 2)) haskey(objects, object_id) || return true # removed objects were skipped by this scan - return _status_view_epoch_is_current(view, model, object_id) + return _status_view_epoch_is_current(canonical_identity, reference_epoch, model, object_id) end +@inline _status_view_key_epoch_is_current(view::CompiledModelStatusView, model, key) = + _status_view_key_epoch_is_current(view.canonical_identity, view.reference_epoch, model, key) + +# Open preparation needs only these fixed scalar fields. Custom/closed schemas +# keep their existing admission callback, including rejection of stale foreign views. +@inline function _status_view_key_epoch_is_current(::Nothing, application_id, view, model, key) + current = view::CompiledModelStatusView + return _status_view_key_epoch_is_current(current.canonical_identity, current.reference_epoch, model, key) +end +@inline _status_view_key_epoch_is_current(schema, application_id, view, model, key) = + Base.@inline _with_model_status_view(_status_view_key_epoch_is_current, + schema, application_id, view, model, key) # Keep the real application inside its finite metadata branch. Transient # views are read only after admission, never captured by a metadata callback. @@ -4006,7 +4038,7 @@ function _refresh_model_status_view_for_target!( return nothing end -function _extend_model_status_views( +function _extend_model_status_views!( model::CompositeModel, compiled::CompiledCompositeModel, applications, @@ -4043,8 +4075,8 @@ function _extend_model_status_views( for (key, previous_view) in views application_id = getfield(key, 1) - current = Base.@inline _with_model_status_view(_status_view_key_epoch_is_current, - compiled.status_view_schema, application_id, previous_view, model, key::Key) + current = _status_view_key_epoch_is_current(compiled.status_view_schema, + application_id, previous_view, model, key::Key) current || push!(affected_keys, key) end @@ -4076,7 +4108,7 @@ function _extend_model_status_views( distributed_outputs, previous_temporal_sources, ) end - return views + return affected_keys end function _append_added_many_call_targets!( @@ -5083,7 +5115,7 @@ function _extend_compiled_scene( application_children = compiled.scenario_plan.application_children application_order = compiled.scenario_plan.application_order started_at = _runtime_performance_start(performance) - status_views_by_target = _extend_model_status_views( + rebuilt_views = _extend_model_status_views!( model, compiled, applications, @@ -5097,6 +5129,7 @@ function _extend_compiled_scene( distributed_outputs, previous_views, ) + status_views_by_target = compiled.status_views_by_target _runtime_performance_finish!( performance, :status_view_refresh, @@ -5105,25 +5138,14 @@ function _extend_compiled_scene( # Keep the published owner's storage type, while admitting each incoming # identity before constructing the key consumed by its Set operations. changed_execution_target_ids = Set{Tuple{Symbol,ObjectId}}() - for (application_id, object_ids) in new_targets - for raw_id in object_ids - object_id = _index_object_id(model.registry.objects, raw_id) - push!(changed_execution_target_ids, (application_id, object_id)) - end - end - for incoming in (affected_temporal_keys, changed_target_ids_seed, changed_call_target_keys) + # A reference can be replaced on an existing organ during growth. An + # execution target must use the same view that was just rebuilt for it. + for incoming in (rebuilt_views, affected_temporal_keys, changed_target_ids_seed, changed_call_target_keys) for (application_id, raw_id) in incoming object_id = _index_object_id(model.registry.objects, raw_id) push!(changed_execution_target_ids, (application_id, object_id)) end end - for raw_id in rewired_consumer_ids - let object_id = _index_object_id(model.registry.objects, raw_id) - _foreach_object_application(compiled, object_id) do application - push!(changed_execution_target_ids, (application.id, object_id)) - end - end - end Key = Tuple{Symbol,keytype(model.registry.objects)} changed_manual_target_ids = Set{Key}() for (application_id, raw_id) in changed_execution_target_ids diff --git a/test/test-model-status-view-cache-admission.jl b/test/test-model-status-view-cache-admission.jl index 62828b9f9..34f5d36df 100644 --- a/test/test-model-status-view-cache-admission.jl +++ b/test/test-model-status-view-cache-admission.jl @@ -254,4 +254,53 @@ end @test reason(data) === nothing end + +@testset "scalar view evidence preserves reference edits, replacements and family admission" begin + data = fixture() + original = view_cache(data)[VIEW_KEY] + canonical = model_status(data.model, :consumer) + @test PSE._status_view_key_epoch_is_current(nothing, :consumer, original, data.model, VIEW_KEY) + canonical.value = 7.0 + @test PSE._status_view_key_epoch_is_current(nothing, :consumer, original, data.model, VIEW_KEY) + replacement = Ref(7.0) + PSE._set_status_reference!(canonical, :value, replacement) + @test !PSE._status_view_key_epoch_is_current(nothing, :consumer, original, data.model, VIEW_KEY) + register_object!(data.model, Object(:unmatched_axis; scale=:Axis, parent=:scene)) + step!(data.simulation) + current = view_cache(data)[VIEW_KEY] + @test current !== original + @test PSE.refvalue(current.status, :value) === replacement + @test model_status(data.model, :consumer).value == 9.0 + @test PSE._status_view_key_epoch_is_current(nothing, :consumer, current, data.model, VIEW_KEY) + canonical = model_status(data.model, :consumer) + PSE._drop_status_reference!(canonical, :value) + @test !PSE._status_view_key_epoch_is_current(nothing, :consumer, current, data.model, VIEW_KEY) + PSE._set_status_reference!(canonical, :value, replacement) + @test !PSE._status_view_key_epoch_is_current(nothing, :consumer, current, data.model, VIEW_KEY) + + data = fixture() + original = view_cache(data)[VIEW_KEY] + canonical = model_status(data.model, :consumer) + fresh = PSE._new_prepared_status(typeof(canonical), Status(( + signal=PSE.refvalue(canonical, :signal), value=PSE.refvalue(canonical, :value), + visits=PSE.refvalue(canonical, :visits)))) + PSE._replace_model_object_status!(data.model, ObjectId(:consumer), fresh) + @test !PSE._status_view_key_epoch_is_current(nothing, :consumer, original, data.model, VIEW_KEY) + @test all(PSE.refvalue(fresh, name) === PSE.refvalue(canonical, name) for name in keys(canonical)) + PSE._replace_model_object_status!(data.model, ObjectId(:consumer), nothing) + @test !PSE._status_view_key_epoch_is_current(nothing, :consumer, original, data.model, VIEW_KEY) + + # Matching scalar evidence must not bypass a closed family's type check. + data = fixture() + original = view_cache(data)[VIEW_KEY] + schema = PSE.CompiledMetadataTable((consumer=typeof(original)[],)) + incompatible = shell(original; bound_inputs=(foreign=0,)) + view_cache(data)[VIEW_KEY] = incompatible + @test_throws "outside its prepared application family" PSE._status_view_key_epoch_is_current( + schema, :consumer, incompatible, data.model, VIEW_KEY) + PSE._set_status_reference!(model_status(data.model, :consumer), :value, Ref(0.0)) + @test_throws "outside its prepared application family" PSE._status_view_key_epoch_is_current( + schema, :consumer, incompatible, data.model, VIEW_KEY) +end + end # module StatusViewCacheAdmissionChecks47 From 636b22af95bc6a4b875f029fa8e96fdfa4f2af68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 09:38:49 +0100 Subject: [PATCH 179/324] Prepare status admission routes by organ family and use local subtree ancestors --- .../prepared_status_manifest.jl | 156 ++++++++++++------ ...st-fixed-status-prospective-distributed.jl | 23 +++ 2 files changed, 128 insertions(+), 51 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 71f8e2dbe..00052b25d 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -1,11 +1,23 @@ # One constructor-owned manifest. This stores names, exact reference classes, # configured selector owners and raw-family correlations, never default values. -mutable struct PreparedStatusManifest{S,A,P,D,R} +# These lists refer to the authored owners and their existing permissions. +# Cardinalities are data: adding organs never specializes the execution model. +struct PreparedBirthRecipe{S,A,F,D,R} + status_type::Type{S} + applications::A + sources::F + destinations::D + raw_families::R +end + +mutable struct PreparedStatusManifest{S,A,P,D,R,B} const status_type::Type{S} const authored::A const permissions::P const destinations::D const raw_families::R + const birth_recipes::Dict{Union{Nothing,Symbol},B} + const all_routes::B end # RAW membership, labels and reference classes are constructor evidence DATA. @@ -208,6 +220,34 @@ function _prepared_status_destinations(plans) for plan in plans] end +function _prepared_birth_recipes(S, applications, permissions, destinations, raw, model) + owners = collect(zip(applications, permissions)) + by_slot = Dict(first(owner).slot => owner for owner in owners) + Source = eltype(fieldtype(eltype(permissions), :sources)) + sources = Tuple{eltype(applications),eltype(permissions),Source}[ + (app, permission, source) for (app, permission) in owners for source in permission.sources] + routes = Tuple{eltype(applications),eltype(permissions),eltype(destinations)}[ + (by_slot[plan.application_slot]..., plan) for plan in destinations] + all_routes = PreparedBirthRecipe(S, owners, sources, routes, raw) + scales = Set{Union{Symbol,Nothing}}(keys(model.registry.by_scale)) + push!(scales, nothing) + for matcher in Iterators.flatten(((app.target_matcher for app in applications), + (source.matcher for (_, _, source) in sources), (plan.matcher for plan in destinations))) + requested = matcher.scale + requested isa Tuple ? union!(scales, requested) : push!(scales, requested) + end + recipes = Dict{Union{Nothing,Symbol},typeof(all_routes)}() + for scale in scales + matches(matcher) = _object_matches_selector_value(scale, matcher.scale) + recipes[scale] = PreparedBirthRecipe(S, + filter(owner -> matches(first(owner).target_matcher), owners), + filter(row -> matches(last(row).matcher), sources), + filter(row -> matches(last(row).matcher), routes), + filter(family -> first(family.labels) === scale, raw)) + end + return recipes, all_routes +end + function _prepared_status_raw_signature(model, object, applications, permissions, destinations) I = keytype(model.registry.objects) selected = Tuple{Int,Int}[(application.slot, _prepared_status_variant_slot(application, object.id)) @@ -369,7 +409,8 @@ function _prepare_status_manifest(model, authored, program, raw_basis) # no biological Ref is created for that slot. physical_refs = map(R -> R === Union{} ? Nothing : R, refs) S = _fixed_status_type(Tuple(names), Tuple{physical_refs...}) - return PreparedStatusManifest(S, applications, permissions, destinations, raw) + recipes_by_scale, all_routes = _prepared_birth_recipes(S, applications, permissions, destinations, raw, model) + return PreparedStatusManifest(S, applications, permissions, destinations, raw, recipes_by_scale, all_routes) end # The catalog references the SAME prepared manifest; runtime never finds a @@ -406,8 +447,8 @@ _prepared_status_variant_reference_allowed(variant, name, reference) = _prepared_status_output_reference_allowed(variant, name, reference) = _prepared_status_reference_allowed(variant.outputs, name, reference) -function _prepared_status_application_reference_allowed(manifest, model, object, parent_id, name, reference) - for (application, permission) in zip(manifest.authored, manifest.permissions) +function _prepared_status_application_reference_allowed(recipe, model, object, parent_id, name, reference) + for (application, permission) in recipe.applications _prepared_status_application_matches(model, object, parent_id, application) || continue variant = _prepared_status_variant_slot(application, object.id) _prepared_status_variant_reference_allowed(permission.variants[variant], name, reference) && return true @@ -419,7 +460,25 @@ end # Registered producers and consumers already belong to the registry's scale # index. A pending object's inherited labels and route still use the full matcher. _prepared_status_context_ids(objects::AbstractDict) = keys(objects) -function _prepared_status_context_ids(model, application) +function _prepared_status_context_ids(model, application, route, object, parent_id) + registry = model.registry + scope = route.matcher.scope + # A subtree source can only be read or written by an ancestor. For an + # object awaiting registration the parent's path is already indexed. + if scope isa Subtree || scope isa Self + id = _index_object_id(registry.objects, object.id) + existing = get(registry.objects, id, nothing) + registered = !isnothing(existing) + if scope isa Self + return registered ? (id,) : () + end + anchor = registered ? id : parent_id + isnothing(anchor) && return () + if !registered || (existing === object && isequal(object.parent, parent_id)) + path = get(registry.ancestor_ids_by_object, anchor, nothing) + isnothing(path) || return path + end + end scale = application.target_matcher.scale scale isa Symbol && return get(model.registry.by_scale, scale, ()) return _prepared_status_context_ids(model.registry.objects) @@ -432,7 +491,7 @@ Base.@constprop :none Base.@noinline function _prepared_status_destination_entry # Visit registered producer identities in place. No candidate vector or # synthetic producer is allocated by this admission path. has_producer = false - for candidate_id in _prepared_status_context_ids(model, application) + for candidate_id in _prepared_status_context_ids(model, application, plan, object, parent_id) execution_id = _index_object_id(model.registry.objects, candidate_id) _prepared_status_application_matches_id(model, model, application.target_matcher, execution_id) || continue @@ -459,15 +518,11 @@ Base.@constprop :none Base.@noinline function _prepared_status_destination_entry return false end -function _prepared_status_destinations_allow(plans, manifest, model, object, parent_id, name, reference) - for plan in plans +function _prepared_status_destinations_allow(recipe, model, object, parent_id, name, reference) + for (application, permission, plan) in recipe.destinations name in plan.variable_names || continue - for (application, permission) in zip(manifest.authored, manifest.permissions) - application.slot == plan.application_slot || continue - _prepared_status_destination_entry_allowed(application, permission, plan, model, object, - parent_id, name, reference) && return true - break - end + _prepared_status_destination_entry_allowed(application, permission, plan, model, object, + parent_id, name, reference) && return true end return false end @@ -491,7 +546,7 @@ function _prepared_status_source_route_admission(source, application, permission declared, allowed = false, true if source.source_var === name has_consumer = false - for candidate_id in _prepared_status_context_ids(model, application) + for candidate_id in _prepared_status_context_ids(model, application, source, object, parent_id) consumer_id = _index_object_id(model.registry.objects, candidate_id) _prepared_status_application_matches_id(model, model, application.target_matcher, consumer_id) || continue @@ -536,9 +591,9 @@ function _prepared_status_source_route_admission(source, application, permission return (declared, allowed, true) end -function _prepared_status_sources_admission(manifest, model, object, parent_id, name, reference) +function _prepared_status_sources_admission(recipe, model, object, parent_id, name, reference) declared, allowed = false, true - for (application, permission) in zip(manifest.authored, manifest.permissions), source in permission.sources + for (application, permission, source) in recipe.sources has_type, matches, compatible = _prepared_status_source_route_admission(source, application, permission, model, object, parent_id, name, reference) compatible || return (false, false, false) @@ -552,14 +607,14 @@ end # permission worker's function boundary. The worker shares its typed body across # field names; no caller needs to inline an application scan for every slot. @generated function _prepared_status_configured_reference_admission( - manifest::PreparedStatusManifest{S}, model, object, parent_id, name, reference, + recipe::PreparedBirthRecipe{S}, model, object, parent_id, name, reference, ) where {S} references = unique(R for slot in fieldtypes(_status_schema_references(S)) for R in Base.uniontypes(slot) if R <: Ref) branches = [quote if reference isa $R return _prepared_status_reference_admission( - manifest, model, object, parent_id, name, reference::$R) + recipe, model, object, parent_id, name, reference::$R) end end for R in references] return quote @@ -570,16 +625,16 @@ end end Base.@constprop :none Base.@noinline function _prepared_status_reference_admission( - manifest, model, object, parent_id, name, reference::R, + recipe, model, object, parent_id, name, reference::R, ) where {R<:Ref} declared, source_allowed, compatible = _prepared_status_sources_admission( - manifest, model, object, parent_id, + recipe, model, object, parent_id, name, reference::R) compatible || return (false, false) allowed = (declared && source_allowed) || - _prepared_status_application_reference_allowed(manifest, + _prepared_status_application_reference_allowed(recipe, model, object, parent_id, name, reference::R) || - _prepared_status_destinations_allow(manifest.destinations, manifest, + _prepared_status_destinations_allow(recipe, model, object, parent_id, name, reference::R) return (allowed, true) end @@ -590,8 +645,8 @@ function _prepared_status_raw_variant(raw, slot) end return 0 end -function _prepared_status_raw_membership_matches(applications, raw, model, object, parent_id) - for application in applications +function _prepared_status_raw_membership_matches(recipe, raw, model, object, parent_id) + for (application, _) in recipe.applications expected = _prepared_status_raw_variant(raw, application.slot) matches = _prepared_status_application_matches(model, object, parent_id, application) if matches @@ -613,7 +668,7 @@ function _prepared_status_raw_has_context(contexts, plan, origin_id, variant) end function _prepared_status_raw_destination_count(application, plan, raw, model, object, parent_id) count = 0 - for candidate_id in _prepared_status_context_ids(model, application) + for candidate_id in _prepared_status_context_ids(model, application, plan, object, parent_id) execution_id = _index_object_id(model.registry.objects, candidate_id) _prepared_status_application_matches_id(model, model, application.target_matcher, execution_id) || continue @@ -625,23 +680,19 @@ function _prepared_status_raw_destination_count(application, plan, raw, model, o end return count end -function _prepared_status_raw_destination_total(plans, manifest, raw, model, object, parent_id) +function _prepared_status_raw_destination_total(recipe, raw, model, object, parent_id) total = 0 - for plan in plans - for application in manifest.authored - application.slot == plan.application_slot || continue - count = _prepared_status_raw_destination_count(application, plan, raw, model, object, parent_id) - count < 0 && return -1 - total += count - break - end + for (application, _, plan) in recipe.destinations + count = _prepared_status_raw_destination_count(application, plan, raw, model, object, parent_id) + count < 0 && return -1 + total += count end return total end function _prepared_status_raw_source_count(source, application, raw, model, object, parent_id) count = 0 - for candidate_id in _prepared_status_context_ids(model, application) + for candidate_id in _prepared_status_context_ids(model, application, source, object, parent_id) consumer_id = _index_object_id(model.registry.objects, candidate_id) _prepared_status_application_matches_id(model, model, application.target_matcher, consumer_id) || continue @@ -662,9 +713,9 @@ function _prepared_status_raw_source_count(source, application, raw, model, obje return count end -function _prepared_status_raw_source_total(manifest, raw, model, object, parent_id) +function _prepared_status_raw_source_total(recipe, raw, model, object, parent_id) total = 0 - for (application, permission) in zip(manifest.authored, manifest.permissions), source in permission.sources + for (application, permission, source) in recipe.sources count = _prepared_status_raw_source_count(source, application, raw, model, object, parent_id) count < 0 && return -1 total += count @@ -672,13 +723,13 @@ function _prepared_status_raw_source_total(manifest, raw, model, object, parent_ return total end -function _prepared_status_raw_matches(raw, manifest, model, object, parent_id) +function _prepared_status_raw_matches(raw, recipe, model, object, parent_id) labels = _prepared_status_object_labels(model, object, parent_id) raw.labels === (labels.scale, labels.kind, labels.species) || return false - _prepared_status_raw_membership_matches(manifest.authored, raw, model, object, parent_id) || return false - _prepared_status_raw_destination_total(manifest.destinations, manifest, + _prepared_status_raw_membership_matches(recipe, raw, model, object, parent_id) || return false + _prepared_status_raw_destination_total(recipe, raw, model, object, parent_id) == length(raw.destinations) || return false - return _prepared_status_raw_source_total(manifest, + return _prepared_status_raw_source_total(recipe, raw, model, object, parent_id) == length(raw.sources) end _prepared_status_raw_reference_allowed(::Nothing, name, reference) = false @@ -691,14 +742,14 @@ end # Visit the prepared namespace in order without building a per-field method body. # The existing finite classifier admits each exact Ref before the shared worker. -function _prepared_status_source_allowed(manifest::PreparedStatusManifest{S}, +function _prepared_status_source_allowed(recipe::PreparedBirthRecipe{S}, model, object, parent_id, source::Status, raw) where {S} present = 0 for name in _status_schema_names(S) reference = _initial_status_reference(source, name) if reference !== nothing present += 1 - allowed, compatible = _prepared_status_configured_reference_admission(manifest, model, + allowed, compatible = _prepared_status_configured_reference_admission(recipe, model, object, parent_id, name, reference) compatible && (allowed || _prepared_status_raw_reference_allowed(raw, name, reference)) || return false @@ -707,17 +758,20 @@ function _prepared_status_source_allowed(manifest::PreparedStatusManifest{S}, return present == _initial_status_reference_count(source) end -# Initial bootstrap supplies the SAME manifest explicitly before the catalog +_object_birth_recipe(manifest, object) = get(manifest.birth_recipes, object.scale, manifest.all_routes) + +# Initial bootstrap supplies the same manifest explicitly before the catalog # exists. Runtime delegates through its typed catalog; there is one gather/body. @inline function _validate_prepared_initial_status(manifest::PreparedStatusManifest, model, object, source_status, parent_id) isnothing(source_status) && return nothing source_status isa Status || throw(ArgumentError("Prepared initial data must be Status or nothing.")) - allowed = Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source_status, nothing) + recipe = _object_birth_recipe(manifest, object) + allowed = Base.@inline _prepared_status_source_allowed(recipe, model, object, parent_id, source_status, nothing) allowed && return nothing - for raw in manifest.raw_families - _prepared_status_raw_matches(raw, manifest, model, object, parent_id) || continue - Base.@inline _prepared_status_source_allowed(manifest, model, object, parent_id, source_status, raw) && return nothing + for raw in recipe.raw_families + _prepared_status_raw_matches(raw, recipe, model, object, parent_id) || continue + Base.@inline _prepared_status_source_allowed(recipe, model, object, parent_id, source_status, raw) && return nothing end throw(ArgumentError("Status reference classes are incompatible with this prepared object configuration/raw family.")) end @@ -743,14 +797,14 @@ function _validate_prepared_status_recipe(model, object_id, recipe) get(model.status_source_owners, source_identity, nothing) == object_id) || throw(ArgumentError("Prepared status source ownership changed.")) end - manifest = _prepared_status_manifest(model) + birth_recipe = _object_birth_recipe(_prepared_status_manifest(model), object) raw_parent = object.parent parent_id = isnothing(raw_parent) ? nothing : _index_object_id(store, raw_parent) # A reparent/Scope change never revokes cells already owned by this object. # Only NEW edits need active permissions; old aliases grant no new rights. for (name, reference) in zip(recipe.edit_names, recipe.edit_references) _initial_status_reference(original, name) === reference && continue - allowed, compatible = _prepared_status_configured_reference_admission(manifest, + allowed, compatible = _prepared_status_configured_reference_admission(birth_recipe, model, object, parent_id, name, reference) allowed && compatible || throw(ArgumentError( "A staged status reference is incompatible with the prepared object configuration.")) diff --git a/test/test-fixed-status-prospective-distributed.jl b/test/test-fixed-status-prospective-distributed.jl index 464f611fc..83eafceea 100644 --- a/test/test-fixed-status-prospective-distributed.jl +++ b/test/test-fixed-status-prospective-distributed.jl @@ -59,4 +59,27 @@ end @test reference[] === 7.0 end +@testset "a leaf birth reuses its family recipe and visits only ancestors for a subtree route" begin + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:north; scale=:Plant, parent=:scene), Object(:south; scale=:Plant, parent=:scene); + applications=(ModelSpec(Source(7.0); name=:delivery, on=Many(scale=:Plant), + outputs_to=(OutputTo(Many(within=Subtree(), scale=:Leaf)),)),)) + manifest = PSE._prepared_status_manifest(model) + leaf = Object(:new_leaf; scale=:Leaf, parent=:north, status=Status(x=2.0)) + sibling = Object(:second_leaf; scale=:Leaf, parent=:south, status=Status(x=3.0)) + recipe = PSE._object_birth_recipe(manifest, leaf) + @test recipe === PSE._object_birth_recipe(manifest, sibling) + @test isempty(recipe.applications) + owner, _, route = only(recipe.destinations) + @test owner.id === :delivery + @test route === only(manifest.destinations) + @test Set(PSE._prepared_status_context_ids(model, owner, route, leaf, leaf.parent)) == + Set(ObjectId.((:scene, :north))) + register_object!(model, leaf) + register_object!(model, sibling) + sim = run!(model; steps=1, outputs=:all) + @test outputs(sim)[(:delivery, leaf.id, :x)] == [(1.0, 7.0)] + @test outputs(sim)[(:delivery, sibling.id, :x)] == [(1.0, 7.0)] +end + end From 2c045e4499718e46537f50fb72854b0b5e460de2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 10:18:33 +0100 Subject: [PATCH 180/324] Keep distributed destination columns typed through organ growth --- src/composite_model/compilation.jl | 89 +++++++++++++++---- test/test-model-distributed-output-runtime.jl | 24 +++++ 2 files changed, 98 insertions(+), 15 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 9447491e9..cd90331b4 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -7054,18 +7054,27 @@ function _output_column_carrier_type(::Type{RT}) where {RT<:Tuple} return Union{carriers...} end +# Use the same physical column layout for the binding and for the collection +# that owns it. Empty target sets can acquire their first members during growth. +function _model_output_column_schema(S, names) + fields, references = _status_schema_names(S), _status_schema_references(S) + families = map(names) do name + field = findfirst(isequal(name), fields) + Tuple{Base.uniontypes(fieldtype(references, field))...} + end + C = NamedTuple{names,Tuple{map(_output_column_carrier_type, families)...}} + return families, C +end + _model_output_destination_columns(model::CompositeModel, plan, destination_ids) = _with_prepared_canonical_status_type(_model_output_destination_columns, model, model, plan, destination_ids) @generated function _model_output_destination_columns(::Type{S}, model, ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, destination_ids, ) where {S<:Status,GROUP,NAMES} - names, references = _status_schema_names(S), _status_schema_references(S) - families = Tuple(Tuple{Base.uniontypes(fieldtype(references, - findfirst(isequal(name), names)))...} for name in NAMES) + families, C = _model_output_column_schema(S, NAMES) all(R -> all(T -> T <: Ref && isconcretetype(T), fieldtypes(R)), families) || return :(throw(ArgumentError("An output column requires exact prepared reference classes."))) - C = NamedTuple{NAMES,Tuple{map(_output_column_carrier_type, families)...}} columns = Expr(:tuple, [:( _model_output_destination_column(model, destination_ids, Val{$(QuoteNode(name))}(), $(families[index])) @@ -7146,14 +7155,33 @@ function _compile_model_output_application_bindings!( ) end +@generated function _model_output_binding_storage(::Type{S}, ::Type{I}, + plans::CompiledDistributedOutputPlans{P,G}, +) where {S<:Status,I<:ObjectId,P,G} + bindings = Union{} + groups = Union{} + for routes in fieldtypes(G) + isempty(fieldtypes(routes)) && continue + row_types = map(fieldtypes(routes)) do route + _, columns = _model_output_column_schema(S, route.parameters[2]) + CompiledModelOutputDestinationBinding{route,columns,Dict{I,Int},I} + end + names = Tuple(route.parameters[1] for route in fieldtypes(routes)) + bindings = Union{bindings,row_types...} + groups = Union{groups,NamedTuple{names,Tuple{row_types...}}} + end + return :(Vector{$bindings}(), Dict{Tuple{Symbol,$I},$groups}()) +end + function _compile_model_output_destination_bindings( model::CompositeModel, resolved_destinations, plans::CompiledDistributedOutputPlans, ) - bindings = Any[] - sizehint!(bindings, length(resolved_destinations)) I = keytype(model.registry.objects) + bindings, by_execution_target = _with_prepared_canonical_status_type( + _model_output_binding_storage, model, I, plans) + sizehint!(bindings, length(resolved_destinations)) resolved_by_plan = Dict{Int,Vector{Tuple{I,Vector{I}}}}() for resolved in resolved_destinations plan = getfield(resolved, :plan)::CompiledModelOutputDestinationPlan @@ -7164,15 +7192,12 @@ function _compile_model_output_destination_bindings( push!(get!(valtype(resolved_by_plan), resolved_by_plan, getfield(plan, :slot)), (execution_object_id, destination_ids)) end - by_execution_target = Dict{Tuple{Symbol,ObjectId},Any}() for application_id in keys(plans.by_application) _with_metadata_entry( _compile_model_output_application_bindings!, plans.by_application, application_id, model, resolved_by_plan, bindings, by_execution_target, ) end - # Keep the same lifecycle cache shell; its values are built from the finite - # authored groups instead of recovering their schema from erased bindings. return bindings, by_execution_target end @@ -7350,6 +7375,39 @@ function _resolve_incremental_model_output_addition!( return true end +# Bindings and their new columns share the route's prepared column layout. +@generated function _model_output_column_additions(::Vector{B}) where {B} + records = Union{} + for binding in Base.uniontypes(B) + C = fieldtype(binding, :columns) + IDs = fieldtype(binding, :destination_ids) + records = Union{records,NamedTuple{(:binding, :destination_ids, :columns),Tuple{binding,IDs,C}}} + end + return :(Vector{$records}()) +end + +# The binding and its columns are one correlated alternative from the existing +# staging vector. Admit them together before constructing that exact record. +@generated function _append_model_output_column_addition!( + additions::Vector{A}, binding, destination_ids, columns, +) where {A} + branches = Expr[] + for record in Base.uniontypes(A) + B, IDs, C = fieldtype(record, :binding), fieldtype(record, :destination_ids), + fieldtype(record, :columns) + push!(branches, quote + if binding isa $B && destination_ids isa $IDs && columns isa $C + push!(additions, $record((binding::$B, destination_ids::$IDs, columns::$C))) + return nothing + end + end) + end + return quote + $(branches...) + throw(ArgumentError("Distributed addition fields do not match their prepared binding.")) + end +end + function _incremental_distributed_output_addition!( model::CompositeModel, previous::CompiledDistributedOutputs, @@ -7389,7 +7447,7 @@ function _incremental_distributed_output_addition!( _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) _prepare_model_output_destination_statuses!(model, resolved_additions) - column_additions = Any[] + column_additions = _model_output_column_additions(previous.bindings) for resolved in resolved_additions key = (resolved.plan.application_id, resolved.execution_object_id) groups = previous.by_execution_target[key] @@ -7404,7 +7462,8 @@ function _incremental_distributed_output_addition!( all(reference -> reference isa eltype(existing_references), added_references) || return nothing end - push!(column_additions, (binding=binding, resolved=resolved, columns=columns)) + _append_model_output_column_addition!(column_additions, binding, + resolved.destination_ids, columns) end for (key, owners) in staged_ownership @@ -7412,7 +7471,7 @@ function _incremental_distributed_output_addition!( end for addition in column_additions binding = addition.binding - resolved = addition.resolved + destination_ids = addition.destination_ids for variable_ in binding.plan.variable_names variable = Symbol(variable_) append!( @@ -7423,11 +7482,11 @@ function _incremental_distributed_output_addition!( (binding.application_id, variable) ] indexed_ids === binding.destination_ids || - _insert_sorted_object_ids!(indexed_ids, resolved.destination_ids) + _insert_sorted_object_ids!(indexed_ids, destination_ids) end first_position = length(binding.destination_ids) + 1 - append!(binding.destination_ids, resolved.destination_ids) - for (offset, object_id) in enumerate(resolved.destination_ids) + append!(binding.destination_ids, destination_ids) + for (offset, object_id) in enumerate(destination_ids) binding.destination_index[object_id] = first_position + offset - 1 end binding.membership_generation = UInt64(model.revision) diff --git a/test/test-model-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index bec93d319..9ac59ea58 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1435,3 +1435,27 @@ include("fixtures/distributed_growth.jl") @test only(sample for sample in lag_stream if first(sample) == 3.0) == (3.0, 14f0) end end + + +@testset "existing distributed producers acquire a new destination together" begin + model = DistributedGrowthFixture.make_model() + simulation = run!(model; steps=2, outputs=:all) + retained = outputs(simulation)[(:distributed, ObjectId(:leaf_a), :delivered)] + supplied = Status(x=20f0, tick=0, delivered=-7f0, prospective=-11f0) + delivered = PlantSimEngine.refvalue(supplied, :delivered) + prospective = PlantSimEngine.refvalue(supplied, :prospective) + # Both producers already exist; only a monotonic new destination is added. + register_object!(model, Object(:leaf_c; scale=:Leaf, parent=:root, status=supplied)) + step!(simulation) + @test outputs(simulation)[(:distributed, ObjectId(:leaf_a), :delivered)] === retained + @test retained == [(1.0, 10f0), (2.0, 20f0), (3.0, 30f0)] + @test PlantSimEngine.refvalue(model_status(model, :leaf_c), :delivered) === delivered + @test PlantSimEngine.refvalue(model_status(model, :leaf_c), :prospective) === prospective + @test delivered[] === 30f0 + @test prospective[] === 60f0 + @test final_state(simulation, :leaf_c).x === 21f0 + # PreviousTimeStep reads A=3, B=11 published at2, and C's initial20. + @test final_state(simulation, :root).lagtotal === 34f0 + @test outputs(simulation)[(:distributed, ObjectId(:leaf_c), :delivered)] == [(3.0, 30f0)] + @test outputs(simulation)[(:prospective_distributor, ObjectId(:leaf_c), :prospective)] == [(3.0, 60f0)] +end From 958014490f5f9b27430cc910fa69e0690b9bc02d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 11:02:22 +0100 Subject: [PATCH 181/324] Validate required fields through the registered status family --- src/composite_model/compilation.jl | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index cd90331b4..03a6a0a78 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6928,8 +6928,9 @@ function _validate_required_model_output_destinations!( for (variable_, declaration) in pairs(resolved.declarations) declaration isa Required || continue variable = Symbol(variable_) - if _status_has_variable(model, destination_id, variable) - value = _model_object(model, destination_id).status[variable] + status = model_status(model, destination_id) + if status isa Status && hasproperty(status, variable) + value = status[variable] expected_type = _input_expected_type(declaration) value isa expected_type || throw(ArgumentError( "Distributed output `$(variable)` on application " * @@ -9386,12 +9387,6 @@ function _bound_model_inputs(input_bindings) return bound end -function _status_has_variable(model::CompositeModel, object_id::ObjectId, variable::Symbol) - object = _model_object(model, object_id) - object.status isa Status || return false - return hasproperty(object.status, variable) -end - function _validate_model_required_inputs!(model::CompositeModel, applications, applications_by_id, input_bindings) bound = _bound_model_inputs(input_bindings) I = keytype(model.registry.objects) @@ -9404,7 +9399,8 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a declaration isa Required || continue input = Symbol(input_) (application.id, object_id, input) in bound && continue - _status_has_variable(model, object_id, input) && continue + status = model_status(model, object_id) + status isa Status && hasproperty(status, input) && continue push!( missing, ( From 07ede0d8ce2844de26ec051d2e1a62f0efe06843 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 11:02:56 +0100 Subject: [PATCH 182/324] Test a newborn producer delivering to thirty existing leaves --- test/fixtures/distributed_growth.jl | 36 ++++++++++++++++- test/test-model-distributed-output-runtime.jl | 40 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/test/fixtures/distributed_growth.jl b/test/fixtures/distributed_growth.jl index 020921740..717d8c731 100644 --- a/test/fixtures/distributed_growth.jl +++ b/test/fixtures/distributed_growth.jl @@ -53,12 +53,17 @@ function PSE.run!(model::Distributor{VARIABLE}, status, environment, constants, return nothing end -function make_model(; reader_every=PSE.Dates.Hour(1), distributor_every=PSE.Dates.Hour(1)) +function hourly_weather() weather = PSE.PlantMeteo.Weather([ PSE.PlantMeteo.Atmosphere(date=PSE.Dates.DateTime(2025, 1, 1) + PSE.Dates.Hour(index - 1), T=temperature, Wind=1.0, Rh=0.5, duration=PSE.Dates.Hour(1)) for (index, temperature) in enumerate((10.0, 20.0, 30.0, 40.0)) ]) + return weather +end + +function make_model(; reader_every=PSE.Dates.Hour(1), distributor_every=PSE.Dates.Hour(1)) + weather = hourly_weather() root = PSE.Object(:root; scale=:Scene, status=PSE.Status(visits=0, seen=0.0, dose=0.0, tick=0, lag=Float32[], lagtotal=0f0)) leaf = PSE.Object(:leaf_a; scale=:Leaf, parent=:root, status=leaf_status(1f0)) @@ -83,4 +88,33 @@ function make_model(; reader_every=PSE.Dates.Hour(1), distributor_every=PSE.Date return model end +# A producer is born while every one of its thirty destinations already exists. +PSE.@process "distributed_producer_birth" verbose=false +struct ProducerBirth <: AbstractDistributed_Producer_BirthModel end +PSE.inputs_(::ProducerBirth) = NamedTuple() +PSE.outputs_(::ProducerBirth) = (visits=0,) +function PSE.run!(::ProducerBirth, status, environment, constants, context) + status.visits += 1 + if status.visits == 2 + PSE.register_object!(PSE.runtime_model(context), PSE.Object(:emitter; + scale=:Emitter, parent=:root, status=PSE.Status(tick=0))) + end + return nothing +end + +producer_birth_leaf_ids() = [PSE.ObjectId(Symbol(:leaf_, index)) for index in 1:30] +function make_producer_birth_model() + objects = PSE.Object[PSE.Object(:root; scale=:Scene, status=PSE.Status(visits=0))] + for (index, id) in enumerate(producer_birth_leaf_ids()) + push!(objects, PSE.Object(id; scale=:Leaf, parent=:root, status=PSE.Status(ordinal=index))) + end + return PSE.CompositeModel(objects...; environment=hourly_weather(), applications=( + PSE.ModelSpec(ProducerBirth(); name=:birth, on=PSE.One(id=:root), every=PSE.Dates.Hour(1)), + PSE.ModelSpec(Distributor{:signal}(2f0); name=:producer, + on=PSE.Many(scale=:Emitter), every=PSE.Dates.Hour(1), + inputs=(:tick => PSE.One(id=:root, within=PSE.SceneScope(), application=:birth, var=:visits),), + outputs_to=(PSE.OutputTo(PSE.Many(PSE.SceneScope(); scale=:Leaf); vars=(:signal,)),)), + )) +end + end diff --git a/test/test-model-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index 9ac59ea58..4959284c4 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1459,3 +1459,43 @@ end @test outputs(simulation)[(:distributed, ObjectId(:leaf_c), :delivered)] == [(3.0, 30f0)] @test outputs(simulation)[(:prospective_distributor, ObjectId(:leaf_c), :prospective)] == [(3.0, 60f0)] end + + +@testset "a newborn producer publishes to all thirty existing leaves on its birth step" begin + model = DistributedGrowthFixture.make_producer_birth_model() + ids = DistributedGrowthFixture.producer_birth_leaf_ids() + leaves = [model_object(model, id) for id in ids] + ordinal_refs = [PlantSimEngine.refvalue(model_status(model, id), :ordinal) for id in ids] + simulation = run!(model; steps=0, outputs=:all) + @test length(model_objects(model; scale=:Leaf)) == 30 + @test !haskey(model.registry.objects, ObjectId(:emitter)) + for day in 0:1 + day == 1 && step!(simulation) + @test current_step(simulation) == day + for (index, id) in enumerate(ids) + @test model_object(model, id) === leaves[index] + @test !hasproperty(model_status(model, id), :signal) + @test isempty(get(outputs(simulation), (:producer, id, :signal), Tuple{Float64,Float32}[])) + end + end + step!(simulation) + @test current_step(simulation) == 2 + @test haskey(model.registry.objects, ObjectId(:emitter)) + @test length(model_objects(model; scale=:Leaf)) == 30 + signal_refs = [PlantSimEngine.refvalue(model_status(model, id), :signal) for id in ids] + streams = [outputs(simulation)[(:producer, id, :signal)] for id in ids] + for day in 2:3 + day == 3 && step!(simulation) + @test current_step(simulation) == day + for (index, id) in enumerate(ids) + status = model_status(model, id) + @test model_object(model, id) === leaves[index] + @test PlantSimEngine.refvalue(status, :ordinal) === ordinal_refs[index] + @test status.ordinal == index + @test PlantSimEngine.refvalue(status, :signal) === signal_refs[index] + @test status.signal === Float32(20day) + @test outputs(simulation)[(:producer, id, :signal)] === streams[index] + @test streams[index] == [(Float64(tick), Float32(20tick)) for tick in 2:day] + end + end +end From 93b22c049f15634e19476cc92681c95ba2424598 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 11:21:57 +0100 Subject: [PATCH 183/324] Refresh existing status views only for organs whose reference cells changed --- src/PlantSimEngine.jl | 1 + src/component_models/ObjectId.jl | 18 +++++ src/component_models/Status.jl | 83 +++++++++++++++++++++++- src/composite_model/compilation.jl | 24 +++++-- src/composite_model/object_families.jl | 25 ++++++- src/composite_model/registry_topology.jl | 21 +----- test/test-fixed-status-scope-growth.jl | 47 ++++++++++++++ 7 files changed, 188 insertions(+), 31 deletions(-) create mode 100644 src/component_models/ObjectId.jl diff --git a/src/PlantSimEngine.jl b/src/PlantSimEngine.jl index 93f824ca4..2bb434312 100644 --- a/src/PlantSimEngine.jl +++ b/src/PlantSimEngine.jl @@ -38,6 +38,7 @@ include("authoring_interface.jl") include("time/multirate.jl") # Object status and reference carriers: +include("component_models/ObjectId.jl") include("component_models/Status.jl") include("component_models/RefVector.jl") diff --git a/src/component_models/ObjectId.jl b/src/component_models/ObjectId.jl new file mode 100644 index 000000000..077265736 --- /dev/null +++ b/src/component_models/ObjectId.jl @@ -0,0 +1,18 @@ +""" + ObjectId(value) + +Stable identity of one [`Object`](@ref) in a [`CompositeModel`](@ref). +Strings are normalized to symbols; an existing `ObjectId` is returned +unchanged. +""" +struct ObjectId{T} + value::T +end +ObjectId(id::ObjectId) = id +ObjectId(id::AbstractString) = ObjectId(Symbol(id)) + +function Base.show(io::IO, id::ObjectId) + print(io, "ObjectId(") + show(io, id.value) + print(io, ')') +end diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 7cbb81e75..78bbe9b8c 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -1,10 +1,38 @@ +# A registered canonical header can be shared by multiple models. Each +# registry records edits under its own ID, even when the other model ran first. +struct _WeakStatusChangeSink + ids::WeakRef +end + +# Construct a registered GC weak reference when copying an entire model. The +# registry owns the copied vector, and the shared deepcopy memo preserves that +# relationship regardless of whether the header or registry is copied first. +function Base.deepcopy_internal(sink::_WeakStatusChangeSink, memo::IdDict) + haskey(memo, sink.ids) && return _WeakStatusChangeSink(memo[sink.ids]::WeakRef) + ids = sink.ids.value::Union{Nothing,Vector{ObjectId}} + weak = WeakRef(ids) + memo[sink.ids] = weak + weak.value = Base.deepcopy_internal(ids, memo) + return _WeakStatusChangeSink(weak) +end + +struct _StatusReferenceWatch + sink::_WeakStatusChangeSink + id::ObjectId +end + +_watch_ids(watch::_StatusReferenceWatch) = watch.sink.ids.value::Union{Nothing,Vector{ObjectId}} + # N is the prepared namespace; the backing determines currently visible fields. mutable struct _FixedStatusStorage{N,R<:Tuple,T<:NamedTuple} refs::T reference_epoch::UInt + watchers::Union{Nothing,_StatusReferenceWatch,Vector{_StatusReferenceWatch}} + function _FixedStatusStorage{N,R,T}(refs, epoch) where {N,R,T} + return new{N,R,T}(refs, epoch, nothing) + end end - # Kernel ports remain a dense NT. The immutable full snapshot captures the SAME # refs and presence, including private/temporal overlays, never a latest owner. struct _ProjectedStatusStorage{N,R<:Tuple,H<:NamedTuple,T<:NamedTuple} @@ -135,6 +163,55 @@ _status_storage_references(storage::Union{_FixedStatusStorage,_ProjectedStatusSt _status_reference_epoch(storage::NamedTuple) = UInt(0) _status_reference_epoch(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}) = storage.reference_epoch _status_reference_epoch(status::Status) = _status_reference_epoch(_status_vars(status)) +function _watch_status_references!(status::Status{N,<:_FixedStatusStorage}, sink, id) where {N} + storage = _status_vars(status) + watched = storage.watchers + current = _StatusReferenceWatch(sink, id) + if isnothing(watched) || (watched isa _StatusReferenceWatch && isnothing(_watch_ids(watched))) + storage.watchers = current + elseif watched isa _StatusReferenceWatch + watched.sink.ids === sink.ids || (storage.watchers = [watched, current]) + else + filter!(watch -> !isnothing(_watch_ids(watch)), watched) + any(watch -> watch.sink.ids === sink.ids, watched) || push!(watched, current) + length(watched) == 1 && (storage.watchers = only(watched)) + end + return nothing +end +_watch_status_references!(status, sink, id) = nothing + +function _unwatch_status_references!(status::Status{N,<:_FixedStatusStorage}, sink) where {N} + storage = _status_vars(status) + watched = storage.watchers + if watched isa _StatusReferenceWatch + watched.sink.ids === sink.ids && (storage.watchers = nothing) + elseif watched isa Vector + filter!(watch -> watch.sink.ids !== sink.ids && !isnothing(_watch_ids(watch)), watched) + length(watched) <= 1 && (storage.watchers = isempty(watched) ? nothing : only(watched)) + end + return nothing +end +_unwatch_status_references!(status, sink) = nothing + +function _record_status_reference_change!(watch::_StatusReferenceWatch) + ids = _watch_ids(watch) + isnothing(ids) && return false + push!(ids, watch.id) + return true +end + +function _advance_status_reference_epoch!(storage::_FixedStatusStorage) + storage.reference_epoch += UInt(1) + watched = storage.watchers + if watched isa _StatusReferenceWatch + _record_status_reference_change!(watched) || (storage.watchers = nothing) + elseif watched isa Vector + filter!(_record_status_reference_change!, watched) + length(watched) <= 1 && (storage.watchers = isempty(watched) ? nothing : only(watched)) + end + return nothing +end + function _set_status_reference!(status::Status{N,<:_FixedStatusStorage}, name::Symbol, reference::Ref) where {N} storage = _status_vars(status) index = findfirst(isequal(name), N) @@ -144,7 +221,7 @@ function _set_status_reference!(status::Status{N,<:_FixedStatusStorage}, name::S old = getfield(storage.refs, index) old === reference && return reference storage.refs = typeof(storage.refs)(Base.setindex(values(storage.refs), reference, index)) - storage.reference_epoch += UInt(1) + _advance_status_reference_epoch!(storage) return reference end function _drop_status_reference!(status::Status{N,<:_FixedStatusStorage}, name::Symbol) where {N} @@ -153,7 +230,7 @@ function _drop_status_reference!(status::Status{N,<:_FixedStatusStorage}, name:: old === nothing && return nothing index = findfirst(isequal(name), N) storage.refs = typeof(storage.refs)(Base.setindex(values(storage.refs), nothing, index)) - storage.reference_epoch += UInt(1) + _advance_status_reference_epoch!(storage) return old end Status(; kwargs...) = Status(NamedTuple{keys(kwargs)}(Ref.(values(values(kwargs))))) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 03a6a0a78..f36cfc88c 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2215,6 +2215,7 @@ function _refresh_prepared_bindings!( _record_runtime_owner_replacement!(model, previous, refreshed) model.bindings_dirty = false _consume_structural_lifecycle_delta!(model) + empty!(model.registry.objects.changed_status_ids) return refreshed end @@ -4073,11 +4074,22 @@ function _extend_model_status_views!( end end - for (key, previous_view) in views - application_id = getfield(key, 1) - current = _status_view_key_epoch_is_current(compiled.status_view_schema, - application_id, previous_view, model, key::Key) - current || push!(affected_keys, key) + # Values written through existing cells leave projections valid. Only a + # registered object's reference edits or a replacement header affect them. + objects = model.registry.objects + for raw_id in objects.changed_status_ids + let object_id = _index_object_id(objects, raw_id) + haskey(objects, object_id) || continue + _foreach_object_application(compiled, object_id) do application + key = (application.id, object_id) + previous_view = get(views, key, nothing) + isnothing(previous_view) && return nothing + current = _status_view_key_epoch_is_current(compiled.status_view_schema, + application.id, previous_view, model, key::Key) + current || push!(affected_keys, key) + return nothing + end + end end positions = Dict( @@ -6704,7 +6716,7 @@ end references = $T($values) if references !== storage.refs storage.refs = references - storage.reference_epoch += UInt(1) + _advance_status_reference_epoch!(storage) end return recipe.original end diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index acde4c3e0..fbb92455f 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -55,6 +55,13 @@ mutable struct ObjectFamilyStore{I<:ObjectId,C} <: AbstractDict{I,Object} const catalog::C const locations::Dict{I,ObjectFamilyLocation} const status_owners::IdDict{Base.RefValue{Nothing},I} + const changed_status_ids::Vector{ObjectId} + const change_sink::_WeakStatusChangeSink +end + +function ObjectFamilyStore(catalog, locations::Dict{I,ObjectFamilyLocation}, owners::IdDict{Base.RefValue{Nothing},I}) where {I<:ObjectId} + ids = ObjectId[] + return ObjectFamilyStore(catalog, locations, owners, ids, _WeakStatusChangeSink(WeakRef(ids))) end ObjectFamilyStore{I}() where {I<:ObjectId} = ObjectFamilyStore( @@ -169,7 +176,12 @@ function _store_object_family_row!(store::ObjectFamilyStore{K}, object::Object, _validate_object_family_status_owner!(store, status, id) slot, family = _object_family_for_write!(store.catalog, K, S) if !isnothing(previous) - _forget_object_family_status!(store, _object_family_status_at(store.catalog, previous), id) + old = _object_family_status_at(store.catalog, previous) + if old !== status + _unwatch_status_references!(old, store.change_sink) + _forget_object_family_status!(store, old, id) + push!(store.changed_status_ids, id) + end end entry = ObjectFamilyRow{K,S}(id, status) row = if !isnothing(previous) && previous.family == slot @@ -181,6 +193,9 @@ function _store_object_family_row!(store::ObjectFamilyStore{K}, object::Object, length(family.rows) end store.locations[id] = ObjectFamilyLocation(slot, row, object) + if store.catalog isa ClosedObjectFamilyCatalog + _watch_status_references!(status, store.change_sink, id) + end status isa Status && (store.status_owners[_status_identity(status)] = id) return status end @@ -197,13 +212,19 @@ end function Base.delete!(store::ObjectFamilyStore, id) location = get(store.locations, id, nothing) isnothing(location) && return store - _forget_object_family_status!(store, _object_family_status_at(store.catalog, location), id) + status = _object_family_status_at(store.catalog, location) + _unwatch_status_references!(status, store.change_sink) + _forget_object_family_status!(store, status, id) _clear_object_family_row!(store.catalog, location) delete!(store.locations, id) return store end function Base.empty!(store::ObjectFamilyStore) + for location in values(store.locations) + _unwatch_status_references!(_object_family_status_at(store.catalog, location), store.change_sink) + end + empty!(store.changed_status_ids) empty!(store.locations) empty!(store.status_owners) for family in store.catalog.families diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 03a45b49e..b8690eda7 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -12,25 +12,6 @@ Base.setindex!(v::ObjectRefVector, value, i::Int) = (v.refs[i][] = value) Base.parent(v::ObjectRefVector) = v.refs Base.dataids(v::ObjectRefVector) = Base.dataids(parent(v)) -""" - ObjectId(value) - -Stable identity of one [`Object`](@ref) in a [`CompositeModel`](@ref). -Strings are normalized to symbols; an existing `ObjectId` is returned -unchanged. -""" -struct ObjectId{T} - value::T -end -ObjectId(id::ObjectId) = id -ObjectId(id::AbstractString) = ObjectId(Symbol(id)) - -function Base.show(io::IO, id::ObjectId) - print(io, "ObjectId(") - show(io, id.value) - print(io, ')') -end - """ Object(id; scale=nothing, kind=nothing, species=nothing, name=nothing, parent=nothing, children=ObjectId[], geometry=nothing, @@ -667,7 +648,7 @@ function _registry_with_prepared_status_manifest(model, manifest) throw(ArgumentError("This authoring refresh changes the prepared Status or typed configuration schema. " * "Construct a new CompositeModel for this configuration.")) replacement = ObjectFamilyStore(ClosedObjectFamilyCatalog(catalog.families, manifest), - store.locations, store.status_owners) + store.locations, store.status_owners, store.changed_status_ids, store.change_sink) registry = ObjectRegistry(replacement, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) typeof(registry) === typeof(previous) || throw(ArgumentError( diff --git a/test/test-fixed-status-scope-growth.jl b/test/test-fixed-status-scope-growth.jl index b60ad539c..7d7e62384 100644 --- a/test/test-fixed-status-scope-growth.jl +++ b/test/test-fixed-status-scope-growth.jl @@ -76,4 +76,51 @@ end @test object_id(model, tuple_status) == ObjectId(tuple_id) @test tuple_status.x === 2.0 end + +@testset "registries sharing a canonical header observe changed references independently" begin + make(id, status) = CompositeModel(Object(id; scale=:Leaf, status); + applications=(ModelSpec(Increment(0f0); on=Many(scale=:Leaf)),)) + first_model = make(:one, Status(x=1f0)) + first_run = run!(first_model; steps=0, outputs=:none) + canonical = model_status(first_model, :one) + second_model = make(:two, canonical) + second_run = run!(second_model; steps=0, outputs=:none) + @test model_status(second_model, :two) === canonical + + detached = copy(canonical) + PSE._set_status_reference!(detached, :x, Ref(99f0)) + @test isempty(first_model.registry.objects.changed_status_ids) + @test isempty(second_model.registry.objects.changed_status_ids) + old = PSE.refvalue(canonical, :x) + replacement = Ref(4f0) + PSE._set_status_reference!(canonical, :x, replacement) + for (model, sim) in ((first_model, first_run), (second_model, second_run)) + register_object!(model, Object(:axis; scale=:Axis)) + step!(sim) + @test isempty(model.registry.objects.changed_status_ids) + end + @test old[] === 1f0 + @test replacement[] === 6f0 + copied = deepcopy(first_model) + copied_status = model_status(copied, :one) + GC.gc() + copied_ref = Ref(20f0) + PSE._set_status_reference!(copied_status, :x, copied_ref) + @test copied.registry.objects.changed_status_ids == [ObjectId(:one)] + @test isempty(first_model.registry.objects.changed_status_ids) + @test isempty(second_model.registry.objects.changed_status_ids) + @test PSE.refvalue(canonical, :x) === replacement + + function temporary_subscriber(s) + short_lived = make(:temporary, s) + return WeakRef(short_lived.registry.objects.changed_status_ids) + end + released = temporary_subscriber(canonical) + GC.gc() + @test isnothing(released.value) + remove_object!(first_model, :one) + PSE._set_status_reference!(canonical, :x, Ref(10f0)) + @test isempty(first_model.registry.objects.changed_status_ids) + @test second_model.registry.objects.changed_status_ids == [ObjectId(:two)] +end end From 7864658c8063d51afe0b41cf6d914c3a15202cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 11:42:38 +0100 Subject: [PATCH 184/324] Preserve registry IDs and input plan types while resolving organ growth --- src/composite_model/compilation.jl | 45 +++++++++++++++++++----------- src/composite_model/selectors.jl | 44 +++++++++++------------------ 2 files changed, 46 insertions(+), 43 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f36cfc88c..05e9df936 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3047,6 +3047,29 @@ function _record_consumer_input_bindings!( return nothing end +# Admit one existing recipe entry before resolving/materializing that route. +function _compile_consumer_input_plan!( + plan, query_slot, bindings, model, application_id, application_process, + consumer_id, applications_by_object, applications_by_id, distributed_outputs, + many_binding_cache, performance, query_cache, +) + if !isnothing(many_binding_cache) + shared_binding = _shared_many_input_binding( + many_binding_cache, model, plan, consumer_id, + ) + if !isnothing(shared_binding) + push!(bindings, shared_binding) + _runtime_performance_count!(performance, :many_input_binding_precompile_reuses) + return nothing + end + end + _resolve_materialize_input_route!( + bindings, model, application_id, application_process, consumer_id, plan, + applications_by_object, applications_by_id, nothing, distributed_outputs; + query_cache, query_slot, + ) +end + function _compile_consumer_input_recipe!( bindings, model, @@ -3062,22 +3085,12 @@ function _compile_consumer_input_recipe!( performance=nothing, ) query_cache = _input_query_cache(model.registry.objects, recipe.query_count) - foreach(recipe.explicit, recipe.query_slots) do plan, query_slot - if !isnothing(many_binding_cache) - shared_binding = _shared_many_input_binding( - many_binding_cache, model, plan, consumer_id, - ) - if !isnothing(shared_binding) - push!(bindings, shared_binding) - _runtime_performance_count!(performance, :many_input_binding_precompile_reuses) - return nothing - end - end - _resolve_materialize_input_route!( - bindings, model, application_id, application_process, consumer_id, plan, - applications_by_object, applications_by_id, nothing, distributed_outputs; - query_cache, query_slot, - ) + # Keep the same positional zip while admitting each heterogeneous plan. + for (slot, query_slot) in zip(eachindex(recipe.explicit), recipe.query_slots) + _with_metadata_entry(_compile_consumer_input_plan!, recipe.explicit, slot, + query_slot, bindings, model, application_id, application_process, + consumer_id, applications_by_object, applications_by_id, + distributed_outputs, many_binding_cache, performance, query_cache) end application_id in manual_application_ids && return bindings foreach(recipe.inferred) do group diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 5f2e35d3e..f69ebb77a 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -549,41 +549,30 @@ function _object_id_from_context(context) return ObjectId(context) end -function _append_descendant_ids!( - ids::Vector{ObjectId}, - model::CompositeModel, - root_id::ObjectId, -) - push!(ids, root_id) - object = _model_object(model, root_id) - for child_id in object.children - _append_descendant_ids!(ids, model, child_id) - end - return ids -end - -function _descendant_ids(model::CompositeModel, root_id::ObjectId) - return _append_descendant_ids!(ObjectId[], model, root_id) -end +# Full and budgeted queries walk the same child order. Only a budgeted +# walk can stop early in favour of the smaller registry index. +_descendant_ids(model::CompositeModel, root_id::ObjectId) = + _descendant_ids_up_to(model, root_id, nothing) function _descendant_ids_up_to( model::CompositeModel, root_id::ObjectId, - limit::Int, + limit::Union{Nothing,Int}, ) - ids = ObjectId[] + objects = model.registry.objects + ids = keytype(objects)[] # Borrow child vectors and retain only a depth-sized cursor stack. Pushing # every child onto a worklist would allocate for a huge subtree even when # a sparse index gives this traversal a budget of only a few objects. cursors = Tuple{Vector{ObjectId},Int}[] - current_id = root_id + current_id = _index_object_id(objects, root_id) while true - length(ids) >= limit && return nothing + !isnothing(limit) && length(ids) >= limit && return nothing push!(ids, current_id) children = _model_object(model, current_id).children if !isempty(children) push!(cursors, (children, 2)) - current_id = first(children) + current_id = _index_object_id(objects, first(children)) continue end found_next = false @@ -591,7 +580,7 @@ function _descendant_ids_up_to( siblings, next_index = pop!(cursors) next_index > length(siblings) && continue push!(cursors, (siblings, next_index + 1)) - current_id = siblings[next_index] + current_id = _index_object_id(objects, siblings[next_index]) found_next = true break end @@ -626,11 +615,11 @@ function _ancestor_id( final_index = lastindex(ancestors) - (include_self ? 0 : 1) final_index < firstindex(ancestors) && return nothing isnothing(scale) && isnothing(kind) && - return @inbounds ancestors[final_index] + return _index_object_id(model.registry.objects, @inbounds ancestors[final_index]) !isnothing(scale) && !haskey(model.registry.by_scale, scale) && return nothing !isnothing(kind) && !haskey(model.registry.by_kind, kind) && return nothing for index in final_index:-1:firstindex(ancestors) - id = @inbounds ancestors[index] + id = _index_object_id(model.registry.objects, @inbounds ancestors[index]) _ancestor_matches_indexed_labels(model, id, scale, kind) && return id end return nothing @@ -1526,13 +1515,14 @@ function _resolve_object_ids( else nothing end + I = keytype(model.registry.objects) local_ids = if !isnothing(subtree_root) - if !haskey(model.registry.objects, subtree_root) - ObjectId[] + if !(subtree_root isa I) || !haskey(model.registry.objects, subtree_root::I) + I[] else budget = isnothing(indexed) ? length(model.registry.objects) : min(indexed.estimate, length(model.registry.objects)) - _descendant_ids_up_to(model, subtree_root, budget) + _descendant_ids_up_to(model, subtree_root::I, budget) end else nothing From 821f410c49f4d8410e1e0f5ee55546f886c0d63f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 12:03:42 +0100 Subject: [PATCH 185/324] Preserve registered identity types in scoped indexes and public object queries --- src/composite_model/compilation.jl | 122 +++++++++++--------- src/composite_model/selectors.jl | 17 ++- test/test-selector-candidate-empty-scope.jl | 82 ++++++++++--- 3 files changed, 145 insertions(+), 76 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 05e9df936..9acd4a648 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -426,6 +426,20 @@ function _application_target_template_cache(::Type{I}) where {I<:ObjectId} return Dict{_ApplicationTargetTemplateKey{I},_ApplicationTargetTemplate}() end +# A fixed key type also covers a registry with several concrete ID families. +# A missing label denotes the unqualified anchor; labeled values retain the +# same Symbol/ObjectId domain admitted by the selector index. +struct _SelectorScopeAnchorKey{I<:ObjectId} + anchor::I + label::Union{Nothing,Symbol} + value::Union{Nothing,Symbol,I} +end + +function _selector_scope_anchor_key(::Type{I}, anchor::I, label::Symbol, value) where {I<:ObjectId} + value isa Union{Symbol,I} || return nothing + return _SelectorScopeAnchorKey{I}(anchor, label, value) +end + """Reverse candidate index for compiled selector matchers.""" struct SelectorCandidateIndex{W,S,K,SP,I,A,R,L,C} wildcard::W @@ -448,7 +462,7 @@ function _selector_candidate_index(model::CompositeModel, application_target_tem Dict{Symbol,Vector{Int}}(), Dict{I,Vector{Int}}(), Dict{ - Union{I,Tuple{I,Symbol,Union{Symbol,I}}}, + _SelectorScopeAnchorKey{I}, Vector{Int}, }(), Set{I}(), @@ -521,16 +535,32 @@ function _selector_scope_anchor( return nothing end -function _selector_candidate_destination( +# Perform the insertion while the chosen dictionary retains its exact key type. +# Selector keys outside a closed registry's ID family remain empty matches. +function _index_selector_candidate_bucket!(index::SelectorCandidateIndex, + groups::AbstractDict{K}, values, candidate_index::Int, +) where {K} + for value in values + value isa K || continue + push!(get!(groups, value::K, Int[]), candidate_index) + !isnothing(index.application_target_templates) && + groups === index.by_scope_anchor && push!(index.scope_roots, + value isa _SelectorScopeAnchorKey ? value.anchor : value) + end + return index +end + +function _index_selector_candidate_destination!( index::SelectorCandidateIndex, model::CompositeModel, matcher::CompiledSelectorMatcher, + candidate_index::Int, context, default_scope, ) scope = isnothing(matcher.scope) ? default_scope : matcher.scope if scope isa Self && isnothing(matcher.relation) - return nothing + return index end # `Ancestor(scale=S)` combined with a source at `scale=S` selects the # nearest matching ancestor. Adding a descendant cannot change that source @@ -540,7 +570,7 @@ function _selector_candidate_destination( scope isa Ancestor && !isnothing(matcher.scale) && matcher.scale == scope.scale - return nothing + return index end anchor = _selector_scope_anchor( model, @@ -550,36 +580,37 @@ function _selector_candidate_destination( ) if !isnothing(anchor) I = keytype(index.by_id) - anchor_id = ObjectId(anchor) + raw_anchor_id = ObjectId(anchor) # An out-of-family anchor cannot acquire an object in this registry. - anchor_id isa I || return nothing - anchor_id = anchor_id::I + raw_anchor_id isa I || return index + anchor_id = raw_anchor_id::I for (label, value) in ( (:id, matcher.id), (:scale, matcher.scale), (:kind, matcher.kind), (:species, matcher.species), ) - isnothing(value) || return ( - index.by_scope_anchor, - Tuple( - (anchor_id, label, candidate) - for candidate in _selector_candidate_values(value) - ), + isnothing(value) || return _index_selector_candidate_bucket!( + index, index.by_scope_anchor, + map(candidate -> _selector_scope_anchor_key(I, anchor_id, label, candidate), + _selector_candidate_values(value)), + candidate_index, ) end - return (index.by_scope_anchor, (anchor_id,)) - end - for (groups, value) in ( - (index.by_id, matcher.id), - (index.by_scale, matcher.scale), - (index.by_kind, matcher.kind), - (index.by_species, matcher.species), - ) - isnothing(value) || - return (groups, _selector_candidate_values(value)) - end - return (nothing, ()) + return _index_selector_candidate_bucket!( + index, index.by_scope_anchor, + (_SelectorScopeAnchorKey{I}(anchor_id, nothing, nothing),), candidate_index) + end + isnothing(matcher.id) || return _index_selector_candidate_bucket!( + index, index.by_id, _selector_candidate_values(matcher.id), candidate_index) + isnothing(matcher.scale) || return _index_selector_candidate_bucket!( + index, index.by_scale, _selector_candidate_values(matcher.scale), candidate_index) + isnothing(matcher.kind) || return _index_selector_candidate_bucket!( + index, index.by_kind, _selector_candidate_values(matcher.kind), candidate_index) + isnothing(matcher.species) || return _index_selector_candidate_bucket!( + index, index.by_species, _selector_candidate_values(matcher.species), candidate_index) + push!(index.wildcard, candidate_index) + return index end function _index_selector_candidate!( @@ -604,31 +635,8 @@ function _index_selector_candidate!( end end end - destination = _selector_candidate_destination( - index, - model, - matcher, - context, - default_scope, - ) - isnothing(destination) && return index - groups, values = destination - if isnothing(groups) - push!(index.wildcard, candidate_index) - else - for value in values - # Selectors may name future/missing IDs, including an ID family - # that this closed registry cannot ever register. Keep them empty. - value isa keytype(groups) || continue - push!(get!(groups, value, Int[]), candidate_index) - tracks_application_targets && - groups === index.by_scope_anchor && push!( - index.scope_roots, - value isa Tuple ? first(value) : value, - ) - end - end - return index + return _index_selector_candidate_destination!( + index, model, matcher, candidate_index, context, default_scope) end # Keep each dictionary/key pair concrete at its lookup rather than joining @@ -638,8 +646,18 @@ end return candidates end -@inline function _union_selector_bucket!(candidates, groups, anchor, label, value) - isnothing(value) || _union_selector_bucket!(candidates, groups, (anchor, label, value)) +@inline function _union_selector_bucket!(candidates, + groups::AbstractDict{_SelectorScopeAnchorKey{I}}, anchor::ObjectId, +) where {I} + return _union_selector_bucket!(candidates, groups, + _SelectorScopeAnchorKey{I}(anchor, nothing, nothing)) +end + +@inline function _union_selector_bucket!(candidates, + groups::AbstractDict{_SelectorScopeAnchorKey{I}}, anchor, label, value, +) where {I} + isnothing(value) || _union_selector_bucket!(candidates, groups, + _SelectorScopeAnchorKey{I}(anchor, label, value)) return candidates end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index f69ebb77a..7b7f4c2ed 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -891,12 +891,17 @@ function _indexed_object_ids(model::CompositeModel; scale=nothing, kind=nothing, if isnothing(candidates) && all(isnothing, (scale, kind, species, id)) return nothing end - candidate_ids = isnothing(candidates) ? keys(model.registry.objects) : candidates.ids - return unique!(ObjectId[ - candidate for candidate in candidate_ids - if haskey(model.registry.objects, candidate) && - _matches_object_criteria(_model_object(model, candidate); scale, kind, species, id) - ]) + objects = model.registry.objects + I = keytype(objects) + ids = I[] + candidate_ids = isnothing(candidates) ? keys(objects) : candidates.ids + for candidate in candidate_ids + candidate isa I || continue + object = get(objects, candidate::I, nothing) + isnothing(object) && continue + _matches_object_criteria(object; scale, kind, species, id) && push!(ids, candidate) + end + return unique!(ids) end # Resolve topology once, before choosing between a bounded local walk and a diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 8df21e4d3..46b706e3c 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -1,6 +1,10 @@ using PlantSimEngine using Test +function _selector_scope_test_key(index, anchor, label=nothing, value=nothing) + return keytype(index.by_scope_anchor)(anchor, label, value) +end + @testset "Selector candidates with and without scoped entries" begin model = CompositeModel( Object(:scene; scale=:Scene), @@ -51,20 +55,20 @@ using Test end @testset "Scoped candidates include the ancestor chain and self" begin - index.by_scope_anchor[ObjectId(:scene)] = [6] - index.by_scope_anchor[ObjectId(:plant)] = [7] - index.by_scope_anchor[ObjectId(:axis)] = [8] - index.by_scope_anchor[leaf_id] = [9] - index.by_scope_anchor[(ObjectId(:plant), :scale, :Leaf)] = [10] - index.by_scope_anchor[(ObjectId(:axis), :kind, :photosynthetic)] = [11] - index.by_scope_anchor[(ObjectId(:scene), :species, :rauh)] = [12] - index.by_scope_anchor[(leaf_id, :id, leaf_id)] = [13] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:scene))] = [6] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:plant))] = [7] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:axis))] = [8] + index.by_scope_anchor[_selector_scope_test_key(index, leaf_id)] = [9] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:plant), :scale, :Leaf)] = [10] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:axis), :kind, :photosynthetic)] = [11] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:scene), :species, :rauh)] = [12] + index.by_scope_anchor[_selector_scope_test_key(index, leaf_id, :id, leaf_id)] = [13] # Another plant and nonmatching labels cannot contribute candidates. - index.by_scope_anchor[ObjectId(:other_plant)] = [94] - index.by_scope_anchor[(ObjectId(:plant), :scale, :Fruit)] = [95] - index.by_scope_anchor[(ObjectId(:axis), :kind, :wood)] = [96] - index.by_scope_anchor[(ObjectId(:scene), :species, :merisier)] = [97] - index.by_scope_anchor[(ObjectId(:plant), :id, ObjectId(:other_leaf))] = [98] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:other_plant))] = [94] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:plant), :scale, :Fruit)] = [95] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:axis), :kind, :wood)] = [96] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:scene), :species, :merisier)] = [97] + index.by_scope_anchor[_selector_scope_test_key(index, ObjectId(:plant), :id, ObjectId(:other_leaf))] = [98] for candidate_index in (index, PlantSimEngine._freeze_selector_candidate_index(index)) candidates = Set([99]) result = PlantSimEngine._union_selector_candidates!( @@ -127,12 +131,27 @@ end I = keytype(model.registry.objects) expected_id_type = closed ? Union{map(id -> typeof(ObjectId(id)), ids)...} : ObjectId @test I === expected_id_type + selected = object_ids(model; id=(ObjectId(leaf_id), ObjectId(plant_id), + ObjectId(leaf_id), ObjectId(1.5))) + @test eltype(selected) === I + @test selected == sort!(ObjectId.([leaf_id, plant_id]); by=id -> string(id.value)) + @test only(model_objects(model; scale=:Leaf)) === model_object(model, leaf_id) + @test isempty(object_ids(model; id=1.5)) index = PlantSimEngine._selector_candidate_index(model, nothing) frozen_empty = PlantSimEngine._freeze_selector_candidate_index(index) @test keytype(index.by_id) === keytype(frozen_empty.by_id) === I @test keytype(index.by_scope_anchor) === keytype(frozen_empty.by_scope_anchor) === - Union{I,Tuple{I,Symbol,Union{Symbol,I}}} + PlantSimEngine._SelectorScopeAnchorKey{I} @test eltype(index.scope_roots) === eltype(frozen_empty.scope_roots) === I + K = keytype(index.by_scope_anchor) + @test isconcretetype(K) + bare = K(ObjectId(plant_id), nothing, nothing) + labeled = K(ObjectId(plant_id), :scale, :Leaf) + @test isequal(bare, K(ObjectId(plant_id), nothing, nothing)) + @test hash(bare) == hash(K(ObjectId(plant_id), nothing, nothing)) + @test isequal(labeled, K(ObjectId(plant_id), :scale, :Leaf)) + @test hash(labeled) == hash(K(ObjectId(plant_id), :scale, :Leaf)) + @test !isequal(bare, labeled) @test isempty(frozen_empty.by_id) && isempty(frozen_empty.by_scope_anchor) selectors = ( Many(id=leaf_id), @@ -142,14 +161,41 @@ end Many(scale=:Leaf, within=Subtree()), Many(within=Subtree()), Many(id=scene_id), + Many(scale=(:Leaf, :Fruit), within=Subtree()), ) for (position, selector) in pairs(selectors) matcher = PlantSimEngine._compile_selector_matcher(model, selector) - PlantSimEngine._index_selector_candidate!( + @test (@inferred PlantSimEngine._index_selector_candidate!( index, model, matcher, position, ObjectId(plant_id), nothing, - ) + )) === index + end + # The same concrete buckets also collect template roots. This + # owner must not widen its dictionaries when choosing a label. + cache = PlantSimEngine._application_target_template_cache(I) + cached = PlantSimEngine._selector_candidate_index(model, cache) + for (position, selector) in pairs(selectors) + matcher = PlantSimEngine._compile_selector_matcher(model, selector) + @test PlantSimEngine._index_selector_candidate!( + cached, model, matcher, position, ObjectId(plant_id), nothing, + ) === cached end - expected = Set([1, 2, 5, 6]) + for field in (:wildcard, :by_id, :by_scale, :by_kind, :by_species, :by_scope_anchor) + @test getfield(cached, field) == getfield(index, field) + @test typeof(getfield(cached, field)) === typeof(getfield(index, field)) + end + @test cached.application_target_templates === cache + @test cached.scope_roots == Set{I}([ObjectId(plant_id)]) + @test isempty(index.scope_roots) + skipped = PlantSimEngine._selector_candidate_index(model, nothing) + for selector in (Many(Self()), Many(Ancestor(scale=:Plant); scale=:Plant)) + matcher = PlantSimEngine._compile_selector_matcher(model, selector) + @test PlantSimEngine._index_selector_candidate!(skipped, model, + matcher, 1, ObjectId(leaf_id), nothing) === skipped + end + @test all(field -> isempty(getfield(skipped, field)), + (:wildcard, :by_id, :by_scale, :by_kind, :by_species, :by_scope_anchor)) + + expected = Set([1, 2, 5, 6, 8]) isnothing(kind) || push!(expected, 3) isnothing(species) || push!(expected, 4) for candidate_index in (index, PlantSimEngine._freeze_selector_candidate_index(index)) @@ -182,7 +228,7 @@ end if future_id isa I @test haskey(future_index.by_id, future_id) @test haskey(future_index.by_scope_anchor, - (ObjectId(plant_id), :id, future_id)) + _selector_scope_test_key(future_index, ObjectId(plant_id), :id, future_id)) register_object!(model, Object(raw_future; scale=:Leaf, parent=axis_id, kind, species)) for candidate_index in (future_index, frozen_future) From 8ebb8641c89dd1e96ec1b4939789edccd8a8f021 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 12:18:45 +0100 Subject: [PATCH 186/324] Resolve growth queries inside each candidate source and reuse ancestor diagnostics --- src/composite_model/selectors.jl | 59 ++++++++------------------ test/test-selector-query-scope-root.jl | 7 ++- 2 files changed, 22 insertions(+), 44 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 7b7f4c2ed..54ec91e81 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -820,27 +820,10 @@ function _scope_object_ids(model::CompositeModel, scope, context) return _descendant_ids(model, current_id) elseif scope isa SelfPlant isnothing(current_id) && error("`SelfPlant()` selectors require a current object context.") - plant_id = _ancestor_id( - model, - current_id, - :Plant, - nothing, - true, - ) - isnothing(plant_id) && error("No `scale=:Plant` ancestor found for object `$(current_id.value)`.") - return _descendant_ids(model, plant_id) + return _descendant_ids(model, _required_scope_anchor(model, scope, current_id)) elseif scope isa Ancestor isnothing(current_id) && error("`Ancestor(...)` selectors require a current object context.") - ancestor_id = _ancestor_id( - model, - current_id; - scale=scope.scale, - include_self=false, - ) - if isnothing(ancestor_id) - error("No matching ancestor found for object `$(current_id.value)` and selector `$(scope)`.") - end - return _descendant_ids(model, ancestor_id) + return _descendant_ids(model, _required_scope_anchor(model, scope, current_id)) elseif scope isa Scope return _descendant_ids(model, _named_scope_root_id(model, scope)) elseif scope isa CompiledNamedScope @@ -913,12 +896,7 @@ function _selector_subtree_root(model::CompositeModel, scope, context) isnothing(current_id) && error("`$(scope)` selectors require a current object context.") _model_object(model, current_id) scope isa Subtree && return current_id - root = _scope_anchor(model, scope, current_id) - if isnothing(root) - scope isa SelfPlant && error("No `scale=:Plant` ancestor found for object `$(current_id.value)`.") - error("No matching ancestor found for object `$(current_id.value)` and selector `$(scope)`.") - end - return root + return _required_scope_anchor(model, scope, current_id) elseif scope isa Scope return _named_scope_root_id(model, scope) elseif scope isa CompiledNamedScope @@ -1532,37 +1510,34 @@ function _resolve_object_ids( else nothing end - # Only the relation resolver guarantees membership. Borrowed index buckets - # still need relation checks, and a completed descendant walk includes self. - relation_resolved = false - candidate_ids = if nearest_ancestor + matching_matcher = _query_scope_matcher(matcher, scope, subtree_root) + # Consume each candidate source while its element and container types are + # still known. Only the relation resolver guarantees relation membership. + matches(candidates, relation_resolved=false) = _matching_selector_ids( + model, matching_matcher, candidates, context, default_to_context, default_scope, relation_resolved, + ) + ids = if nearest_ancestor current_id = _object_id_from_context(context) isnothing(current_id) && error( "`Ancestor(...)` selectors require a current object context.", ) ancestor_id = _ancestor_id(model, current_id; scale=scope.scale, include_self=false) - isnothing(ancestor_id) ? ObjectId[] : ObjectId[ancestor_id] + matches(isnothing(ancestor_id) ? () : (ancestor_id,)) elseif !isnothing(local_ids) - local_ids + matches(local_ids) elseif !isnothing(relation) && relation != :descendants - relation_resolved = true - _relation_object_ids(model, relation, context) + matches(_relation_object_ids(model, relation, context), true) elseif scope isa Self && isnothing(relation) self_ids = _scope_object_ids(model, scope, context) _model_object(model, only(self_ids)) - self_ids + matches(self_ids) elseif !isnothing(indexed) - indexed.ids + matches(indexed.ids) elseif isnothing(relation) - _scope_object_ids(model, scope, context) + matches(_scope_object_ids(model, scope, context)) else - relation_resolved = true - _relation_object_ids(model, relation, context) + matches(_relation_object_ids(model, relation, context), true) end - matching_matcher = _query_scope_matcher(matcher, scope, subtree_root) - ids = _matching_selector_ids( - model, matching_matcher, candidate_ids, context, default_to_context, default_scope, relation_resolved, - ) # Cardinality diagnostics may need all available labels in the topology # scope. Materialize them only on an error, never for empty Many queries. diff --git a/test/test-selector-query-scope-root.jl b/test/test-selector-query-scope-root.jl index 08027445c..e77f6e5d1 100644 --- a/test/test-selector-query-scope-root.jl +++ b/test/test-selector-query-scope-root.jl @@ -107,8 +107,11 @@ end @test_throws "current object context" resolve_object_ids(model, Many(Subtree(); scale=:Leaf)) @test_throws "current object context" resolve_object_ids(model, Many(Ancestor(scale=:Plant); scale=:Leaf)) - @test_throws "No matching ancestor" resolve_object_ids(model, - Many(Ancestor(scale=:Axis); scale=:Leaf); context=:plant_a) + missing = query_error(model, Many(Ancestor(scale=:Axis); scale=:Leaf); context=:plant_a) + @test occursin("No matching ancestor", missing) + @test occursin("object `plant_a` and scale `Axis`", missing) + @test occursin("object `scene` and scale `nothing`", query_error(model, + Many(Ancestor(); scale=:Leaf); context=:scene)) @test_throws "No `scale=:Plant` ancestor" resolve_object_ids(model, Many(SelfPlant(); scale=:Leaf); context=:scene) @test_throws "No instance or object ID" resolve_object_ids(model, From 53bdcbec2088a8e3cbc90be9834c472fc90fee53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 12:38:56 +0100 Subject: [PATCH 187/324] Keep native growth regressions for local neighbours and distributed destinations --- .../local_palm_leaf_birth/Project.toml | 13 + .../src/PSELocalPalmLeafBirth.jl | 101 +++++++ .../local_palm_leaf_birth/src/fixture.jl | 257 ++++++++++++++++++ .../local_palm_leaf_birth/src/prepare.jl | 114 ++++++++ .../distributed_producer_birth/Project.toml | 12 + .../src/PSEThirtyProducerControl.jl | 17 ++ .../distributed_producer_birth/src/prepare.jl | 104 +++++++ test/integration/native_fixture_apps.jl | 50 ++++ test/integration/native_growth.jl | 80 ++++++ test/integration/native_preparation.jl | 79 ++++++ test/test-model-local-leaf-birth.jl | 156 +++++++++++ test/test_groups.jl | 1 + 12 files changed, 984 insertions(+) create mode 100644 test/fixtures/local_palm_leaf_birth/Project.toml create mode 100644 test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl create mode 100644 test/fixtures/local_palm_leaf_birth/src/fixture.jl create mode 100644 test/fixtures/local_palm_leaf_birth/src/prepare.jl create mode 100644 test/integration/fixtures/distributed_producer_birth/Project.toml create mode 100644 test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl create mode 100644 test/integration/fixtures/distributed_producer_birth/src/prepare.jl create mode 100644 test/integration/native_fixture_apps.jl create mode 100644 test/integration/native_growth.jl create mode 100644 test/integration/native_preparation.jl create mode 100644 test/test-model-local-leaf-birth.jl diff --git a/test/fixtures/local_palm_leaf_birth/Project.toml b/test/fixtures/local_palm_leaf_birth/Project.toml new file mode 100644 index 000000000..3257e080c --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/Project.toml @@ -0,0 +1,13 @@ +name = "PSELocalPalmLeafBirth" +uuid = "b6daedc5-c1c3-4c8e-a43e-b4ee2ff54a35" +version = "0.1.0" + +[deps] +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" +PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" + +[sources] +PlantSimEngine = {path = "../../.."} + +[compat] +julia = "1.13" diff --git a/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl b/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl new file mode 100644 index 000000000..2edbad519 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl @@ -0,0 +1,101 @@ +module PSELocalPalmLeafBirth + +include("native_preparation.jl") +include("fixture.jl") +include("prepare.jl") +using .LocalPalmLeafBirth +using .LocalPalmLeafBirthPreparation: prepare_native_scene +import PlantSimEngine as PSE + +# A alone is the only retained payload. The native count is command-line data. +const STATE = prepare_native_scene() + +pack(value::Float32) = UInt64(reinterpret(UInt32,value)) +pack(value::Int64) = reinterpret(UInt64,value) + +function append_history!(report,simulation,application,id,variable,::Type{T}) where {T} + samples = PSE.outputs(simulation)[(application,PSE.ObjectId(id),variable)]::Vector{Tuple{Float64,T}} + push!(report,UInt64(length(samples))) + for (time,value) in samples + push!(report,reinterpret(UInt64,time),pack(value)) + end + return report +end + +# Bounded binary output avoids IO formatting in the safe runtime. The same +# ordered A values and all 16 retained output series are compared by the host. +function a_report(state,requested) + a = first(state.records) + report = UInt64[0x50414c4d42495254,UInt64(requested),UInt64(length(state.records)), + UInt64(length(PSE.runtime_model(state.simulation).registry.objects)), + UInt64(PSE.current_step(state.simulation))] + for value in values(palm_values(a.palm)) + push!(report,pack(value)) + end + for leaf in (a.leaf[1],a.leaf[2],state.newborn) + for value in values(leaf_values(leaf)) + push!(report,pack(value)) + end + end + append_history!(report,state.simulation,:palm_supply,Int64(1),:supply,Float32) + append_history!(report,state.simulation,:palm_carbon,Int64(1),:carbon,Float32) + append_history!(report,state.simulation,:palm_carbon,Int64(1),:reserve,Float32) + append_history!(report,state.simulation,:palm_carbon,Int64(1),:leaf_count,Int64) + for id in (Int64(2),Int64(3),Int64(4)) + append_history!(report,state.simulation,:leaf_assimilation,id,:assimilation,Float32) + append_history!(report,state.simulation,:leaf_assimilation,id,:water_seen,Float32) + append_history!(report,state.simulation,:leaf_assimilation,id,:previous_seen,Float32) + append_history!(report,state.simulation,:leaf_assimilation,id,:visits,Int64) + end + return report +end + +function write_report(words::Vector{UInt64},fd::Cint=Cint(1)) + byte_count = sizeof(UInt64)*length(words) + written = GC.@preserve words ccall(:write,Clong,(Cint,Ptr{UInt8},Csize_t), + fd,Ptr{UInt8}(pointer(words)),byte_count) + return written == byte_count +end + +# A separate bounded report retains every neighbour's final values and all +# twelve scientific output histories. No sample is discarded or averaged. +function neighbour_report(state,timings) + report=UInt64[0x4e45494748424f52,UInt64(state.neighbours)] + for r in state.records[2:end] + push!(report,UInt64(r.id),UInt64(r.leaves[1]),UInt64(r.leaves[2])) + for value in values(palm_values(r.palm)) + push!(report,pack(value)) + end + for leaf in r.leaf, value in values(leaf_values(leaf)) + push!(report,pack(value)) + end + append_history!(report,state.simulation,:palm_supply,r.id,:supply,Float32) + append_history!(report,state.simulation,:palm_carbon,r.id,:carbon,Float32) + append_history!(report,state.simulation,:palm_carbon,r.id,:reserve,Float32) + append_history!(report,state.simulation,:palm_carbon,r.id,:leaf_count,Int64) + for id in r.leaves + append_history!(report,state.simulation,:leaf_assimilation,id,:assimilation,Float32) + append_history!(report,state.simulation,:leaf_assimilation,id,:water_seen,Float32) + append_history!(report,state.simulation,:leaf_assimilation,id,:previous_seen,Float32) + append_history!(report,state.simulation,:leaf_assimilation,id,:visits,Int64) + end + end + # The last six words are a tag plus five UInt64 nanosecond durations. + push!(report,0x50484153454e5343) + for elapsed in values(timings) + push!(report,elapsed) + end + return report +end + +function (@main)(args) + length(args)==1 || return 2 + neighbours=parse(Int,args[1]) + neighbours in (0,100) || return 2 + result=native_run!(STATE,neighbours) + result.ok || return 1 + write_report(a_report(result.state,neighbours)) || return 3 + return write_report(neighbour_report(result.state,result.timings),Cint(2)) ? 0 : 3 +end + +end diff --git a/test/fixtures/local_palm_leaf_birth/src/fixture.jl b/test/fixtures/local_palm_leaf_birth/src/fixture.jl new file mode 100644 index 000000000..0edaba979 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/fixture.jl @@ -0,0 +1,257 @@ +module LocalPalmLeafBirth + +import PlantSimEngine as PSE +using Dates: Day + +export make_scene, prepare_scene, register_leaf!, refresh_zero!, ordinary_step! +export palm_id, leaf_ids, palm_values, leaf_values, record_values, expected_assimilation +export acquire_neighbours!, native_run! + +PSE.@process "local_birth_water_supply" verbose=false +PSE.@process "local_birth_leaf_assimilation" verbose=false +PSE.@process "local_birth_palm_carbon" verbose=false + +struct PalmSupply{T} <: AbstractLocal_Birth_Water_SupplyModel end +struct LeafAssimilation{T} <: AbstractLocal_Birth_Leaf_AssimilationModel + efficiency::T + memory::T +end +struct PalmCarbon{T} <: AbstractLocal_Birth_Palm_CarbonModel end + +PSE.inputs_(::PalmSupply{T}) where {T} = (soil_water=PSE.Required(T),) +PSE.outputs_(::PalmSupply{T}) where {T} = (supply=zero(T),) +PSE.inputs_(::LeafAssimilation{T}) where {T} = + (area=PSE.Required(T), water=PSE.Required(T), previous_assimilation=PSE.Default(zero(T))) +PSE.outputs_(::LeafAssimilation{T}) where {T} = + (assimilation=zero(T), water_seen=zero(T), previous_seen=zero(T), visits=Int64(0)) +PSE.environment_inputs_(::LeafAssimilation{T}) where {T} = (par=zero(T),) +PSE.inputs_(::PalmCarbon{T}) where {T} = (leaf_assimilations=PSE.Default(T[]),) +PSE.outputs_(::PalmCarbon{T}) where {T} = + (carbon=zero(T), reserve=zero(T), leaf_count=Int64(0)) + +const WATER = PSE.VariableContract(unit=:fraction, basis=:palm, + temporal=:instantaneous, aggregation=:state, extent=:intensive) +const AREA = PSE.VariableContract(unit=:m2, basis=:leaf, + temporal=:instantaneous, aggregation=:state, extent=:extensive) +const LEAF_CARBON = PSE.VariableContract(unit=:illustrative_carbon, basis=:leaf, + temporal=:instantaneous, aggregation=:state, extent=:extensive) +const PALM_CARBON = PSE.VariableContract(unit=:illustrative_carbon, basis=:palm, + temporal=:instantaneous, aggregation=:total, extent=:extensive) +PSE.variable_contracts_(::PalmSupply) = (soil_water=WATER, supply=WATER) +PSE.variable_contracts_(::LeafAssimilation) = + (area=AREA, water=WATER, previous_assimilation=LEAF_CARBON, + assimilation=LEAF_CARBON, water_seen=WATER, previous_seen=LEAF_CARBON) +PSE.variable_contracts_(::PalmCarbon) = + (leaf_assimilations=LEAF_CARBON, carbon=PALM_CARBON, reserve=PALM_CARBON) + +function PSE.run!(::PalmSupply, status, environment, constants, context) + status.supply = status.soil_water + return nothing +end +function PSE.run!(model::LeafAssimilation, status, environment, constants, context) + status.water_seen = status.water + status.previous_seen = status.previous_assimilation + status.assimilation = status.area * status.water * environment.par * model.efficiency + + model.memory * status.previous_assimilation + status.visits += 1 + return nothing +end +function PSE.run!(::PalmCarbon, status, environment, constants, context) + status.carbon = sum(status.leaf_assimilations; init=zero(status.carbon)) + status.reserve += status.carbon + status.leaf_count = length(status.leaf_assimilations) + return nothing +end + +palm_id(index::Integer) = index == 0 ? Int64(1) : Int64(1000 + 10index) +leaf_ids(index::Integer) = index == 0 ? (Int64(2), Int64(3)) : + (palm_id(index) + 1, palm_id(index) + 2) +const NEW_LEAF = Int64(4) + +palm_cells(::Type{T}, soil) where {T} = + (soil_water=Ref(T(soil)), supply=Ref(zero(T)), carbon=Ref(zero(T)), + reserve=Ref(zero(T)), leaf_count=Ref(Int64(0))) +leaf_cells(::Type{T}, area) where {T} = + (area=Ref(T(area)), water=Ref(zero(T)), previous_assimilation=Ref(zero(T)), + assimilation=Ref(zero(T)), water_seen=Ref(zero(T)), previous_seen=Ref(zero(T)), + visits=Ref(Int64(0))) + +function record(index::Integer, ::Type{T}) where {T} + soil = index == 0 ? T(3) / T(4) : T(1) / T(2) + T(index) / T(512) + areas = index == 0 ? (T(1), T(1) / T(2)) : + (T(1) / T(2) + T(mod(index, 4)) / T(8), + T(1) / T(4) + T(mod(index, 3)) / T(16)) + return (index=Int(index), id=palm_id(index), leaves=leaf_ids(index), + palm=palm_cells(T, soil), leaf=(leaf_cells(T, areas[1]), leaf_cells(T, areas[2]))) +end + +"""A structural carbon-flow fixture, not a calibrated palm physiology model. + +Every leaf reads only its direct Palm ancestor, its own previous assimilation, +and a common immutable environment. Every Palm sums only its own subtree. +A and its new leaf have identical IDs, initial cells and parameters for any +number of independent neighbouring palms. No selector spans the forest. +""" +function make_scene(neighbours::Integer; T::Type{<:AbstractFloat}=Float32) + neighbours >= 0 || throw(ArgumentError("neighbours must be nonnegative")) + records = [record(index, T) for index in 0:neighbours] + objects = PSE.Object[PSE.Object(Int64(0); scale=:Forest, kind=:forest)] + for r in records + push!(objects, PSE.Object(r.id; scale=:Palm, kind=:plant, + species=:Elaeis_guineensis, name=r.index == 0 ? "A" : "neighbour_$(r.index)", + parent=Int64(0), status=PSE.Status(r.palm))) + for k in 1:2 + push!(objects, PSE.Object(r.leaves[k]; scale=:Leaf, kind=:leaf, + species=:Elaeis_guineensis, parent=r.id, status=PSE.Status(r.leaf[k]))) + end + end + model = PSE.CompositeModel(objects...; applications=( + PSE.ModelSpec(PalmSupply{T}(); name=:palm_supply, on=PSE.Many(scale=:Palm), + inputs=(soil_water=PSE.One(within=PSE.Self(), from_status=true, var=:soil_water),)), + PSE.ModelSpec(LeafAssimilation(T(1) / T(8), T(1) / T(8)); + name=:leaf_assimilation, on=PSE.Many(scale=:Leaf), + inputs=(:area => PSE.One(within=PSE.Self(), from_status=true, var=:area), + :water => PSE.One(within=PSE.Ancestor(scale=:Palm), scale=:Palm, + application=:palm_supply, var=:supply), + PSE.PreviousTimeStep(:previous_assimilation) => PSE.One(within=PSE.Self(), + application=:leaf_assimilation, var=:assimilation))), + PSE.ModelSpec(PalmCarbon{T}(); name=:palm_carbon, on=PSE.Many(scale=:Palm), + inputs=(leaf_assimilations=PSE.Many(within=PSE.Subtree(), scale=:Leaf, + application=:leaf_assimilation, var=:assimilation),)), + ), environment=(duration=Day(1), par=T(8))) + newborn = leaf_cells(T, T(1) / T(4)) + object = PSE.Object(NEW_LEAF; scale=:Leaf, kind=:leaf, species=:Elaeis_guineensis, + parent=palm_id(0), status=PSE.Status(newborn)) + return (model=model, records=records, newborn=newborn, newborn_object=object, + neighbours=Int(neighbours)) +end + +prepare_scene(scene; performance=false) = + (; scene..., simulation=PSE.run!(scene.model; steps=0, outputs=:all, performance)) +"""Acquire runtime neighbours before the control trajectory, using ordinary growth. + +The initial prepared state contains A alone. Neither the count nor the resulting +objects are embedded in a specialised simulation type. The same helper is used +by the ordinary control and by one compiled executable with a runtime count. +""" +function acquire_neighbours!(state, neighbours::Integer) + neighbours >= 0 || throw(ArgumentError("neighbours must be nonnegative")) + length(state.records) == 1 && PSE.current_step(state.simulation) == 0 || + throw(ArgumentError("Acquire neighbours once, before the first step.")) + model = PSE.runtime_model(state.simulation) + T = typeof(first(state.records).palm.soil_water[]) + for index in 1:neighbours + r = record(index,T) + PSE.register_object!(model,PSE.Object(r.id;scale=:Palm,kind=:plant, + species=:Elaeis_guineensis,name="neighbour",parent=Int64(0),status=PSE.Status(r.palm))) + for k in 1:2 + PSE.register_object!(model,PSE.Object(r.leaves[k];scale=:Leaf,kind=:leaf, + species=:Elaeis_guineensis,parent=r.id,status=PSE.Status(r.leaf[k]))) + end + push!(state.records,r) + end + PSE.continue!(state.simulation;steps=0) + return (; state...,neighbours=Int(neighbours)) +end + +register_leaf!(state) = PSE.register_object!(PSE.runtime_model(state.simulation), state.newborn_object) +# Public zero-step continuation follows the ordinary dynamic refresh boundary. +# It refreshes bindings/cohorts/retention/requests but executes no scientific step. +refresh_zero!(state) = PSE.continue!(state.simulation; steps=0) +ordinary_step!(state) = PSE.step!(state.simulation) + +palm_values(c) = (soil_water=c.soil_water[], supply=c.supply[], carbon=c.carbon[], + reserve=c.reserve[], leaf_count=c.leaf_count[]) +leaf_values(c) = (area=c.area[], assimilation=c.assimilation[], water_seen=c.water_seen[], + previous_seen=c.previous_seen[], visits=c.visits[]) +record_values(r) = (id=r.id, leaves=r.leaves, palm=palm_values(r.palm), + leaf=(leaf_values(r.leaf[1]), leaf_values(r.leaf[2]))) + +# Independent recurrence: no model kernel, binding or history supplies expected values. +function expected_assimilation(area, water, steps) + value, previous = zero(area), zero(area) + for _ in 1:steps + previous = value + value = area * water * 8f0 * 0.125f0 + 0.125f0 * previous + end + return (; value, previous) +end + +function _all_record_values_ok(state) + day = PSE.current_step(state.simulation) + for record in state.records + water = record.palm.soil_water[] + expected = map(cell -> expected_assimilation(cell.area[], water, day), record.leaf) + for index in 1:2 + cell = record.leaf[index] + leaf_values(cell) == (area=cell.area[], assimilation=expected[index].value, + water_seen=water, previous_seen=expected[index].previous, + visits=Int64(day)) || return false + end + born = record.index == 0 + newborn = born ? expected_assimilation(state.newborn.area[], water, day - 3) : nothing + carbon = expected[1].value + expected[2].value + (born ? newborn.value : 0f0) + reserve = zero(water) + for tick in 1:day + daily = expected_assimilation(record.leaf[1].area[], water, tick).value + + expected_assimilation(record.leaf[2].area[], water, tick).value + if born && tick >= 4 + daily += expected_assimilation(state.newborn.area[], water, tick - 3).value + end + reserve += daily + end + palm_values(record.palm) == (soil_water=water, supply=water, carbon=carbon, + reserve=reserve, leaf_count=Int64(born ? 3 : 2)) || return false + if born + leaf_values(state.newborn) == (area=state.newborn.area[], + assimilation=newborn.value, water_seen=water, + previous_seen=newborn.previous, visits=Int64(day - 3)) || return false + end + end + return true +end + +"""Run the same acquisition and local birth in ordinary and native modes. + +The five nanosecond intervals exclude observations. Construction/preparation of +A occurs separately on the host, before this runtime action. +""" +function native_run!(initial, neighbours::Integer) + started = time_ns() + state = acquire_neighbours!(initial, neighbours) + acquisition_ns = time_ns() - started + + started = time_ns() + for _ in 1:3 + ordinary_step!(state) + end + warmup_ns = time_ns() - started + + neighbours_before = [record_values(record) for record in state.records[2:end]] + a_before = record_values(first(state.records)) + step_before = PSE.current_step(state.simulation) + + started = time_ns() + register_leaf!(state) + registration_ns = time_ns() - started + + started = time_ns() + refresh_zero!(state) + refresh_ns = time_ns() - started + + unchanged = PSE.current_step(state.simulation) == step_before && + record_values(first(state.records)) == a_before + for index in 2:length(state.records) + unchanged &= record_values(state.records[index]) == neighbours_before[index - 1] + end + + started = time_ns() + ordinary_step!(state) + ordinary_after_birth_ns = time_ns() - started + + valid = unchanged && _all_record_values_ok(state) + timings = (acquisition_ns, warmup_ns, registration_ns, refresh_ns, ordinary_after_birth_ns) + return (; state, ok=valid, timings) +end + +end # module diff --git a/test/fixtures/local_palm_leaf_birth/src/prepare.jl b/test/fixtures/local_palm_leaf_birth/src/prepare.jl new file mode 100644 index 000000000..e0d81d684 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/prepare.jl @@ -0,0 +1,114 @@ +module LocalPalmLeafBirthPreparation + +import PlantSimEngine as PSE +using ..LocalPalmLeafBirth +using ..NativePreparation: close_registry, RuntimeTypes, InputTrace, remember!, batch_schema + +const APPLICATION_IDS = (:palm_supply, :leaf_assimilation, :palm_carbon) + +# Preparation alone closes the actual registry's ID family. All canonical +# objects, status owners, references, and authored applications are retained. +function prepare(scene; environment_schema, input_binding_storage=nothing, status_view_schema=nothing) + model = close_registry(scene.model) + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:all, + constants=PSE.Constants(), environment_schema, input_binding_storage, status_view_schema) + return (; scene..., model, simulation) +end + +# Host observations are outside the runtime payload. They retain each palm and +# leaf value, ordered history, newborn value, and all canonical biological cells. +function snapshot(state) + return (step=PSE.current_step(state.simulation), + records=map(record_values,state.records), newborn=leaf_values(state.newborn), + histories=Dict(key=>deepcopy(collect(stream)) for (key,stream) in pairs(PSE.outputs(state.simulation)))) +end +function cells(state) + result = Any[] + for record in state.records + append!(result,values(record.palm)) + for leaf in record.leaf + append!(result,values(leaf)) + end + end + return result +end +function advance_host!(state,neighbours; observe_batch=(state->nothing)) + observe_batch(state) + state = acquire_neighbours!(state,neighbours) + observations = [snapshot(state)] + references = cells(state) + observe_batch(state) + for _ in 1:3 + ordinary_step!(state) + observe_batch(state) + push!(observations,snapshot(state)) + end + before = record_values(first(state.records)) + neighbours = map(record_values,state.records[2:end]) + register_leaf!(state) + refresh_zero!(state) + observe_batch(state) + PSE.current_step(state.simulation) == 3 || error("Refresh advanced the timeline.") + record_values(first(state.records)) == before || error("Birth advanced A's biology.") + map(record_values,state.records[2:end]) == neighbours || error("Birth changed a neighbour.") + all(a===b for (a,b) in zip(references,cells(state))) || error("Birth replaced a canonical cell.") + push!(observations,snapshot(state)) + ordinary_step!(state) + observe_batch(state) + push!(observations,snapshot(state)) + return observations +end + +"""Prepare the same fresh local-birth scene using only host-observed families. + +All training runs execute the original shared register!/refresh/step! actions. +No trajectory that was used to collect schemas becomes the native payload. +""" +function prepare_native_scene() + # The real 100-neighbour acquisition admits the same families as runtime 0. + neighbours = 100 + baseline = advance_host!(prepare_scene(make_scene(0)),neighbours) + observed = RuntimeTypes() + input_trace = InputTrace(observed) + collected = PSE._collecting_environment_binding_schema() + recording = prepare(make_scene(0); environment_schema=collected, + input_binding_storage=input_trace,status_view_schema=observed) + advance_host!(recording,neighbours) == baseline || error("Recording changed state/history.") + isempty(input_trace) || error("Input prototype was mutated.") + all(B -> isconcretetype(B) && B <: PSE.CompiledModelInputBinding,observed.inputs) || + error("Invalid input-binding family.") + input_prototype = Vector{Union{observed.inputs...}}() + views = PSE.CompiledMetadataTable(NamedTuple{APPLICATION_IDS}(map(APPLICATION_IDS) do id + types = observed.views[id] + all(V -> isconcretetype(V) && V <: PSE.CompiledModelStatusView,types) || error("Invalid view family.") + Vector{Union{types...}}() + end)) + environment_schema = PSE._freeze_environment_binding_schema(collected) + finite = prepare(make_scene(0);environment_schema, + input_binding_storage=input_prototype,status_view_schema=views) + batches = Dict(id=>DataType[] for id in APPLICATION_IDS) + function observe_batches(state) + simulation = state.simulation + simulation.compiled.input_bindings isa Vector && + eltype(simulation.compiled.input_bindings) === eltype(input_prototype) || error("Lost finite input owner.") + simulation.compiled.status_view_schema === views && all(isempty,values(views)) || error("Lost view admission.") + simulation.environment_bindings.environment_schema === environment_schema || error("Lost environment admission.") + isempty(input_prototype) || error("Finite input prototype was mutated.") + for group in simulation.execution_plan.groups, batch in group.batches + remember!(batches[batch.application.id],typeof(batch)) + end + return nothing + end + advance_host!(finite,neighbours;observe_batch=observe_batches) == baseline || error("Finite owners changed state/history.") + schemas = NamedTuple{APPLICATION_IDS}(map(id->batch_schema(batches[id]),APPLICATION_IDS)) + final = prepare(make_scene(0);environment_schema, + input_binding_storage=input_prototype,status_view_schema=views) + simulation = PSE._prepare_execution_batch_schemas(final.simulation,schemas) + state = (; final...,simulation) + snapshot(state) == snapshot(prepare_scene(make_scene(0))) || error("Final pristine initial state/history changed.") + length(state.records)==1 && length(collect(PSE.model_objects(state.model)))==4 || error("Native payload must contain A alone.") + PSE.current_step(simulation) == 0 || error("Preparation advanced the final scene.") + return state +end + +end # module diff --git a/test/integration/fixtures/distributed_producer_birth/Project.toml b/test/integration/fixtures/distributed_producer_birth/Project.toml new file mode 100644 index 000000000..812ae9a60 --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/Project.toml @@ -0,0 +1,12 @@ +name = "PSEThirtyProducerControl" +uuid = "3c96ca4e-58bc-4f40-935b-d8fae20d6519" +version = "0.1.0" + +[deps] +PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" + +[sources] +PlantSimEngine = {path = "../../../.."} + +[compat] +julia = "1.13" diff --git a/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl new file mode 100644 index 000000000..919a97704 --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl @@ -0,0 +1,17 @@ +module PSEThirtyProducerControl +import PlantSimEngine as PSE +include("native_preparation.jl") +using .NativePreparation: close_registry, RuntimeTypes, InputTrace, remember!, batch_schema +include("distributed_growth.jl") +include("prepare.jl") +const STATE = prepare_control() +function (@main)(args) + isempty(args) || return Cint(2) + checkpoint(STATE, 0) || return Cint(10) + for day in 1:3 + PSE.step!(STATE.simulation) + checkpoint(STATE, day) || return Cint(10 + day) + end + return Cint(0) +end +end diff --git a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl new file mode 100644 index 000000000..6245e43eb --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl @@ -0,0 +1,104 @@ +# Host preparation only: one public scenario, actual finite core owners. +const APPLICATION_IDS = (:birth, :producer) +function state_for(simulation) + ids = DistributedGrowthFixture.producer_birth_leaf_ids() + S = typeof(PSE.model_status(simulation, first(ids))) + leaves = S[PSE.model_status(simulation, id)::S for id in ids] + ordinals = Base.RefValue{Int}[PSE.refvalue(status, :ordinal) for status in leaves] + objects = PSE.Object[PSE.model_object(simulation, id) for id in ids] + return (; simulation, ids, leaves, ordinals, objects, + signals=Base.RefValue{Float32}[], streams=Vector{Tuple{Float64,Float32}}[]) +end + +# Individual public observations, not an aggregate or a second execution path. +function checkpoint(state, day) + sim, model = state.simulation, state.simulation.model + PSE.current_step(sim) == day || return false + length(state.ids) == 30 || return false + length(PSE.model_objects(model; scale=:Leaf)) == 30 || return false + length(model.registry.objects) == 31 + Int(day >= 2) || return false + haskey(model.registry.objects, PSE.ObjectId(:emitter)) == (day >= 2) || return false + for index in eachindex(state.ids) + id, status = state.ids[index], state.leaves[index] + object = PSE.model_object(model, id) + object === state.objects[index] && object.scale === :Leaf || return false + PSE.refvalue(status, :ordinal) === state.ordinals[index] || return false + status.ordinal == index || return false + reference = PSE._initial_status_reference(status, :signal) + stream = get(PSE.outputs(sim), (:producer, id, :signal), nothing) + if day < 2 + isnothing(reference) || return false + (isnothing(stream) || (stream isa Vector{Tuple{Float64,Float32}} && isempty(stream))) || return false + else + reference isa Base.RefValue{Float32} || return false + reference[] === Float32(20day) || return false + stream isa Vector{Tuple{Float64,Float32}} || return false + stream = stream::Vector{Tuple{Float64,Float32}} + length(stream) == day - 1 || return false + for sample in eachindex(stream) + stream[sample] === (Float64(sample + 1), Float32(20(sample + 1))) || return false + end + if day == 2 + push!(state.signals, reference) + push!(state.streams, stream) + else + reference === state.signals[index] || return false + stream === state.streams[index] || return false + end + end + end + return true +end + +function advance_host!(state; observe=(_ -> nothing)) + checkpoint(state, 0) || error("Thirty initial individual checkpoints changed.") + observe(state.simulation) + for day in 1:3 + PSE.step!(state.simulation) + checkpoint(state, day) || error("Thirty individual values/history changed at step $day.") + observe(state.simulation) + end + return nothing +end + +function prepare_control() + # The public ordinary maintained test is independently executed by the host gate. + baseline = state_for(PSE.run!(DistributedGrowthFixture.make_producer_birth_model(); + steps=0, outputs=:all)) + advance_host!(baseline) + observed = RuntimeTypes() + input_trace = InputTrace(observed) + environment = PSE._collecting_environment_binding_schema() + recording = PSE._prepare_simulation!(close_registry(DistributedGrowthFixture.make_producer_birth_model()); + steps=0, outputs=:all, constants=PSE.Constants(), environment_schema=environment, + input_binding_storage=input_trace, status_view_schema=observed) + advance_host!(state_for(recording)) + isempty(input_trace) || error("Input prototype was mutated.") + all(T -> isconcretetype(T) && T <: PSE.CompiledModelInputBinding, observed.inputs) || error("Invalid actual input evidence.") + prototype = Vector{Union{observed.inputs...}}() + schema = PSE.CompiledMetadataTable(NamedTuple{APPLICATION_IDS}(map(APPLICATION_IDS) do id + types = observed.views[id] + all(T -> isconcretetype(T) && T <: PSE.CompiledModelStatusView, types) || error("Invalid actual view evidence.") + Vector{Union{types...}}() + end)) + environment = PSE._freeze_environment_binding_schema(environment) + prepare() = PSE._prepare_simulation!(close_registry(DistributedGrowthFixture.make_producer_birth_model()); + steps=0, outputs=:all, constants=PSE.Constants(), environment_schema=environment, + input_binding_storage=prototype, status_view_schema=schema) + finite = prepare() + batches = Dict(id => DataType[] for id in APPLICATION_IDS) + function observe_batches(sim) + sim.compiled.input_bindings isa Vector{eltype(prototype)} || error("Lost finite input owner.") + sim.compiled.status_view_schema === schema || error("Lost finite view owner.") + for group in sim.execution_plan.groups, batch in group.batches + types = batches[batch.application.id] + remember!(types, typeof(batch)) + end + end + advance_host!(state_for(finite); observe=observe_batches) + schemas = NamedTuple{APPLICATION_IDS}(map(id -> batch_schema(batches[id]), APPLICATION_IDS)) + simulation = PSE._prepare_execution_batch_schemas(prepare(), schemas) + state = state_for(simulation) + checkpoint(state, 0) || error("Final native scene was advanced or changed.") + return state +end diff --git a/test/integration/native_fixture_apps.jl b/test/integration/native_fixture_apps.jl new file mode 100644 index 000000000..86de54060 --- /dev/null +++ b/test/integration/native_fixture_apps.jl @@ -0,0 +1,50 @@ +module NativeFixtureApps +import PlantSimEngine as PSE +import TOML +export stage_native_fixture + +"""Stage a self-contained test app from canonical source files. + +Project.toml, src and an optional Manifest.toml are copied. Source paths resolve against the original +project, and PSE is the package actually loaded by this integration test. +""" +function stage_native_fixture(template; fixture_sources=()) + template = abspath(template) + directory = mktempdir(; prefix="pse-native-fixture-") + app = joinpath(directory, "app") + mkpath(app) + cp(joinpath(template, "src"), joinpath(app, "src")) + cp(joinpath(@__DIR__, "native_preparation.jl"), + joinpath(app, "src", "native_preparation.jl")) + for (source, name) in fixture_sources + basename(name) == name || throw(ArgumentError("A staged fixture needs a source filename.")) + cp(source, joinpath(app, "src", name)) + end + project = TOML.parsefile(joinpath(template, "Project.toml")) + sources = get!(Dict{String,Any}, project, "sources") + for source in values(sources) + haskey(source, "path") || continue + source["path"] = abspath(joinpath(template, source["path"])) + end + sources["PlantSimEngine"] = Dict("path" => realpath(pkgdir(PSE))) + open(joinpath(app, "Project.toml"), "w") do io + TOML.print(io, project) + end + manifest = joinpath(template, "Manifest.toml") + if isfile(manifest) + lock = TOML.parsefile(manifest) + for entries in values(lock["deps"]), entry in entries + if entry["uuid"] == project["deps"]["PlantSimEngine"] + entry["path"] = realpath(pkgdir(PSE)) + elseif haskey(entry, "path") + entry["path"] = entry["uuid"] == project["uuid"] ? app : + abspath(joinpath(template, entry["path"])) + end + end + open(joinpath(app, "Manifest.toml"), "w") do io + TOML.print(io, lock) + end + end + return app +end +end # module diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl new file mode 100644 index 000000000..10ff96b6d --- /dev/null +++ b/test/integration/native_growth.jl @@ -0,0 +1,80 @@ +# Separate from the short public native_compilation.jl runner and its 15-minute budget. +# Run in the same PSE/JuliaC environment, with builds performed sequentially. +using PlantSimEngine, JuliaC, Test, SHA +include("native_fixture_apps.jl") +using .NativeFixtureApps + +const _growth_root = pkgdir(PlantSimEngine) +const _palm_growth_app = stage_native_fixture(joinpath(_growth_root, + "test", "fixtures", "local_palm_leaf_birth")) +const _producer_growth_app = stage_native_fixture(joinpath(_growth_root, + "test", "integration", "fixtures", "distributed_producer_birth"); + fixture_sources=(joinpath(_growth_root, "test", "fixtures", "distributed_growth.jl") => "distributed_growth.jl",)) +# App modules and all preparation methods exist before entering the testset. +Base.include(@__MODULE__, joinpath(_palm_growth_app, "src", "PSELocalPalmLeafBirth.jl")) +Base.include(@__MODULE__, joinpath(_producer_growth_app, "src", "PSEThirtyProducerControl.jl")) + +function _split_neighbour_report(words) + length(words) >= 8 || error("Incomplete native neighbour report.") + words[end-5] == 0x50484153454e5343 || error("Missing native phase timing tag.") + names = (:acquisition, :warmup3, :register, :refresh0, :postbirth_step) + return (neighbours=words[1:end-6], + timings_ns=NamedTuple{names}(Tuple(words[end-4:end]))) +end + +function _ordinary_palm_growth_report(neighbours) + fixture = PSELocalPalmLeafBirth.LocalPalmLeafBirth + initial = fixture.prepare_scene(fixture.make_scene(0)) + result = fixture.native_run!(initial, neighbours) + result.ok || error("The ordinary public palm control failed.") + report = _split_neighbour_report(PSELocalPalmLeafBirth.neighbour_report(result.state, result.timings)) + return (; a=PSELocalPalmLeafBirth.a_report(result.state, neighbours), report...) +end + +function _native_palm_growth_report(executable, neighbours, directory) + stdout_path = joinpath(directory, "palm-$(neighbours)-stdout.bin") + stderr_path = joinpath(directory, "palm-$(neighbours)-stderr.bin") + open(stdout_path, "w") do stdout_io + open(stderr_path, "w") do stderr_io + # Exactly one process for each count, using the same executable. + run(pipeline(`$executable $neighbours`; stdout=stdout_io, stderr=stderr_io)) + end + end + stdout_bytes, stderr_bytes = read(stdout_path), read(stderr_path) + length(stdout_bytes) % sizeof(UInt64) == 0 || error("Invalid native A report.") + length(stderr_bytes) % sizeof(UInt64) == 0 || error("Invalid native neighbour report.") + a = copy(reinterpret(UInt64, stdout_bytes)) + report = _split_neighbour_report(copy(reinterpret(UInt64, stderr_bytes))) + return (; a, report...) +end + +@testset "Native growth preserves local palms and thirty distributed destinations" begin + mktempdir() do directory + expected_zero = _ordinary_palm_growth_report(0) + expected_hundred = _ordinary_palm_growth_report(100) + # Header counts differ; A's timestep, values and sixteen histories do not. + @test expected_zero.a[5:end] == expected_hundred.a[5:end] + palm = Compilation.compile(_palm_growth_app; destination=joinpath(directory, "palm")) + @test isfile(palm.executable) + digest = sha256(read(palm.executable)) + zero = _native_palm_growth_report(palm.executable, 0, directory) + hundred = _native_palm_growth_report(palm.executable, 100, directory) + @test sha256(read(palm.executable)) == digest + @test zero.a == expected_zero.a + @test hundred.a == expected_hundred.a + @test zero.a[5:end] == hundred.a[5:end] + @test zero.neighbours == expected_zero.neighbours + @test hundred.neighbours == expected_hundred.neighbours + # Durations are observations, with no threshold or cross-process equality. + @info "Native palm phases (nanoseconds)" neighbours=0 phases=zero.timings_ns + @info "Native palm phases (nanoseconds)" neighbours=100 phases=hundred.timings_ns + + @test PSEThirtyProducerControl.checkpoint(PSEThirtyProducerControl.STATE, 0) + @test PSEThirtyProducerControl.main(String[]) == 0 + producer = Compilation.compile(_producer_growth_app; + destination=joinpath(directory, "producer")) + @test isfile(producer.executable) + # main checks every destination, every sample, and the same cells/streams. + @test success(`$(producer.executable)`) + end +end diff --git a/test/integration/native_preparation.jl b/test/integration/native_preparation.jl new file mode 100644 index 000000000..47801a7eb --- /dev/null +++ b/test/integration/native_preparation.jl @@ -0,0 +1,79 @@ +module NativePreparation +import PlantSimEngine as PSE +export close_registry, RuntimeTypes, InputTrace, remember!, batch_schema + +function close_registry(model) + previous = model.registry + manifest = PSE._scenario_preparation(model).status_manifest + for object in PSE.model_objects(model) + status = PSE.model_status(model, object) + (status === nothing || typeof(status) === manifest.status_type) || + error("Fresh objects lost the prepared canonical Status owner.") + status === object.status || error("The facade lost its canonical status.") + end + store = PSE._closed_object_family_store(previous.objects) + store.catalog.status_manifest === manifest || error("Registry closure changed the manifest.") + registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + # Build-time reconstruction retains every field of this exact model. + return PSE.CompositeModel(registry, + (getfield(model, index) for index in 2:fieldcount(typeof(model)))...) +end + +mutable struct RuntimeTypes + inputs::Vector{DataType} + views::Dict{Symbol,Vector{DataType}} +end +RuntimeTypes() = RuntimeTypes(DataType[], Dict{Symbol,Vector{DataType}}()) +remember!(pool, T) = (T in pool || push!(pool, T); nothing) +struct InputTrace <: AbstractVector{PSE.CompiledModelInputBinding} + data::Vector{PSE.CompiledModelInputBinding} + observed::RuntimeTypes +end +InputTrace(observed) = InputTrace(PSE.CompiledModelInputBinding[], observed) +Base.IndexStyle(::Type{InputTrace}) = IndexLinear() +Base.size(values::InputTrace) = size(values.data) +Base.getindex(values::InputTrace, index::Int) = values.data[index] +function Base.setindex!(values::InputTrace, binding, index::Int) + remember!(values.observed.inputs, typeof(binding)); values.data[index] = binding; return values +end +function Base.push!(values::InputTrace, binding) + remember!(values.observed.inputs, typeof(binding)); push!(values.data, binding); return values +end +function Base.insert!(values::InputTrace, index::Integer, binding) + remember!(values.observed.inputs, typeof(binding)); insert!(values.data, index, binding); return values +end +Base.append!(values::InputTrace, bindings) = (foreach(binding -> push!(values, binding), bindings); values) +Base.similar(values::InputTrace, n::Integer) = + InputTrace(Vector{PSE.CompiledModelInputBinding}(undef, n), values.observed) +function Base.similar(values::InputTrace, ::Type{T}, dims::Dims{1}) where {T} + T === PSE.CompiledModelInputBinding || error("Preserve the input trace element contract.") + return similar(values, only(dims)) +end +Base.copy(values::InputTrace) = InputTrace(copy(values.data), values.observed) +Base.empty!(values::InputTrace) = (empty!(values.data); values) +Base.resize!(values::InputTrace, n::Integer) = (resize!(values.data, n); values) +Base.sizehint!(values::InputTrace, n::Integer) = (sizehint!(values.data, n); values) +Base.deleteat!(values::InputTrace, indices) = (deleteat!(values.data, indices); values) +PSE._construct_model_status_view(::RuntimeTypes, application::Symbol, parts) = + PSE._construct_model_status_view(nothing, application, parts) +function PSE._admit_model_status_view!(observed::RuntimeTypes, application::Symbol, view) + remember!(get!(Vector{DataType}, observed.views, application), typeof(view)); return view +end +function PSE._with_model_status_view(f::F, ::RuntimeTypes, application::Symbol, + view, args::Vararg{Any,N}) where {F,N} + return f(view, args...) +end +function PSE._with_temporal_copy_payloads(f::F, ::RuntimeTypes, binding, status, + args::Vararg{Any,N}) where {F,N} + return f(nothing, binding, status, args...) +end + + +function batch_schema(types) + isempty(types) && error("Missing actual finite-owner batch evidence.") + all(B -> isconcretetype(B) && B <: PSE.CompiledExecutionBatch,types) || error("Not real batch types.") + return PSE.PreparedExecutionBatchSchema{Vector{Union{types...}}}() +end + +end # module diff --git a/test/test-model-local-leaf-birth.jl b/test/test-model-local-leaf-birth.jl new file mode 100644 index 000000000..51a2c02c1 --- /dev/null +++ b/test/test-model-local-leaf-birth.jl @@ -0,0 +1,156 @@ +module LocalLeafBirthChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine +include(joinpath(@__DIR__, "fixtures", "local_palm_leaf_birth", "src", "fixture.jl")) +using .LocalPalmLeafBirth + +const BIOLOGICAL_FIELDS = (:soil_water, :supply, :carbon, :reserve, :leaf_count, + :area, :assimilation, :water_seen, :previous_seen, :visits) + +function retained_history(simulation, ids) + return Dict(key => deepcopy(collect(stream)) for (key, stream) in outputs(simulation) + if key[2].value in ids) +end + +function snapshot(state, ids) + simulation = state.simulation + topology = Dict(id => let object = model_object(simulation, id) + (parent=isnothing(object.parent) ? nothing : object.parent.value, + children=[child.value for child in object.children], scale=object.scale, + kind=object.kind, species=object.species, name=object.name) + end for id in ids) + return (step=current_step(simulation), topology=topology, + states=Dict(id => final_state(simulation, id) for id in ids), + history=retained_history(simulation, ids)) +end + +function biological_references(state, ids) + return [(id=id, variable=name, + reference=PSE.refvalue(model_status(state.simulation, id), name)) + for id in ids for name in keys(model_status(state.simulation, id)) + if name in BIOLOGICAL_FIELDS] +end + +references_match(state, previous) = all(previous) do entry + PSE.refvalue(model_status(state.simulation, entry.id), entry.variable) === entry.reference +end + +function numeric_mismatches(state; born=false) + day = current_step(state.simulation) + mismatches = Int64[] + for record in state.records + water = record.palm.soil_water[] + expected = map(cell -> expected_assimilation(cell.area[], water, day), record.leaf) + matches = all(1:2) do index + cell, actual = record.leaf[index], expected[index] + leaf_values(cell) == (area=cell.area[], assimilation=actual.value, + water_seen=water, previous_seen=actual.previous, visits=Int64(day)) + end + newborn = born && record.index == 0 ? + expected_assimilation(state.newborn.area[], water, day - 3) : nothing + carbon = expected[1].value + expected[2].value + + (isnothing(newborn) ? 0f0 : newborn.value) + reserve = 0f0 + for tick in 1:day + contribution = expected_assimilation(record.leaf[1].area[], water, tick).value + + expected_assimilation(record.leaf[2].area[], water, tick).value + if born && record.index == 0 && tick >= 4 + contribution += expected_assimilation(state.newborn.area[], water, tick - 3).value + end + reserve += contribution + end + matches &= palm_values(record.palm) == (soil_water=water, supply=water, + carbon=carbon, reserve=reserve, leaf_count=Int64(isnothing(newborn) ? 2 : 3)) + if !isnothing(newborn) + matches &= leaf_values(state.newborn) == (area=state.newborn.area[], + assimilation=newborn.value, water_seen=water, + previous_seen=newborn.previous, visits=Int64(day - 3)) + end + matches || push!(mismatches, record.id) + end + return mismatches +end + +function selections_match(state; born=false) + model = runtime_model(state.simulation) + for record in state.records + expected = born && record.index == 0 ? [record.leaves..., Int64(4)] : collect(record.leaves) + selected = resolve_object_ids(model, Many(Subtree(); scale=:Leaf); context=record.id) + [id.value for id in selected] == expected || return false + for leaf in expected + ancestor = only(resolve_object_ids(model, + One(Ancestor(scale=:Palm); scale=:Palm); context=leaf)) + ancestor.value == record.id || return false + model_object(model, leaf).parent.value == record.id || return false + end + end + return true +end + +function check_birth(neighbours) + initial = prepare_scene(make_scene(0)) + initial_a = snapshot(initial, Int64[1, 2, 3]) + state = acquire_neighbours!(initial, neighbours) + simulation = state.simulation + @test current_step(simulation) == 0 + @test length(state.records) == neighbours + 1 + @test snapshot(state, Int64[1, 2, 3]) == initial_a + for _ in 1:3 + ordinary_step!(state) + end + @test current_step(simulation) == 3 + @test isempty(numeric_mismatches(state)) + @test selections_match(state) + ids = Int64[r.id for r in state.records] + append!(ids, (id for r in state.records for id in r.leaves)) + neighbour_ids = [id for id in ids if !(id in (Int64(1), Int64(2), Int64(3)))] + previous_neighbours = snapshot(state, neighbour_ids) + previous_a = snapshot(state, Int64[1, 2, 3]) + previous_biology = record_values(first(state.records)) + previous_refs = biological_references(state, ids) + previous_streams = Dict(key => stream for (key, stream) in outputs(simulation)) + + register_leaf!(state) + refresh_zero!(state) + @test current_step(simulation) == 3 + @test snapshot(state, neighbour_ids) == previous_neighbours + @test record_values(first(state.records)) == previous_biology + @test retained_history(simulation, Int64[1, 2, 3]) == previous_a.history + @test references_match(state, previous_refs) + @test all(outputs(simulation)[key] === stream for (key, stream) in previous_streams) + @test selections_match(state; born=true) + @test state.newborn.visits[] == 0 + # A's live Many input changes membership, while its biological cells do not advance. + carrier = model_status(simulation, Int64(1)).leaf_assimilations + expected_refs = [PSE.refvalue(model_status(simulation, id), :assimilation) for id in Int64[2, 3, 4]] + @test length(carrier) == length(parent(carrier)) == 3 + @test all(reference === expected for (reference, expected) in zip(parent(carrier), expected_refs)) + @test collect(carrier) == [first(state.records).leaf[1].assimilation[], + first(state.records).leaf[2].assimilation[], 0f0] + after_refresh_a = snapshot(state, Int64[1, 2, 3, 4]) + + ordinary_step!(state) + @test current_step(simulation) == 4 + @test isempty(numeric_mismatches(state; born=true)) + @test references_match(state, previous_refs) + @test all(outputs(simulation)[key] === stream for (key, stream) in previous_streams) + # Neighbours execute their normal fourth day, retaining their complete old prefixes. + following = snapshot(state, neighbour_ids) + @test all(previous_neighbours.history) do (key, samples) + current = following.history[key] + length(current) == length(samples) + 1 && current[1:end-1] == samples && + last(current)[2] === getproperty(following.states[key[2].value], key[3]) && + (isempty(samples) || last(current)[1] > last(samples)[1]) + end + return (before=previous_a, after_refresh=after_refresh_a, + after_step=snapshot(state, Int64[1, 2, 3, 4])) +end + +@testset "a local leaf birth preserves independent palms and previous-step inputs" begin + alone = check_birth(0) + surrounded = check_birth(100) + @test alone == surrounded +end + +end # module diff --git a/test/test_groups.jl b/test/test_groups.jl index 1f1ef7c60..e61d53509 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -8,6 +8,7 @@ const TEST_GROUPS = ( "test-object-families.jl", "test-prepared-status-registration.jl", "test-fixed-status-scope-growth.jl", + "test-model-local-leaf-birth.jl", ), "Concrete runtime object identities" => ( "test-model-concrete-object-identities.jl", From 0506b5673cb52635349124bde43ec880d71eb9ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 14:47:07 +0100 Subject: [PATCH 188/324] Keep a compact handle to each execution status snapshot --- src/component_models/Status.jl | 9 +++--- src/composite_model/status_construction.jl | 32 ++++++++++++---------- test/test-status-fixed-storage.jl | 2 ++ 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 78bbe9b8c..1454ed2a0 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -35,10 +35,10 @@ end # Kernel ports remain a dense NT. The immutable full snapshot captures the SAME # refs and presence, including private/temporal overlays, never a latest owner. -struct _ProjectedStatusStorage{N,R<:Tuple,H<:NamedTuple,T<:NamedTuple} - hot::H - refs::T - reference_epoch::UInt +mutable struct _ProjectedStatusStorage{N,R<:Tuple,H<:NamedTuple,T<:NamedTuple} + const hot::H + const refs::T + const reference_epoch::UInt end """ @@ -370,7 +370,6 @@ end return nothing end -_status_snapshot_references(status::Status) = _initial_status_reference_storage(status) _dense_status_type(names::Tuple, references::Type{<:Tuple}) = Status{names,NamedTuple{names,references}} function _projected_status_type(::Type{C}, hot_names::Tuple, hot_references::Type{<:Tuple}) where {C<:Status} names = _status_schema_names(C) diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl index c1e164fe4..bbec05b42 100644 --- a/src/composite_model/status_construction.jl +++ b/src/composite_model/status_construction.jl @@ -32,11 +32,6 @@ _status_schema_references(::Type{Status{Names,T}}) where {Names,T} = return QuoteNode(_projected_status_type(C, NAMES, R)) end -_status_schema_values(::Nothing) = () -_status_schema_values(status::Status{N,<:NamedTuple}) where {N} = refvalues(status) -_status_schema_values(status::Status{N,<:Union{_FixedStatusStorage,_ProjectedStatusStorage}}) where {N} = - values(_status_snapshot_references(status)) - _selected_status_reference_type(::ExistingStatusReference{I}, existing, edited) where {I} = fieldtype(existing, I) _selected_status_reference_type(::EditedStatusReference{I}, existing, edited) where {I} = @@ -75,20 +70,29 @@ end projected = Storage <: _ProjectedStatusStorage Names = projected ? fieldnames(fieldtype(Storage, :hot)) : _status_schema_names(Result) Refs = projected ? fieldtype(Storage, :hot).parameters[2] : _status_schema_references(Result) - # Actions are metadata carried by the sole existing factory, not runtime types. + # Read the reference layout once. Each action indexes this named tuple + # directly, including when a field is present only in the full snapshot. + load_refs = Existing === Nothing ? :(NamedTuple()) : :(_initial_status_reference_storage(original)) hot = [:( _status_construction_reference(getfield(factory.construction.actions,$i), - _status_schema_values(original), edited)::$(fieldtype(Refs,i)) ) for i in eachindex(Names)] + original_refs, edited)::$(fieldtype(Refs,i)) ) for i in eachindex(Names)] Hot = NamedTuple{Names,Refs} - projected || return :(Status($Hot($(Expr(:tuple,hot...))))::Result) + dense = :($Hot($(Expr(:tuple,hot...)))) + projected || return quote + original_refs = $load_refs + return Status($dense)::Result + end FullNames = _status_schema_names(Result) Full = fieldtype(Storage, :refs) - full = [begin - index = findfirst(isequal(name), Names) - isnothing(index) ? :(_initial_status_reference(original,$(QuoteNode(name)))::$(fieldtype(Full,i))) : - :(getfield(hot,$index)::$(fieldtype(Full,i))) - end for (i,name) in enumerate(FullNames)] + full = map(eachindex(FullNames)) do i + name = FullNames[i] + hot_index = findfirst(isequal(name), Names) + reference = isnothing(hot_index) ? :(get(original_refs,$(QuoteNode(name)),nothing)) : + :(getfield(hot,$hot_index)) + :($reference::$(fieldtype(Full,i))) + end return quote - hot = $Hot($(Expr(:tuple,hot...))) + original_refs = $load_refs + hot = $dense snapshot = $Full($(Expr(:tuple,full...))) return Status($Storage(hot, snapshot, _status_reference_epoch(original)))::Result end diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index b6a7e4c51..0f8db2e76 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -67,6 +67,8 @@ end owner = PSE._new_prepared_status(SCHEMA,Status(x=3f0,q=1//2,seed=Float32[2])) private = Ref(100.0) Projected = @inferred PSE._projected_status_type(SCHEMA,Val((:x,:q)),Tuple{RF64,RR}) + # Execution targets carry a handle to the snapshot, even for a wide namespace. + @test sizeof(Projected) == sizeof(SCHEMA) @test Projected === PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF64,RR}) @test PSE._projected_status_type(SCHEMA,Val(()),Tuple{}) === PSE._projected_status_type(SCHEMA,(),Tuple{}) From 1c2ff4081e0c53df5ffde056ea45da394d1c4af9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 15:18:26 +0100 Subject: [PATCH 189/324] Use canonical writer declarations to type direct status reads --- src/composite_model/compilation.jl | 27 ++++++++++++++++---- test/test-model-temporal-initial-typing.jl | 29 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 9acd4a648..b16142d44 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8523,9 +8523,28 @@ function _many_model_variant_types(producer) return ((model, ports.output_types, ports.output_element_types),) end +function _add_status_writer_reference_types!(references, model, selector, variable, writers, plans) + for writer in writers + _application_may_output_variable(writer, variable, selector, + _model_canonical_output_names(writer), plans) || continue + _foreach_application_variant(writer) do _, ports + R = _prepared_status_declared_reference(model.status_conversion, variable, + getproperty(ports.output_types, variable), get(ports.output_element_types, variable, nothing)) + R === Union{} || append!(references, Base.uniontypes(R)) + end + end + return references +end + function _prepare_input_reference_types(model, consumer, input, selector, - source_var, producer_ids, applications_by_id, distributed_output_plans) + source_var, producer_ids, applications_by_id, writer_applications, distributed_output_plans) references = Any[] + # A status read can see a canonical output before its first value has been + # materialized. Its declared cell type does not create a stream dependency. + if _selector_from_status(selector) + _add_status_writer_reference_types!(references, model, selector, source_var, + get(writer_applications, source_var, ()), distributed_output_plans) + end add(R) = R in references || push!(references, R) declared_input = _configured_status_value_type(model.status_conversion, input, getproperty(_application_ports(consumer).input_types, input), nothing) @@ -8554,7 +8573,6 @@ function _prepare_input_reference_types(model, consumer, input, selector, current = _many_current_source_ids(model, consumer, producer, variant, selector, source_selectors, distributed) missing_current = copy(current) - observed_any = false for source_selector in source_selectors matcher = _authored_selector_matcher(source_selector) for object in values(model.registry.objects) @@ -8565,7 +8583,6 @@ function _prepare_input_reference_types(model, consumer, input, selector, reference = refvalue(status, source_var) reference isa Ref || continue add(typeof(reference)) - observed_any = true delete!(missing_current, object.id) end end @@ -8588,7 +8605,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, # Existing complete references remain valid evidence; no transform # is called here to manufacture an additional type witness. if isempty(candidates) - (current_complete || (isnothing(producer) && observed_any) || + (current_complete || (isnothing(producer) && !isempty(references)) || (selector isa OptionalOne && isempty(current))) && continue end isempty(candidates) && throw(ArgumentError( @@ -8686,7 +8703,7 @@ Base.@nospecializeinfer function _compiled_model_input_plan( _selector_window(selector), _prepare_input_reference_types(model, application, input, selector, source_var, potential_source_application_ids, - applications_by_id, distributed_output_plans), + applications_by_id, writer_applications, distributed_output_plans), ) end diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index c0e02197f..bc399938a 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -30,6 +30,35 @@ function fixture(::Type{T}; empty=false) where {T} end input(sim) = only(sim.compiled.status_views_by_target[(:consumer, ObjectId(:scene))].temporal_inputs) +@testset "Many can read a newly materialized canonical output through its status" begin + function status_scene(mode, scale) + return CompositeModel(Object(:scene; scale=:Scene), Object(:a; scale=:Leaf, parent=:scene); + applications=( + ModelSpec(Source(2f0); name=:source, on=Many(scale=scale), + output_routing=(signal=mode,)), + ModelSpec(Consumer{Float32}(); name=:consumer, on=One(scale=:Scene), + inputs=(signals=Many(scale=:Leaf, within=SceneScope(), + var=:signal, from_status=true, after=:source),)), + ), environment=(duration=Hour(1),)) + end + model = status_scene(:canonical, :Leaf) + sim = run!(model; steps=1, outputs=:all) + binding = only(sim.compiled.input_bindings) + @test fieldtypes(binding.plan.reference_types) == (Base.RefValue{Float32},) + @test isempty(binding.plan.potential_source_application_ids) + @test isempty(binding.source_application_ids) + @test binding.order_after_application_ids == (:source,) + @test only(parent(binding.carrier)) === PSE.refvalue(model_status(model, :a), :signal) + @test final_state(sim, :scene).total === 3f0 + register_object!(model, Object(:b; scale=:Leaf, parent=:scene)) + step!(sim) + @test final_state(sim, :scene).total === 7f0 + @test outputs(sim)[(:consumer, ObjectId(:scene), :total)] == [(1.0, 3f0), (2.0, 7f0)] + for (mode, scale) in ((:stream_only, :Leaf), (:canonical, :Root)) + @test_throws "no concrete configured source type" run!(status_scene(mode, scale); steps=0) + end +end + @testset "homogeneous initial values retain their numerical schema across growth" begin for T in (Float32, Float64), retention in (:none, :all) model = fixture(T) From b5ff85d466b4c6109c35f27c39576fea92f3bef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 15:20:00 +0100 Subject: [PATCH 190/324] Pin downstream benchmarks to the triggering PSE commit --- .github/workflows/FullPerformance.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/FullPerformance.yml b/.github/workflows/FullPerformance.yml index 3fbd5bd56..0a277c173 100644 --- a/.github/workflows/FullPerformance.yml +++ b/.github/workflows/FullPerformance.yml @@ -69,7 +69,7 @@ jobs: - name: Check out PlantSimEngine uses: actions/checkout@v7 with: - ref: ${{ github.event.pull_request.head.sha || github.ref }} + ref: ${{ github.event.pull_request.head.sha || github.sha }} - name: Check out XPalm uses: actions/checkout@v7 From 21d7c6f96ccecad8de2de751251fbe998cf400ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 16:57:04 +0100 Subject: [PATCH 191/324] Exercise sparse reference changes on a wide prepared status --- test/test-status-fixed-storage.jl | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 0f8db2e76..4a7cff349 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -115,6 +115,36 @@ end @test PSE.refvalue(state,:x) === replacement end +@testset "sparse edits preserve aliases and commit atomically across a wide status" begin + names = ntuple(i -> Symbol(:port_, i), 160) + schema = PSE._fixed_status_type(names, NTuple{length(names), RF32}) + state = PSE._new_prepared_status(schema, nothing) + recipe = PSE._CanonicalStatusRecipe(state, true) + epoch = PSE._status_reference_epoch(state) + shared = Ref(4f0) + for name in (last(names), first(names), names[80]) + PSE._status_recipe_set_reference!(recipe, name, shared) + end + @test PSE._finish_canonical_status_recipe!(recipe) === state + @test keys(state) == (first(names), names[80], last(names)) + @test all(name -> PSE.refvalue(state, name) === shared, keys(state)) + @test PSE._status_reference_epoch(state) == epoch + 1 + PSE._finish_canonical_status_recipe!(recipe) + @test PSE._status_reference_epoch(state) == epoch + 1 + + # A bad edit after a valid one must leave both the reference and its epoch alone. + for (name, reference, error_type) in ((:unprepared, shared, KeyError), + (last(names), Ref(4.0), ArgumentError)) + pending = PSE._CanonicalStatusRecipe(state, false) + PSE._status_recipe_set_reference!(pending, first(names), Ref(5f0)) + push!(pending.edit_names, name) + push!(pending.edit_references, reference) + @test_throws error_type PSE._finish_canonical_status_recipe!(pending) + @test PSE.refvalue(state, first(names)) === shared + @test PSE._status_reference_epoch(state) == epoch + 1 + end +end + @testset "deepcopy preserves internal ref aliases, RefAny and RefReal stay exact" begin S = PSE._fixed_status_type((:a,:b,:abstract,:opaque),Tuple{RF32,RF32,Base.RefValue{Real},Base.RefValue{Any}}) reference = Ref(1f0) From 761d268bf9d070ddc57c6275c789a8ef67f8af4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 17:05:56 +0100 Subject: [PATCH 192/324] Apply staged status references in one pass over the prepared layout --- src/composite_model/compilation.jl | 61 ++++++++++++++++-------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b16142d44..8c3fb72fb 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6722,35 +6722,38 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end -# One prepared physical schema handles every presence pattern. Slot construction -# validates ALL edits before its single metadata assignment; no runtime type/name -# discovery, terminal-layout enumeration or alternate Open algorithm remains. -@generated function _finish_canonical_status_recipe!( - recipe::_CanonicalStatusRecipe{S}, -) where {N,R,T,S<:Status{N,_FixedStatusStorage{N,R,T}}} - cells = [gensym(:cell) for _ in N] - reads = [quote - position = findfirst(isequal($(QuoteNode(name))), recipe.edit_names) - $(cells[i]) = isnothing(position) ? - getfield(_status_vars(recipe.original).refs, $i) : recipe.edit_references[position] - $(cells[i]) isa $(fieldtype(T,i)) || throw(ArgumentError("Staged reference is outside its prepared slot family.")) - end for (i,name) in enumerate(N)] - values = Expr(:tuple, [:( $(cells[i])::$(fieldtype(T,i)) ) for i in eachindex(N)]...) - return quote - $(Expr(:meta, :noinline)) - recipe.changed || return recipe.original - for name in recipe.edit_names - name in $(QuoteNode(N)) || throw(KeyError(name)) - end - $(reads...) - storage = _status_vars(recipe.original) - references = $T($values) - if references !== storage.refs - storage.refs = references - _advance_status_reference_epoch!(storage) - end - return recipe.original - end +# Stage one reference directory. Committing it once keeps every existing status +# projection on its original cells if any edit fails admission. +function _finish_canonical_status_recipe!(recipe::_CanonicalStatusRecipe) + original = recipe.original + isempty(recipe.edit_names) && return original + storage = _status_vars(original) + current = storage.refs + slots = typeof(current) + cells = Vector{Union{Nothing,Ref}}(undef, nfields(current)) + for slot in eachindex(cells) + cells[slot] = getfield(current, slot) + end + changed = false + for (name, reference) in zip(recipe.edit_names, recipe.edit_references) + slot = Base.fieldindex(slots, name, false) + iszero(slot) && throw(KeyError(name)) + reference isa fieldtype(slots, slot) || + throw(ArgumentError("Staged reference is outside its prepared slot family.")) + changed |= cells[slot] !== reference + cells[slot] = reference + end + if changed + storage.refs = _status_reference_directory(slots, cells) + _advance_status_reference_epoch!(storage) + end + return original +end + +# Every cell already belongs to its prepared field. Use Julia's constructor for +# exact NamedTuple fields to retain those references without per-field conversion. +Base.@noinline function _status_reference_directory(::Type{T}, cells::Vector{Union{Nothing,Ref}}) where {T<:NamedTuple} + return Base._new_NamedTuple(T, Tuple(cells)) end function _model_object_status_for_preparation( From 8044970e5671e2476ad6fc6a7180e05e2b100ab6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 17:47:23 +0100 Subject: [PATCH 193/324] Copy wide status reference directories without boxing each slot --- src/composite_model/compilation.jl | 13 ++++++++++--- test/test-status-fixed-storage.jl | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 8c3fb72fb..378fff7e8 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6722,6 +6722,15 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end +# Keep the directory as one function argument. Indexing a wide NamedTuple +# loaded from a mutable status can otherwise box the entire tuple at each slot. +Base.@noinline function _copy_status_reference_cells!(cells, directory::NamedTuple) + for slot in eachindex(cells) + cells[slot] = getfield(directory, slot) + end + return cells +end + # Stage one reference directory. Committing it once keeps every existing status # projection on its original cells if any edit fails admission. function _finish_canonical_status_recipe!(recipe::_CanonicalStatusRecipe) @@ -6731,9 +6740,7 @@ function _finish_canonical_status_recipe!(recipe::_CanonicalStatusRecipe) current = storage.refs slots = typeof(current) cells = Vector{Union{Nothing,Ref}}(undef, nfields(current)) - for slot in eachindex(cells) - cells[slot] = getfield(current, slot) - end + _copy_status_reference_cells!(cells, current) changed = false for (name, reference) in zip(recipe.edit_names, recipe.edit_references) slot = Base.fieldindex(slots, name, false) diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 4a7cff349..7f57596c0 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -145,6 +145,24 @@ end end end +function _wide_status_commit_bytes!(recipe, name, value) + PSE._status_recipe_set_reference!(recipe, name, Ref(value)) + return @allocated PSE._finish_canonical_status_recipe!(recipe) +end + +@testset "a sparse edit copies a heterogeneous status directory once" begin + names = ntuple(i -> Symbol(:port_, i), 160) + classes = ntuple(i -> isodd(i) ? RF32 : RF64, length(names)) + schema = PSE._fixed_status_type(names, Tuple{classes...}) + state = PSE._new_prepared_status(schema, nothing) + recipe = PSE._CanonicalStatusRecipe(state, true) + _wide_status_commit_bytes!(recipe, first(names), 1f0) + bytes = _wide_status_commit_bytes!(recipe, first(names), 2f0) + # Allow space for the staging vector, the tuple and its final directory. + @test bytes <= 64 * length(names) + 4096 + @test PSE.refvalue(state, first(names))[] === 2f0 +end + @testset "deepcopy preserves internal ref aliases, RefAny and RefReal stay exact" begin S = PSE._fixed_status_type((:a,:b,:abstract,:opaque),Tuple{RF32,RF32,Base.RefValue{Real},Base.RefValue{Any}}) reference = Ref(1f0) From b75e60b915c9650d41d730049722a0992b674735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 18:04:33 +0100 Subject: [PATCH 194/324] Stage model input and output defaults from their prepared declarations --- src/composite_model/compilation.jl | 163 ++++++++++--------------- src/processes/models_inputs_outputs.jl | 6 +- 2 files changed, 66 insertions(+), 103 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 378fff7e8..a108a5092 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6883,46 +6883,31 @@ end return status::S end -_stage_model_output_defaults!(preparation, ::Tuple{}, ::Tuple{}, context) = nothing - -function _stage_model_output_defaults!( - preparation, - variables::Tuple{Symbol,Vararg{Symbol}}, - defaults::Tuple{V,Vararg}, - context, -) where {V} - variable = first(variables) - value = first(defaults) - if _publish_mode_for_output(context.application.spec, variable) == :canonical +# Stage only missing defaults. Dispatch on each value in its complete declaration +# so wide model schemas share workers instead of compiling every tuple suffix. +function _stage_model_status_defaults!(preparation, defaults::NamedTuple, variables, + stage_default!::F, context, +) where {F} + rewrites_avoided = 0 + for variable in variables if preparation isa Status - if !(hasproperty(preparation, variable)) - recipe = _status_recipe_for_object!( - context.recipes, - context.recipe_order, - context.model, - context.object_id, - ) - return Base.@inline _with_canonical_status_recipe( - _stage_model_output_defaults!, context.recipes, recipe, - variables, defaults, context, - ) - end - else - Base.@inline _status_recipe_add_default!( - context.model, - preparation, - context.object_id, - variable, - value; - application_id=context.application.id, - origin=:model_output_default, - conversion_records=context.conversion_records, - ) + hasproperty(preparation, variable) && continue + preparation = _status_recipe_for_object!(context.recipes, context.recipe_order, + context.model, context.object_id) + elseif _status_recipe_has_variable(preparation, variable) + continue end + rewrites_avoided += _with_metadata_entry(stage_default!, defaults, variable, + preparation, variable, context) end - return _stage_model_output_defaults!( - preparation, Base.tail(variables), Base.tail(defaults), context, - ) + return rewrites_avoided +end + +Base.@noinline function _stage_model_output_default!(value, recipe, variable, context) + _status_recipe_add_default!(context.model, recipe, context.object_id, variable, value; + application_id=context.application_id, origin=:model_output_default, + conversion_records=context.conversion_records) + return 0 end function _prepare_model_output_statuses!( @@ -6940,6 +6925,7 @@ function _prepare_model_output_statuses!( for partial in applications Base.@inline _with_model_application(applications_by_id, partial) do application schemas = _application_default_schemas(application, Val(:outputs)) + routing = output_routing(application.spec) for object_id in application.target_ids Base.@inline _with_application_defaults(application, object_id, schemas, Val(:outputs)) do defaults preparation = _status_preparation_for_object!( @@ -6948,12 +6934,15 @@ function _prepare_model_output_statuses!( model, object_id, ) - context = (; model, application, object_id, recipes, - recipe_order, conversion_records) + variables = Iterators.filter(keys(defaults)) do variable + _publish_mode_for_output(routing, variable) === :canonical + end + context = (; model, application_id=application.id, object_id, + recipes, recipe_order, conversion_records) Base.@inline _with_canonical_status_preparation( - _stage_model_output_defaults!, recipes, - model.registry.objects.catalog, preparation, - keys(defaults), values(defaults), context, + _stage_model_status_defaults!, recipes, model.registry.objects.catalog, + preparation, defaults, variables, + _stage_model_output_default!, context, ) end end @@ -7844,40 +7833,19 @@ end end end -_stage_model_input_defaults!(preparation, ::Tuple{}, ::Tuple{}, context) = 0 -function _stage_model_input_defaults!(preparation, variables::Tuple, - defaults::Tuple{V,Vararg}, context, -) where {V} - variable, value = first(variables), first(defaults) - if preparation isa Status - if !(hasproperty(preparation, variable)) - recipe = _status_recipe_for_object!(context.recipes, - context.recipe_order, context.model, context.object_id) - return _with_canonical_status_recipe(_stage_model_input_defaults!, - context.recipes, recipe, variables, defaults, context) - end - return _stage_model_input_defaults!(preparation, - Base.tail(variables), Base.tail(defaults), context) - end - avoided = 0 - if !_status_recipe_has_variable(preparation, variable) - reference = isnothing(context.final_references) ? nothing : - get(context.final_references, - (context.application.id, context.object_id, variable), nothing) - if isnothing(reference) - Base.@inline _status_recipe_add_default!(context.model, preparation, - context.object_id, variable, value; - application_id=context.application.id, origin=:model_input_default, - conversion_records=context.conversion_records) - context.default_status_updates[(context.object_id, variable)] = true - else - avoided = Base.@inline _with_model_input_status_reference( - _stage_model_input_default_reference!, context.bindings, reference, - preparation, variable, value, context) - end +Base.@noinline function _stage_model_input_default!(value, recipe, variable, context) + reference = isnothing(context.final_references) ? nothing : + get(context.final_references, (context.application_id, context.object_id, variable), nothing) + if isnothing(reference) + _status_recipe_add_default!(context.model, recipe, context.object_id, variable, value; + application_id=context.application_id, origin=:model_input_default, + conversion_records=context.conversion_records) + context.default_status_updates[(context.object_id, variable)] = true + return 0 end - return avoided + _stage_model_input_defaults!(preparation, - Base.tail(variables), Base.tail(defaults), context) + return Base.@inline _with_model_input_status_reference( + _stage_model_input_default_reference!, context.bindings, reference, + recipe, variable, value, context) end function _stage_model_input_default_reference!(reference, preparation, variable, @@ -7886,7 +7854,7 @@ function _stage_model_input_default_reference!(reference, preparation, variable, # Keep the existing conversion/validation even when the carrier owns storage. _no_status_conversion(context.model.status_conversion) || _materialize_status_value(context.model, variable, value; - object_id=context.object_id, application_id=context.application.id, + object_id=context.object_id, application_id=context.application_id, origin=:model_input_default, private_copy=true, conversion_records=context.conversion_records) _status_recipe_set_reference!(preparation, variable, reference) @@ -7916,33 +7884,26 @@ end ) return Base.@inline _with_model_input_status_reference( _stage_admitted_model_input_reference!, binding, - reference, preparation, binding, context) + reference, preparation, binding.consumer_id, binding.input, context) end -function _stage_admitted_model_input_reference!(reference, preparation, binding, - context, +# Once the binding has admitted its carrier, staging needs only its destination +# and cell. Bindings with different selectors or clocks can share this worker. +Base.@noinline function _stage_admitted_model_input_reference!(reference, preparation, + object_id, variable, context, ) if preparation isa Status - if hasproperty(preparation, binding.input) && - refvalue(preparation, binding.input) === reference - context.default_status_updates[(binding.consumer_id, binding.input)] = false - return nothing + if !hasproperty(preparation, variable) || refvalue(preparation, variable) !== reference + recipe = _status_recipe_for_object!(context.recipes, context.recipe_order, + context.model, object_id) + _with_canonical_status_recipe(_status_recipe_set_reference!, context.recipes, + recipe, variable, reference) end - recipe = _status_recipe_for_object!(context.recipes, context.recipe_order, - context.model, binding.consumer_id) - return _with_canonical_status_recipe(_set_model_input_status_reference!, - context.recipes, recipe, reference, binding, context) - elseif _status_recipe_has_variable(preparation, binding.input) && - _status_recipe_reference(preparation, binding.input) === reference - context.default_status_updates[(binding.consumer_id, binding.input)] = false - return nothing + elseif !_status_recipe_has_variable(preparation, variable) || + _status_recipe_reference(preparation, variable) !== reference + _status_recipe_set_reference!(preparation, variable, reference) end - return _set_model_input_status_reference!(preparation, reference, binding, context) -end - -function _set_model_input_status_reference!(preparation, reference, binding, context) - _status_recipe_set_reference!(preparation, binding.input, reference) - context.default_status_updates[(binding.consumer_id, binding.input)] = false + context.default_status_updates[(object_id, variable)] = false return nothing end @@ -7972,10 +7933,10 @@ function _prepare_model_input_statuses_batched!( rewrites_avoided += Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults preparation = _status_preparation_for_object!( recipes, recipe_order, model, object_id) - selected = (; context..., application, object_id) - _with_canonical_status_preparation(_stage_model_input_defaults!, - recipes, model.registry.objects.catalog, preparation, - keys(defaults), values(defaults), selected) + selected = (; context..., application_id=application.id, object_id) + _with_canonical_status_preparation(_stage_model_status_defaults!, + recipes, model.registry.objects.catalog, preparation, defaults, + keys(defaults), _stage_model_input_default!, selected) end end return rewrites_avoided diff --git a/src/processes/models_inputs_outputs.jl b/src/processes/models_inputs_outputs.jl index c08ec0d96..f1d06574b 100644 --- a/src/processes/models_inputs_outputs.jl +++ b/src/processes/models_inputs_outputs.jl @@ -68,8 +68,10 @@ function _policy_for_output(model, variable::Symbol) ) end -function _publish_mode_for_output(spec::ModelSpec, variable::Symbol) - modes = output_routing(spec) +_publish_mode_for_output(spec::ModelSpec, variable::Symbol) = + _publish_mode_for_output(output_routing(spec), variable) + +function _publish_mode_for_output(modes::NamedTuple, variable::Symbol) mode = variable in keys(modes) ? modes[variable] : :canonical mode in (:canonical, :stream_only) || error( "Unsupported output routing mode `$(mode)` for `$(variable)`." From 02ffcf25f60bf48bd914e351f0e55536f1163451 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 18:05:06 +0100 Subject: [PATCH 195/324] Format compound object identifiers in native lookup diagnostics --- src/composite_model/registry_topology.jl | 7 +++++- test/test-object-families.jl | 28 +++++++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index b8690eda7..de5236ce1 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1211,10 +1211,15 @@ function _replace_model_object_status!(model::CompositeModel, object_id, status) return _replace_model_object_status!(model, _model_object(model, object_id), status) end +# Scalar diagnostics retain their ordinary display. Composite identities use +# the existing typed printer rather than Julia's generic syntax display. +_object_id_diagnostic_text(value) = string(value) +_object_id_diagnostic_text(value::Tuple) = _selector_diagnostic_text(value) + function _model_object(model::CompositeModel, id) oid = ObjectId(id) object = get(model.registry.objects, oid, nothing) - isnothing(object) && error("No model object with id `$(oid.value)`.") + isnothing(object) && error("No model object with id `", _object_id_diagnostic_text(oid.value), "`.") return object end diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 74e5cce41..912f86190 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -31,7 +31,8 @@ const PSE = PlantSimEngine exception end @test failure isa ErrorException - @test sprint(showerror, failure) == "No model object with id `$(id)`." + expected = id isa Tuple ? "(Symbol(\"plant\"), 4)" : string(id) + @test sprint(showerror, failure) == "No model object with id `$(expected)`." end @test canonical !== supplied @test PSE.refvalue(canonical, :value) === reference @@ -53,6 +54,31 @@ const PSE = PlantSimEngine @test family.rows[location.row].status === canonical end +@testset "missing object diagnostics preserve scalar values and complete tuple identities" begin + present = Object((:plant, :leaf, 1); status=Status(value=2f0)) + model = CompositeModel(present) + @test model_object(model, present.id) === present + @test model_status(model, present.id) === present.status + cases = ( + :missing => "missing", + "missing" => "missing", + 17 => "17", + 2.5 => "2.5", + true => "true", + (:missing, :leaf, 2) => "(Symbol(\"missing\"), Symbol(\"leaf\"), 2)", + (:missing, (:leaf, 2)) => "(Symbol(\"missing\"), (Symbol(\"leaf\"), 2))", + ) + for (id, expected) in cases, lookup in (model_object, model_status, object_id) + failure = try + lookup(model, ObjectId(id)) + catch exception + exception + end + @test failure isa ErrorException + @test sprint(showerror, failure) == "No model object with id `$(expected)`." + end +end + # Genuine model configuration declares the replacement's numerical types at # preparation; no dummy object or explicit canonical Status prototype is needed. PSE.@process "canonical_family_replacement" verbose=false From fd3d58f67969db87b583a7ae5f7ba8b8b272b0a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 18:14:45 +0100 Subject: [PATCH 196/324] Keep prospective object labels concrete during route admission --- src/composite_model/selectors.jl | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 54ec91e81..6714fde02 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1598,13 +1598,13 @@ end # Pre-registration matching sees the exact admitted parent and the labels that # normal registration would inherit. Every other object remains the real model. -struct _PreparedStatusObjectTopology{M,I<:ObjectId,P,K,SP} +struct _PreparedStatusObjectTopology{M,I<:ObjectId,P} model::M object::Object id::I parent::P - kind::K - species::SP + kind::Union{Nothing,Symbol} + species::Union{Nothing,Symbol} end function _prepared_status_object_labels(model, object, parent_id) @@ -1691,9 +1691,12 @@ function _prepared_status_route_matches(model, object, parent_id, application, # Output destinations and from-status input sources use the same predicate. id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) - _prepared_status_scope_is_current(model, topology, destination_plan.matcher.scope, execution_id) || return false - return _selector_matches_object_id(topology, destination_plan.matcher, - id, execution_id, true, _default_dependency_scope(topology, execution_id), false) + matcher = destination_plan.matcher + _prepared_status_scope_is_current(model, topology, matcher.scope, execution_id) || return false + default_scope = isnothing(matcher.scope) && isnothing(matcher.relation) ? + _default_dependency_scope(topology, execution_id) : nothing + return _selector_matches_object_id(topology, matcher, + id, execution_id, true, default_scope, false) end # This is the actual object awaiting registration, never a manufactured origin. From f28cc81f01e71f5f46fd257765fbe8436947163a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 19:11:09 +0100 Subject: [PATCH 197/324] Prepare retained outputs from their application and timeline owners Keep temporal window selection, distributed output names and request resolution in shared workers that take their actual model metadata. This keeps the whole compiled scene out of inference while preparing XPalm output retention. Exercise none, all and a named request against ordinary and prepared histories. --- src/composite_model/runtime_outputs.jl | 281 ++++++++++++--------- test/test-model-output-retention-owners.jl | 12 + 2 files changed, 171 insertions(+), 122 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 50062cea9..7ae1f98be 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1714,9 +1714,15 @@ explain_environment_bindings(sim::Simulation) = @inline function _compiled_application_by_id(f::F, compiled::CompiledCompositeModel, id::Symbol, ) where {F} - haskey(compiled.applications_by_id, id) || + return _compiled_application_by_id(f, compiled.applications_by_id, id) +end + +@inline function _compiled_application_by_id(f::F, + applications_by_id::CompiledMetadataTable, id::Symbol, +) where {F} + haskey(applications_by_id, id) || error("No compiled model application with id `$(id)`.") - return _with_metadata_entry(f, compiled.applications_by_id, id) + return _with_metadata_entry(f, applications_by_id, id) end _compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) = @@ -4798,6 +4804,14 @@ end # application/plan values never cross into the retention computation. function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, binding::CompiledModelInputBinding, +) where {F} + return _with_model_temporal_retention(f, compiled.applications_by_id, + compiled.scenario_plan.input_plans, compiled.scenario_plan.timeline, binding) +end + +Base.@noinline function _with_model_temporal_retention(f::F, + applications_by_id::CompiledMetadataTable, input_plans, timeline, + binding::CompiledModelInputBinding, ) where {F} input_plan = getfield(binding, :plan) application_id, plan_slot = input_plan.application_id, input_plan.slot @@ -4807,14 +4821,13 @@ function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, policy = getfield(binding, :policy) integrates = policy isa Union{Integrate,Aggregate} interpolates = policy isa Union{Interpolate,PreviousTimeStep} - consumer_dt = _compiled_application_by_id(compiled, application_id) do consumer + consumer_dt = _compiled_application_by_id(applications_by_id, application_id) do consumer consumer.clock.dt end # The old loop resolves its consumer/plan owner but does not validate a # window when no real producer is selected. has_sources = !isempty(source_application_ids) - timeline = compiled.scenario_plan.timeline - window_steps = _with_metadata_entry(compiled.scenario_plan.input_plans, plan_slot) do actual_plan + window_steps = _with_metadata_entry(input_plans, plan_slot) do actual_plan actual_plan.application_id === application_id && actual_plan.input === input_name && actual_plan.source_var === source_var || throw(ArgumentError("A temporal retention binding is outside its current input plan owner.")) @@ -4823,7 +4836,7 @@ function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, end has_sources || return true for source_application_id in source_application_ids - source_dt = _compiled_application_by_id(compiled, source_application_id) do source + source_dt = _compiled_application_by_id(applications_by_id, source_application_id) do source source.clock.dt end required = _model_temporal_retention_horizon(window_steps, integrates, interpolates, source_dt) @@ -4838,7 +4851,7 @@ function _model_output_retention_covers_binding( binding::CompiledModelInputBinding, ) plan.retain_all && return true - return Base.@inline _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required + return _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required key = (source_application_id, source_var) key in plan.temporal_dependencies && get(plan.dependency_horizons, key, -Inf) >= required end @@ -4905,31 +4918,28 @@ function _model_status_view_refresh_is_pure_addition( return all(key -> last(key) in added_object_ids, new_keys) end -function _model_application_output_variables( - compiled, - application, - ::NoCompiledDistributedOutputs, -) +_retention_destination_ids(::NoCompiledDistributedOutputs) = nothing +_retention_destination_ids(outputs::CompiledDistributedOutputs) = + outputs.destination_ids_by_application_variable +_retention_output_plans(::NoCompiledDistributedOutputPlans) = nothing +_retention_output_plans(plans::CompiledDistributedOutputPlans) = plans.by_application + +function _model_application_output_variables(application, ::Nothing, plans_by_application) return _model_output_names(application) end function _model_application_output_variables( - compiled, - application, - distributed_outputs::CompiledDistributedOutputs, + application, destinations_by_application_variable::AbstractDict, plans_by_application, ) variables = Symbol[Symbol(variable) for variable in _model_output_names(application)] - for ((application_id, variable), destination_ids) in - distributed_outputs.destination_ids_by_application_variable + for ((application_id, variable), destination_ids) in destinations_by_application_variable application_id == application.id || continue isempty(destination_ids) && continue variable in variables || push!(variables, variable) end - # Plans with an initially empty destination set still define retainable - # variables that may acquire destinations at a later lifecycle barrier. - plans = compiled.scenario_plan.distributed_output_plans - if plans isa CompiledDistributedOutputPlans - for plan in _application_plans(plans.by_application, application.id) + # Empty routes retain their declarations before any destination is born. + if !isnothing(plans_by_application) + for plan in _application_plans(plans_by_application, application.id) for variable_ in plan.variable_names variable = Symbol(variable_) variable in variables || push!(variables, variable) @@ -4939,59 +4949,91 @@ function _model_application_output_variables( return Tuple(variables) end -_model_application_output_variables(compiled, application) = - _model_application_output_variables( - compiled, - application, - compiled.distributed_outputs, - ) +function _append_retained_application_outputs!( + application, all_outputs, destinations, plans_by_application, +) + for variable in _model_application_output_variables(application, destinations, plans_by_application) + push!(all_outputs, (application.id, variable)) + end + return nothing +end -function compile_model_output_retention( - compiled::CompiledCompositeModel, - output_requests; - retain_all::Bool=false, - accepted_call_times=Dict{Symbol,Float64}(), +Base.@noinline function _collect_retained_output_keys( + applications_by_id, destinations, plans_by_application, +) + all_outputs = Set{Tuple{Symbol,Symbol}}() + for application_id in keys(applications_by_id) + _with_metadata_entry(_append_retained_application_outputs!, applications_by_id, + application_id, all_outputs, destinations, plans_by_application) + end + return all_outputs +end + +Base.@noinline function _compile_temporal_output_retention( + input_bindings, applications_by_id, input_plans, timeline, ) temporal_dependencies = Set{Tuple{Symbol,Symbol}}() dependency_horizons = Dict{Tuple{Symbol,Symbol},Float64}() - for binding in compiled.input_bindings + for binding in input_bindings binding.carrier_hint == :temporal_stream || continue - Base.@inline _with_model_temporal_retention(compiled, binding) do source_application_id, source_var, required + _with_model_temporal_retention(applications_by_id, input_plans, timeline, binding) do source_application_id, source_var, required key = (source_application_id, source_var) push!(temporal_dependencies, key) dependency_horizons[key] = max(get(dependency_horizons, key, 0.0), required) return true end end + return temporal_dependencies, dependency_horizons +end + +function _retain_requested_model_output!(request, model, applications_by_id, + destinations, plans_by_application, manual_application_ids, requested_outputs, + names, accepted_call_times, +) + request.name in names && error( + "Duplicate output request name `$(request.name)`. Request names must be unique." + ) + push!(names, request.name) + application_id = _model_request_application_id(model, applications_by_id, + destinations, plans_by_application, manual_application_ids, request) + push!(requested_outputs, (application_id, request.var)) + if application_id in manual_application_ids + get!(accepted_call_times, application_id, -Inf) + end + return nothing +end +Base.@noinline function _compile_requested_output_retention( + model, applications_by_id, destinations, plans_by_application, + manual_application_ids, output_requests, accepted_call_times, +) requested_outputs = Set{Tuple{Symbol,Symbol}}() names = Set{Symbol}() - _foreach_output_request(output_requests) do request - request.name in names && error( - "Duplicate output request name `$(request.name)`. Request names must be unique." - ) - push!(names, request.name) - application_id = _model_request_application_id( - compiled.model, - compiled, - request, - ) - push!(requested_outputs, (application_id, request.var)) - if application_id in compiled.scenario_plan.manual_application_ids - get!(accepted_call_times, application_id, -Inf) - end - end + _foreach_output_request(_retain_requested_model_output!, output_requests, + model, applications_by_id, destinations, plans_by_application, + manual_application_ids, requested_outputs, names, accepted_call_times) + return requested_outputs +end + +function compile_model_output_retention( + compiled::CompiledCompositeModel, + output_requests; + retain_all::Bool=false, + accepted_call_times=Dict{Symbol,Float64}(), +) + temporal_dependencies, dependency_horizons = _compile_temporal_output_retention( + compiled.input_bindings, compiled.applications_by_id, + compiled.scenario_plan.input_plans, compiled.scenario_plan.timeline) + destinations = _retention_destination_ids(compiled.distributed_outputs) + plans_by_application = _retention_output_plans(compiled.scenario_plan.distributed_output_plans) + requested_outputs = _compile_requested_output_retention( + compiled.model, compiled.applications_by_id, destinations, plans_by_application, + compiled.scenario_plan.manual_application_ids, output_requests, accepted_call_times) retained_outputs_by_application = Dict{Symbol,Vector{Symbol}}() retained_keys = if retain_all - all_outputs = Set{Tuple{Symbol,Symbol}}() - for retained_application_id in keys(compiled.applications_by_id) - _compiled_application_by_id(compiled, retained_application_id) do application - for variable in _model_application_output_variables(compiled, application) - push!(all_outputs, (application.id, variable)) - end - end - end - all_outputs + _collect_retained_output_keys(compiled.applications_by_id, + _retention_destination_ids(compiled.distributed_outputs), + _retention_output_plans(compiled.scenario_plan.distributed_output_plans)) else union(temporal_dependencies, requested_outputs) end @@ -5016,15 +5058,9 @@ end function _explain_output_retention(compiled::CompiledCompositeModel, plan) keys_to_explain = if plan.retain_all - all_outputs = Set{Tuple{Symbol,Symbol}}() - for retained_application_id in keys(compiled.applications_by_id) - _compiled_application_by_id(compiled, retained_application_id) do application - for variable in _model_application_output_variables(compiled, application) - push!(all_outputs, (application.id, variable)) - end - end - end - all_outputs + _collect_retained_output_keys(compiled.applications_by_id, + _retention_destination_ids(compiled.distributed_outputs), + _retention_output_plans(compiled.scenario_plan.distributed_output_plans)) else union(plan.temporal_dependencies, plan.requested_outputs) end @@ -7853,12 +7889,12 @@ end variable::Symbol, ) = _prepared_output_request_types(_execution_cohort_schema(schema), variable) -@inline _visit_output_request(request, operation::F) where {F} = operation(request) -@inline _visit_output_request(record::CompiledOutputRequest, operation::F) where {F} = operation(record.request) +@inline _visit_output_request(request, operation::F, args::Vararg{Any,N}) where {F,N} = operation(request, args...) +@inline _visit_output_request(record::CompiledOutputRequest, operation::F, args::Vararg{Any,N}) where {F,N} = operation(record.request, args...) -function _foreach_output_request(operation::F, requests) where {F} +function _foreach_output_request(operation::F, requests, args::Vararg{Any,N}) where {F,N} for slot in 1:length(requests) - Base.@inline _with_metadata_entry(_visit_output_request, requests, slot, operation) + Base.@inline _with_metadata_entry(_visit_output_request, requests, slot, operation, args...) end return nothing end @@ -8440,32 +8476,56 @@ function _materialize_model_output_rows(rows, sink) end function _model_request_application_id(model::CompositeModel, compiled::CompiledCompositeModel, request) + return _model_request_application_id(model, compiled.applications_by_id, + _retention_destination_ids(compiled.distributed_outputs), + _retention_output_plans(compiled.scenario_plan.distributed_output_plans), + compiled.scenario_plan.manual_application_ids, request) +end + +Base.@noinline function _model_request_application_id(model::CompositeModel, + applications_by_id, destinations, plans_by_application, manual_application_ids, request, +) I = keytype(typeof(model.registry.objects)) requested_ids = Set{I}() for id in resolve_object_ids(model, request.selector; context=request.context) push!(requested_ids, _index_object_id(model.registry.objects, id)) end declared_scale = _selector_declared_scale(request.selector) + return _select_model_request_application(model.registry.objects, applications_by_id, + destinations, plans_by_application, manual_application_ids, request, + requested_ids, declared_scale) +end + +function _model_request_application_matches(application, objects, destinations, + plans_by_application, request, requested_ids, declared_scale, +) + isnothing(request.application) || + application.id == request.application || + application.name == request.application || + return false + local_output = request.var in _model_output_names(application) + local_match = local_output && ( + any(id -> id in requested_ids, application.target_ids) || + (!isnothing(declared_scale) && + _model_application_matches_scale(objects, application, declared_scale)) + ) + distributed_match = _model_request_matches_distributed_output( + application, request, requested_ids, destinations, plans_by_application, + ) + (local_match || distributed_match) || return false + return !(isnothing(request.application) && !distributed_match && + _publish_mode_for_output(application.spec, request.var) == :stream_only) +end + +Base.@noinline function _select_model_request_application(objects, applications_by_id, + destinations, plans_by_application, manual_application_ids, request, + requested_ids, declared_scale, +) candidates = Symbol[] - for application_id in keys(compiled.applications_by_id) - matches = _compiled_application_by_id(compiled, application_id) do application - isnothing(request.application) || - application.id == request.application || - application.name == request.application || - return false - local_output = request.var in _model_output_names(application) - local_match = local_output && ( - any(id -> id in requested_ids, application.target_ids) || - (!isnothing(declared_scale) && - _model_application_matches_scale(model, application, declared_scale)) - ) - distributed_match = _model_request_matches_distributed_output( - compiled, application, request, requested_ids, - ) - (local_match || distributed_match) || return false - return !(isnothing(request.application) && !distributed_match && - _publish_mode_for_output(application.spec, request.var) == :stream_only) - end + for application_id in keys(applications_by_id) + matches = _with_metadata_entry(_model_request_application_matches, + applications_by_id, application_id, objects, destinations, + plans_by_application, request, requested_ids, declared_scale) matches && push!(candidates, application_id) end if isempty(candidates) @@ -8479,7 +8539,6 @@ function _model_request_application_id(model::CompositeModel, compiled::Compiled error(String(take!(io))) elseif length(candidates) > 1 if isnothing(request.application) - manual_application_ids = _manual_call_application_ids(compiled) root_candidates = filter( id -> !(id in manual_application_ids), candidates, @@ -8501,63 +8560,41 @@ function _model_request_application_id(model::CompositeModel, compiled::Compiled end _model_request_matches_distributed_output( - compiled, - application, - request, - requested_ids, - ::NoCompiledDistributedOutputs, + application, request, requested_ids, ::Nothing, plans_by_application, ) = false -function _model_request_matches_distributed_output( - compiled, - application, - request, - requested_ids, - distributed_outputs::CompiledDistributedOutputs, +function _model_request_matches_distributed_output(application, request, requested_ids, + destinations_by_application_variable::AbstractDict, plans_by_application, ) destination_ids = get( - distributed_outputs.destination_ids_by_application_variable, + destinations_by_application_variable, (application.id, request.var), (), ) concrete_match = any(id -> id in requested_ids, destination_ids) isempty(requested_ids) || return concrete_match - plans = compiled.scenario_plan.distributed_output_plans - plans isa CompiledDistributedOutputPlans || return false + isnothing(plans_by_application) && return false return any( plan -> request.var in plan.variable_names && _selector_labels_may_overlap(request.selector, plan.selector), - _application_plans(plans.by_application, application.id), + _application_plans(plans_by_application, application.id), ) end -_model_request_matches_distributed_output( - compiled, - application, - request, - requested_ids, -) = _model_request_matches_distributed_output( - compiled, - application, - request, - requested_ids, - compiled.distributed_outputs, -) - function _selector_declared_scale(selector::AbstractObjectMultiplicity) selector_criteria = criteria(selector) return _criteria_get(selector_criteria, :scale, nothing) end function _model_application_matches_scale( - model::CompositeModel, + objects::AbstractDict, application::CompiledModelApplication, scale::Symbol, ) declared_scale = _selector_declared_scale(application.applies_to) declared_scale == scale && return true for object_id in application.target_ids - object = get(model.registry.objects, object_id, nothing) + object = get(objects, object_id, nothing) !isnothing(object) && object.scale == scale && return true end return false diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl index 6f969635b..3948b812b 100644 --- a/test/test-model-output-retention-owners.jl +++ b/test/test-model-output-retention-owners.jl @@ -134,6 +134,18 @@ end finite = construction_trace(; schema, prototype) @test finite.snapshots == control.snapshots @test finite.conversions == control.conversions + request = OutputRequest(Many(scale=:Leaf), :private; name=:chosen, application=:writer) + for (requests, retain_all) in (((), false), ((), true), ((request,), false)) + ordinary_retention = PSE.compile_model_output_retention( + control.simulation.compiled, requests; retain_all) + finite_retention = PSE.compile_model_output_retention( + finite.simulation.compiled, requests; retain_all) + @test PSE._same_model_output_retention(ordinary_retention, finite_retention) + @test finite_retention.temporal_dependencies == Set([(:writer, :private)]) + @test finite_retention.dependency_horizons == Dict((:writer, :private) => 2.0) + @test PSE._explain_output_retention(control.simulation.compiled, ordinary_retention) == + PSE._explain_output_retention(finite.simulation.compiled, finite_retention) + end @test isempty(prototype) @test all(isempty, values(schema)) @test all(typeof(view) in control.schema.families[application] From e65ce525636dec976d95385b268aaeaa81204699 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 19:15:42 +0100 Subject: [PATCH 198/324] Scan the supplied status references once during object admission Read the immutable directory outside the prepared-name loop and use its field index for lookup. The finite recipe still checks each reference against the configured classes before registration. One generic directory scan supports newborn layouts in a safe native build. --- src/component_models/Status.jl | 15 ++++++++++----- .../prepared_status_manifest.jl | 13 +++++++------ test/test-fixed-status-manifest.jl | 19 +++++++++++++++++++ 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 1454ed2a0..946458786 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -329,17 +329,22 @@ Base.copy(status::Status) = Status(_copy_status_storage(_status_vars(status))) storage isa Union{_FixedStatusStorage,_ProjectedStatusStorage} || throw(ArgumentError("Unknown Status backing.")) return getfield(storage, :refs) end -@inline function _initial_status_reference_count(source::Status) - references = _initial_status_reference_storage(source) +@inline _initial_status_reference_count(source::Status) = + _initial_status_reference_count(_initial_status_reference_storage(source)) +# A newborn may supply any admitted layout. Box its directory once at this +# boundary so scanning a wide, mutable Status does not copy it for each field. +Base.@noinline Base.@nospecializeinfer function _initial_status_reference_count(@nospecialize(references::NamedTuple)) count = 0 for index in 1:nfields(references) getfield(references, index) === nothing || (count += 1) end return count end -@inline function _initial_status_reference(source::Status, name::Symbol) - references = _initial_status_reference_storage(source) - return isdefined(references, name) ? getfield(references, name) : nothing +@inline _initial_status_reference(source::Status, name::Symbol) = + _initial_status_reference(_initial_status_reference_storage(source), name) +@inline function _initial_status_reference(references::NamedTuple, name::Symbol) + slot = Base.fieldindex(typeof(references), name, false) + return iszero(slot) ? nothing : getfield(references, slot) end # S is admitted by the prepared owner BEFORE this generated operation. No source diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 00052b25d..2c4633b7a 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -742,11 +742,11 @@ end # Visit the prepared namespace in order without building a per-field method body. # The existing finite classifier admits each exact Ref before the shared worker. -function _prepared_status_source_allowed(recipe::PreparedBirthRecipe{S}, - model, object, parent_id, source::Status, raw) where {S} +Base.@noinline Base.@nospecializeinfer function _prepared_status_source_allowed(recipe::PreparedBirthRecipe{S}, + model, object, parent_id, @nospecialize(references::NamedTuple), raw) where {S} present = 0 for name in _status_schema_names(S) - reference = _initial_status_reference(source, name) + reference = _initial_status_reference(references, name) if reference !== nothing present += 1 allowed, compatible = _prepared_status_configured_reference_admission(recipe, model, @@ -755,7 +755,7 @@ function _prepared_status_source_allowed(recipe::PreparedBirthRecipe{S}, _prepared_status_raw_reference_allowed(raw, name, reference)) || return false end end - return present == _initial_status_reference_count(source) + return present == _initial_status_reference_count(references) end _object_birth_recipe(manifest, object) = get(manifest.birth_recipes, object.scale, manifest.all_routes) @@ -767,11 +767,12 @@ _object_birth_recipe(manifest, object) = get(manifest.birth_recipes, object.scal isnothing(source_status) && return nothing source_status isa Status || throw(ArgumentError("Prepared initial data must be Status or nothing.")) recipe = _object_birth_recipe(manifest, object) - allowed = Base.@inline _prepared_status_source_allowed(recipe, model, object, parent_id, source_status, nothing) + references = _initial_status_reference_storage(source_status) + allowed = _prepared_status_source_allowed(recipe, model, object, parent_id, references, nothing) allowed && return nothing for raw in recipe.raw_families _prepared_status_raw_matches(raw, recipe, model, object, parent_id) || continue - Base.@inline _prepared_status_source_allowed(recipe, model, object, parent_id, source_status, raw) && return nothing + _prepared_status_source_allowed(recipe, model, object, parent_id, references, raw) && return nothing end throw(ArgumentError("Status reference classes are incompatible with this prepared object configuration/raw family.")) end diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index 9fb64a401..f9db4ebf0 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -19,6 +19,25 @@ PSE.inputs_(::Reader) = (x=Default(0f0),) PSE.outputs_(::Reader) = (;) PSE.run!(::Reader, status, environment, constants, context) = nothing +function _wide_leaf_admission_bytes(model, leaf, status) + return @allocated PSE._validate_prepared_initial_status(model, leaf, status, leaf.parent) +end + +@testset "admission reads a wide prepared leaf status without copying it for each field" begin + names = ntuple(i -> Symbol(:raw_, i), 160) + cells = ntuple(i -> isodd(i) ? Ref(i) : Ref(Float64(i)), length(names)) + scene = Object(:scene; scale=:Scene, status=Status(NamedTuple{names}(cells))) + old = Object(:old; scale=:Leaf, parent=:scene, status=Status(x=2.0)) + model = CompositeModel(scene, old; applications=( + ModelSpec(Source(0.0, 0.0, Ref(0)); name=:leaf_source, on=Many(scale=:Leaf)),)) + supplied = copy(model_status(model, :old)) + leaf = Object(:new; scale=:Leaf, parent=:scene, status=supplied) + _wide_leaf_admission_bytes(model, leaf, supplied) + @test _wide_leaf_admission_bytes(model, leaf, supplied) <= 4096 + @test register_object!(model, leaf) === leaf + @test PSE.refvalue(model_status(model, :new), :x) === PSE.refvalue(supplied, :x) +end + @testset "future declarations bound storage without cross-config numeric admission" begin a = Source(1f0, 2.0, Ref(0)) b = Source(1.0, 2f0, Ref(0)) From e9e6e3ccac0bd5af59e08521b8b27133b34fc6a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 19:24:32 +0100 Subject: [PATCH 199/324] Avoid repeated nested target types during cohort preparation Store nullable execution targets in a concrete row slot and publish each refreshed group directly into the plan arrays. Keeping the deep group type out of the intermediate NamedTuple avoids repeated subtype comparisons while preserving stable indices, removal and the same group counters. --- .../execution_cohort_refresh.jl | 2 +- src/composite_model/execution_cohorts.jl | 23 ++++++++----- src/composite_model/runtime_outputs.jl | 34 +++++++------------ test/test-execution-cohort-refresh.jl | 2 +- test/test-execution-cohorts.jl | 6 ++-- test/test-model-canonical-cohorts.jl | 4 +-- test/test-model-closed-cohort-schemas.jl | 6 ++-- test/test-model-cohort-store-identities.jl | 16 ++++----- test/test-model-temporal-initial-typing.jl | 4 +-- 9 files changed, 48 insertions(+), 49 deletions(-) diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index 71e7bcf2b..f99261a96 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -11,7 +11,7 @@ struct ExecutionCohortMembership{S<:ExecutionCohortSchema,I<:ObjectId,L<:Executi end function _execution_cohort_target(cohort::ExecutionCohort{T}, row::Int) where {T} - target = cohort.rows[row] + target = cohort[row] isnothing(target) && throw(ArgumentError( "An execution membership refers to a removed or replaced payload schema.", )) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 54c9dd1a2..c4f3c2458 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -1,12 +1,18 @@ abstract type AbstractExecutionCohort end +# The row array has a nominal element type, including when T is a nested call +# target. Removing a target releases it without invalidating existing row indices. +struct _ExecutionCohortSlot{T} + value::Union{Nothing,T} +end + mutable struct ExecutionCohort{T,I<:ObjectId,O} <: AbstractExecutionCohort owner::O application_id::Symbol - rows::Vector{Union{Nothing,T}} + rows::Vector{_ExecutionCohortSlot{T}} indices::Dict{I,Int} - ExecutionCohort{T,I,O}(owner::O, application_id::Symbol, rows::Vector{Union{Nothing,T}}, + ExecutionCohort{T,I,O}(owner::O, application_id::Symbol, rows::Vector{_ExecutionCohortSlot{T}}, indices::Dict{I,Int}) where {T,I<:ObjectId,O} = new{T,I,O}(owner, application_id, rows, indices) end @@ -234,7 +240,7 @@ Base.dataids(rows::ExecutionCohortRows) = Base.@propagate_inbounds function Base.getindex(rows::ExecutionCohortRows{T}, index::Int) where {T} @boundscheck checkbounds(rows.indices, index) slot = @inbounds rows.indices[index] - target = @inbounds rows.cohort.rows[slot] + target = @inbounds rows.cohort[slot] isnothing(target) && throw(ArgumentError( "This execution target was removed or changed its payload schema.", )) @@ -252,13 +258,14 @@ function _execution_cohort(store::ExecutionCohortStore{StoreI,O}, owner, applica I <: StoreI || throw(ArgumentError("The execution target identity is outside the store schema.")) owner = _execution_store_owner(store, owner) cohort = get!(store.cohorts, _execution_cohort_key(store, owner, application_id, T)) do - ExecutionCohort{T,I,O}(owner, application_id, Union{Nothing,T}[], Dict{I,Int}()) + ExecutionCohort{T,I,O}(owner, application_id, _ExecutionCohortSlot{T}[], Dict{I,Int}()) end return cohort::ExecutionCohort{T,I,O} end -function _clear_execution_cohort_row!(cohort::ExecutionCohort, row::Int) - cohort.rows[row] = nothing +Base.@propagate_inbounds Base.getindex(cohort::ExecutionCohort, row::Int) = cohort.rows[row].value +function _clear_execution_cohort_row!(cohort::ExecutionCohort{T}, row::Int) where {T} + cohort.rows[row] = _ExecutionCohortSlot{T}(nothing) return nothing end @@ -283,11 +290,11 @@ function _store_execution_cohort_target!( end slot = get(cohort.indices, object_id, 0) if iszero(slot) - push!(cohort.rows, target) + push!(cohort.rows, _ExecutionCohortSlot{T}(target)) slot = length(cohort.rows) cohort.indices[object_id] = slot else - cohort.rows[slot] = target + cohort.rows[slot] = _ExecutionCohortSlot{T}(target) end store.locations[_execution_location_key(store, owner, cohort.application_id, object_id)] = ExecutionCohortLocation(cohort, slot) return slot diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 7ae1f98be..f069f22be 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3810,13 +3810,10 @@ function compile_model_execution_plan( application.id in manual_application_ids && continue previous_group = isnothing(batch_schemas) ? nothing : _prepared_execution_group(application,getproperty(batch_schemas,application.id),cohorts) - refreshed = _refresh_model_execution_group!( - previous_group, cohorts, compiled, env_bindings, application, + _refresh_model_execution_group!( + groups, batches, previous_group, cohorts, compiled, env_bindings, application, temporal_streams, output_retention, constants, nothing, nothing, ) - isnothing(refreshed.group) && continue - push!(groups, refreshed.group) - append!(batches, refreshed.group.batches) end application_count = length(compiled.scenario_plan.applications) return CompiledExecutionPlan( @@ -4444,7 +4441,7 @@ function _same_execution_members(left, right) end function _refresh_model_execution_group!( - previous_group, + groups, batches, previous_group, cohorts::ExecutionCohortStore, compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, @@ -4514,12 +4511,12 @@ function _refresh_model_execution_group!( if !isnothing(group) && group === previous_group && group_changed _runtime_performance_count!(performance, :execution_groups_updated_in_place) end - return ( - group=group, - targets_constructed=refreshed.targets_constructed, - batches_constructed=assembled.batches_constructed, - group_reused=reused_group && !group_changed, - ) + if !isnothing(group) + push!(groups, group) + append!(batches, group.batches) + end + return (refreshed.targets_constructed, assembled.batches_constructed, + Int(reused_group && !group_changed)) end function _changed_execution_target_ids_by_application(changed_execution_target_ids, @@ -4683,16 +4680,11 @@ function _refresh_model_execution_plan( end changed_ids = isnothing(changed_by_application) ? nothing : get(changed_by_application, application.id, ()) - refreshed = _refresh_model_execution_group!( - previous_group, previous.cohorts, compiled, env_bindings, application, - temporal_streams, output_retention, constants, performance, changed_ids, + return _refresh_model_execution_group!( + groups, batches, previous_group, previous.cohorts, compiled, env_bindings, + application, temporal_streams, output_retention, constants, performance, + changed_ids, ) - if !isnothing(refreshed.group) - push!(groups, refreshed.group) - append!(batches, refreshed.group.batches) - end - return (refreshed.targets_constructed, refreshed.batches_constructed, - Int(refreshed.group_reused)) end end targets_constructed += counts[1] diff --git a/test/test-execution-cohort-refresh.jl b/test/test-execution-cohort-refresh.jl index 047246d49..7db47a710 100644 --- a/test/test-execution-cohort-refresh.jl +++ b/test/test-execution-cohort-refresh.jl @@ -141,7 +141,7 @@ end @test length(store.cohorts) == 2 @test execution_refresh_test_targets(extended.membership)[1] === changed @test execution_refresh_test_targets(extended.membership)[2] === last - @test isnothing(first_location.cohort.rows[first_location.row]) + @test isnothing(first_location.cohort[first_location.row]) @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location empty!(checked) diff --git a/test/test-execution-cohorts.jl b/test/test-execution-cohorts.jl index 9359584f8..41b5f097d 100644 --- a/test/test-execution-cohorts.jl +++ b/test/test-execution-cohorts.jl @@ -97,7 +97,7 @@ end @test getproperty.(rows, :object_id) == ObjectId.([0, 30]) @test PlantSimEngine.remove_cohort_target!(store, :growth, ObjectId(10)) @test isnothing(PlantSimEngine.cohort_location(store, :growth, ObjectId(10))) - @test isnothing(rows.cohort.rows[first_location.row]) + @test isnothing(rows.cohort[first_location.row]) @test !PlantSimEngine.remove_cohort_target!(store, :growth, ObjectId(10)) insert!(rows, 2, first) @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location @@ -124,7 +124,7 @@ end @test changed_rows.cohort !== rows.cohort @test changed_rows[1] === changed @test PlantSimEngine.cohort_location(store, :growth, changed.object_id).cohort === changed_rows.cohort - @test isnothing(rows.cohort.rows[first_location.row]) + @test isnothing(rows.cohort[first_location.row]) @test_throws ArgumentError rows[1] @test rows[2] === last @test PlantSimEngine.cohort_location(store, :growth, last.object_id) === last_location @@ -135,5 +135,5 @@ end @test restored[1] === first @test PlantSimEngine.cohort_location(store, :growth, first.object_id) === first_location @test rows[2] === last - @test isnothing(changed_rows.cohort.rows[1]) + @test isnothing(changed_rows.cohort[1]) end diff --git a/test/test-model-canonical-cohorts.jl b/test/test-model-canonical-cohorts.jl index c951173e0..4a085396e 100644 --- a/test/test-model-canonical-cohorts.jl +++ b/test/test-model-canonical-cohorts.jl @@ -82,7 +82,7 @@ function assert_canonical_storage(simulation) @test isconcretetype(eltype(view)) @test length(view.indices) == length(view) for (index, target) in enumerate(view) - @test view.cohort.rows[view.indices[index]] === target + @test view.cohort[view.indices[index]] === target location = PSE.cohort_location(store, batch.application.id, target.object_id) @test location.cohort === view.cohort @test location.row == view.indices[index] @@ -274,7 +274,7 @@ end function assert_manual_location(store, application, target, owner) location = PSE.cohort_location(store, application, object_id(target); owner) - @test location.cohort.rows[location.row] === target.execution_target + @test location.cohort[location.row] === target.execution_target return nothing end diff --git a/test/test-model-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl index 49ef5b577..00ff215ad 100644 --- a/test/test-model-closed-cohort-schemas.jl +++ b/test/test-model-closed-cohort-schemas.jl @@ -41,7 +41,7 @@ end replaced = refresh(store, targets, (1, 3), (1,); previous=membership, schema) @test replaced.membership === membership @test flatten(membership) == [changed, last] - @test isnothing(first_location.cohort.rows[first_location.row]) + @test isnothing(first_location.cohort[first_location.row]) @test Base.last(membership.runs) === old_rows @test old_rows.indices == [last_location.row] @test only(old_rows) === last @@ -175,7 +175,7 @@ end @test only(flatten(added.membership)) === witness PSE.refresh_cohort_membership!(builder, store, :growth, ids(()), ids((7,)); previous=membership) @test isempty(membership.runs) - @test isnothing(location.cohort.rows[location.row]) + @test isnothing(location.cohort[location.row]) PSE.refresh_cohort_membership!(builder, store, :growth, ids((7,)), ids((7,)); previous=membership) @test calls[] == 2 @test PSE.cohort_location(store, :growth, witness.object_id) === location @@ -210,7 +210,7 @@ end @test_throws ArgumentError PSE._append_execution_cohort_target!(rows, first) @test length(rows) == 2 @test changed_rows[1] === changed - @test isnothing(original_locations[1].cohort.rows[original_locations[1].row]) + @test isnothing(original_locations[1].cohort[original_locations[1].row]) end PSE.@process "closed_cohort_owner" verbose=false diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index d62756c5c..a75ebf14d 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -94,8 +94,8 @@ end alias_owner = PSE._execution_call_owner(alias_calls.binding) first_location = PSE.cohort_location(store, :leaf, ObjectId(1); owner=first_owner) alias_location = PSE.cohort_location(store, :leaf, ObjectId(1); owner=alias_owner) - first_target = first_location.cohort.rows[first_location.row] - alias_target = alias_location.cohort.rows[alias_location.row] + first_target = first_location.cohort[first_location.row] + alias_target = alias_location.cohort[alias_location.row] first_context = first_target.context reference = PSE.refvalue(model_status(data.model, 1), :value) @test first_location.cohort !== alias_location.cohort @@ -113,7 +113,7 @@ end retained = PSE.cohort_location(store, :leaf, ObjectId(1); owner=first_owner) @test retained.cohort === first_location.cohort @test retained.row == first_location.row - @test retained.cohort.rows[retained.row] === first_target + @test retained.cohort[retained.row] === first_target @test first_target.context === first_context @test PSE.refvalue(model_status(data.model, 1), :value) === reference @test model_status(data.model, 1).value === 4.0f0 @@ -168,7 +168,7 @@ end second end @test refreshed.membership === initial.membership - @test isnothing(location.cohort.rows[location.row]) + @test isnothing(location.cohort[location.row]) @test only(only(refreshed.membership.runs)) === second @test second.status === status @test length(store.cohorts) == 2 @@ -255,7 +255,7 @@ end previous = simulation.execution_plan store = check_store(simulation, closed) location = PSE.cohort_location(store,:controller,ObjectId(:root)) - target = location.cohort.rows[location.row] + target = location.cohort[location.row] reference = PSE.refvalue(model_status(data.model, 1), :value) # Removing an application prepares a new configuration through the # existing authoring API. Preserve the genuine scientific cells while @@ -279,7 +279,7 @@ end @test (@inferred plan_cohorts(refreshed.plan)) === store @test only(refreshed.plan.groups).application.id === :leaf @test isnothing(PSE.cohort_location(store,:controller,ObjectId(:root))) - @test isnothing(location.cohort.rows[location.row]) + @test isnothing(location.cohort[location.row]) @test target.status_view.status.ticks == 0 @test model_status(data.model, 1).value === 0.0f0 @test PSE.refvalue(model_status(data.model, 1), :value) === reference @@ -308,7 +308,7 @@ Base.hash(owner::OwnerAlias, seed::UInt) = hash(owner.value, seed) rows = PSE.cohort_rows!(store, :leaf, [payload]; owner=stored) location = PSE.cohort_location(store, :leaf, ObjectId(1); owner=query) @test location.cohort === rows.cohort - @test location.cohort.rows[location.row] === payload + @test location.cohort[location.row] === payload @test PSE._execution_cohort(store, query, :leaf, typeof(payload)) === rows.cohort @test length(store.cohorts) == 1 stored_key = PSE._execution_location_key(store, stored, :leaf, ObjectId(1)) @@ -316,7 +316,7 @@ Base.hash(owner::OwnerAlias, seed::UInt) = hash(owner.value, seed) @test isequal(query_key, stored_key) @test hash(query_key) == hash(stored_key) @test PSE.remove_cohort_target!(store, :leaf, ObjectId(1); owner=query) - @test isnothing(rows.cohort.rows[location.row]) + @test isnothing(rows.cohort[location.row]) @test isempty(store.locations) @test PSE.refvalue(payload.status, :value) === PSE.refvalue(status, :value) end diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index bc399938a..95b26f98c 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -452,7 +452,7 @@ function check_initially_empty_publication() @test isempty(source_group.batches) @test isnothing(PSE.cohort_location(previous_rows.store, :source, ObjectId(:newborn); owner=previous_rows.cohort.owner)) - @test isnothing(retired.cohort.rows[retired.row]) + @test isnothing(retired.cohort[retired.row]) for (data, old_history) in zip((ordinary, candidate), retained_histories) @test all(history(data)[key] == values for (key, values) in old_history) register_object!(data.model, Object(:regrown; scale=:Leaf, parent=:scene, @@ -468,7 +468,7 @@ function check_initially_empty_publication() owner=previous_rows.cohort.owner) @test regrown.cohort === retired.cohort @test regrown.row != retired.row - @test isnothing(retired.cohort.rows[retired.row]) + @test isnothing(retired.cohort[retired.row]) regrown_status = model_status(candidate.model, :regrown) @test only(regrown_batch.targets).status_view.canonical_status === regrown_status @test PSE.refvalue(only(regrown_batch.targets).status_view.status, :signal) === From 82ff9e6d79498ed406a5dc2f6eb386d900a9b86c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 19:39:16 +0100 Subject: [PATCH 200/324] Admit declared future object identities when closing a prepared registry Allow a compiled scenario to provide the finite identity types of organs it can create later. Validate existing keys before copying rows, share the prepared status owners and avoid reinstalling watchers when the same domain is already closed. Exercise mixed newborn identities, the empty registry and rejection. --- src/composite_model/object_families.jl | 18 ++++++++ test/integration/native_preparation.jl | 5 ++- test/test-object-families.jl | 60 ++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 2 deletions(-) diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index fbb92455f..5d7e8fe29 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -240,6 +240,24 @@ function _closed_object_family_store(store::ObjectFamilyStore{K,<:ClosedObjectFa # closure narrows only that ID domain, never discovers another Status layout. K !== ObjectId && return store I = isempty(store) ? K : Union{unique(typeof(id) for id in keys(store))...} + return _copy_closed_object_family_store(store, I) +end + +function _closed_object_family_store(store::ObjectFamilyStore{K,<:ClosedObjectFamilyCatalog}, + ::Type{I}) where {K,I} + members = Base.uniontypes(I) + !isempty(members) && all(T -> T <: ObjectId && isconcretetype(T), members) || + throw(ArgumentError("A declared closed identity domain requires concrete ObjectId types.")) + K === I && return store + # Validate any narrower domain before copying a row: row admission installs + # reference-change watchers on the existing canonical Status headers. + (K <: I || all(id -> id isa I, keys(store))) || + throw(ArgumentError("The declared closed identity domain excludes an existing object.")) + return _copy_closed_object_family_store(store, I) +end + +function _copy_closed_object_family_store(store::ObjectFamilyStore{K,<:ClosedObjectFamilyCatalog}, + ::Type{I}) where {K,I} manifest = store.catalog.status_manifest S = manifest.status_type families = (ObjectFamily{I,Nothing}(Union{Nothing,ObjectFamilyRow{I,Nothing}}[]), diff --git a/test/integration/native_preparation.jl b/test/integration/native_preparation.jl index 47801a7eb..30e79baef 100644 --- a/test/integration/native_preparation.jl +++ b/test/integration/native_preparation.jl @@ -2,7 +2,7 @@ module NativePreparation import PlantSimEngine as PSE export close_registry, RuntimeTypes, InputTrace, remember!, batch_schema -function close_registry(model) +function close_registry(model, id_type=nothing) previous = model.registry manifest = PSE._scenario_preparation(model).status_manifest for object in PSE.model_objects(model) @@ -11,7 +11,8 @@ function close_registry(model) error("Fresh objects lost the prepared canonical Status owner.") status === object.status || error("The facade lost its canonical status.") end - store = PSE._closed_object_family_store(previous.objects) + store = isnothing(id_type) ? PSE._closed_object_family_store(previous.objects) : + PSE._closed_object_family_store(previous.objects, id_type) store.catalog.status_manifest === manifest || error("Registry closure changed the manifest.") registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 912f86190..74eeb4ad2 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -411,4 +411,64 @@ end end end +@testset "declared closed ID domains admit real future identities before row copies" begin + parent = Object(:plant; kind=:plant, status=Status(value=1f0)) + model = CompositeModel(parent; applications=(ModelSpec( + FamilyReplacement((value=0f0,)); name=:leaves, on=Many(kind=:leaf)),)) + original = model_status(model, :plant) + reference = PSE.refvalue(original, :value) + snapshot_watchers() = begin + watchers = PSE._status_vars(original).watchers + watchers isa Vector ? copy(watchers) : watchers + end + before_watchers = snapshot_watchers() + for invalid in (ObjectId, Int, Union{}, ObjectId{Int}) + @test_throws ArgumentError PSE._closed_object_family_store(model.registry.objects, invalid) + @test snapshot_watchers() == before_watchers + @test model_status(model, :plant) === original + @test PSE.refvalue(original, :value) === reference + end + I = Union{ObjectId{Symbol},ObjectId{Tuple{Symbol,Symbol,Int}}} + store = PSE._closed_object_family_store(model.registry.objects, I) + @test keytype(store) === I + @test store.catalog.status_manifest === model.registry.objects.catalog.status_manifest + admitted_watchers = snapshot_watchers() + @test PSE._closed_object_family_store(store, I) === store + @test snapshot_watchers() == admitted_watchers + registry = PSE.ObjectRegistry(store, model.registry.by_scale, model.registry.by_kind, + model.registry.by_species, model.registry.ancestor_ids_by_object) + closed = PSE.CompositeModel(registry, + (getfield(model, index) for index in 2:fieldcount(typeof(model)))...) + @test model_object(closed, :plant) === parent + @test model_status(closed, :plant) === original + @test PSE.refvalue(model_status(closed, :plant), :value) === reference + supplied = Status(value=2f0) + newborn_reference = PSE.refvalue(supplied, :value) + newborn = Object((:plant, :leaf, 1); kind=:leaf, parent=:plant, status=supplied) + register_object!(closed, newborn) + @test model_object(closed, newborn.id) === newborn + @test object_id(closed, newborn) === ObjectId((:plant, :leaf, 1)) + @test model_status(closed, newborn.id) === newborn.status + @test PSE.refvalue(newborn.status, :value) === newborn_reference + children = copy(parent.children) + @test_throws ArgumentError register_object!(closed, + Object(17; kind=:leaf, parent=:plant, status=Status(value=3f0))) + @test !haskey(store, ObjectId(17)) + @test parent.children == children + @test PSE._closed_object_family_store(store) === store + + empty_model = CompositeModel(; applications=(ModelSpec( + FamilyReplacement((value=0f0,)); name=:leaves, on=Many(kind=:leaf)),)) + empty_store = empty_model.registry.objects + legacy_empty = PSE._closed_object_family_store(empty_store) + @test isempty(legacy_empty) + @test keytype(legacy_empty) === ObjectId + @test legacy_empty !== empty_store + @test legacy_empty.catalog.status_manifest === empty_store.catalog.status_manifest + declared_empty = PSE._closed_object_family_store(empty_store, I) + @test isempty(declared_empty) + @test keytype(declared_empty) === I + @test PSE._closed_object_family_store(declared_empty, I) === declared_empty +end + end From 1a09d5b8d9471312e841df7f0bc1ac84b3d475da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 19:56:07 +0100 Subject: [PATCH 201/324] Use the canonical application slots when closing a fixed plan Build the fixed slot tuple with the same slot assignment used by ordinary execution and refresh. This drops a second application-id dictionary and preserves empty/manual slots and the identities of closed groups. --- src/composite_model/execution_dispatch.jl | 5 ++--- test/test-model-cohort-store-identities.jl | 3 +++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/composite_model/execution_dispatch.jl b/src/composite_model/execution_dispatch.jl index e40221c89..d2ad77a20 100644 --- a/src/composite_model/execution_dispatch.jl +++ b/src/composite_model/execution_dispatch.jl @@ -29,9 +29,8 @@ end """Close schedule container schemas without copying the live execution payloads.""" function _fixed_execution_plan(plan::CompiledExecutionPlan) groups = Tuple(_close_execution_group_cohorts(group; batches=Tuple(group.batches)) for group in plan.groups) - groups_by_id = Dict(group.application.id => group for group in groups) - groups_by_slot = Tuple(isnothing(group) ? nothing : groups_by_id[group.application.id] - for group in plan.groups_by_application_slot) + groups_by_slot = Tuple(_execution_groups_by_application_slot(groups, + length(plan.groups_by_application_slot))) batches = Tuple(batch for group in groups for batch in group.batches) return CompiledExecutionPlan( plan.cohorts, diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index a75ebf14d..e1e425767 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -196,6 +196,9 @@ end @test fixed.topology isa PSE.FixedExecution @test fixed.cohorts === original.cohorts === store @test fieldtype(typeof(fixed), :cohorts) === typeof(store) + @test map(isnothing, fixed.groups_by_application_slot) == + Tuple(map(isnothing, original.groups_by_application_slot)) + @test fixed.groups_by_application_slot[only(fixed.groups).application.slot] === only(fixed.groups) @test only(only(fixed.groups).batches) === batch @test only(only(only(fixed.groups).batches).targets) === target fixed_simulation = PSE._simulation_with_execution_plan(simulation, fixed) From 39e8f2d641438ee4cfab5defbd70ed4872bb3911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 22:58:42 +0100 Subject: [PATCH 202/324] Require the payload type when constructing empty cohort slots --- src/composite_model/execution_cohorts.jl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index c4f3c2458..3512e77bd 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -4,6 +4,8 @@ abstract type AbstractExecutionCohort end # target. Removing a target releases it without invalidating existing row indices. struct _ExecutionCohortSlot{T} value::Union{Nothing,T} + + _ExecutionCohortSlot{T}(value::Union{Nothing,T}) where {T} = new{T}(value) end mutable struct ExecutionCohort{T,I<:ObjectId,O} <: AbstractExecutionCohort From 4efc1956056ab13ac0cdb5e8ce97547102870f7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 22:58:58 +0100 Subject: [PATCH 203/324] Exercise ambiguous newborn calls with a declared leaf value --- test/test-model-hard-calls.jl | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/test-model-hard-calls.jl b/test/test-model-hard-calls.jl index 6494a1ea6..b3d300289 100644 --- a/test/test-model-hard-calls.jl +++ b/test/test-model-hard-calls.jl @@ -1574,18 +1574,19 @@ end :newborn_leaf; scale=:Leaf, parent=:scene, - status=Status(marker=1.0), + status=Status(value=1.0), ), ) newborn_status = model_status(model, newborn) - @test propertynames(newborn_status) == (:marker,) + @test propertynames(newborn_status) == (:value,) @test_throws "Expected exactly one object" run_call!( context, :children; objects=newborn, publish=true, ) - @test propertynames(model_status(model, newborn)) == (:marker,) + @test propertynames(model_status(model, newborn)) == (:value,) + @test newborn_status.value == 1.0 @test model_status(model, :existing_leaf).calls == existing_calls @test Advanced.bindings_dirty(model) @test simulation.compiled === context.compiled From 1eec4bd5407d2d8f6f31894df87cddd4416a9cba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Wed, 18 Nov 2026 23:44:47 +0100 Subject: [PATCH 204/324] Hash concrete call-owner fields in closed cohort dictionaries --- src/composite_model/execution_cohorts.jl | 15 +++++++++++++-- test/test-model-cohort-store-identities.jl | 9 ++++++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/composite_model/execution_cohorts.jl b/src/composite_model/execution_cohorts.jl index 3512e77bd..4db069dee 100644 --- a/src/composite_model/execution_cohorts.jl +++ b/src/composite_model/execution_cohorts.jl @@ -38,8 +38,19 @@ end isequal(left.owner, right.owner) && left.application_id === right.application_id && isequal(left.item, right.item) -@inline Base.hash(key::ExecutionCohortKey, seed::UInt) = - hash(key.item, hash(key.application_id, hash(key.owner, seed))) +@inline function Base.hash(key::ExecutionCohortKey, seed::UInt) + owner = key.owner + if owner isa Tuple{Symbol,ObjectId,Symbol,Symbol} + # A call's owner can contain several caller ID types. Hash the four + # fields directly so a closed dictionary needs no tuple dispatch. + application, caller, name, mode = owner + seed = hash(mode, hash((), seed)) + seed = hash(application, hash(caller, hash(name, seed))) + else + seed = hash(owner, seed) + end + return hash(key.item, hash(key.application_id, seed)) +end """Persistent payload storage with identity/owner types independent of target types. diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index e1e425767..844785a41 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -328,15 +328,16 @@ end _key_value(dict, key) = get(dict, key, 0) @testset "bounded keys admit independent caller and callee identities" begin - I = Union{ObjectId{Int},ObjectId{Symbol}} + leaf = ObjectId((:tree, :leaf, 1)) + I = Union{ObjectId{Int},ObjectId{Symbol},typeof(leaf)} O = Union{Nothing,Tuple{Symbol,I,Symbol,Symbol}} store = PSE.ExecutionCohortStore{I,O}() K = PSE.ExecutionCohortKey{O,I} @test isconcretetype(K) @test fieldtype(K, :owner) === O @test fieldtype(K, :item) === I - # Both cross-products are valid: caller identity is not the callee's type. - for (caller,callee) in ((ObjectId(:root),ObjectId(1)),(ObjectId(1),ObjectId(:leaf))) + for (caller,callee) in ((ObjectId(:root),ObjectId(1)), (ObjectId(1),ObjectId(:leaf)), + (leaf,ObjectId(:root)), (ObjectId(:root),leaf)) first = (:controller,caller,:first,:call) alias = (:controller,caller,:alias,:call) scheduled = PSE._execution_location_key(store, nothing, :leaf, callee) @@ -344,6 +345,8 @@ _key_value(dict, key) = get(dict, key, 0) aliased = PSE._execution_location_key(store, alias, :leaf, callee) @test typeof(scheduled) === typeof(called) === typeof(aliased) === K @test !isequal(scheduled, called) && !isequal(called, aliased) + seed = UInt(17) + @test hash(called, seed) == hash(callee, hash(:leaf, hash(first, seed))) values = Dict{K,Int}(scheduled=>1,called=>2,aliased=>3) @test (@inferred _key_value(values, called)) == 2 @test values[scheduled] == 1 && values[aliased] == 3 From 638a98947107573ae43193206ba314bbf60dca4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 00:20:44 +0100 Subject: [PATCH 205/324] Use typed object identities in model diagnostics --- src/composite_model/compilation.jl | 30 +++++++++--------- src/composite_model/object_families.jl | 2 +- src/composite_model/registry_topology.jl | 40 ++++++++++++------------ src/composite_model/runtime_outputs.jl | 30 +++++++++--------- src/composite_model/selectors.jl | 18 +++++------ test/test-object-families.jl | 13 ++++++++ 6 files changed, 73 insertions(+), 60 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index a108a5092..5a7f22450 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3128,7 +3128,7 @@ function _compile_consumer_input_recipe!( isempty(matches) && return nothing if length(matches) > 1 error( - "Input `$(plan.input)` on application `$(application_id)` for object `$(consumer_id.value)` " * + "Input `$(plan.input)` on application `$(application_id)` for object `$(_object_id_diagnostic_text(consumer_id))` " * "has ambiguous same-object producers: `$([match.application for match in matches])`. " * "Add `inputs=(:$(plan.input) => One(...),)` to disambiguate." ) @@ -5598,7 +5598,7 @@ function _explain_initialization(model, applications, input_bindings, provided_type=provided_type, conversion..., detail=disposition == :required ? - "Provide `$(variable)` on object `$(object_id.value)` Status or add `inputs=(:$(variable) => ..., )` to application `$(application.id)`." : + "Provide `$(variable)` on object `$(_object_id_diagnostic_text(object_id))` Status or add `inputs=(:$(variable) => ..., )` to application `$(application.id)`." : nothing, )) end @@ -5950,7 +5950,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) if _declares_update_without_previous_writer(application.spec, variable, previous) error( "Application `$(application.id)` declares `Updates($(variable))` for object ", - "`$(object_id.value)`, but no previous writer for `$(variable)` exists. ", + "`$(_object_id_diagnostic_text(object_id))`, but no previous writer for `$(variable)` exists. ", "Move it after the producer named in `after=...`." ) end @@ -5963,7 +5963,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) previous_labels = join(sort!([String(label) for label in labels]), ", ") error( "Ambiguous canonical writers for variable `$(variable)` on object ", - "`$(object_id.value)`. ", + "`$(_object_id_diagnostic_text(object_id))`. ", "applications. Application `$(application.id)` must declare ", "`Updates(:$(variable); after=...)` matching one of the previous writers ", "`$(previous_labels)`." @@ -5974,7 +5974,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) previous_writer = last(previous) error( "Application `$(application.id)` updates `$(variable)` on object ", - "`$(object_id.value)` without an ordering relation to the immediately ", + "`$(_object_id_diagnostic_text(object_id))` without an ordering relation to the immediately ", "previous writer `$(previous_writer)`. Add that application identifier ", "to `Updates(:$(variable); after=...)`." ) @@ -6148,7 +6148,7 @@ function _validate_compiled_writer_ownership!(ownership, applications_by_id) if owner.application_slot == owners[index - 1].application_slot error( "Application `$(owner.application_id)` declares more than one canonical " * - "writer for `$(variable)` on object `$(object_id.value)`. Ensure its " * + "writer for `$(variable)` on object `$(_object_id_diagnostic_text(object_id))`. Ensure its " * "`on=...` targets and `outputs_to` destinations do not overlap.", ) end @@ -6769,7 +6769,7 @@ function _model_object_status_for_preparation( ) status = model_status(model, object_id) (isnothing(status) || status isa Status) || error( - "Model object `$(object_id.value)` uses model applications but its status has type " * + "Model object `$(_object_id_diagnostic_text(object_id))` uses model applications but its status has type " * "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." ) return status @@ -6874,7 +6874,7 @@ end status = _replace_model_object_status!(model, object, replacement) end status isa Status || error( - "Model object `$(object_id.value)` uses model applications but its status has type ", + "Model object `$(_object_id_diagnostic_text(object_id))` uses model applications but its status has type ", "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." ) status isa S || throw(ArgumentError( @@ -6977,13 +6977,13 @@ function _validate_required_model_output_destinations!( value isa expected_type || throw(ArgumentError( "Distributed output `$(variable)` on application " * "`$(resolved.plan.application_id)` requires `$(expected_type)` " * - "on destination `$(destination_id.value)`; got `$(typeof(value))`.", + "on destination `$(_object_id_diagnostic_text(destination_id))`; got `$(typeof(value))`.", )) continue end push!(missing, "`$(resolved.plan.application_id).$(resolved.plan.group)` requires " * - "`$(variable)` on destination object `$(destination_id.value)`") + "`$(variable)` on destination object `$(_object_id_diagnostic_text(destination_id))`") end end end @@ -7007,7 +7007,7 @@ function _validate_model_output_destination_statuses!( (isnothing(status) || status isa Status) && continue error( "Output destination `$(resolved.plan.application_id).$(resolved.plan.group)` " * - "selected object `$(destination_id.value)` with status type " * + "selected object `$(_object_id_diagnostic_text(destination_id))` with status type " * "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`.", ) end @@ -7135,7 +7135,7 @@ function _model_output_destination_index(destination_ids::AbstractVector{I}) whe for (position, object_id) in pairs(destination_ids) haskey(index, object_id) && error( "Compiled output destination membership contains duplicate object " * - "ID `$(object_id.value)`.", + "ID `$(_object_id_diagnostic_text(object_id))`.", ) index[object_id] = position end @@ -8014,8 +8014,8 @@ function _temporal_source_application( binding.policy isa PreviousTimeStep && return nothing error( "Temporal model input `$(binding.input)` from ", - "`$(source_id.value).$(binding.source_var)` has no source application ", - "matching object `$(source_id.value)`.", + "`$(_object_id_diagnostic_text(source_id)).$(binding.source_var)` has no source application ", + "matching object `$(_object_id_diagnostic_text(source_id))`.", ) elseif binding.policy isa PreviousTimeStep return last(sort!(matches; by=application_id -> application_positions[application_id])) @@ -9448,7 +9448,7 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a isempty(missing) && return nothing details = join( [ - "`$(row.application_id)` on object `$(row.object_id.value)` requires `$(row.input)`" + "`$(row.application_id)` on object `$(_object_id_diagnostic_text(row.object_id))` requires `$(row.input)`" for row in missing ], "; ", diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 5d7e8fe29..197fcea59 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -149,7 +149,7 @@ function _validate_object_family_status_owner!(store::ObjectFamilyStore, status, if !isnothing(existing) && existing != id throw(ArgumentError( "The same Status instance cannot be owned by model objects " * - "`$(existing.value)` and `$(id.value)`. Give each Object its own Status instance.", + "`$(_object_id_diagnostic_text(existing))` and `$(_object_id_diagnostic_text(id))`. Give each Object its own Status instance.", )) end return nothing diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index de5236ce1..4f5566d62 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -286,7 +286,7 @@ function _register_mtg_object_identity!(adapter::MTGObjectAdapter, node) error( "The MTG id accessor maps nodes " * "$(MultiScaleTreeGraph.node_id(existing)) and " * - "$(MultiScaleTreeGraph.node_id(node)) to duplicate ObjectId `$(id.value)`.", + "$(MultiScaleTreeGraph.node_id(node)) to duplicate ObjectId `$(_object_id_diagnostic_text(id))`.", ) end adapter.object_ids_by_node[node] = id @@ -453,7 +453,7 @@ function _collect_model_items(items, instances) end ids = Set{ObjectId}() for object in objects - object.id in ids && error("CompositeModel contains object id `$(object.id.value)` more than once.") + object.id in ids && error("CompositeModel contains object id `$(_object_id_diagnostic_text(object.id))` more than once.") push!(ids, object.id) end return objects, mounted_instances @@ -481,13 +481,13 @@ function _prepare_object_instances!(objects, instances) for instance in instances root_id = _instance_root_id(instance) haskey(objects_by_id, root_id) || error( - "Object instance `$(instance.name)` refers to missing root object `$(root_id.value)`." + "Object instance `$(instance.name)` refers to missing root object `$(_object_id_diagnostic_text(root_id))`." ) ids = _object_descendant_ids(objects_by_id, root_id) for id in ids if haskey(claimed_ids, id) error( - "Object `$(id.value)` belongs to both instances `$(claimed_ids[id])` and `$(instance.name)`." + "Object `$(_object_id_diagnostic_text(id))` belongs to both instances `$(claimed_ids[id])` and `$(instance.name)`." ) end claimed_ids[id] = instance.name @@ -1146,7 +1146,7 @@ end throw( ArgumentError( "The same Status instance cannot be owned by model objects " * - "`$(existing.value)` and `$(object_id.value)`. Give each Object " * + "`$(_object_id_diagnostic_text(existing))` and `$(_object_id_diagnostic_text(object_id))`. Give each Object " * "its own Status instance.", ), ) @@ -1187,7 +1187,7 @@ function _replace_model_object_status!( status, ) (isnothing(status) || status isa Status) || error( - "Model object `$(object.id.value)` status must be a `Status` or `nothing`, " * + "Model object `$(_object_id_diagnostic_text(object.id))` status must be a `Status` or `nothing`, " * "got `$(typeof(status))`.", ) object.status === status && return status @@ -1213,13 +1213,13 @@ end # Scalar diagnostics retain their ordinary display. Composite identities use # the existing typed printer rather than Julia's generic syntax display. -_object_id_diagnostic_text(value) = string(value) -_object_id_diagnostic_text(value::Tuple) = _selector_diagnostic_text(value) +_object_id_diagnostic_text(id::ObjectId) = string(id.value) +_object_id_diagnostic_text(id::ObjectId{<:Tuple}) = _selector_diagnostic_text(id.value) function _model_object(model::CompositeModel, id) oid = ObjectId(id) object = get(model.registry.objects, oid, nothing) - isnothing(object) && error("No model object with id `", _object_id_diagnostic_text(oid.value), "`.") + isnothing(object) && error("No model object with id `", _object_id_diagnostic_text(oid), "`.") return object end @@ -1262,7 +1262,7 @@ function object_id(model::CompositeModel, object::Object) registered = _model_object(model, object.id) registered === object || throw( ArgumentError( - "Object `$(object.id.value)` is not the Object instance registered by this model.", + "Object `$(_object_id_diagnostic_text(object.id))` is not the Object instance registered by this model.", ), ) return object.id @@ -1277,7 +1277,7 @@ function object_id(model::CompositeModel, status::Status) matched_id = index[identity] _model_object(model, matched_id).status === status || error( "PlantSimEngine's Status identity index is inconsistent for object " * - "`$(matched_id.value)`. Replace runtime status through the model API.", + "`$(_object_id_diagnostic_text(matched_id))`. Replace runtime status through the model API.", ) return matched_id end @@ -1328,7 +1328,7 @@ function source_node(model::CompositeModel, source) id = object_id(model, source) node = get(adapter.nodes_by_object_id, id, nothing) isnothing(node) && error( - "No source MTG node is registered for model object `$(id.value)`.", + "No source MTG node is registered for model object `$(_object_id_diagnostic_text(id))`.", ) return node end @@ -1339,7 +1339,7 @@ function _object_ancestor_ids( ) ancestors = get(registry.ancestor_ids_by_object, object_id, nothing) isnothing(ancestors) && error( - "No cached topology path for model object `$(object_id.value)`.", + "No cached topology path for model object `$(_object_id_diagnostic_text(object_id))`.", ) return ancestors end @@ -1454,10 +1454,10 @@ end ) registry = model.registry id = _index_object_id(registry.objects, object.id) - haskey(registry.objects, id) && error("CompositeModel already contains object id `$(id.value)`.") + haskey(registry.objects, id) && error("CompositeModel already contains object id `$(_object_id_diagnostic_text(id))`.") parent_id = isnothing(parent) ? nothing : _index_object_id(registry.objects, ObjectId(parent)) if !isnothing(parent_id) && !haskey(registry.objects, parent_id) - error("No model object with id `$(parent_id.value)`.") + error("No model object with id `$(_object_id_diagnostic_text(parent_id))`.") end return _register_object_status!(model, object, id, parent_id, status_values_materialized) end @@ -1687,7 +1687,7 @@ function _validate_mutable_object_subtree!( ) isempty(instance_roots) && return nothing error( - "Cannot $(operation) object `$(object.id.value)` because its subtree contains ", + "Cannot $(operation) object `$(_object_id_diagnostic_text(object.id))` because its subtree contains ", "immutable ObjectInstance root(s) `$([id.value for id in instance_roots])`. ", "Mutate ordinary instance descendants instead.", ) @@ -1703,7 +1703,7 @@ function remove_object!(model::CompositeModel, id; recursive::Bool=true) descendant_ids, ) if !recursive && !isempty(object.children) - error("Cannot remove object `$(object.id.value)` with children unless `recursive=true`.") + error("Cannot remove object `$(_object_id_diagnostic_text(object.id))` with children unless `recursive=true`.") end snapshots = LifecycleObjectSnapshot[ _lifecycle_object_snapshot(model, _model_object(model, object_id)) @@ -1737,12 +1737,12 @@ function reparent_object!(model::CompositeModel, id, new_parent) ) new_parent_id = isnothing(new_parent) ? nothing : ObjectId(new_parent) if !isnothing(new_parent_id) - haskey(model.registry.objects, new_parent_id) || error("No model object with id `$(new_parent_id.value)`.") + haskey(model.registry.objects, new_parent_id) || error("No model object with id `$(_object_id_diagnostic_text(new_parent_id))`.") new_parent_id == object.id && error( - "Cannot reparent object `$(object.id.value)` to itself.", + "Cannot reparent object `$(_object_id_diagnostic_text(object.id))` to itself.", ) new_parent_id in descendant_ids && error( - "Cannot reparent object `$(object.id.value)` below its descendant `$(new_parent_id.value)`.", + "Cannot reparent object `$(_object_id_diagnostic_text(object.id))` below its descendant `$(_object_id_diagnostic_text(new_parent_id))`.", ) end old_parent_id = object.parent diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f069f22be..a0c4d2197 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -413,7 +413,7 @@ end hasproperty(context.bound_inputs, input) || throw( ArgumentError( "Application `$(context.application.id)` on object " * - "`$(context.object_id.value)` has no declared Many input " * + "`$(_object_id_diagnostic_text(context.object_id))` has no declared Many input " * "`$(input)`. Available identity-aware inputs: " * "`$(propertynames(context.bound_inputs))`.", ), @@ -460,7 +460,7 @@ end @noinline function _missing_distributed_output_target(context, name) throw(ArgumentError( - "Application `$(context.application.id)` on object `$(context.object_id.value)` " * + "Application `$(context.application.id)` on object `$(_object_id_diagnostic_text(context.object_id))` " * "has no distributed output `$(name)`. Available variables: " * "`$(propertynames(context.output_targets))`.", )) @@ -1737,7 +1737,7 @@ end function _model_object_status(model::CompositeModel, object_id::ObjectId) status = model_status(model, object_id) status isa Status || error( - "CompositeModel object `$(object_id.value)` has no `Status`; model runtime requires status-backed objects." + "CompositeModel object `$(_object_id_diagnostic_text(object_id))` has no `Status`; model runtime requires status-backed objects." ) return status end @@ -1751,7 +1751,7 @@ end key = (application.id, id) haskey(compiled.status_views_by_target, key) || error( "No compiled status view for application `$(application.id)` on object ", - "`$(object_id.value)`.", + "`$(_object_id_diagnostic_text(object_id))`.", ) return Base.@inline _with_model_status_view(identity, compiled.status_view_schema, application.id, compiled.status_views_by_target[key]) @@ -2435,7 +2435,7 @@ function _model_temporal_source_value( ) policy isa PreviousTimeStep && return nothing error( - "Temporal model input from `$(source_id.value).$(source_var)` has no ", + "Temporal model input from `$(_object_id_diagnostic_text(source_id)).$(source_var)` has no ", "source application for policy `$(typeof(policy))`." ) end @@ -2504,7 +2504,7 @@ function _materialize_model_temporal_input!( policy isa PreviousTimeStep || error( "No temporal model value available for input ", "`$(plan.input)` from ", - "`$(source_ids[index].value).$(plan.source_var)` ", + "`$(_object_id_diagnostic_text(source_ids[index])).$(plan.source_var)` ", "at t=$(time).", ) value = temporal_input.initial[index] @@ -2527,7 +2527,7 @@ function _materialize_model_temporal_input!( if isnothing(value) policy isa PreviousTimeStep || error( "No temporal model value available for input `$(plan.input)` from ", - "`$(source_id.value).$(plan.source_var)` at t=$(time).", + "`$(_object_id_diagnostic_text(source_id)).$(plan.source_var)` at t=$(time).", ) value = temporal_input.initial end @@ -2676,7 +2676,7 @@ function _materialize_model_temporal_input!( policy isa PreviousTimeStep || error( "No temporal model value available for input ", "`$(plan.input)` from ", - "`$(source_ids[index].value).$(plan.source_var)` ", + "`$(_object_id_diagnostic_text(source_ids[index])).$(plan.source_var)` ", "at t=$(time).", ) value = temporal_input.initial[index] @@ -2696,7 +2696,7 @@ function _materialize_model_temporal_input!( if isnothing(value) policy isa PreviousTimeStep || error( "No temporal model value available for input `$(plan.input)` from ", - "`$(source_id.value).$(plan.source_var)` at t=$(time).", + "`$(_object_id_diagnostic_text(source_id)).$(plan.source_var)` at t=$(time).", ) value = temporal_input.initial end @@ -3218,7 +3218,7 @@ function _runtime_temporal_source_stream( stream = get(streams, key, nothing) isnothing(stream) && error( "No initialized temporal source stream for application ", - "`$(application_id)` on object `$(binding.source_ids[index].value)` ", + "`$(application_id)` on object `$(_object_id_diagnostic_text(binding.source_ids[index]))` ", "and variable `$(binding.source_var)`.", ) return stream @@ -3297,7 +3297,7 @@ Base.@nospecializeinfer function _runtime_model_output_streams( if isnothing(stream) initialize_missing || error( "No initialized retained output stream for application ", - "`$(application.id)` on object `$(object_id.value)` and variable ", + "`$(application.id)` on object `$(_object_id_diagnostic_text(object_id))` and variable ", "`$(variable)`.", ) stream = _model_new_output_stream( @@ -5721,7 +5721,7 @@ end available = Symbol[targets.binding.call for targets in context.calls] error( "Application `$(context.application.id)` on object ", - "`$(context.object_id.value)` did not declare call `$(name)`. ", + "`$(_object_id_diagnostic_text(context.object_id))` did not declare call `$(name)`. ", "Declared calls: $(available).", ) end @@ -6052,7 +6052,7 @@ function _targeted_new_object_call_targets( initialization_key = (only(binding.potential_callee_application_ids), object_id) initialization_key in delta.initialized_targets && error( "Application `$(first(initialization_key))` already initialized newly " * - "registered object `$(object_id.value)` in this lifecycle event.", + "registered object `$(_object_id_diagnostic_text(object_id))` in this lifecycle event.", ) end @@ -6396,7 +6396,7 @@ function _current_topology_call_targets( available = Symbol[candidate.call for candidate in bindings] error( "Application `$(context.application.id)` on object ", - "`$(context.object_id.value)` did not declare call `$(name)`. ", + "`$(_object_id_diagnostic_text(context.object_id))` did not declare call `$(name)`. ", "Declared calls: $(available).", ) end @@ -6515,7 +6515,7 @@ function _environment_binding_for_current_context(context::RunContext) if isnothing(binding) || isnothing(binding.backend) error( "Cannot commit environment state for `$(context.application.id)` on object ", - "`$(context.object_id.value)`: no environment binding is configured. ", + "`$(_object_id_diagnostic_text(context.object_id))`: no environment binding is configured. ", "Attach an environment with `CompositeModel(...; environment=...)` and ", "`ModelSpec(model; environment=Environment(...))`." ) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 6714fde02..94743c7ce 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -389,7 +389,7 @@ function _object_override_models(instance::ObjectInstance, specs, instance_ids) valid_ids = Set(instance_ids) for override in instance.object_overrides override.object in valid_ids || error( - "Object override for `$(override.object.value)` does not belong to instance `$(instance.name)`." + "Object override for `$(_object_id_diagnostic_text(override.object))` does not belong to instance `$(instance.name)`." ) matches = findall( index -> @@ -398,23 +398,23 @@ function _object_override_models(instance::ObjectInstance, specs, instance_ids) eachindex(specs), ) isempty(matches) && error( - "Object override for `$(override.object.value)` in instance `$(instance.name)` ", + "Object override for `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)` ", "does not match a template application." ) length(matches) == 1 || error( - "Object override for `$(override.object.value)` in instance `$(instance.name)` ", + "Object override for `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)` ", "matches several template applications." ) index = only(matches) object_models = get!(entries, index, Pair{ObjectId,AbstractModel}[]) any(entry -> first(entry) == override.object, object_models) && error( "Several object overrides target application `$(_mounted_application_name(specs[index], index))` ", - "on object `$(override.object.value)` in instance `$(instance.name)`." + "on object `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)`." ) _validate_model_override_contract!( model_(specs[index]), override.model; - description="Object override for `$(override.object.value)` in instance `$(instance.name)`", + description="Object override for `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)`", ) push!(object_models, override.object => override.model) end @@ -749,7 +749,7 @@ function _named_scope_root_id(model::CompositeModel, scope::Scope) root_id, instance_name = _named_scope_root_candidate(model, scope) haskey(model.registry.objects, root_id) && return root_id isnothing(instance_name) || error( - "Object instance `$(instance_name)` has no current root object `$(root_id.value)`.", + "Object instance `$(instance_name)` has no current root object `$(_object_id_diagnostic_text(root_id))`.", ) available_ids = [id.value for id in object_ids(model)] available_instances = sort!(Symbol[instance.name for instance in model.instances]; by=string) @@ -757,7 +757,7 @@ function _named_scope_root_id(model::CompositeModel, scope::Scope) suggestions = root_id.value isa Symbol ? _near_symbol_matches(root_id.value, unique!([available_instances; symbolic_ids])) : Symbol[] error( - "No instance or object ID `$(root_id.value)` found in the model registry. ", + "No instance or object ID `$(_object_id_diagnostic_text(root_id))` found in the model registry. ", "available_ids=$(available_ids), available_instances=$(available_instances), ", "suggestions=$(suggestions).", ) @@ -955,9 +955,9 @@ end end _missing_point_scope_anchor(::CompositeModel, ::SelfPlant, id) = - error("No `scale=:Plant` ancestor found for object `$(id.value)`.") + error("No `scale=:Plant` ancestor found for object `$(_object_id_diagnostic_text(id))`.") _missing_point_scope_anchor(::CompositeModel, scope::Ancestor, id) = - error("No matching ancestor found for object `$(id.value)` and scale `$(scope.scale)`.") + error("No matching ancestor found for object `$(_object_id_diagnostic_text(id))` and scale `$(scope.scale)`.") @inline _point_scope_contains(topology, scope::Union{SelfPlant,Ancestor}, origin, object) = _relation_in_subtree(topology, object, _required_scope_anchor(topology, scope, origin)) diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 74eeb4ad2..00832cf2e 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -89,6 +89,19 @@ PSE.inputs_(::FamilyReplacement) = (;) PSE.outputs_(model::FamilyReplacement) = model.defaults PSE.run!(::FamilyReplacement, status, environment, constants, context) = nothing +@testset "application status diagnostics identify unselected objects" begin + root = Object(:root; status=Status(value=1f0)) + leaf = Object((:tree, :leaf, 2); scale=:Leaf, parent=:root, status=Status(value=2f0)) + model = CompositeModel(root, leaf; applications=(ModelSpec( + FamilyReplacement((value=1f0,)); name=:replacement, on=One(id=:root)),)) + compiled = run!(model; steps=0).compiled + application = PSE._compiled_application_by_id(compiled, :replacement) + @test !isnothing(PSE._model_status_view_for_application(compiled, application, root.id)) + @test_throws ErrorException("No compiled status view for application `replacement` on object " * + "`(Symbol(\"tree\"), Symbol(\"leaf\"), 2)`.") PSE._model_status_view_for_application( + compiled, application, leaf.id) +end + @noinline function escape_registered_status!(sink, model, id, count) for _ in 1:count sink[] = model_status(model, id) From 295c701e3e96c841f6a1f02476514e36a3944a95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 00:22:54 +0100 Subject: [PATCH 206/324] Resolve ancestor scopes through the same typed lookup --- src/composite_model/compilation.jl | 22 +++------------------- src/composite_model/selectors.jl | 18 +----------------- test/test-selector-ancestor-index.jl | 3 ++- 3 files changed, 6 insertions(+), 37 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 5a7f22450..6459dc2c1 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -509,23 +509,7 @@ function _selector_scope_anchor( isnothing(context) && return nothing context_id = _object_id_from_context(context) scope isa Union{Self,Subtree} && return context_id - if scope isa SelfPlant - return _ancestor_id( - model, - context_id, - :Plant, - nothing, - true, - ) - elseif scope isa Ancestor - return _ancestor_id( - model, - context_id, - scope.scale, - nothing, - false, - ) - end + scope isa Union{SelfPlant,Ancestor} && return _scope_anchor(model, scope, context_id) if isnothing(scope) && !isnothing(matcher.relation) relation = _compiled_relation_symbol(matcher.relation) relation in (:self, :children, :descendants) && return context_id @@ -3270,12 +3254,12 @@ function _many_binding_scope_anchor( return _many_scope_anchor(model, :scene, nothing) elseif scope isa SelfPlant return _many_scope_anchor(model, :plant, - _ancestor_id(model, consumer_id; scale=:Plant)) + _scope_anchor(model, scope, consumer_id)) elseif scope isa Scope return _many_scope_anchor(model, :scope, _named_scope_root_id(model, scope)) elseif scope isa Ancestor return _many_scope_anchor(model, :ancestor, - _ancestor_id(model, consumer_id; scale=scope.scale, include_self=false)) + _scope_anchor(model, scope, consumer_id)) end return _many_scope_anchor(model, :consumer, consumer_id) end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 94743c7ce..461ef9d6e 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -588,22 +588,6 @@ function _descendant_ids_up_to( end end -function _ancestor_id( - model::CompositeModel, - current_id::ObjectId; - scale=nothing, - kind=nothing, - include_self::Bool=true, -) - return _ancestor_id( - model, - current_id, - _maybe_symbol(scale), - _maybe_symbol(kind), - include_self, - ) -end - function _ancestor_id( model::CompositeModel, current_id::ObjectId, @@ -1521,7 +1505,7 @@ function _resolve_object_ids( isnothing(current_id) && error( "`Ancestor(...)` selectors require a current object context.", ) - ancestor_id = _ancestor_id(model, current_id; scale=scope.scale, include_self=false) + ancestor_id = _scope_anchor(model, scope::Ancestor, current_id) matches(isnothing(ancestor_id) ? () : (ancestor_id,)) elseif !isnothing(local_ids) matches(local_ids) diff --git a/test/test-selector-ancestor-index.jl b/test/test-selector-ancestor-index.jl index c40fc152d..6f111915f 100644 --- a/test/test-selector-ancestor-index.jl +++ b/test/test-selector-ancestor-index.jl @@ -4,7 +4,8 @@ using Test, PlantSimEngine using PlantSimEngine.GraphEditor const PSE = PlantSimEngine -nearest_ancestor(model, id; kwargs...) = PSE._ancestor_id(model, ObjectId(id); kwargs...) +nearest_ancestor(model, id; scale=nothing, kind=nothing, include_self=true) = + PSE._ancestor_id(model, ObjectId(id), scale, kind, include_self) function ancestor_scene() CompositeModel( Object(:scene; scale=:Scene, kind=:scene), From e6821c6618eba5019cacd34fd75455b5b173880a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 00:22:54 +0100 Subject: [PATCH 207/324] Index object labels after checking the prepared status owner --- src/composite_model/registry_topology.jl | 16 +++------------- src/visualization/model_graph_editor_api.jl | 4 +++- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 4f5566d62..3a598dcb4 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1104,9 +1104,7 @@ function _delete_index!(index::Dict{Symbol,Set{ObjectId}}, key, id::ObjectId) return nothing end -function _index_object!(registry::ObjectRegistry, object::Object) - id = _index_object_id(registry.objects, object.id) - _validate_status_identity_available!(registry, object.status, id) +function _index_object_labels!(registry::ObjectRegistry, object::Object, id::ObjectId) _push_index!(registry.by_scale, object.scale, id) _push_index!(registry.by_kind, object.kind, id) _push_index!(registry.by_species, object.species, id) @@ -1121,14 +1119,6 @@ function _deindex_object!(registry::ObjectRegistry, object::Object) return nothing end -function _validate_status_identity_available!( - registry::ObjectRegistry, - status, - object_id::ObjectId, -) - return _validate_object_family_status_owner!(registry.objects, status, object_id) -end - @inline function _validate_status_source_identity_available!( model::CompositeModel, identity::Union{Nothing,Base.RefValue{Nothing}}, @@ -1492,14 +1482,14 @@ end converted end registry = model.registry - _validate_status_identity_available!(registry, status, id) + _validate_object_family_status_owner!(registry.objects, status, id) object.status = status instance = isnothing(parent_id) ? nothing : _instance_for_object(model, parent_id) _apply_instance_labels!(object, instance) object.parent = parent_id store = registry.objects _store_object_family_row!(store, object, id, status) - _index_object!(registry, object) + _index_object_labels!(registry, object, id) _set_status_source_identity!(model, id, identity) ancestors = isnothing(parent_id) ? ObjectId[id] : diff --git a/src/visualization/model_graph_editor_api.jl b/src/visualization/model_graph_editor_api.jl index d4435189a..ad54a2820 100644 --- a/src/visualization/model_graph_editor_api.jl +++ b/src/visualization/model_graph_editor_api.jl @@ -978,6 +978,8 @@ function _apply_model_graph_edit!(model::CompositeModel, edit::SetModelObjectMet allowed = Set((:scale, :kind, :species, :name, :geometry, :parent)) unknown = setdiff(Set(Symbol.(keys(edit.configuration))), allowed) isempty(unknown) || error("Unsupported object metadata fields: $(sort!(collect(unknown); by=string)).") + id = _index_object_id(model.registry.objects, object.id) + _validate_object_family_status_owner!(model.registry.objects, object.status, id) _deindex_object!(model.registry, object) for (key_, value) in pairs(edit.configuration) key = Symbol(key_) @@ -991,7 +993,7 @@ function _apply_model_graph_edit!(model::CompositeModel, edit::SetModelObjectMet setfield!(object, key, isnothing(value) ? nothing : Symbol(value)) end end - _index_object!(model.registry, object) + _index_object_labels!(model.registry, object, id) if haskey(edit.configuration, :parent) before = _object_instance_name(model, object.id) reparent_object!(model, object.id, edit.configuration.parent) From c18edfc6e510ec8a1a71c38fa8ecfd1f8bbc5215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 00:22:54 +0100 Subject: [PATCH 208/324] Exercise compound leaf identities in both growth runtimes --- test/fixtures/distributed_growth.jl | 2 +- test/integration/native_growth.jl | 58 ++++++++++++++++------------- 2 files changed, 33 insertions(+), 27 deletions(-) diff --git a/test/fixtures/distributed_growth.jl b/test/fixtures/distributed_growth.jl index 717d8c731..df982dbb0 100644 --- a/test/fixtures/distributed_growth.jl +++ b/test/fixtures/distributed_growth.jl @@ -102,7 +102,7 @@ function PSE.run!(::ProducerBirth, status, environment, constants, context) return nothing end -producer_birth_leaf_ids() = [PSE.ObjectId(Symbol(:leaf_, index)) for index in 1:30] +producer_birth_leaf_ids() = [PSE.ObjectId((:tree, :leaf, index)) for index in 1:30] function make_producer_birth_model() objects = PSE.Object[PSE.Object(:root; scale=:Scene, status=PSE.Status(visits=0))] for (index, id) in enumerate(producer_birth_leaf_ids()) diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl index 10ff96b6d..129ddb1e0 100644 --- a/test/integration/native_growth.jl +++ b/test/integration/native_growth.jl @@ -49,32 +49,38 @@ function _native_palm_growth_report(executable, neighbours, directory) end @testset "Native growth preserves local palms and thirty distributed destinations" begin - mktempdir() do directory - expected_zero = _ordinary_palm_growth_report(0) - expected_hundred = _ordinary_palm_growth_report(100) - # Header counts differ; A's timestep, values and sixteen histories do not. - @test expected_zero.a[5:end] == expected_hundred.a[5:end] - palm = Compilation.compile(_palm_growth_app; destination=joinpath(directory, "palm")) - @test isfile(palm.executable) - digest = sha256(read(palm.executable)) - zero = _native_palm_growth_report(palm.executable, 0, directory) - hundred = _native_palm_growth_report(palm.executable, 100, directory) - @test sha256(read(palm.executable)) == digest - @test zero.a == expected_zero.a - @test hundred.a == expected_hundred.a - @test zero.a[5:end] == hundred.a[5:end] - @test zero.neighbours == expected_zero.neighbours - @test hundred.neighbours == expected_hundred.neighbours - # Durations are observations, with no threshold or cross-process equality. - @info "Native palm phases (nanoseconds)" neighbours=0 phases=zero.timings_ns - @info "Native palm phases (nanoseconds)" neighbours=100 phases=hundred.timings_ns + @testset "Palm with zero and one hundred neighbours" begin + mktempdir() do directory + expected_zero = _ordinary_palm_growth_report(0) + expected_hundred = _ordinary_palm_growth_report(100) + # Header counts differ; A's timestep, values and sixteen histories do not. + @test expected_zero.a[5:end] == expected_hundred.a[5:end] + palm = Compilation.compile(_palm_growth_app; destination=joinpath(directory, "palm")) + @test isfile(palm.executable) + digest = sha256(read(palm.executable)) + zero = _native_palm_growth_report(palm.executable, 0, directory) + hundred = _native_palm_growth_report(palm.executable, 100, directory) + @test sha256(read(palm.executable)) == digest + @test zero.a == expected_zero.a + @test hundred.a == expected_hundred.a + @test zero.a[5:end] == hundred.a[5:end] + @test zero.neighbours == expected_zero.neighbours + @test hundred.neighbours == expected_hundred.neighbours + # Durations are observations, with no threshold or cross-process equality. + @info "Native palm phases (nanoseconds)" neighbours=0 phases=zero.timings_ns + @info "Native palm phases (nanoseconds)" neighbours=100 phases=hundred.timings_ns + end + end - @test PSEThirtyProducerControl.checkpoint(PSEThirtyProducerControl.STATE, 0) - @test PSEThirtyProducerControl.main(String[]) == 0 - producer = Compilation.compile(_producer_growth_app; - destination=joinpath(directory, "producer")) - @test isfile(producer.executable) - # main checks every destination, every sample, and the same cells/streams. - @test success(`$(producer.executable)`) + @testset "New producer publishes to thirty existing leaves" begin + mktempdir() do directory + @test PSEThirtyProducerControl.checkpoint(PSEThirtyProducerControl.STATE, 0) + @test PSEThirtyProducerControl.main(String[]) == 0 + producer = Compilation.compile(_producer_growth_app; + destination=joinpath(directory, "producer")) + @test isfile(producer.executable) + # main checks every destination, every sample, and the same cells/streams. + @test success(`$(producer.executable)`) + end end end From b6c8490c444f75655392d5816aea8bc6b8aed219 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 00:57:01 +0100 Subject: [PATCH 209/324] Preserve public object ordering for compiled compound identities --- src/composite_model/registry_topology.jl | 22 ++++++++++++++++++- src/composite_model/selectors.jl | 11 ++++++---- .../distributed_producer_birth/src/prepare.jl | 7 ++++-- test/test-object-families.jl | 15 +++++++++++++ 4 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 3a598dcb4..0f95ef681 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1838,6 +1838,25 @@ function _geometry_inheriting_descendants(model::CompositeModel, root_id::Object end +_object_list_sort_key(id::ObjectId) = string(id.value) +_object_list_sort_key(id::ObjectId{<:Tuple}) = sprint(_show_object_id_element, id.value) + +_show_object_id_element(io, value) = show(io, value) +# Inline Julia's Symbol branch to keep its spelling without compiling expression display. +_show_object_id_element(io, value::Symbol) = + Base.@inline Base.show_unquoted_quote_expr(io, value, 0, 0, 0) + +function _show_object_id_element(io, value::Tuple) + print(io, '(') + if !Base.show_circular(io, value) + context = IOContext(io, :SHOWN_SET => value, :typeinfo => Any) + _print_tuple_items(_show_object_id_element, context, value) + length(value) == 1 && print(io, ',') + end + print(io, ')') + return nothing +end + function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) ids = _indexed_object_ids( model; @@ -1847,7 +1866,8 @@ function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species= id=_normalize_object_id_criterion(id), ) isnothing(ids) && (ids = collect(keys(model.registry.objects))) - return sort!(ids; by=id -> string(id.value)) + length(ids) < 2 && return ids + return ids[sortperm(map(_object_list_sort_key, ids))] end model_objects(model::CompositeModel; kwargs...) = [_model_object(model, id) for id in object_ids(model; kwargs...)] diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 461ef9d6e..368cfcadd 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -868,7 +868,7 @@ function _indexed_object_ids(model::CompositeModel; scale=nothing, kind=nothing, isnothing(object) && continue _matches_object_criteria(object; scale, kind, species, id) && push!(ids, candidate) end - return unique!(ids) + return candidate_ids isa AbstractSet ? ids : unique!(identity, ids; seen=Set{I}()) end # Resolve topology once, before choosing between a bounded local walk and a @@ -1145,16 +1145,19 @@ function _print_selector_diagnostic_value(io, ::Type{T}, ancestors) where {T} return nothing end -function _print_selector_diagnostic_items(io, items::Tuple, ancestors) +function _print_tuple_items(emit::F, io, items::Tuple, args::Vararg{Any,N}) where {F,N} isempty(items) && return nothing - _print_selector_diagnostic(io, first(items), ancestors) + emit(io, first(items), args...) if length(items) > 1 print(io, ", ") - _print_selector_diagnostic_items(io, Base.tail(items), ancestors) + _print_tuple_items(emit, io, Base.tail(items), args...) end return nothing end +_print_selector_diagnostic_items(io, items::Tuple, ancestors) = + _print_tuple_items(_print_selector_diagnostic, io, items, ancestors) + function _print_selector_diagnostic_items(io, items::AbstractVector, ancestors) for (index, item) in enumerate(items) index == 1 || print(io, ", ") diff --git a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl index 6245e43eb..9232c196d 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl @@ -6,7 +6,8 @@ function state_for(simulation) leaves = S[PSE.model_status(simulation, id)::S for id in ids] ordinals = Base.RefValue{Int}[PSE.refvalue(status, :ordinal) for status in leaves] objects = PSE.Object[PSE.model_object(simulation, id) for id in ids] - return (; simulation, ids, leaves, ordinals, objects, + listed_objects = objects[sortperm(ids; by=id -> string(id.value))] + return (; simulation, ids, leaves, ordinals, objects, listed_objects, signals=Base.RefValue{Float32}[], streams=Vector{Tuple{Float64,Float32}}[]) end @@ -15,7 +16,9 @@ function checkpoint(state, day) sim, model = state.simulation, state.simulation.model PSE.current_step(sim) == day || return false length(state.ids) == 30 || return false - length(PSE.model_objects(model; scale=:Leaf)) == 30 || return false + listed = PSE.model_objects(model; scale=:Leaf) + length(listed) == 30 || return false + all(i -> listed[i] === state.listed_objects[i], eachindex(listed)) || return false length(model.registry.objects) == 31 + Int(day >= 2) || return false haskey(model.registry.objects, PSE.ObjectId(:emitter)) == (day >= 2) || return false for index in eachindex(state.ids) diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 00832cf2e..c36adbadd 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -54,6 +54,21 @@ const PSE = PlantSimEngine @test family.rows[location.row].status === canonical end +@testset "object lists retain textual order across identity types" begin + raw_ids = Any[10, 2, :root, Symbol("2"), (:tree, :leaf, 2), (:tree, :leaf, 10), + (:tree, Symbol("a b"), 1), (:tree, (:leaf, 1)), (:tree,), ()] + model = CompositeModel((Object(id; scale=:Leaf) for id in raw_ids)...) + ids = collect(keys(model.registry.objects)) + for id in ids + @test PSE._object_list_sort_key(id) == string(id.value) + end + expected = sort(collect(model.registry.by_scale[:Leaf]); by=id -> string(id.value)) + @test object_ids(model; scale=:Leaf) == expected + @test all(object === model_object(model, id) + for (object, id) in zip(model_objects(model; scale=:Leaf), expected)) + @test object_ids(model; id=[2, 10, 2]) == ObjectId.([10, 2]) +end + @testset "missing object diagnostics preserve scalar values and complete tuple identities" begin present = Object((:plant, :leaf, 1); status=Status(value=2f0)) model = CompositeModel(present) From 53aee78662078038aed52392e90379325b80c611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 01:23:56 +0100 Subject: [PATCH 210/324] Keep selector diagnostics typed for mixed registry identities --- src/composite_model/selectors.jl | 6 ++++-- test/test-model-binding-index-identities.jl | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 368cfcadd..4b9e7efd9 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1058,7 +1058,9 @@ function _available_selector_labels(model::CompositeModel, candidate_ids) scales = Symbol[] kinds = Symbol[] species = Symbol[] - ids = Vector{keytype(model.registry.objects)}() + I = keytype(model.registry.objects) + V = fieldtype(I, :value) + ids = I[] for object in objects isnothing(object.scale) || push!(scales, object.scale) isnothing(object.kind) || push!(kinds, object.kind) @@ -1069,7 +1071,7 @@ function _available_selector_labels(model::CompositeModel, candidate_ids) scales=sort!(unique!(scales); by=string), kinds=sort!(unique!(kinds); by=string), species=sort!(unique!(species); by=string), - ids=[id.value for id in _sort_object_ids!(unique!(ids))], + ids=V[id.value for id in _sort_object_ids!(unique!(identity, ids; seen=Set{I}()))], ) end diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index a0860173f..05c7dddb4 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -457,6 +457,14 @@ end catch error sprint(showerror, error) end + mixed = close_registry(CompositeModel( + Object(:root; scale=:Scene), Object((:tree, :leaf, 2); scale=:Leaf, parent=:root))) + I = keytype(mixed.registry.objects) + for ids in (I[], I[ObjectId(:root)], collect(keys(mixed.registry.objects))) + available = @inferred PSE._available_selector_labels(mixed, ids) + @test eltype(available.ids) === Union{Symbol,Tuple{Symbol,Symbol,Int}} + @test Set(available.ids) == Set(id.value for id in ids) + end for selector in (One(scale=:Leaf), One(scale=:Leef)) expected = message(ordinary, selector) @test occursin("Expected exactly one object", expected) From 8e405b2262e1e5054afbae60e47e2e5a796db3df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 01:38:59 +0100 Subject: [PATCH 211/324] Reuse the native-safe Julia spelling of organ IDs in diagnostics --- src/composite_model/compilation.jl | 40 +++++----- src/composite_model/environment_bindings.jl | 2 +- src/composite_model/object_families.jl | 2 +- src/composite_model/registry_topology.jl | 79 +++++++++---------- src/composite_model/runtime_outputs.jl | 30 +++---- src/composite_model/selectors.jl | 18 ++--- ...test-model-environment-binding-identity.jl | 5 ++ test/test-object-families.jl | 10 +-- 8 files changed, 93 insertions(+), 93 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6459dc2c1..2dee714bc 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3112,7 +3112,7 @@ function _compile_consumer_input_recipe!( isempty(matches) && return nothing if length(matches) > 1 error( - "Input `$(plan.input)` on application `$(application_id)` for object `$(_object_id_diagnostic_text(consumer_id))` " * + "Input `$(plan.input)` on application `$(application_id)` for object `$(_object_id_text(consumer_id))` " * "has ambiguous same-object producers: `$([match.application for match in matches])`. " * "Add `inputs=(:$(plan.input) => One(...),)` to disambiguate." ) @@ -4595,7 +4595,7 @@ function _refresh_scene_call_bindings!( replacements = get(replacement_call_bindings_by_target, key, ()) length(existing) == length(replacements) || error( "Incremental hard-call refresh changed the number of declared calls ", - "for application `$(first(key))` on object `$(last(key).value)`.", + "for application `$(first(key))` on object `$(_object_id_text(last(key)))`.", ) for binding in existing binding_index = findfirst( @@ -4604,7 +4604,7 @@ function _refresh_scene_call_bindings!( ) isnothing(binding_index) && error( "Incremental hard-call refresh lost the existing compiled binding ", - "for application `$(first(key))` on object `$(last(key).value)`.", + "for application `$(first(key))` on object `$(_object_id_text(last(key)))`.", ) replacement_index = findfirst( candidate -> @@ -4615,7 +4615,7 @@ function _refresh_scene_call_bindings!( isnothing(replacement_index) && error( "Incremental hard-call refresh lost declared call ", "`$(_compiled_call_name(binding))` for application ", - "`$(first(key))` on object `$(last(key).value)`.", + "`$(first(key))` on object `$(_object_id_text(last(key)))`.", ) replacement = replacements[replacement_index] if binding.callee_object_ids != replacement.callee_object_ids || @@ -5582,7 +5582,7 @@ function _explain_initialization(model, applications, input_bindings, provided_type=provided_type, conversion..., detail=disposition == :required ? - "Provide `$(variable)` on object `$(_object_id_diagnostic_text(object_id))` Status or add `inputs=(:$(variable) => ..., )` to application `$(application.id)`." : + "Provide `$(variable)` on object `$(_object_id_text(object_id))` Status or add `inputs=(:$(variable) => ..., )` to application `$(application.id)`." : nothing, )) end @@ -5934,7 +5934,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) if _declares_update_without_previous_writer(application.spec, variable, previous) error( "Application `$(application.id)` declares `Updates($(variable))` for object ", - "`$(_object_id_diagnostic_text(object_id))`, but no previous writer for `$(variable)` exists. ", + "`$(_object_id_text(object_id))`, but no previous writer for `$(variable)` exists. ", "Move it after the producer named in `after=...`." ) end @@ -5947,7 +5947,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) previous_labels = join(sort!([String(label) for label in labels]), ", ") error( "Ambiguous canonical writers for variable `$(variable)` on object ", - "`$(_object_id_diagnostic_text(object_id))`. ", + "`$(_object_id_text(object_id))`. ", "applications. Application `$(application.id)` must declare ", "`Updates(:$(variable); after=...)` matching one of the previous writers ", "`$(previous_labels)`." @@ -5958,7 +5958,7 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) previous_writer = last(previous) error( "Application `$(application.id)` updates `$(variable)` on object ", - "`$(_object_id_diagnostic_text(object_id))` without an ordering relation to the immediately ", + "`$(_object_id_text(object_id))` without an ordering relation to the immediately ", "previous writer `$(previous_writer)`. Add that application identifier ", "to `Updates(:$(variable); after=...)`." ) @@ -6132,7 +6132,7 @@ function _validate_compiled_writer_ownership!(ownership, applications_by_id) if owner.application_slot == owners[index - 1].application_slot error( "Application `$(owner.application_id)` declares more than one canonical " * - "writer for `$(variable)` on object `$(_object_id_diagnostic_text(object_id))`. Ensure its " * + "writer for `$(variable)` on object `$(_object_id_text(object_id))`. Ensure its " * "`on=...` targets and `outputs_to` destinations do not overlap.", ) end @@ -6753,7 +6753,7 @@ function _model_object_status_for_preparation( ) status = model_status(model, object_id) (isnothing(status) || status isa Status) || error( - "Model object `$(_object_id_diagnostic_text(object_id))` uses model applications but its status has type " * + "Model object `$(_object_id_text(object_id))` uses model applications but its status has type " * "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." ) return status @@ -6858,7 +6858,7 @@ end status = _replace_model_object_status!(model, object, replacement) end status isa Status || error( - "Model object `$(_object_id_diagnostic_text(object_id))` uses model applications but its status has type ", + "Model object `$(_object_id_text(object_id))` uses model applications but its status has type ", "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." ) status isa S || throw(ArgumentError( @@ -6961,13 +6961,13 @@ function _validate_required_model_output_destinations!( value isa expected_type || throw(ArgumentError( "Distributed output `$(variable)` on application " * "`$(resolved.plan.application_id)` requires `$(expected_type)` " * - "on destination `$(_object_id_diagnostic_text(destination_id))`; got `$(typeof(value))`.", + "on destination `$(_object_id_text(destination_id))`; got `$(typeof(value))`.", )) continue end push!(missing, "`$(resolved.plan.application_id).$(resolved.plan.group)` requires " * - "`$(variable)` on destination object `$(_object_id_diagnostic_text(destination_id))`") + "`$(variable)` on destination object `$(_object_id_text(destination_id))`") end end end @@ -6991,7 +6991,7 @@ function _validate_model_output_destination_statuses!( (isnothing(status) || status isa Status) && continue error( "Output destination `$(resolved.plan.application_id).$(resolved.plan.group)` " * - "selected object `$(_object_id_diagnostic_text(destination_id))` with status type " * + "selected object `$(_object_id_text(destination_id))` with status type " * "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`.", ) end @@ -7119,7 +7119,7 @@ function _model_output_destination_index(destination_ids::AbstractVector{I}) whe for (position, object_id) in pairs(destination_ids) haskey(index, object_id) && error( "Compiled output destination membership contains duplicate object " * - "ID `$(_object_id_diagnostic_text(object_id))`.", + "ID `$(_object_id_text(object_id))`.", ) index[object_id] = position end @@ -7998,8 +7998,8 @@ function _temporal_source_application( binding.policy isa PreviousTimeStep && return nothing error( "Temporal model input `$(binding.input)` from ", - "`$(_object_id_diagnostic_text(source_id)).$(binding.source_var)` has no source application ", - "matching object `$(_object_id_diagnostic_text(source_id))`.", + "`$(_object_id_text(source_id)).$(binding.source_var)` has no source application ", + "matching object `$(_object_id_text(source_id))`.", ) elseif binding.policy isa PreviousTimeStep return last(sort!(matches; by=application_id -> application_positions[application_id])) @@ -9432,7 +9432,7 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a isempty(missing) && return nothing details = join( [ - "`$(row.application_id)` on object `$(_object_id_diagnostic_text(row.object_id))` requires `$(row.input)`" + "`$(row.application_id)` on object `$(_object_id_text(row.object_id))` requires `$(row.input)`" for row in missing ], "; ", @@ -9750,7 +9750,7 @@ function _compile_model_call_bindings( end if mode === :manual && isempty(callee_application_ids) && selector isa One - matched_objects = join([string(id.value) for id in callee_object_ids], ", ") + matched_objects = join([_object_id_text(id) for id in callee_object_ids], ", ") error( "Call `$(call_sym)` on application `$(application.id)` matched objects ", "[$(matched_objects)] but no model application", @@ -9893,7 +9893,7 @@ function explain_applications(compiled::CompiledCompositeModel) ) for (object_id, model) in sort!( collect(_application_model_overrides(application)); - by=pair -> string(first(pair).value), + by=pair -> _object_id_text(first(pair)), ) ], ) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 72f64bd8e..4598a9b23 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -634,7 +634,7 @@ end function _missing_model_environment_input_detail( application_id, process, object_id, target, source, available, ) - location = string(application_id, "/", object_id.value, " (", process, ")") + location = string(application_id, "/", _object_id_text(object_id), " (", process, ")") variables = join(sort!(collect(available); by=string), ", ") return string(location, " needs `", target, "` from source `", source, "`; available=(", variables, ")") diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 197fcea59..b2285ddfb 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -149,7 +149,7 @@ function _validate_object_family_status_owner!(store::ObjectFamilyStore, status, if !isnothing(existing) && existing != id throw(ArgumentError( "The same Status instance cannot be owned by model objects " * - "`$(_object_id_diagnostic_text(existing))` and `$(_object_id_diagnostic_text(id))`. Give each Object its own Status instance.", + "`$(_object_id_text(existing))` and `$(_object_id_text(id))`. Give each Object its own Status instance.", )) end return nothing diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 0f95ef681..f1110827c 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -286,7 +286,7 @@ function _register_mtg_object_identity!(adapter::MTGObjectAdapter, node) error( "The MTG id accessor maps nodes " * "$(MultiScaleTreeGraph.node_id(existing)) and " * - "$(MultiScaleTreeGraph.node_id(node)) to duplicate ObjectId `$(_object_id_diagnostic_text(id))`.", + "$(MultiScaleTreeGraph.node_id(node)) to duplicate ObjectId `$(_object_id_text(id))`.", ) end adapter.object_ids_by_node[node] = id @@ -453,7 +453,7 @@ function _collect_model_items(items, instances) end ids = Set{ObjectId}() for object in objects - object.id in ids && error("CompositeModel contains object id `$(_object_id_diagnostic_text(object.id))` more than once.") + object.id in ids && error("CompositeModel contains object id `$(_object_id_text(object.id))` more than once.") push!(ids, object.id) end return objects, mounted_instances @@ -481,13 +481,13 @@ function _prepare_object_instances!(objects, instances) for instance in instances root_id = _instance_root_id(instance) haskey(objects_by_id, root_id) || error( - "Object instance `$(instance.name)` refers to missing root object `$(_object_id_diagnostic_text(root_id))`." + "Object instance `$(instance.name)` refers to missing root object `$(_object_id_text(root_id))`." ) ids = _object_descendant_ids(objects_by_id, root_id) for id in ids if haskey(claimed_ids, id) error( - "Object `$(_object_id_diagnostic_text(id))` belongs to both instances `$(claimed_ids[id])` and `$(instance.name)`." + "Object `$(_object_id_text(id))` belongs to both instances `$(claimed_ids[id])` and `$(instance.name)`." ) end claimed_ids[id] = instance.name @@ -1136,7 +1136,7 @@ end throw( ArgumentError( "The same Status instance cannot be owned by model objects " * - "`$(_object_id_diagnostic_text(existing))` and `$(_object_id_diagnostic_text(object_id))`. Give each Object " * + "`$(_object_id_text(existing))` and `$(_object_id_text(object_id))`. Give each Object " * "its own Status instance.", ), ) @@ -1177,7 +1177,7 @@ function _replace_model_object_status!( status, ) (isnothing(status) || status isa Status) || error( - "Model object `$(_object_id_diagnostic_text(object.id))` status must be a `Status` or `nothing`, " * + "Model object `$(_object_id_text(object.id))` status must be a `Status` or `nothing`, " * "got `$(typeof(status))`.", ) object.status === status && return status @@ -1201,15 +1201,29 @@ function _replace_model_object_status!(model::CompositeModel, object_id, status) return _replace_model_object_status!(model, _model_object(model, object_id), status) end -# Scalar diagnostics retain their ordinary display. Composite identities use -# the existing typed printer rather than Julia's generic syntax display. -_object_id_diagnostic_text(id::ObjectId) = string(id.value) -_object_id_diagnostic_text(id::ObjectId{<:Tuple}) = _selector_diagnostic_text(id.value) +_object_id_text(id::ObjectId) = string(id.value) +_object_id_text(id::ObjectId{<:Tuple}) = sprint(_show_object_id_element, id.value) + +_show_object_id_element(io, value) = show(io, value) +# Inline Julia's Symbol branch to keep its spelling without compiling expression display. +_show_object_id_element(io, value::Symbol) = + Base.@inline Base.show_unquoted_quote_expr(io, value, 0, 0, 0) + +function _show_object_id_element(io, value::Tuple) + print(io, '(') + if !Base.show_circular(io, value) + context = IOContext(io, :SHOWN_SET => value, :typeinfo => Any) + _print_tuple_items(_show_object_id_element, context, value) + length(value) == 1 && print(io, ',') + end + print(io, ')') + return nothing +end function _model_object(model::CompositeModel, id) oid = ObjectId(id) object = get(model.registry.objects, oid, nothing) - isnothing(object) && error("No model object with id `", _object_id_diagnostic_text(oid), "`.") + isnothing(object) && error("No model object with id `", _object_id_text(oid), "`.") return object end @@ -1252,7 +1266,7 @@ function object_id(model::CompositeModel, object::Object) registered = _model_object(model, object.id) registered === object || throw( ArgumentError( - "Object `$(_object_id_diagnostic_text(object.id))` is not the Object instance registered by this model.", + "Object `$(_object_id_text(object.id))` is not the Object instance registered by this model.", ), ) return object.id @@ -1267,7 +1281,7 @@ function object_id(model::CompositeModel, status::Status) matched_id = index[identity] _model_object(model, matched_id).status === status || error( "PlantSimEngine's Status identity index is inconsistent for object " * - "`$(_object_id_diagnostic_text(matched_id))`. Replace runtime status through the model API.", + "`$(_object_id_text(matched_id))`. Replace runtime status through the model API.", ) return matched_id end @@ -1318,7 +1332,7 @@ function source_node(model::CompositeModel, source) id = object_id(model, source) node = get(adapter.nodes_by_object_id, id, nothing) isnothing(node) && error( - "No source MTG node is registered for model object `$(_object_id_diagnostic_text(id))`.", + "No source MTG node is registered for model object `$(_object_id_text(id))`.", ) return node end @@ -1329,7 +1343,7 @@ function _object_ancestor_ids( ) ancestors = get(registry.ancestor_ids_by_object, object_id, nothing) isnothing(ancestors) && error( - "No cached topology path for model object `$(_object_id_diagnostic_text(object_id))`.", + "No cached topology path for model object `$(_object_id_text(object_id))`.", ) return ancestors end @@ -1444,10 +1458,10 @@ end ) registry = model.registry id = _index_object_id(registry.objects, object.id) - haskey(registry.objects, id) && error("CompositeModel already contains object id `$(_object_id_diagnostic_text(id))`.") + haskey(registry.objects, id) && error("CompositeModel already contains object id `$(_object_id_text(id))`.") parent_id = isnothing(parent) ? nothing : _index_object_id(registry.objects, ObjectId(parent)) if !isnothing(parent_id) && !haskey(registry.objects, parent_id) - error("No model object with id `$(_object_id_diagnostic_text(parent_id))`.") + error("No model object with id `$(_object_id_text(parent_id))`.") end return _register_object_status!(model, object, id, parent_id, status_values_materialized) end @@ -1677,7 +1691,7 @@ function _validate_mutable_object_subtree!( ) isempty(instance_roots) && return nothing error( - "Cannot $(operation) object `$(_object_id_diagnostic_text(object.id))` because its subtree contains ", + "Cannot $(operation) object `$(_object_id_text(object.id))` because its subtree contains ", "immutable ObjectInstance root(s) `$([id.value for id in instance_roots])`. ", "Mutate ordinary instance descendants instead.", ) @@ -1693,7 +1707,7 @@ function remove_object!(model::CompositeModel, id; recursive::Bool=true) descendant_ids, ) if !recursive && !isempty(object.children) - error("Cannot remove object `$(_object_id_diagnostic_text(object.id))` with children unless `recursive=true`.") + error("Cannot remove object `$(_object_id_text(object.id))` with children unless `recursive=true`.") end snapshots = LifecycleObjectSnapshot[ _lifecycle_object_snapshot(model, _model_object(model, object_id)) @@ -1727,12 +1741,12 @@ function reparent_object!(model::CompositeModel, id, new_parent) ) new_parent_id = isnothing(new_parent) ? nothing : ObjectId(new_parent) if !isnothing(new_parent_id) - haskey(model.registry.objects, new_parent_id) || error("No model object with id `$(_object_id_diagnostic_text(new_parent_id))`.") + haskey(model.registry.objects, new_parent_id) || error("No model object with id `$(_object_id_text(new_parent_id))`.") new_parent_id == object.id && error( - "Cannot reparent object `$(_object_id_diagnostic_text(object.id))` to itself.", + "Cannot reparent object `$(_object_id_text(object.id))` to itself.", ) new_parent_id in descendant_ids && error( - "Cannot reparent object `$(_object_id_diagnostic_text(object.id))` below its descendant `$(_object_id_diagnostic_text(new_parent_id))`.", + "Cannot reparent object `$(_object_id_text(object.id))` below its descendant `$(_object_id_text(new_parent_id))`.", ) end old_parent_id = object.parent @@ -1838,25 +1852,6 @@ function _geometry_inheriting_descendants(model::CompositeModel, root_id::Object end -_object_list_sort_key(id::ObjectId) = string(id.value) -_object_list_sort_key(id::ObjectId{<:Tuple}) = sprint(_show_object_id_element, id.value) - -_show_object_id_element(io, value) = show(io, value) -# Inline Julia's Symbol branch to keep its spelling without compiling expression display. -_show_object_id_element(io, value::Symbol) = - Base.@inline Base.show_unquoted_quote_expr(io, value, 0, 0, 0) - -function _show_object_id_element(io, value::Tuple) - print(io, '(') - if !Base.show_circular(io, value) - context = IOContext(io, :SHOWN_SET => value, :typeinfo => Any) - _print_tuple_items(_show_object_id_element, context, value) - length(value) == 1 && print(io, ',') - end - print(io, ')') - return nothing -end - function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) ids = _indexed_object_ids( model; @@ -1867,7 +1862,7 @@ function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species= ) isnothing(ids) && (ids = collect(keys(model.registry.objects))) length(ids) < 2 && return ids - return ids[sortperm(map(_object_list_sort_key, ids))] + return ids[sortperm(map(_object_id_text, ids))] end model_objects(model::CompositeModel; kwargs...) = [_model_object(model, id) for id in object_ids(model; kwargs...)] diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index a0c4d2197..1fb249847 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -413,7 +413,7 @@ end hasproperty(context.bound_inputs, input) || throw( ArgumentError( "Application `$(context.application.id)` on object " * - "`$(_object_id_diagnostic_text(context.object_id))` has no declared Many input " * + "`$(_object_id_text(context.object_id))` has no declared Many input " * "`$(input)`. Available identity-aware inputs: " * "`$(propertynames(context.bound_inputs))`.", ), @@ -460,7 +460,7 @@ end @noinline function _missing_distributed_output_target(context, name) throw(ArgumentError( - "Application `$(context.application.id)` on object `$(_object_id_diagnostic_text(context.object_id))` " * + "Application `$(context.application.id)` on object `$(_object_id_text(context.object_id))` " * "has no distributed output `$(name)`. Available variables: " * "`$(propertynames(context.output_targets))`.", )) @@ -1737,7 +1737,7 @@ end function _model_object_status(model::CompositeModel, object_id::ObjectId) status = model_status(model, object_id) status isa Status || error( - "CompositeModel object `$(_object_id_diagnostic_text(object_id))` has no `Status`; model runtime requires status-backed objects." + "CompositeModel object `$(_object_id_text(object_id))` has no `Status`; model runtime requires status-backed objects." ) return status end @@ -1751,7 +1751,7 @@ end key = (application.id, id) haskey(compiled.status_views_by_target, key) || error( "No compiled status view for application `$(application.id)` on object ", - "`$(_object_id_diagnostic_text(object_id))`.", + "`$(_object_id_text(object_id))`.", ) return Base.@inline _with_model_status_view(identity, compiled.status_view_schema, application.id, compiled.status_views_by_target[key]) @@ -2435,7 +2435,7 @@ function _model_temporal_source_value( ) policy isa PreviousTimeStep && return nothing error( - "Temporal model input from `$(_object_id_diagnostic_text(source_id)).$(source_var)` has no ", + "Temporal model input from `$(_object_id_text(source_id)).$(source_var)` has no ", "source application for policy `$(typeof(policy))`." ) end @@ -2504,7 +2504,7 @@ function _materialize_model_temporal_input!( policy isa PreviousTimeStep || error( "No temporal model value available for input ", "`$(plan.input)` from ", - "`$(_object_id_diagnostic_text(source_ids[index])).$(plan.source_var)` ", + "`$(_object_id_text(source_ids[index])).$(plan.source_var)` ", "at t=$(time).", ) value = temporal_input.initial[index] @@ -2527,7 +2527,7 @@ function _materialize_model_temporal_input!( if isnothing(value) policy isa PreviousTimeStep || error( "No temporal model value available for input `$(plan.input)` from ", - "`$(_object_id_diagnostic_text(source_id)).$(plan.source_var)` at t=$(time).", + "`$(_object_id_text(source_id)).$(plan.source_var)` at t=$(time).", ) value = temporal_input.initial end @@ -2676,7 +2676,7 @@ function _materialize_model_temporal_input!( policy isa PreviousTimeStep || error( "No temporal model value available for input ", "`$(plan.input)` from ", - "`$(_object_id_diagnostic_text(source_ids[index])).$(plan.source_var)` ", + "`$(_object_id_text(source_ids[index])).$(plan.source_var)` ", "at t=$(time).", ) value = temporal_input.initial[index] @@ -2696,7 +2696,7 @@ function _materialize_model_temporal_input!( if isnothing(value) policy isa PreviousTimeStep || error( "No temporal model value available for input `$(plan.input)` from ", - "`$(_object_id_diagnostic_text(source_id)).$(plan.source_var)` at t=$(time).", + "`$(_object_id_text(source_id)).$(plan.source_var)` at t=$(time).", ) value = temporal_input.initial end @@ -3218,7 +3218,7 @@ function _runtime_temporal_source_stream( stream = get(streams, key, nothing) isnothing(stream) && error( "No initialized temporal source stream for application ", - "`$(application_id)` on object `$(_object_id_diagnostic_text(binding.source_ids[index]))` ", + "`$(application_id)` on object `$(_object_id_text(binding.source_ids[index]))` ", "and variable `$(binding.source_var)`.", ) return stream @@ -3297,7 +3297,7 @@ Base.@nospecializeinfer function _runtime_model_output_streams( if isnothing(stream) initialize_missing || error( "No initialized retained output stream for application ", - "`$(application.id)` on object `$(_object_id_diagnostic_text(object_id))` and variable ", + "`$(application.id)` on object `$(_object_id_text(object_id))` and variable ", "`$(variable)`.", ) stream = _model_new_output_stream( @@ -5721,7 +5721,7 @@ end available = Symbol[targets.binding.call for targets in context.calls] error( "Application `$(context.application.id)` on object ", - "`$(_object_id_diagnostic_text(context.object_id))` did not declare call `$(name)`. ", + "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", "Declared calls: $(available).", ) end @@ -6052,7 +6052,7 @@ function _targeted_new_object_call_targets( initialization_key = (only(binding.potential_callee_application_ids), object_id) initialization_key in delta.initialized_targets && error( "Application `$(first(initialization_key))` already initialized newly " * - "registered object `$(_object_id_diagnostic_text(object_id))` in this lifecycle event.", + "registered object `$(_object_id_text(object_id))` in this lifecycle event.", ) end @@ -6396,7 +6396,7 @@ function _current_topology_call_targets( available = Symbol[candidate.call for candidate in bindings] error( "Application `$(context.application.id)` on object ", - "`$(_object_id_diagnostic_text(context.object_id))` did not declare call `$(name)`. ", + "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", "Declared calls: $(available).", ) end @@ -6515,7 +6515,7 @@ function _environment_binding_for_current_context(context::RunContext) if isnothing(binding) || isnothing(binding.backend) error( "Cannot commit environment state for `$(context.application.id)` on object ", - "`$(_object_id_diagnostic_text(context.object_id))`: no environment binding is configured. ", + "`$(_object_id_text(context.object_id))`: no environment binding is configured. ", "Attach an environment with `CompositeModel(...; environment=...)` and ", "`ModelSpec(model; environment=Environment(...))`." ) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 4b9e7efd9..6ed0fd55b 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -389,7 +389,7 @@ function _object_override_models(instance::ObjectInstance, specs, instance_ids) valid_ids = Set(instance_ids) for override in instance.object_overrides override.object in valid_ids || error( - "Object override for `$(_object_id_diagnostic_text(override.object))` does not belong to instance `$(instance.name)`." + "Object override for `$(_object_id_text(override.object))` does not belong to instance `$(instance.name)`." ) matches = findall( index -> @@ -398,23 +398,23 @@ function _object_override_models(instance::ObjectInstance, specs, instance_ids) eachindex(specs), ) isempty(matches) && error( - "Object override for `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)` ", + "Object override for `$(_object_id_text(override.object))` in instance `$(instance.name)` ", "does not match a template application." ) length(matches) == 1 || error( - "Object override for `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)` ", + "Object override for `$(_object_id_text(override.object))` in instance `$(instance.name)` ", "matches several template applications." ) index = only(matches) object_models = get!(entries, index, Pair{ObjectId,AbstractModel}[]) any(entry -> first(entry) == override.object, object_models) && error( "Several object overrides target application `$(_mounted_application_name(specs[index], index))` ", - "on object `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)`." + "on object `$(_object_id_text(override.object))` in instance `$(instance.name)`." ) _validate_model_override_contract!( model_(specs[index]), override.model; - description="Object override for `$(_object_id_diagnostic_text(override.object))` in instance `$(instance.name)`", + description="Object override for `$(_object_id_text(override.object))` in instance `$(instance.name)`", ) push!(object_models, override.object => override.model) end @@ -733,7 +733,7 @@ function _named_scope_root_id(model::CompositeModel, scope::Scope) root_id, instance_name = _named_scope_root_candidate(model, scope) haskey(model.registry.objects, root_id) && return root_id isnothing(instance_name) || error( - "Object instance `$(instance_name)` has no current root object `$(_object_id_diagnostic_text(root_id))`.", + "Object instance `$(instance_name)` has no current root object `$(_object_id_text(root_id))`.", ) available_ids = [id.value for id in object_ids(model)] available_instances = sort!(Symbol[instance.name for instance in model.instances]; by=string) @@ -741,7 +741,7 @@ function _named_scope_root_id(model::CompositeModel, scope::Scope) suggestions = root_id.value isa Symbol ? _near_symbol_matches(root_id.value, unique!([available_instances; symbolic_ids])) : Symbol[] error( - "No instance or object ID `$(_object_id_diagnostic_text(root_id))` found in the model registry. ", + "No instance or object ID `$(_object_id_text(root_id))` found in the model registry. ", "available_ids=$(available_ids), available_instances=$(available_instances), ", "suggestions=$(suggestions).", ) @@ -939,9 +939,9 @@ end end _missing_point_scope_anchor(::CompositeModel, ::SelfPlant, id) = - error("No `scale=:Plant` ancestor found for object `$(_object_id_diagnostic_text(id))`.") + error("No `scale=:Plant` ancestor found for object `$(_object_id_text(id))`.") _missing_point_scope_anchor(::CompositeModel, scope::Ancestor, id) = - error("No matching ancestor found for object `$(_object_id_diagnostic_text(id))` and scale `$(scope.scale)`.") + error("No matching ancestor found for object `$(_object_id_text(id))` and scale `$(scope.scale)`.") @inline _point_scope_contains(topology, scope::Union{SelfPlant,Ancestor}, origin, object) = _relation_in_subtree(topology, object, _required_scope_anchor(topology, scope, origin)) diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 436e1472b..5efea875b 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -565,6 +565,11 @@ end model, compiled.applications, plans) tables = (compiled.applications_by_id, Dict(application.id => application for application in compiled.applications)) + compound_id = ObjectId((:plant, :leaf, 2)) + @test PSE._missing_model_environment_input_detail( + :leaf, :environment_shell_leaf, compound_id, :T, :missing, (:wind, :PAR), + ) == "leaf/(:plant, :leaf, 2) (environment_shell_leaf) needs `T` from source " * + "`missing`; available=(PAR, wind)" messages = String[] expected = if local_backend "Composite model environment is missing required source inputs: leaf/one " * diff --git a/test/test-object-families.jl b/test/test-object-families.jl index c36adbadd..be988b54a 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -31,7 +31,7 @@ const PSE = PlantSimEngine exception end @test failure isa ErrorException - expected = id isa Tuple ? "(Symbol(\"plant\"), 4)" : string(id) + expected = string(id) @test sprint(showerror, failure) == "No model object with id `$(expected)`." end @test canonical !== supplied @@ -60,7 +60,7 @@ end model = CompositeModel((Object(id; scale=:Leaf) for id in raw_ids)...) ids = collect(keys(model.registry.objects)) for id in ids - @test PSE._object_list_sort_key(id) == string(id.value) + @test PSE._object_id_text(id) == string(id.value) end expected = sort(collect(model.registry.by_scale[:Leaf]); by=id -> string(id.value)) @test object_ids(model; scale=:Leaf) == expected @@ -80,8 +80,8 @@ end 17 => "17", 2.5 => "2.5", true => "true", - (:missing, :leaf, 2) => "(Symbol(\"missing\"), Symbol(\"leaf\"), 2)", - (:missing, (:leaf, 2)) => "(Symbol(\"missing\"), (Symbol(\"leaf\"), 2))", + (:missing, :leaf, 2) => "(:missing, :leaf, 2)", + (:missing, (:leaf, 2)) => "(:missing, (:leaf, 2))", ) for (id, expected) in cases, lookup in (model_object, model_status, object_id) failure = try @@ -113,7 +113,7 @@ PSE.run!(::FamilyReplacement, status, environment, constants, context) = nothing application = PSE._compiled_application_by_id(compiled, :replacement) @test !isnothing(PSE._model_status_view_for_application(compiled, application, root.id)) @test_throws ErrorException("No compiled status view for application `replacement` on object " * - "`(Symbol(\"tree\"), Symbol(\"leaf\"), 2)`.") PSE._model_status_view_for_application( + "`(:tree, :leaf, 2)`.") PSE._model_status_view_for_application( compiled, application, leaf.id) end From 5c48db1bd0db25bf53557e0ec3f7e1ed4260b833 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 01:58:43 +0100 Subject: [PATCH 212/324] Format compound organ IDs consistently in input and output reports --- src/composite_model/compilation.jl | 2 +- src/composite_model/registry_topology.jl | 4 ++-- src/composite_model/runtime_outputs.jl | 6 +++--- src/composite_model/source_compilation.jl | 2 +- src/composite_model/status_conversion.jl | 2 +- test/test-object-families.jl | 4 ++++ 6 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 2dee714bc..46de0bcae 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -9371,7 +9371,7 @@ function _validate_model_input_source!( isempty(status_source_ids) && return nothing io = IOBuffer() print(io, "Input binding `", input_sym, "` on application `", application_id, - "` for object `", consumer_id.value, "` reads `", source_var, "` from objects `[") + "` for object `", _object_id_text(consumer_id), "` reads `", source_var, "` from objects `[") for (index, source_id) in pairs(status_source_ids) index == 1 || print(io, ", ") _print_selector_diagnostic(io, source_id.value, Any[]) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index f1110827c..9dbf6d0b9 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -731,9 +731,9 @@ function CompositeModel( inferred_name = if !isnothing(name) Symbol(name) elseif root isa Object - Symbol(string(root.id.value)) + Symbol(_object_id_text(root.id)) else - Symbol(string(ObjectId(root).value)) + Symbol(_object_id_text(ObjectId(root))) end instance = ObjectInstance( inferred_name, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 1fb249847..42db9f58d 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -8439,7 +8439,7 @@ function _model_output_rows(sim::Simulation, filter_object=nothing, filter_var=n rows = NamedTuple[] for ((application_id, object_id, variable), samples) in sort!( collect(sim.temporal_streams); - by=pair -> (string(first(pair)[1]), string(first(pair)[2].value), string(first(pair)[3])), + by=pair -> (string(first(pair)[1]), _object_id_text(first(pair)[2]), string(first(pair)[3])), ) isnothing(filter_object) || object_id == ObjectId(filter_object) || continue isnothing(filter_var) || variable == Symbol(filter_var) || continue @@ -8668,7 +8668,7 @@ function _model_requested_output_rows( for row in sort!( nonempty_source_rows; by=row -> ( - string(row.object_id.value), + _object_id_text(row.object_id), row.membership.start_time, ), ) @@ -8806,7 +8806,7 @@ function explain_outputs(sim::Simulation) ) for ((application_id, object_id, variable), samples) in sort!( collect(sim.temporal_streams); - by=pair -> (string(first(pair)[1]), string(first(pair)[2].value), string(first(pair)[3])), + by=pair -> (string(first(pair)[1]), _object_id_text(first(pair)[2]), string(first(pair)[3])), ) ] end diff --git a/src/composite_model/source_compilation.jl b/src/composite_model/source_compilation.jl index de09e7507..4fe2b45d5 100644 --- a/src/composite_model/source_compilation.jl +++ b/src/composite_model/source_compilation.jl @@ -209,7 +209,7 @@ end function _compiled_source_application_models(application::CompiledModelApplication) models = Any[_application_default_model(application)] if !isnothing(_application_model_overrides(application)) - for object_id in sort!(collect(keys(_application_model_overrides(application))); by=id -> string(id.value)) + for object_id in sort!(collect(keys(_application_model_overrides(application))); by=_object_id_text) push!(models, _application_model_overrides(application)[object_id]) end end diff --git a/src/composite_model/status_conversion.jl b/src/composite_model/status_conversion.jl index fa4dd973c..e287c5909 100644 --- a/src/composite_model/status_conversion.jl +++ b/src/composite_model/status_conversion.jl @@ -80,7 +80,7 @@ _status_transform(model) = model.status_conversion.transform function _status_conversion_context(; object_id=nothing, application_id=nothing, origin=:unknown) parts = String["status variable"] - isnothing(object_id) || push!(parts, "on object `$(ObjectId(object_id).value)`") + isnothing(object_id) || push!(parts, "on object `$(_object_id_text(ObjectId(object_id)))`") isnothing(application_id) || push!(parts, "for application `$(application_id)`") origin === :unknown || push!(parts, "from `$(origin)`") return join(parts, " ") diff --git a/test/test-object-families.jl b/test/test-object-families.jl index be988b54a..49534b0c9 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -115,6 +115,10 @@ PSE.run!(::FamilyReplacement, status, environment, constants, context) = nothing @test_throws ErrorException("No compiled status view for application `replacement` on object " * "`(:tree, :leaf, 2)`.") PSE._model_status_view_for_application( compiled, application, leaf.id) + @test_throws ErrorException("Input binding `demand` on application `replacement` " * + "for object `(:tree, :leaf, 2)` reads `supply` from objects `[Symbol(\"root\")]`, " * + "but no source `Status` reference is available.") PSE._validate_model_input_source!( + model, :replacement, leaf.id, :demand, :supply, [root.id], nothing, :status) end @noinline function escape_registered_status!(sink, model, id, count) From b26f61f53b7799bd63caccc302de08d236e70ceb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 02:20:31 +0100 Subject: [PATCH 213/324] Keep prospective organs in the prepared registry identity family --- src/composite_model/selectors.jl | 13 +++-- test/test-prepared-status-registration.jl | 65 +++++++++++++++++++---- 2 files changed, 64 insertions(+), 14 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 6ed0fd55b..f683031ae 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1587,11 +1587,11 @@ end # Pre-registration matching sees the exact admitted parent and the labels that # normal registration would inherit. Every other object remains the real model. -struct _PreparedStatusObjectTopology{M,I<:ObjectId,P} +struct _PreparedStatusObjectTopology{M,I<:ObjectId} model::M object::Object id::I - parent::P + parent::Union{Nothing,I} kind::Union{Nothing,Symbol} species::Union{Nothing,Symbol} end @@ -1609,7 +1609,8 @@ function _prepared_status_topology(model, object, id, parent_id) return model end labels = _prepared_status_object_labels(model, object, parent) - return _PreparedStatusObjectTopology(model, object, id, parent, labels.kind, labels.species) + I = keytype(model.registry.objects) + return _PreparedStatusObjectTopology{typeof(model),I}(model, object, id, parent, labels.kind, labels.species) end @inline _relation_same_object(topology::_PreparedStatusObjectTopology, left, right) = @@ -1666,7 +1667,11 @@ end function _prepared_status_application_matches(model, object, parent_id, application) id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) - return _prepared_status_application_matches_id(model, topology, application.target_matcher, id) + matcher = application.target_matcher + if topology isa _PreparedStatusObjectTopology + return Base.@inline _prepared_status_application_matches_id(model, topology, matcher, id) + end + return Base.@inline _prepared_status_application_matches_id(model, model, matcher, id) end function _prepared_status_application_matches_id(model, topology, matcher, id) diff --git a/test/test-prepared-status-registration.jl b/test/test-prepared-status-registration.jl index 67da4e892..af97d74e7 100644 --- a/test/test-prepared-status-registration.jl +++ b/test/test-prepared-status-registration.jl @@ -10,7 +10,7 @@ PSE.inputs_(::Source) = NamedTuple() PSE.outputs_(model::Source) = (x=model.initial,) PSE.run!(::Source, status, environment, constants, context) = nothing -function fixture(second_id=17) +function fixture(second_id=17; finite_ids=false) first = Object(:plant_a; scale=:Plant) second = Object(second_id; scale=:Plant) a = Object(:leaf_a; scale=:Leaf, parent=first.id, status=Status(x=1f0)) @@ -21,6 +21,14 @@ function fixture(second_id=17) model = CompositeModel( ObjectInstance(:a, template(0f0); root=first, objects=(a,)), ObjectInstance(:b, template(0.0); root=second, objects=(b,))) + if finite_ids + previous = model.registry + objects = PSE._closed_object_family_store(previous.objects) + registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, + previous.by_species, previous.ancestor_ids_by_object) + model = PSE.CompositeModel(registry, + (getfield(model, index) for index in 2:fieldcount(typeof(model)))...) + end return (; model, first, second, a, b) end @@ -73,15 +81,8 @@ end end @testset "prospective matching uses the finite registry identity family" begin - data = fixture(:plant_b) - previous = data.model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - fields = map(fieldnames(typeof(data.model))) do name - name === :registry ? registry : getfield(data.model, name) - end - model = PSE.CompositeModel(fields...) + data = fixture(:plant_b; finite_ids=true) + model = data.model @test keytype(model.registry.objects) === ObjectId{Symbol} wrong = Object(:wrong_closed; scale=:Leaf, status=Status(x=6.0)) @@ -163,4 +164,48 @@ end @test resolve_object_ids(model, selector) == [root.id] end +@testset "prospective topology retains one identity family and real relations" begin + data = fixture((:tree, :plant, 2); finite_ids=true) + model = data.model + first = Object(:pending_symbol; scale=:Leaf, parent=data.first.id, status=Status(x=3f0)) + second = Object((:tree, :leaf, 3); scale=:Leaf, parent=data.second.id, status=Status(x=4.0)) + orphan = Object(:pending_orphan; scale=:Leaf, status=Status(x=5f0)) + parents_before = (copy(data.first.children), copy(data.second.children)) + + a = PSE._prepared_status_topology(model, first, first.id, first.parent) + b = PSE._prepared_status_topology(model, second, second.id, second.parent) + c = PSE._prepared_status_topology(model, orphan, orphan.id, nothing) + @test typeof(a) === typeof(b) === typeof(c) + for (topology, object, parent) in ( + (a, first, data.first.id), + (b, second, data.second.id), + (c, orphan, nothing), + ) + @test topology.model === model + @test topology.object === object + @test topology.id === object.id + @test topology.parent === parent + end + + @test a.kind === b.kind === :tree + @test a.species === b.species === :same + @test PSE._relation_parent(a, first.id) === data.first.id + @test PSE._relation_parent(b, second.id) === data.second.id + @test PSE._relation_parent(a, data.b.id) === data.second.id + @test PSE._scope_ancestor(a, first.id, :Plant, true) === data.first.id + @test PSE._scope_ancestor(b, second.id, :Plant, true) === data.second.id + @test !PSE._relation_in_subtree(c, orphan.id, data.first.id) + @test (data.first.children, data.second.children) == parents_before + @test PSE._prepared_status_topology(model, data.a, data.a.id, data.a.parent) === model + + first_cell = PSE.refvalue(first.status, :x) + second_cell = PSE.refvalue(second.status, :x) + @test register_object!(model, first) === first + @test register_object!(model, second) === second + @test PSE.refvalue(model_status(model, first.id), :x) === first_cell + @test PSE.refvalue(model_status(model, second.id), :x) === second_cell + @test PSE._prepared_status_topology(model, first, first.id, first.parent) === model + @test PSE._prepared_status_topology(model, second, second.id, second.parent) === model +end + end From eeeb365d9875e2645e493a81e184d08cdc537f2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 02:30:12 +0100 Subject: [PATCH 214/324] Keep mixed organ IDs concrete in simulation binding indexes --- src/composite_model/compilation.jl | 162 ++++++++-------- src/composite_model/environment_bindings.jl | 19 +- src/composite_model/object_key_indexes.jl | 173 ++++++++++++++++++ src/composite_model_api.jl | 1 + ...test-model-environment-index-identities.jl | 41 ++++- test/test-model-object-id.jl | 133 ++++++++++++++ 6 files changed, 429 insertions(+), 100 deletions(-) create mode 100644 src/composite_model/object_key_indexes.jl diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 46de0bcae..4a6c385c7 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -278,7 +278,7 @@ end """Compiled columnar references for one execution object and output group.""" mutable struct CompiledModelOutputDestinationBinding{P,C,I,ID<:ObjectId} const plan::P - const execution_object_id::ObjectId + const execution_object_id::ID destination_ids::Vector{ID} columns::C destination_index::I @@ -2455,7 +2455,7 @@ function _index_observed_manual_call_bindings_by_callee_target( applications_by_id, objects::ObjectFamilyStore{I}, ) where {I<:ObjectId} - index = Dict{Tuple{Symbol,I},Vector{Int}}() + index = _object_key_index(Tuple{Symbol,I}, Vector{Int}) for (binding_index, binding) in pairs(bindings) _index_observed_manual_call_binding_by_callee_target!( index, @@ -2536,7 +2536,7 @@ end function _group_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B,I<:ObjectId} K = Tuple{Symbol,I} - grouped = Dict{K,Vector{B}}() + grouped = _object_key_index(K, Vector{B}) for binding in bindings key = _model_binding_target_key(binding, I) values = get!(grouped, key) do @@ -2588,7 +2588,7 @@ function _index_model_call_bindings!(index, bindings, plans_by_application, ::Ty end function _index_model_call_bindings(bindings::AbstractVector{B}, plans_by_application, ::Type{I}) where {B,I<:ObjectId} - index = Dict{Tuple{Symbol,I},Tuple{Vararg{B}}}() + index = _object_key_index(Tuple{Symbol,I}, Tuple{Vararg{B}}) return _index_model_call_bindings!(index, bindings, plans_by_application, I) end @@ -2811,7 +2811,7 @@ function _compile_scene( status_views_by_target, status_view_schema, Set{Symbol}(application.id for application in applications), - Set(keys(status_views_by_target)), + _object_key_set(keytype(status_views_by_target), keys(status_views_by_target)), false, application_order, model.revision, @@ -3822,7 +3822,7 @@ end function _previous_temporal_source_storage(model::CompositeModel) I = keytype(model.registry.objects) - return Dict{Tuple{Symbol,I,Symbol},Vector{I}}() + return _object_key_index(Tuple{Symbol,I,Symbol}, Vector{I}) end function _record_previous_temporal_sources!(view::CompiledModelStatusView, sources, key) @@ -4019,12 +4019,11 @@ end # Keep the real application inside its finite metadata branch. Transient # views are read only after admission, never captured by a metadata callback. -function _refresh_model_status_view_for_target!( - application, model, compiled, views, previous_views, key, - input_bindings_by_target, applications_by_id, positions, - distributed_outputs, previous_temporal_sources, -) - application_id, object_id = key +function _refresh_model_status_view_for_target!(application, object_id, state) + (; model, compiled, views, previous_views, input_bindings_by_target, + applications_by_id, positions, distributed_outputs, previous_temporal_sources) = state + application_id = application.id + key = (application_id, object_id) previous_view = get(previous_views, key, nothing) if !isnothing(previous_view) Base.@inline _with_model_status_view(_record_previous_temporal_sources!, @@ -4070,7 +4069,7 @@ function _extend_model_status_views!( ) views = compiled.status_views_by_target Key = Tuple{Symbol,keytype(model.registry.objects)} - affected_keys = Set{Key}() + affected_keys = _object_key_set(Key) for (application_id, raw_id) in affected_temporal_keys object_id = _index_object_id(model.registry.objects, raw_id) push!(affected_keys, (application_id, object_id)) @@ -4126,14 +4125,11 @@ function _extend_model_status_views!( current && delete!(affected_keys, key) end end - for key in affected_keys - application_id = getfield(key, 1) - _with_metadata_entry( - _refresh_model_status_view_for_target!, applications_by_id, - application_id, model, compiled, views, previous_views, key, - input_bindings_by_target, applications_by_id, positions, - distributed_outputs, previous_temporal_sources, - ) + state = (; model, compiled, views, previous_views, input_bindings_by_target, + applications_by_id, positions, distributed_outputs, previous_temporal_sources) + for (application_id, object_id) in affected_keys + Base.@inline _with_metadata_entry(_refresh_model_status_view_for_target!, + applications_by_id, application_id, object_id, state) end return affected_keys end @@ -4209,12 +4205,12 @@ function _propagate_changed_manual_call_owners!( performance=nothing, ) where {I<:ObjectId} Key = Tuple{Symbol,I} - frontier = Key[] + frontier = _object_key_set(Key) for (application_id, raw_id) in changed_callee_target_ids object_id = _index_object_id(objects, raw_id) push!(frontier, (application_id, object_id)) end - seen_owner_keys = Set{Key}(frontier) + seen_owner_keys = copy(frontier) while !isempty(frontier) _runtime_performance_count!( performance, @@ -4231,7 +4227,7 @@ function _propagate_changed_manual_call_owners!( union!(candidate_binding_indices, binding_indices) end isempty(candidate_binding_indices) && break - next_frontier = Key[] + next_frontier = _object_key_set(Key) for binding_index in candidate_binding_indices _runtime_performance_count!( performance, @@ -4266,7 +4262,7 @@ function _changed_previous_time_step_targets( input_bindings, input_bindings_by_target, ) where {I<:ObjectId} - changed_target_ids = Set{Tuple{Symbol,I}}() + changed_target_ids = _object_key_set(Tuple{Symbol,I}) for (application_id, raw_id, input) in keys(previous_temporal_sources) object_id = _index_object_id(objects, raw_id) target_key = (application_id, object_id) @@ -4307,7 +4303,7 @@ end # Rebind keys use the same prepared identity family as the registry index. _input_binding_key_set(::AbstractDict{I}) where {I<:ObjectId} = - Set{Tuple{Symbol,I,Symbol}}() + _object_key_set(Tuple{Symbol,I,Symbol}) function _prepare_structural_compiled_delta( model::CompositeModel, @@ -4321,7 +4317,7 @@ function _prepare_structural_compiled_delta( for object_id in dirty_object_ids push!(dirty, _index_object_id(model.registry.objects, object_id)) end - removed_target_keys = Set{Tuple{Symbol,ObjectId}}() + removed_target_keys = _object_key_set(Tuple{Symbol,I}) changed_application_ids = Set{Symbol}() applications_by_object = compiled.applications_by_object for object_id in dirty @@ -4376,7 +4372,7 @@ function _prepare_structural_compiled_delta( end push!(call_bindings, binding) end - forced_call_target_keys = Set{Tuple{Symbol,ObjectId}}() + forced_call_target_keys = _object_key_set(Tuple{Symbol,I}) for binding in call_bindings _compiled_call_membership_is_observed(binding) || continue _sorted_object_ids_intersect_set(binding.callee_object_ids, dirty) || @@ -4477,8 +4473,8 @@ function _refresh_scene_call_bindings!( has_calls = !isempty(compiled.scenario_plan.call_plans) I = keytype(model.registry.objects) K = Tuple{Symbol,I} - rebuilt_existing_call_targets = Set{K}() - changed_call_target_keys = Set{K}() + rebuilt_existing_call_targets = _object_key_set(K) + changed_call_target_keys = _object_key_set(K) for (application_id, raw_id) in forced_call_target_keys key = (application_id, _index_object_id(model.registry.objects, raw_id)) push!(rebuilt_existing_call_targets, key) @@ -4826,11 +4822,11 @@ function _extend_compiled_scene( compiled::CompiledCompositeModel, added_objects; forced_input_binding_keys=_input_binding_key_set(model.registry.objects), - forced_call_target_keys=Set{Tuple{Symbol,ObjectId}}(), + forced_call_target_keys=_object_key_set(Tuple{Symbol,keytype(model.registry.objects)}), previous_views=compiled.status_views_by_target, previous_temporal_sources_seed=_previous_temporal_source_storage(model), changed_application_ids_seed=Set{Symbol}(), - changed_target_ids_seed=Set{Tuple{Symbol,ObjectId}}(), + changed_target_ids_seed=_object_key_set(Tuple{Symbol,keytype(model.registry.objects)}), pure_addition::Bool=true, structural_dirty_ids=ObjectId[], performance=nothing, @@ -4966,7 +4962,7 @@ function _extend_compiled_scene( many_binding_cache = compiled.many_input_binding_cache changed_bindings = similar(input_bindings, 0) rewired_consumer_ids = Set{ObjectId}() - affected_temporal_keys = Set{Tuple{Symbol,ObjectId}}() + affected_temporal_keys = _object_key_set(Tuple{Symbol,I}) previous_temporal_sources = copy(previous_temporal_sources_seed) processed_many_sources = IdDict{Any,Nothing}() previous_shared_many_sources = IdDict{Any,Vector{I}}() @@ -5164,7 +5160,7 @@ function _extend_compiled_scene( ) # Keep the published owner's storage type, while admitting each incoming # identity before constructing the key consumed by its Set operations. - changed_execution_target_ids = Set{Tuple{Symbol,ObjectId}}() + changed_execution_target_ids = _object_key_set(Tuple{Symbol,I}) # A reference can be replaced on an existing organ during growth. An # execution target must use the same view that was just rebuilt for it. for incoming in (rebuilt_views, affected_temporal_keys, changed_target_ids_seed, changed_call_target_keys) @@ -5173,8 +5169,8 @@ function _extend_compiled_scene( push!(changed_execution_target_ids, (application_id, object_id)) end end - Key = Tuple{Symbol,keytype(model.registry.objects)} - changed_manual_target_ids = Set{Key}() + Key = Tuple{Symbol,I} + changed_manual_target_ids = _object_key_set(Key) for (application_id, raw_id) in changed_execution_target_ids application_id in manual_application_ids || continue object_id = _index_object_id(model.registry.objects, raw_id) @@ -5849,7 +5845,7 @@ end function _model_writer_groups( applications, applications_by_id, ::Type{I}, skipped_application_ids=(), ) where {I<:ObjectId} - groups = Dict{Tuple{I,Symbol},Vector{Tuple{Int,Symbol}}}() + groups = _object_key_index(Tuple{I,Symbol}, Vector{Tuple{Int,Symbol}}) for application in applications Base.@inline _with_model_application(applications_by_id, application) do current current.id in skipped_application_ids && return nothing @@ -6123,7 +6119,7 @@ function _record_destination_writers!(ownership, previous, resolved_destinations end function _validate_compiled_writer_ownership!(ownership, applications_by_id) - groups = Dict{keytype(ownership),Vector{Tuple{Int,Symbol}}}() + groups = _object_key_index(keytype(ownership), Vector{Tuple{Int,Symbol}}) for ((object_id, variable), owners) in ownership length(owners) > 1 || continue sort!(owners; by=owner -> owner.application_slot) @@ -6150,7 +6146,7 @@ function _compile_model_writer_ownership( manual_application_ids, resolved_destinations, ) where {I<:ObjectId} - ownership = Dict{Tuple{I,Symbol},Vector{CompiledWriterOwner}}() + ownership = _object_key_index(Tuple{I,Symbol}, Vector{CompiledWriterOwner}) for partial in applications getfield(getfield(partial, :plan), :id) in manual_application_ids && continue _with_model_application(_record_application_writers!, applications_by_id, partial, @@ -6183,7 +6179,7 @@ function _validate_model_writers_for_objects!( isempty(object_ids) && return nothing objects = compiled.model.registry.objects I = keytype(objects) - groups = Dict{Tuple{I,Symbol},Vector{Tuple{Int,Symbol}}}() + groups = _object_key_index(Tuple{I,Symbol}, Vector{Tuple{Int,Symbol}}) manual_application_ids = compiled.scenario_plan.manual_application_ids for raw_id in object_ids object_id = _index_object_id(objects, raw_id) @@ -7197,7 +7193,7 @@ end bindings = Union{bindings,row_types...} groups = Union{groups,NamedTuple{names,Tuple{row_types...}}} end - return :(Vector{$bindings}(), Dict{Tuple{Symbol,$I},$groups}()) + return :(Vector{$bindings}(), _object_key_index(Tuple{Symbol,$I}, $groups)) end function _compile_model_output_destination_bindings( @@ -7325,31 +7321,29 @@ function _compile_model_distributed_outputs( ) end -function _distributed_output_target_membership( - objects::AbstractDict{I}, outputs::CompiledDistributedOutputs, -) where {I<:ObjectId} - membership = Dict{Tuple{Symbol,I,Symbol},Vector{I}}() - for raw_binding in outputs.bindings - binding = raw_binding::CompiledModelOutputDestinationBinding - plan = getfield(binding, :plan)::CompiledModelOutputDestinationPlan - object_id = _index_object_id(objects, getfield(binding, :execution_object_id)) - destination_ids = getfield(binding, :destination_ids)::Vector{I} - key = (getfield(plan, :application_id), object_id, getfield(plan, :group)) - membership[key] = destination_ids +# The origin index already holds every output group and its ordered destinations. +# Comparing it directly also distinguishes an absent group from an empty group. +function _model_output_membership_matches(before::NamedTuple, after::NamedTuple) + length(before) == length(after) || return false + return all(keys(before)) do name + prior = getproperty(before, name) + next = get(after, name, nothing) + !isnothing(next) && getfield(prior, :destination_ids) == getfield(next, :destination_ids) end - return membership end -function _changed_distributed_output_target_ids( - objects::AbstractDict{I}, previous, current, -) where {I<:ObjectId} - previous_membership = _distributed_output_target_membership(objects, previous) - current_membership = _distributed_output_target_membership(objects, current) - changed = Set{Tuple{Symbol,I}}() - for key in union(keys(previous_membership), keys(current_membership)) - get(previous_membership, key, nothing) == - get(current_membership, key, nothing) && continue - push!(changed, (key[1], key[2])) +function _changed_distributed_output_target_ids(previous, current) + before = previous.by_execution_target + after = current.by_execution_target + changed = _object_key_set(keytype(after)) + for (target, groups) in after + prior = get(before, target, nothing) + if isnothing(prior) || !_model_output_membership_matches(prior, groups) + push!(changed, target) + end + end + for key in keys(before) + haskey(after, key) || push!(changed, key) end return changed end @@ -7365,7 +7359,7 @@ function _refresh_model_distributed_outputs( new_targets, pure_addition, ) - return previous, Set{Tuple{Symbol,ObjectId}}(), nothing + return previous, _object_key_set(Tuple{Symbol,keytype(model.registry.objects)}), nothing end # Admit the old route through the existing finite plan owner before selecting @@ -7378,19 +7372,14 @@ function _resolve_incremental_model_output_addition!( previous_plan isa P || return false execution_id = _index_object_id(objects, getfield(binding, :execution_object_id)) previous_ids = getfield(binding, :destination_ids)::Vector{I} - default_scope = _default_dependency_scope(model, execution_id) - destination_ids = I[ - object_id for object_id in added_ids - if _selector_matches_object_id( - model, - previous_plan.matcher, - object_id, - execution_id, - true, - default_scope, - false, - ) && !first(_sorted_object_id_position(previous_ids, object_id)) - ] + matcher = previous_plan.matcher + default_scope = isnothing(matcher.scope) ? _default_dependency_scope(model, execution_id) : nothing + destination_ids = I[] + for object_id in added_ids + Base.@inline _selector_matches_object_id(model, matcher, object_id, execution_id, + true, default_scope, false) || continue + first(_sorted_object_id_position(previous_ids, object_id)) || push!(destination_ids, object_id) + end isempty(destination_ids) && return true _sort_object_ids!(destination_ids) if !isempty(previous_ids) && @@ -7518,13 +7507,10 @@ function _incremental_distributed_output_addition!( end binding.membership_generation = UInt64(model.revision) end - changed_targets = Set{Tuple{Symbol,ObjectId}}( - ( - resolved.plan.application_id, - resolved.execution_object_id, - ) - for resolved in resolved_additions - ) + changed_targets = _object_key_set(keytype(previous.by_execution_target)) + for resolved in resolved_additions + push!(changed_targets, (resolved.plan.application_id, resolved.execution_object_id)) + end return previous, changed_targets, nothing end @@ -7559,9 +7545,7 @@ function _refresh_model_distributed_outputs( manual_application_ids, plans, ) - changed_targets = _changed_distributed_output_target_ids( - model.registry.objects, previous, current, - ) + changed_targets = _changed_distributed_output_target_ids(previous, current) changed_writers_by_variable = if pure_addition # A new origin may write to a destination already in the registry. _new_writers_on_existing_destinations( @@ -8006,7 +7990,7 @@ function _temporal_source_application( end io = IOBuffer() print(io, "Temporal model input `", binding.input, "` from `", - source_id.value, '.', binding.source_var, + _object_id_text(source_id), '.', binding.source_var, "` has ambiguous source applications `") _print_selector_diagnostic(io, matches, Any[]) print(io, "`. Add `application=...` to the `inputs=...` selector.") @@ -8067,7 +8051,7 @@ function _compile_model_status_views( distributed_outputs=NoCompiledDistributedOutputs(); status_view_schema, ) - views = Dict{Tuple{Symbol,ObjectId},Any}() + views = _object_key_index(Tuple{Symbol,keytype(model.registry.objects)}, Any) previous = getfield(model, :binding_cache) previous_views = previous isa CompiledCompositeModel ? previous.status_views_by_target : nothing positions = Dict( diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 4598a9b23..6369b5ef2 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -746,10 +746,11 @@ end end function _index_environment_binding_positions(bindings, ::Type{I}) where {I<:ObjectId} - return Dict{Tuple{Symbol,I},Int}( - _environment_binding_target_key(binding, I) => index - for (index, binding) in pairs(bindings) - ) + result = _object_key_index(Tuple{Symbol,I}, Int) + for (position, binding) in pairs(bindings) + result[_environment_binding_target_key(binding, I)] = position + end + return result end function _index_environment_targets_by_object(bindings, ::Type{I}) where {I<:ObjectId} @@ -770,7 +771,7 @@ function _index_environment_bindings(bindings, ::Type{I}) where {I<:ObjectId} # Keep lifecycle indexing open to future binding families; reads validate the # CompiledEnvironmentBinding domain. Execution targets retain concrete # handles and sampling plans. - by_target = Dict{Tuple{Symbol,I},Any}() + by_target = _object_key_index(Tuple{Symbol,I}, Any) sizehint!(by_target, length(bindings)) for binding in bindings by_target[_environment_binding_target_key(binding, I)] = binding @@ -971,7 +972,7 @@ function _reconcile_environment_binding_metadata( context = _object_environment_context(application.id, application.process, object, object_id) _, geometry_source_object_id, geometry_source = _environment_binding_object(model, object) - binding = _reconcile_environment_binding(environment_schema, old, plan, + binding = Base.@inline _reconcile_environment_binding(environment_schema, old, plan, object_id, context, geometry_source_object_id, geometry_source, keytype(cached.targets_by_object)) isnothing(binding) && return nothing @@ -1029,8 +1030,8 @@ function _refresh_environment_bindings_for_objects( dirty_ids, ) K = keytype(cached.by_target) - stale_targets = Set{K}() - replacements = Dict{K,Any}() + stale_targets = _object_key_set(K) + replacements = _object_key_index(K, Any) empty_targets = K[] for dirty_id in dirty_ids object_id = _index_object_id(cached.targets_by_object, dirty_id) @@ -1080,7 +1081,7 @@ function _refresh_environment_bindings_for_objects( pop!(cached.bindings) delete!(cached.by_target, target) object_targets = cached.targets_by_object[target[2]] - target_index = findfirst(==(target), object_targets) + target_index = findfirst(key -> key[1] === target[1], object_targets) isnothing(target_index) || deleteat!(object_targets, target_index) isempty(object_targets) && delete!(cached.targets_by_object, target[2]) end diff --git a/src/composite_model/object_key_indexes.jl b/src/composite_model/object_key_indexes.jl new file mode 100644 index 000000000..4aa94993f --- /dev/null +++ b/src/composite_model/object_key_indexes.jl @@ -0,0 +1,173 @@ +# Tuple types are covariant: a tuple containing different organ ID types +# can have several concrete types. A fixed record lets JuliaC specialize the +# hash table while callers keep their original tuple keys and iteration order. +struct _StoredObjectKey{A,B,C,L} + first::A + second::B + third::C +end + +_stored_object_key_type(::Type{Tuple{A,B}}) where {A,B} = + _StoredObjectKey{A,B,Nothing,2} +_stored_object_key_type(::Type{Tuple{A,B,C}}) where {A,B,C} = + _StoredObjectKey{A,B,C,3} + +function _stored_object_key(::Type{N}, key::Tuple{Any,Any}) where {N<:_StoredObjectKey} + return N(key[1], key[2], nothing) +end + +function _stored_object_key(::Type{N}, key::Tuple{Any,Any,Any}) where {N<:_StoredObjectKey} + return N(key...) +end + +_stored_object_key_arity(::_StoredObjectKey{A,B,C,L}) where {A,B,C,L} = L + +function _raw_object_key(key::_StoredObjectKey) + return _stored_object_key_arity(key) == 2 ? (key.first, key.second) : + (key.first, key.second, key.third) +end + +function Base.hash(key::_StoredObjectKey, seed::UInt) + tail = hash((), seed) + if _stored_object_key_arity(key) == 3 + tail = hash(key.third, tail) + end + return hash(key.first, hash(key.second, tail)) +end + +Base.isequal(left::_StoredObjectKey, right::_StoredObjectKey) = + _stored_object_key_arity(left) == _stored_object_key_arity(right) && + isequal(left.first, right.first) && isequal(left.second, right.second) && + isequal(left.third, right.third) + +@inline function _object_key_for_insertion(::Type{K}, key) where {K} + key isa K && return key + converted = convert(K, key)::K + isequal(converted, key) || _invalid_object_index_key(K, key) + return converted +end + +@static if isdefined(Base, :KeyTypeError) + _invalid_object_index_key(::Type{K}, key) where {K} = throw(Base.KeyTypeError(K, key)) +else + _invalid_object_index_key(::Type{K}, key) where {K} = + throw(ArgumentError("$(Base.limitrepr(key)) is not a valid key for type $K")) +end + +struct _ObjectKeyIndex{K,V,N} <: AbstractDict{K,V} + data::Dict{N,V} +end + +function _object_key_index(::Type{K}, ::Type{V}) where {K<:Tuple,V} + any(type -> type isa Union, fieldtypes(K)) || return Dict{K,V}() + N = _stored_object_key_type(K) + return _ObjectKeyIndex{K,V,N}(Dict{N,V}()) +end + +Base.length(index::_ObjectKeyIndex) = length(index.data) + +function Base.iterate(index::_ObjectKeyIndex{K,V}, state...) where {K,V} + row = iterate(index.data, state...) + isnothing(row) && return nothing + ((stored, value), next) = row + return Pair{K,V}(_raw_object_key(stored), value), next +end + +function Base.getindex(index::_ObjectKeyIndex{K,V,N}, key) where {K,V,N} + key isa K || throw(KeyError(key)) + stored = _stored_object_key(N, key) + return get(index.data, stored) do + throw(KeyError(_raw_object_key(stored))) + end +end + +function Base.setindex!(index::_ObjectKeyIndex{K,V,N}, @nospecialize(value), key) where {K,V,N} + checked = Base.@inline _object_key_for_insertion(K, key) + index.data[_stored_object_key(N, checked)] = value + return index +end + +Base.get(index::_ObjectKeyIndex{K,V,N}, key, default) where {K,V,N} = + key isa K ? get(index.data, _stored_object_key(N, key), default) : default +Base.haskey(index::_ObjectKeyIndex{K,V,N}, key) where {K,V,N} = + key isa K && haskey(index.data, _stored_object_key(N, key)) + +function Base.get!(make::Union{Function,Type}, index::_ObjectKeyIndex{K,V,N}, key) where {K,V,N} + checked = Base.@inline _object_key_for_insertion(K, key) + return get!(make, index.data, _stored_object_key(N, checked)) +end + +function Base.get!(index::_ObjectKeyIndex{K,V,N}, key, default) where {K,V,N} + checked = Base.@inline _object_key_for_insertion(K, key) + return get!(index.data, _stored_object_key(N, checked), default) +end + +@inline function Base.pop!(index::_ObjectKeyIndex{K,V,N}, key) where {K,V,N} + key isa K || throw(KeyError(key)) + stored = _stored_object_key(N, key) + haskey(index.data, stored) || throw(KeyError(key)) + return pop!(index.data, stored) +end + +Base.pop!(index::_ObjectKeyIndex{K,V,N}, key, default) where {K,V,N} = + key isa K ? pop!(index.data, _stored_object_key(N, key), default) : default + +function Base.delete!(index::_ObjectKeyIndex{K,V,N}, key) where {K,V,N} + key isa K && delete!(index.data, _stored_object_key(N, key)) + return index +end + +Base.empty(index::_ObjectKeyIndex{K,V}) where {K,V} = _object_key_index(K, V) +Base.empty!(index::_ObjectKeyIndex) = (empty!(index.data); index) +Base.copy(index::_ObjectKeyIndex) = typeof(index)(copy(index.data)) +function Base.sizehint!(index::_ObjectKeyIndex, n::Integer; kwargs...) + sizehint!(index.data, n; kwargs...) + return index +end + +struct _ObjectKeySet{K,N} <: AbstractSet{K} + data::Set{N} +end + +function _object_key_set(::Type{K}) where {K<:Tuple} + any(type -> type isa Union, fieldtypes(K)) || return Set{K}() + N = _stored_object_key_type(K) + return _ObjectKeySet{K,N}(Set{N}()) +end + +function Base.push!(set::_ObjectKeySet{K,N}, key) where {K,N} + checked = Base.@inline _object_key_for_insertion(K, key) + push!(set.data, _stored_object_key(N, checked)) + return set +end + +Base.in(key, set::_ObjectKeySet{K,N}) where {K,N} = + key isa K && _stored_object_key(N, key) in set.data +Base.length(set::_ObjectKeySet) = length(set.data) + +function Base.iterate(set::_ObjectKeySet, state...) + row = iterate(set.data, state...) + isnothing(row) && return nothing + return _raw_object_key(row[1]), row[2] +end + +function Base.delete!(set::_ObjectKeySet{K,N}, key) where {K,N} + key isa K && delete!(set.data, _stored_object_key(N, key)) + return set +end + +Base.empty(set::_ObjectKeySet{K}) where {K} = _object_key_set(K) +Base.empty!(set::_ObjectKeySet) = (empty!(set.data); set) +Base.copy(set::_ObjectKeySet) = typeof(set)(copy(set.data)) +function Base.sizehint!(set::_ObjectKeySet, n::Integer; kwargs...) + sizehint!(set.data, n; kwargs...) + return set +end + +function _object_key_set(::Type{K}, raw) where {K<:Tuple} + result = _object_key_set(K) + for key in raw + push!(result, key) + end + return result +end diff --git a/src/composite_model_api.jl b/src/composite_model_api.jl index b6f611147..d4d5a9a0e 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -1,6 +1,7 @@ # The Composite Model/Object API is one public compiler and runtime. Internal ownership is # split by dependency direction; these files are not modules and add no public # abstraction boundary. +include("composite_model/object_key_indexes.jl") include("composite_model/status_conversion.jl") include("composite_model/registry_topology.jl") include("composite_model/status_construction.jl") diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index a3ef4f161..6ef3e83e0 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -67,11 +67,11 @@ function close_registry(model::CompositeModel) ) end -function fixture(closed::Bool; environment_schema=PSE.EnvironmentBindingSchema()) +function fixture(closed::Bool; environment_schema=PSE.EnvironmentBindingSchema(), first_id=1) backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, Any[], nothing) model = CompositeModel( Object(:root; scale=:Scene, status=Status(seen=0.0f0, visits=0)), - Object(1; scale=:Leaf, parent=:root, geometry=(cell=:a,), + Object(first_id; scale=:Leaf, parent=:root, geometry=(cell=:a,), status=Status(seen=0.0f0, visits=0)), Object(:leaf; scale=:Leaf, parent=:root, geometry=(cell=:b,), status=Status(seen=0.0f0, visits=0)); @@ -582,6 +582,43 @@ end end end + +@testset "environment bindings retain symbolic and compound leaf identities through growth" begin + for closed in (false, true) + first_id = (:tree, :leaf, 1) + next_id = (:tree, :leaf, 2) + (; model, simulation) = fixture(closed; first_id) + owner = simulation.environment_bindings + check_indexes(model, owner) + + leaf_key = (:probe, ObjectId(:leaf)) + first_key = (:probe, ObjectId(first_id)) + survivor = owner.by_target[leaf_key] + old_binding = owner.by_target[first_key] + cell = PSE.refvalue(model_status(model, :leaf), :seen) + mark_environment_binding_dirty!(model, first_id) + continue!(simulation; steps=0) + refreshed = simulation.environment_bindings + @test refreshed.by_target === owner.by_target + @test refreshed.positions_by_target === owner.positions_by_target + @test refreshed.targets_by_object === owner.targets_by_object + @test refreshed.by_target[leaf_key] === survivor + @test refreshed.by_target[first_key] !== old_binding + check_indexes(model, refreshed) + + remove_object!(model, first_id) + continue!(simulation; steps=0) + @test !haskey(simulation.environment_bindings.by_target, first_key) + register_object!(model, Object(next_id; scale=:Leaf, parent=:root, geometry=(cell=:a,), + status=Status(seen=0.0f0, visits=0))) + step!(simulation) + check_indexes(model, simulation.environment_bindings) + @test model_status(model, next_id).visits == 1 + @test model_status(model, :leaf).visits == 2 + @test PSE.refvalue(model_status(model, :leaf), :seen) === cell + end +end + end module SwitchingBackendRepro diff --git a/test/test-model-object-id.jl b/test/test-model-object-id.jl index dc618f324..a507791a0 100644 --- a/test/test-model-object-id.jl +++ b/test/test-model-object-id.jl @@ -612,3 +612,136 @@ end @test model_status(model, 200).total == 9.0 @test last.(outputs(simulation)[(:first__source, ObjectId(102), :signal)]) == [1.0] end + +module ObjectKeyIndexContractChecks +using Test, PlantSimEngine +const PSE = PlantSimEngine +const I = Union{ObjectId{Symbol},ObjectId{Tuple{Symbol,Symbol,Int}}} + +struct UnfaithfulKey{T} + value::T +end +Base.convert(::Type{K}, key::UnfaithfulKey) where {K<:Tuple} = convert(K, key.value) + +function caught(f) + try + f() + return nothing + catch error + return error + end +end + +@testset "nominal object indexes preserve public tuple collection contracts" begin + for arity in (2, 3) + K = arity == 2 ? Tuple{Symbol,I} : Tuple{Symbol,I,Symbol} + index = PSE._object_key_index(K, Any) + reference = Dict{K,Any}() + raw_keys = K[] + for number in 1:64 + id = isodd(number) ? ObjectId(Symbol(:leaf_, number)) : ObjectId((:tree, :leaf, number)) + key = arity == 2 ? (:probe, id) : (:probe, id, :signal) + cell = Ref{Any}(number) + push!(raw_keys, key) + @test setindex!(index, cell, key) === index + reference[key] = cell + @test index[key] === cell + stored = PSE._stored_object_key(PSE._stored_object_key_type(K), key) + @test isconcretetype(typeof(stored)) + for seed in (UInt(0), UInt(0x123456), typemax(UInt)) + @test hash(stored, seed) == hash(key, seed) + end + end + @test collect(keys(index)) == collect(keys(reference)) + @test collect(index) == collect(reference) + @test Dict(index) == reference + clone = copy(index) + @test typeof(clone) === typeof(index) + @test clone !== index + @test all(clone[key] === reference[key] for key in raw_keys) + first_key = first(raw_keys) + first_cell = index[first_key] + clone[first_key] = Ref{Any}(:copy_only) + @test index[first_key] === first_cell + bare = empty(index) + @test isempty(bare) && typeof(bare) === typeof(index) + @test sizehint!(bare, 128) === bare + bare[first_key] = first_cell + @test bare[first_key] === first_cell + @test empty!(bare) === bare && isempty(bare) + + actual_set = PSE._object_key_set(K) + reference_set = Set{K}() + @test sizehint!(actual_set, 128) === actual_set + sizehint!(reference_set, 128) + union!(actual_set, raw_keys) + union!(reference_set, raw_keys) + @test collect(actual_set) == collect(reference_set) + @test all(key in actual_set for key in raw_keys) + set_clone = copy(actual_set) + delete!(set_clone, first_key) + @test first_key in actual_set && !(first_key in set_clone) + @test typeof(empty(actual_set)) === typeof(actual_set) + @test isempty(empty(actual_set)) + @test empty!(set_clone) === set_clone && isempty(set_clone) + + missing_id = ObjectId((:tree, :leaf, 999)) + missing = arity == 2 ? (:probe, missing_id) : (:probe, missing_id, :signal) + for operation in (getindex, pop!) + error = caught(() -> operation(index, missing)) + @test error isa KeyError + @test error.key === missing + end + marker = Ref{Any}(:missing) + @test get(index, missing, marker) === marker + @test pop!(index, missing, marker) === marker + outside = arity == 2 ? (:probe, ObjectId(1)) : (:probe, ObjectId(1), :signal) + @test get(index, outside, marker) === get(reference, outside, marker) === marker + @test haskey(index, outside) == haskey(reference, outside) == false + @test delete!(index, outside) === index + @test length(index) == length(reference) + bad = UnfaithfulKey(first_key) + for mode in (:setindex, :get_default, :get_thunk) + target = empty(index) + control = Dict{K,Any}() + calls = Ref(0) + make = () -> (calls[] += 1; marker) + operation = mode === :setindex ? ((d, k) -> setindex!(d, marker, k)) : + mode === :get_default ? ((d, k) -> get!(d, k, marker)) : + ((d, k) -> get!(make, d, k)) + expected = caught(() -> operation(control, bad)) + observed = caught(() -> operation(target, bad)) + @test typeof(observed) === typeof(expected) + @test observed isa Exception + @test isempty(target) && isempty(control) + @test calls[] == 0 + end + bad_set = PSE._object_key_set(K) + expected = caught(() -> push!(Set{K}(), bad)) + observed = caught(() -> push!(bad_set, bad)) + @test typeof(observed) === typeof(expected) + @test isempty(bad_set) + end +end + +@testset "stored key arity and ordinary identity pools" begin + pair = (:probe, ObjectId(:leaf)) + triple = (:probe, ObjectId(:leaf), nothing) + KP = Tuple{Symbol,I} + KT = Tuple{Symbol,I,Nothing} + stored_pair = PSE._stored_object_key(PSE._stored_object_key_type(KP), pair) + stored_triple = PSE._stored_object_key(PSE._stored_object_key_type(KT), triple) + @test !isequal(stored_pair, stored_triple) + for seed in (UInt(0), UInt(42)) + @test hash(stored_pair, seed) == hash(pair, seed) + @test hash(stored_triple, seed) == hash(triple, seed) + end + @test PSE._object_key_index(Tuple{Symbol,ObjectId{Int}}, Any) isa Dict + @test PSE._object_key_set(Tuple{Symbol,ObjectId{Int}}) isa Set + open_index = PSE._object_key_index(Tuple{Symbol,ObjectId}, Any) + @test open_index isa Dict + cell = Ref{Any}(:live) + open_index[(:probe, ObjectId((:future, 1.0f0)))] = cell + @test only(values(open_index)) === cell +end +end From 230ac05c0451fcbd9ce8b0a8c9fd27fa1d63fcee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 08:16:46 +0100 Subject: [PATCH 215/324] Balance the full CI matrix around the Julia 1.10 prepared-call suite --- .github/workflows/CI.yml | 6 +++--- test/runtests.jl | 3 ++- test/test_groups.jl | 12 ++++++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 6a39f9811..d54ff9d60 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -20,7 +20,7 @@ concurrency: jobs: test: if: ${{ github.event_name != 'workflow_dispatch' || !inputs.juliac_safe }} - name: Julia ${{ matrix.version }} - ${{ matrix.os }} - shard ${{ matrix.shard }}/3 - ${{ github.event_name }} + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - shard ${{ matrix.shard }}/4 - ${{ github.event_name }} runs-on: ${{ matrix.os }} # Keep the full suite within the limit by running independent test groups separately. timeout-minutes: 180 @@ -38,7 +38,7 @@ jobs: - ubuntu-latest - macOS-latest - windows-latest - shard: [1, 2, 3] + shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 @@ -49,7 +49,7 @@ jobs: - uses: julia-actions/julia-runtest@v1 env: JULIA_NUM_THREADS: 4 - PSE_TEST_SHARD_COUNT: "3" + PSE_TEST_SHARD_COUNT: "4" PSE_TEST_SHARD_INDEX: ${{ matrix.shard }} - uses: julia-actions/julia-processcoverage@v1 - uses: codecov/codecov-action@v7 diff --git a/test/runtests.jl b/test/runtests.jl index eb3672493..c2613af4d 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -38,7 +38,8 @@ else shard_index = parse(Int, get(ENV, "PSE_TEST_SHARD_INDEX", "1")) 1 <= shard_index <= shard_count <= length(TEST_GROUPS) || error("Test shard index/count must satisfy 1 <= index <= count <= $(length(TEST_GROUPS)).") - group_indices = shard_index:shard_count:length(TEST_GROUPS) + group_indices = shard_count == length(CI_TEST_SHARDS) ? + CI_TEST_SHARDS[shard_index] : (shard_index:shard_count:length(TEST_GROUPS)) @info "Test partition" shard_index shard_count groups=length(group_indices) @testset "Testing PlantSimEngine" begin diff --git a/test/test_groups.jl b/test/test_groups.jl index e61d53509..629eac55f 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -303,3 +303,15 @@ const TEST_GROUPS = ( "test-model-call-evaluation-temporal-inputs.jl", ), ) + +# On Julia 1.10 the prepared execution tests alone can take over two hours. +# Run them together in one job; the other three jobs retain source order. +const CI_TEST_SHARDS = let + group_index(name) = only(findall(group -> first(group) == name, TEST_GROUPS)) + prepared = group_index("Prepared execution schemas") + newborn = group_index("Newborn retained manual calls") + identities = group_index("Identity-aware Many inputs") + @assert prepared < newborn < identities + (filter(!=(prepared), 1:(newborn - 1)), prepared:prepared, + newborn:(identities - 1), identities:lastindex(TEST_GROUPS)) +end From 4f72300465391d50637faf823332cfe344220734 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 08:46:46 +0100 Subject: [PATCH 216/324] Keep the registry identity type when validating required inputs --- src/composite_model/compilation.jl | 9 ++-- test/test-model-binding-index-identities.jl | 53 +++++++++++++++++++++ 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 4a6c385c7..7a99b5bc8 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -9374,20 +9374,21 @@ function _validate_declared_model_input_name!(application, input_sym::Symbol) ) end -function _bound_model_inputs(input_bindings) - bound = Set{Tuple{Symbol,ObjectId,Symbol}}() +function _bound_model_inputs(input_bindings, objects::AbstractDict{I}) where {I<:ObjectId} + bound = _object_key_set(Tuple{Symbol,I,Symbol}) for binding in input_bindings binding.policy isa PreviousTimeStep && continue binding.carrier_hint == :optional_default && isnothing(binding.carrier) && continue - push!(bound, (binding.application_id, binding.consumer_id, binding.input)) + consumer_id = _index_object_id(objects, binding.consumer_id) + push!(bound, (binding.application_id, consumer_id, binding.input)) end return bound end function _validate_model_required_inputs!(model::CompositeModel, applications, applications_by_id, input_bindings) - bound = _bound_model_inputs(input_bindings) + bound = _bound_model_inputs(input_bindings, model.registry.objects) I = keytype(model.registry.objects) missing = NamedTuple{(:application_id, :object_id, :input),Tuple{Symbol,I,Symbol}}[] for partial in applications diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 05c7dddb4..3dbb38b91 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -813,4 +813,57 @@ end end end +@testset "required inputs retain the registry identity domain" begin + consumer = (:tree, :leaf, 1) + for closed in (false, true) + cell = Ref(3f0) + model = CompositeModel( + Object(:source; scale=:Leaf, status=Status((x=cell,))), + Object(consumer; scale=:Leaf); + applications=( + ModelSpec(Leaf(); name=:leaf, on=One(id=:source)), + ModelSpec(Reader(); name=:reader, on=One(id=ObjectId(consumer)), + inputs=(single=One(id=:source, within=SceneScope(), application=:leaf, var=:x),)), + )) + closed && (model = close_registry(model)) + simulation = run!(model; steps=0, outputs=:none) + bound = PSE._bound_model_inputs(simulation.compiled.input_bindings, model.registry.objects) + @test eltype(bound) === Tuple{Symbol,keytype(model.registry.objects),Symbol} + @test (:reader, ObjectId(consumer), :single) in bound + @test !((:reader, ObjectId(:source), :single) in bound) + binding = only(filter(binding -> binding.input === :single, simulation.compiled.input_bindings)) + @test binding.carrier === cell + @test PSE.refvalue(model_status(model, :source), :x) === cell + @test cell[] === 3f0 + @test current_step(simulation) == 0 + + for provided in (true, false) + status = provided ? Status((single=cell,)) : Status() + direct = CompositeModel(Object(:root; scale=:Plant), + Object(consumer; scale=:Leaf, parent=:root, status); + applications=(ModelSpec(Reader(); name=:reader, on=One(id=ObjectId(consumer))),)) + closed && (direct = close_registry(direct)) + if provided + direct_simulation = run!(direct; steps=0, outputs=:none) + direct_bound = PSE._bound_model_inputs(direct_simulation.compiled.input_bindings, + direct.registry.objects) + @test !((:reader, ObjectId(consumer), :single) in direct_bound) + @test PSE.refvalue(model_status(direct, consumer), :single) === cell + @test current_step(direct_simulation) == 0 + else + exception = try + run!(direct; steps=0, outputs=:none) + nothing + catch error + error + end + @test exception isa ErrorException + @test occursin("requires `single`", sprint(showerror, exception)) + @test occursin("tree", sprint(showerror, exception)) + @test cell[] === 3f0 + end + end + end +end + end From ad69a5993dcfcd596595b43f8e89362849e70134 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 10:57:39 +0100 Subject: [PATCH 217/324] Reuse route indexes for initial status preparation Collect the real producer and consumer identities from the same scope and scale indexes used at organ birth. This avoids scanning all registered objects for every initial leaf and retains the route and numerical variant checks. --- .../prepared_status_manifest.jl | 26 +++++++-------- ...st-fixed-status-prospective-distributed.jl | 32 +++++++++++++++++++ 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 2c4633b7a..ddd5e4f4a 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -248,6 +248,16 @@ function _prepared_birth_recipes(S, applications, permissions, destinations, raw return recipes, all_routes end +function _append_prepared_raw_contexts!(contexts, model, object, application, route) + for candidate in _prepared_status_context_ids(model, application, route, object, object.parent) + id = _index_object_id(model.registry.objects, candidate) + _prepared_status_application_matches_id(model, model, application.target_matcher, id) || continue + _prepared_status_route_matches(model, object, object.parent, application, route, id) || continue + push!(contexts, (route.slot, id, _prepared_status_variant_slot(application, id))) + end + return contexts +end + function _prepared_status_raw_signature(model, object, applications, permissions, destinations) I = keytype(model.registry.objects) selected = Tuple{Int,Int}[(application.slot, _prepared_status_variant_slot(application, object.id)) @@ -256,23 +266,11 @@ function _prepared_status_raw_signature(model, object, applications, permissions routes = Tuple{Int,I,Int}[] for plan in destinations application = only(a for a in applications if a.slot == plan.application_slot) - for (execution_id, producer) in model.registry.objects - _prepared_status_application_matches(model, producer, producer.parent, application) || continue - _prepared_status_route_matches(model, object, object.parent, - application, plan, execution_id) || continue - push!(routes, (plan.slot, execution_id, - _prepared_status_variant_slot(application, execution_id))) - end + _append_prepared_raw_contexts!(routes, model, object, application, plan) end sources = Tuple{Int,I,Int}[] for (application, permission) in zip(applications, permissions), source in permission.sources - for (consumer_id, consumer) in model.registry.objects - _prepared_status_application_matches(model, consumer, consumer.parent, application) || continue - _prepared_status_route_matches(model, object, object.parent, - application, source, consumer_id) || continue - push!(sources, (source.slot, consumer_id, - _prepared_status_variant_slot(application, consumer_id))) - end + _append_prepared_raw_contexts!(sources, model, object, application, source) end labels = _prepared_status_object_labels(model, object, object.parent) return (labels=(labels.scale, labels.kind, labels.species), diff --git a/test/test-fixed-status-prospective-distributed.jl b/test/test-fixed-status-prospective-distributed.jl index 83eafceea..05f9aa3c8 100644 --- a/test/test-fixed-status-prospective-distributed.jl +++ b/test/test-fixed-status-prospective-distributed.jl @@ -82,4 +82,36 @@ end @test outputs(sim)[(:delivery, sibling.id, :x)] == [(1.0, 7.0)] end +struct LeafAreaSum <: AbstractFixed_Status_Future_DistributedModel end +PSE.inputs_(::LeafAreaSum) = (areas=Default(Float64[]),) +PSE.outputs_(::LeafAreaSum) = (leaf_area=0.0,) +function PSE.run!(::LeafAreaSum, status, environment, constants, context) + status.leaf_area = sum(bound_input(context, :areas); init=0.0) + return nothing +end + +@testset "initial leaves record their own producer and consumer on each palm" begin + model = CompositeModel( + Object(:scene; scale=:Scene), + Object(:north; scale=:Plant, parent=:scene), + Object(:south; scale=:Plant, parent=:scene), + Object(:first; scale=:Leaf, parent=:north, status=Status(area=2.0)), + Object(:second; scale=:Leaf, parent=:south, status=Status(area=3.0)); + applications=( + ModelSpec(Source(7.0); name=:delivery, on=Many(scale=:Plant), + outputs_to=(OutputTo(Many(Subtree(); scale=:Leaf)),)), + ModelSpec(LeafAreaSum(); name=:area_sum, on=Many(scale=:Plant), + inputs=(areas=Many(Subtree(); scale=:Leaf, var=:area, from_status=true),)), + ), + ) + leaf_families = filter(f -> f.labels[1] === :Leaf, PSE._prepared_status_manifest(model).raw_families) + @test length(leaf_families) == 2 + @test Set((only(f.destinations)[2], only(f.sources)[2]) for f in leaf_families) == + Set((ObjectId(id), ObjectId(id)) for id in (:north, :south)) + run!(model; steps=1) + @test model_status(model, :north).leaf_area == 2.0 + @test model_status(model, :south).leaf_area == 3.0 + @test model_status(model, :first).x == model_status(model, :second).x == 7.0 +end + end From 83e60048ac8a9ec59a992605fabdb83f01ee4f45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 11:54:51 +0100 Subject: [PATCH 218/324] Read declared kernel ports directly from their prepared status --- src/component_models/Status.jl | 2 +- test/test-status-fixed-storage.jl | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 946458786..1bd9eea47 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -142,7 +142,7 @@ _status_storage_reference_types(::Type{NamedTuple{N,R}}) where {N,R} = R _status_storage_reference_types(::Type{<:_FixedStatusStorage{N,R}}) where {N,R} = R _status_storage_reference_types(::Type{<:_ProjectedStatusStorage{N,R}}) where {N,R} = R @inline _status_reference(storage::NamedTuple, key) = getfield(storage, key) -@inline function _status_reference(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}, key::Symbol) +@inline function _status_reference(storage::_FixedStatusStorage, key::Symbol) reference = getfield(storage.refs, key) reference === nothing && throw(KeyError(key)) return reference diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 7f57596c0..918d873da 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -75,6 +75,12 @@ end @test_throws ArgumentError PSE._projected_status_type(SCHEMA,Val((:unprepared,)),Tuple{RF32}) factory = PSE.ExactReferenceFactory(SCHEMA,Tuple{RF64},Projected,(:x,)) old = PSE._construct_status(factory,owner,(private,)) + # Both directories share the same cells, so comparing values alone cannot + # detect a kernel read falling back to the canonical presence check. + projected_storage = typeof(getfield(old, :vars)) + canonical_storage = typeof(getfield(owner, :vars)) + @test which(PSE._status_reference, (projected_storage, Symbol)) !== + which(PSE._status_reference, (canonical_storage, Symbol)) @test old.x === 100.0 && first(Tuple(old)) === 100.0 @test PSE.refvalue(old,:x) === private @test PSE.refvalue(old,:seed) === PSE.refvalue(owner,:seed) From 3652ea197b17995b7ca982f74c1e05250f0babdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 14:50:11 +0100 Subject: [PATCH 219/324] Validate required inputs from prepared model declarations --- src/composite_model/compilation.jl | 21 +++-- test/test-model-authored-port-inventory.jl | 101 +++++++++++++++++++++ 2 files changed, 115 insertions(+), 7 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 7a99b5bc8..cef25bd3a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5425,12 +5425,21 @@ function explain_initialization(model::CompositeModel) return _explain_initialization(report) end +# Required membership comes from the exact declaration-type witnesses; the +# literal tuple keeps declaration order at any width without replaying inputs_. +@generated function _required_input_names_from_types(::NamedTuple{Names,Types}) where {Names,Types} + required = Tuple(name for (name, declaration) in zip(Names, fieldtypes(Types)) + if declaration <: Type{<:Required}) + return QuoteNode(required) +end + +_required_input_names(ports) = + _required_input_names_from_types(_authored_metadata_value(ports.input_declaration_types)) + function _initialization_required_input_schema(application) ports = _application_ports(application) required = Dict{Symbol,Required}() - for name in ports.input_names - declaration = getproperty(ports.input_declaration_types, name) - declaration <: Required || continue + for name in _required_input_names(ports) required[name] = Required(getproperty(ports.input_types, name)) end return required @@ -9393,11 +9402,9 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a missing = NamedTuple{(:application_id, :object_id, :input),Tuple{Symbol,I,Symbol}}[] for partial in applications _with_model_application(applications_by_id, partial) do application - schema = _model_input_schema(application) + required_names = _required_input_names(_application_ports(application)) for object_id in application.target_ids - for (input_, declaration) in pairs(schema) - declaration isa Required || continue - input = Symbol(input_) + for input in required_names (application.id, object_id, input) in bound && continue status = model_status(model, object_id) status isa Status && hasproperty(status, input) && continue diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index c05d8c310..db737de3f 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -679,4 +679,105 @@ Base.showerror(io::IO, error::TaggedHookError) = print(io, "saved hook error: ", end end +PSE.@process "captured_required_names" verbose=false +struct InstanceRequiredNames{D,C} <: AbstractCaptured_Required_NamesModel + names::NTuple{3,Symbol} + declarations::D + calls::C +end +function PSE.inputs_(model::InstanceRequiredNames) + model.calls[] += 1 + return NamedTuple{model.names}(model.declarations) +end +PSE.outputs_(::InstanceRequiredNames) = NamedTuple() +PSE.run!(::InstanceRequiredNames, status, environment, constants, context) = nothing + +function required_name_model(; reverse=false) + names = reverse ? (:a, :buffer, :z) : (:z, :buffer, :a) + declarations = reverse ? (Required(Integer), Default(1f0), Required(Float32)) : + (Required(Float32), Default(1f0), Required(Integer)) + return InstanceRequiredNames(names, declarations, Ref(0)) +end + +@testset "Required validation uses captured instance names in declaration order" begin + process_model = required_name_model() + cell = Ref(3f0) + model = CompositeModel(Object(:first; status=Status((z=cell, a=Ref(4),))); + applications=(ModelSpec(process_model; name=:dynamic, on=Many()),)) + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) + table = PSE._applications_by_id(applications) + application = only(applications) + before = process_model.calls[] + @test PSE._required_input_names(PSE._application_ports(application)) === (:z, :a) + @test PSE._validate_model_required_inputs!(model, applications, table, + PSE.CompiledModelInputBinding[]) === nothing + @test process_model.calls[] == before + @test PSE.refvalue(model_status(model, :first), :z) === cell + required = PSE._initialization_required_input_schema(application) + @test Set(keys(required)) == Set((:z, :a)) + @test required[:z] isa Required{Float32} + @test required[:a] isa Required{Integer} + @test process_model.calls[] == before + # Real-value inspection remains fresh; only Required membership is captured. + @test keys(PSE._model_input_schema(application)) === (:z, :buffer, :a) + @test process_model.calls[] == before + 1 + + # The supplied object provides the physical cell type for Required(Integer). + missing_model = CompositeModel(Object(:first), Object(:second), + Object(:supplied; status=Status(z=1f0, a=1)); + applications=(ModelSpec(process_model; name=:dynamic, on=Many()),)) + missing_apps = PSE._compile_model_applications(missing_model, PSE._model_timeline(missing_model)) + before = process_model.calls[] + error = try + PSE._validate_model_required_inputs!(missing_model, missing_apps, + PSE._applications_by_id(missing_apps), PSE.CompiledModelInputBinding[]) + nothing + catch exception + exception + end + @test error isa ErrorException + fields = [(match.captures[1], match.captures[2]) for match in + eachmatch(r"on object `([^`]+)` requires `([^`]+)`", sprint(showerror, error))] + @test fields == [("first", "z"), ("first", "a"), ("second", "z"), ("second", "a")] + @test process_model.calls[] == before +end + +@testset "object overrides preserve canonical Required order without replay" begin + base, replacement = required_name_model(), required_name_model(; reverse=true) + template = CompositeModelTemplate((ModelSpec(base; name=:dynamic, on=Many(scale=:Leaf)),)) + instance = ObjectInstance(:stand, template; root=Object(:plant; scale=:Plant), + objects=(Object(:base_leaf; scale=:Leaf, parent=:plant, status=Status(z=1f0, a=1)), + Object(:leaf; scale=:Leaf, parent=:plant)), + object_overrides=(Override(object=:leaf, application=:dynamic, model=replacement),)) + model = CompositeModel(instance) + applications = PSE._compile_model_applications(model, PSE._model_timeline(model)) + before = (base.calls[], replacement.calls[]) + error = try + PSE._validate_model_required_inputs!(model, applications, + PSE._applications_by_id(applications), PSE.CompiledModelInputBinding[]) + nothing + catch exception + exception + end + @test error isa ErrorException + fields = [match.captures[1] for match in eachmatch(r"requires `([^`]+)`", sprint(showerror, error))] + @test fields == ["z", "a"] + @test (base.calls[], replacement.calls[]) == before + application = only(applications) + PSE._with_application_variant(application, ObjectId(:leaf)) do effective, ports + @test effective === replacement + @test ports.input_names === (:a, :buffer, :z) + @test getproperty(ports.input_declaration_types, :a) === Required{Integer} + @test getproperty(ports.input_declaration_types, :z) === Required{Float32} + end +end + +@testset "Required names are inferred for wide prepared contracts" begin + names = ntuple(i -> Symbol(:field_, i), 32) + declarations = ntuple(i -> isodd(i) ? Required(Integer) : Default(1.0), length(names)) + types = PSE._authored_port_types(typeof, NamedTuple{names}(declarations)) + ports = (input_names=names, input_declaration_types=types) + @test (@inferred PSE._required_input_names(ports)) === names[1:2:end] +end + end From 77e60af9f5f030ee1057c916166e99bf7c3e03f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 15:08:19 +0100 Subject: [PATCH 220/324] Move reusable scenario tests to the lighter CI shard --- test/test_groups.jl | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/test/test_groups.jl b/test/test_groups.jl index 629eac55f..2f41d9b13 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -304,14 +304,15 @@ const TEST_GROUPS = ( ), ) -# On Julia 1.10 the prepared execution tests alone can take over two hours. -# Run them together in one job; the other three jobs retain source order. +# Prepared execution alone can take over two hours on Julia 1.10. On macOS +# the reusable scenario tests also need a separate share of the three-hour job budget. const CI_TEST_SHARDS = let group_index(name) = only(findall(group -> first(group) == name, TEST_GROUPS)) prepared = group_index("Prepared execution schemas") + reusable = group_index("Reusable scenario plans") newborn = group_index("Newborn retained manual calls") identities = group_index("Identity-aware Many inputs") - @assert prepared < newborn < identities - (filter(!=(prepared), 1:(newborn - 1)), prepared:prepared, - newborn:(identities - 1), identities:lastindex(TEST_GROUPS)) + @assert prepared < reusable < newborn < identities + (filter(i -> i != prepared && i != reusable, 1:(newborn - 1)), prepared:prepared, + newborn:(identities - 1), [reusable; identities:lastindex(TEST_GROUPS)]) end From aa0aca0a9defd9bbe4aa9ddebca79cc45c88b36f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 18:36:49 +0100 Subject: [PATCH 221/324] Allow cold macOS and downstream XPalm tests to finish --- .github/workflows/CI.yml | 4 ++-- .github/workflows/Integration.yml | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index d54ff9d60..67d59a74c 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -22,8 +22,8 @@ jobs: if: ${{ github.event_name != 'workflow_dispatch' || !inputs.juliac_safe }} name: Julia ${{ matrix.version }} - ${{ matrix.os }} - shard ${{ matrix.shard }}/4 - ${{ github.event_name }} runs-on: ${{ matrix.os }} - # Keep the full suite within the limit by running independent test groups separately. - timeout-minutes: 180 + # Cold compilation of the nested call tests can take 170 minutes on macOS 1.10. + timeout-minutes: ${{ matrix.os == 'macOS-latest' && matrix.version == '1.10' && 225 || 180 }} permissions: # needed to allow julia-actions/cache to proactively delete old caches that it has created actions: write diff --git a/.github/workflows/Integration.yml b/.github/workflows/Integration.yml index 44296f382..7b0010d72 100644 --- a/.github/workflows/Integration.yml +++ b/.github/workflows/Integration.yml @@ -28,7 +28,7 @@ jobs: - version: "1.12" os: ubuntu-latest # The complete XPalm suite includes cold compilation and VPalm tests. - timeout_minutes: 90 + timeout_minutes: 120 package: { name: XPalm, user: PalmStudio, repo: XPalm.jl, branch: main, default: main } - version: "1" os: ubuntu-latest @@ -39,6 +39,7 @@ jobs: # XPalm's existing mode runs its full-cycle scientific oracle on latest Julia. - version: "1" os: ubuntu-latest + timeout_minutes: 75 package: { name: XPalm, user: PalmStudio, repo: XPalm.jl, branch: main, default: main } test_args: reference-regression steps: From a7082d264fb776dfa97aaab1159db1cd6ee32eea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 19:24:41 +0100 Subject: [PATCH 222/324] Keep input-default telemetry out of the staging return path --- src/composite_model/compilation.jl | 34 +++++++++++++----------- test/test-model-status-type-lifecycle.jl | 31 +++++++++++++++++++++ 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index cef25bd3a..bd9ae4c75 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6877,7 +6877,6 @@ end function _stage_model_status_defaults!(preparation, defaults::NamedTuple, variables, stage_default!::F, context, ) where {F} - rewrites_avoided = 0 for variable in variables if preparation isa Status hasproperty(preparation, variable) && continue @@ -6886,17 +6885,17 @@ function _stage_model_status_defaults!(preparation, defaults::NamedTuple, variab elseif _status_recipe_has_variable(preparation, variable) continue end - rewrites_avoided += _with_metadata_entry(stage_default!, defaults, variable, + _with_metadata_entry(stage_default!, defaults, variable, preparation, variable, context) end - return rewrites_avoided + return nothing end Base.@noinline function _stage_model_output_default!(value, recipe, variable, context) _status_recipe_add_default!(context.model, recipe, context.object_id, variable, value; application_id=context.application_id, origin=:model_output_default, conversion_records=context.conversion_records) - return 0 + return nothing end function _prepare_model_output_statuses!( @@ -7818,11 +7817,12 @@ Base.@noinline function _stage_model_input_default!(value, recipe, variable, con application_id=context.application_id, origin=:model_input_default, conversion_records=context.conversion_records) context.default_status_updates[(context.object_id, variable)] = true - return 0 + return nothing end - return Base.@inline _with_model_input_status_reference( + Base.@inline _with_model_input_status_reference( _stage_model_input_default_reference!, context.bindings, reference, recipe, variable, value, context) + return nothing end function _stage_model_input_default_reference!(reference, preparation, variable, @@ -7835,7 +7835,9 @@ function _stage_model_input_default_reference!(reference, preparation, variable, origin=:model_input_default, private_copy=true, conversion_records=context.conversion_records) _status_recipe_set_reference!(preparation, variable, reference) - return 1 + counter = context.input_default_rewrites_avoided + isnothing(counter) || (counter[] += 1) + return nothing end function _stage_model_bound_input_reference!(binding, context) @@ -7898,25 +7900,26 @@ function _prepare_model_input_statuses_batched!( record_conversions = !_no_status_conversion(model.status_conversion) conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records default_status_updates = Dict{Tuple{I,Symbol},Bool}() - input_default_rewrites_avoided = 0 + # Keep optional telemetry local until the staged status transaction succeeds. + input_default_rewrites_avoided = isnothing(performance) ? nothing : Ref(0) context = (; model, recipes, recipe_order, bindings, final_references, - conversion_records, default_status_updates) + conversion_records, default_status_updates, input_default_rewrites_avoided) for partial in applications - input_default_rewrites_avoided += Base.@inline _with_model_application(applications_by_id, partial) do application - rewrites_avoided = 0 + Base.@inline _with_model_application(applications_by_id, partial) do application _model_input_names(application) schemas = _application_default_schemas(application, Val(:inputs)) for object_id in application.target_ids - rewrites_avoided += Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults + Base.@inline _with_application_defaults(application, object_id, schemas, Val(:inputs)) do defaults preparation = _status_preparation_for_object!( recipes, recipe_order, model, object_id) selected = (; context..., application_id=application.id, object_id) _with_canonical_status_preparation(_stage_model_status_defaults!, recipes, model.registry.objects.catalog, preparation, defaults, keys(defaults), _stage_model_input_default!, selected) + return nothing end end - return rewrites_avoided + return nothing end end @@ -7944,12 +7947,13 @@ function _prepare_model_input_statuses_batched!( delete!(variables, variable) end end - iszero(input_default_rewrites_avoided) || + if !isnothing(input_default_rewrites_avoided) && !iszero(input_default_rewrites_avoided[]) _runtime_performance_count!( performance, :input_default_status_rewrites_avoided, - input_default_rewrites_avoided, + input_default_rewrites_avoided[], ) + end return result end diff --git a/test/test-model-status-type-lifecycle.jl b/test/test-model-status-type-lifecycle.jl index 72f9e6e1c..bd1d5fec3 100644 --- a/test/test-model-status-type-lifecycle.jl +++ b/test/test-model-status-type-lifecycle.jl @@ -132,6 +132,37 @@ function PlantSimEngine.run!( return nothing end +@testset "input default rewrite telemetry preserves cells across batched births" begin + metric = :input_default_status_rewrites_avoided + for enabled in (false, true) + model = CompositeModel(Object(:plant; scale=:Plant), + Object(:leaf_1; scale=:Leaf, parent=:plant); + applications=( + ModelSpec(StatusTypeLifecycleIncrementModel(); name=:source, on=Many(scale=:Leaf)), + ModelSpec(StatusTypeLifecycleBoundConsumerModel(); name=:consumer, on=Many(scale=:Leaf), + inputs=(bound_value=One(Self(); application=:source, var=:value),)), + ), environment=(duration=Hour(1),)) + simulation = run!(model; steps=0, outputs=:all, performance=enabled) + performance = Advanced.runtime_performance(simulation) + @test isnothing(performance) == !enabled + before = enabled ? get(performance.counts, metric, 0) : 0 + register_object!(model, Object(:leaf_2; scale=:Leaf, parent=:plant)) + register_object!(model, Object(:leaf_3; scale=:Leaf, parent=:plant)) + continue!(simulation) + for id in (:leaf_1, :leaf_2, :leaf_3) + status = model_status(model, id) + @test status.value === status.bound_value === status.seen === 1.0 + @test PlantSimEngine.refvalue(status, :bound_value) === + PlantSimEngine.refvalue(status, :value) + end + performance = Advanced.runtime_performance(simulation) + @test isnothing(performance) == !enabled + if enabled + @test performance.counts[metric] - before == 2 + end + end +end + @testset "pure additions preserve bound-default conversion diagnostics" begin calls = Ref(0) model = CompositeModel( From 207b8a0c8e1b74ec4a1d8f2ebfaf82205ca266e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 21:06:16 +0100 Subject: [PATCH 223/324] Keep declared reference cells inline in kernel statuses --- src/component_models/Status.jl | 26 ++++++++++++++-------- src/composite_model/status_construction.jl | 7 +++--- test/test-status-fixed-storage.jl | 7 ++++-- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 1bd9eea47..a3a74535b 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -33,14 +33,21 @@ mutable struct _FixedStatusStorage{N,R<:Tuple,T<:NamedTuple} end end -# Kernel ports remain a dense NT. The immutable full snapshot captures the SAME -# refs and presence, including private/temporal overlays, never a latest owner. -mutable struct _ProjectedStatusStorage{N,R<:Tuple,H<:NamedTuple,T<:NamedTuple} - const hot::H +# A kernel carries its declared reference cells inline. The wider directory of +# visible cells and the epoch at which it was captured travel as one handle. +mutable struct _ProjectedStatusSnapshot{T<:NamedTuple} const refs::T const reference_epoch::UInt end +struct _ProjectedStatusStorage{N,R<:Tuple,H<:NamedTuple,T<:NamedTuple} + hot::H + snapshot::_ProjectedStatusSnapshot{T} +end + +@inline _status_reference_slots(storage::_FixedStatusStorage) = storage.refs +@inline _status_reference_slots(storage::_ProjectedStatusStorage) = storage.snapshot.refs + """ Status(vars) @@ -137,7 +144,7 @@ _fixed_status(names::Val{N}, references::Type{<:Tuple}) where {N} = _status_storage_names(storage::NamedTuple) = keys(storage) _status_storage_names(storage::Union{_FixedStatusStorage{N},_ProjectedStatusStorage{N}}) where {N} = - filter(name -> getfield(storage.refs, name) !== nothing, N) + filter(name -> getfield(_status_reference_slots(storage), name) !== nothing, N) _status_storage_reference_types(::Type{NamedTuple{N,R}}) where {N,R} = R _status_storage_reference_types(::Type{<:_FixedStatusStorage{N,R}}) where {N,R} = R _status_storage_reference_types(::Type{<:_ProjectedStatusStorage{N,R}}) where {N,R} = R @@ -149,7 +156,7 @@ _status_storage_reference_types(::Type{<:_ProjectedStatusStorage{N,R}}) where {N end @inline function _status_reference(storage::_ProjectedStatusStorage{N,R,H}, key::Symbol) where {N,R,H} hasfield(H, key) && return getfield(storage.hot, key) - reference = getfield(storage.refs, key) + reference = getfield(_status_reference_slots(storage), key) reference === nothing && throw(KeyError(key)) return reference end @@ -161,7 +168,8 @@ _status_storage_references(storage::Union{_FixedStatusStorage,_ProjectedStatusSt # Reference/presence edits invalidate projections; ref[] = value does not. _status_reference_epoch(storage::NamedTuple) = UInt(0) -_status_reference_epoch(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}) = storage.reference_epoch +_status_reference_epoch(storage::_FixedStatusStorage) = storage.reference_epoch +_status_reference_epoch(storage::_ProjectedStatusStorage) = storage.snapshot.reference_epoch _status_reference_epoch(status::Status) = _status_reference_epoch(_status_vars(status)) function _watch_status_references!(status::Status{N,<:_FixedStatusStorage}, sink, id) where {N} storage = _status_vars(status) @@ -327,7 +335,7 @@ Base.copy(status::Status) = Status(_copy_status_storage(_status_vars(status))) storage = _status_vars(source) storage isa NamedTuple && return storage storage isa Union{_FixedStatusStorage,_ProjectedStatusStorage} || throw(ArgumentError("Unknown Status backing.")) - return getfield(storage, :refs) + return _status_reference_slots(storage) end @inline _initial_status_reference_count(source::Status) = _initial_status_reference_count(_initial_status_reference_storage(source)) @@ -397,7 +405,7 @@ end name::Symbol, ) where {N} branches = [:(name === $(QuoteNode(field)) && - return getfield(getfield(storage, :refs), $index) !== nothing) + return getfield(_status_reference_slots(storage), $index) !== nothing) for (index, field) in enumerate(N)] return quote $(Expr(:meta, :inline)) diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl index bbec05b42..0856deb4f 100644 --- a/src/composite_model/status_construction.jl +++ b/src/composite_model/status_construction.jl @@ -82,7 +82,7 @@ end return Status($dense)::Result end FullNames = _status_schema_names(Result) - Full = fieldtype(Storage, :refs) + Full = fieldtype(fieldtype(Storage, :snapshot), :refs) full = map(eachindex(FullNames)) do i name = FullNames[i] hot_index = findfirst(isequal(name), Names) @@ -93,7 +93,8 @@ end return quote original_refs = $load_refs hot = $dense - snapshot = $Full($(Expr(:tuple,full...))) - return Status($Storage(hot, snapshot, _status_reference_epoch(original)))::Result + refs = $Full($(Expr(:tuple,full...))) + snapshot = _ProjectedStatusSnapshot(refs, _status_reference_epoch(original)) + return Status($Storage(hot, snapshot))::Result end end diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 918d873da..e94c5f76b 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -67,8 +67,11 @@ end owner = PSE._new_prepared_status(SCHEMA,Status(x=3f0,q=1//2,seed=Float32[2])) private = Ref(100.0) Projected = @inferred PSE._projected_status_type(SCHEMA,Val((:x,:q)),Tuple{RF64,RR}) - # Execution targets carry a handle to the snapshot, even for a wide namespace. - @test sizeof(Projected) == sizeof(SCHEMA) + # The kernel header size depends only on the ports it uses. + extra = ntuple(i -> Symbol(:other_, i), 64) + wide = PSE._fixed_status_type((:x, :q, extra...), Tuple{RF32,RR,Vararg{RF32,64}}) + wide_projection = PSE._projected_status_type(wide, (:x, :q), Tuple{RF64,RR}) + @test sizeof(wide_projection) == sizeof(Projected) @test Projected === PSE._projected_status_type(SCHEMA,(:x,:q),Tuple{RF64,RR}) @test PSE._projected_status_type(SCHEMA,Val(()),Tuple{}) === PSE._projected_status_type(SCHEMA,(),Tuple{}) From 570f83a8a54dcddb15a054eebcdc65e9d237b221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 21:10:41 +0100 Subject: [PATCH 224/324] Share rebuilt input binding storage across previous binding types --- src/composite_model/compilation.jl | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index bd9ae4c75..aedc4117e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4671,6 +4671,17 @@ function _refresh_scene_call_bindings!( observed_manual_call_binding_indices_by_callee_target end +# A replacement can belong to any of the prepared input binding types. +# Keep the admission and store independent of the binding being replaced. +Base.@noinline function _store_rebuilt_input_binding!( + bindings, changed_bindings, index, replacement, cache, model, +) + binding = _share_many_input_binding!(cache, model, only(replacement)) + bindings[index] = binding + push!(changed_bindings, binding) + return binding +end + # One existing-binding lifecycle operation; admission precedes this worker. function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S) where {B<:CompiledModelInputBinding,S} (; @@ -4790,13 +4801,9 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S get(many_binding_cache.by_query, old_cache_key, nothing) === binding delete!(many_binding_cache.by_query, old_cache_key) end - replacement_binding = _share_many_input_binding!( - many_binding_cache, - model, - only(replacement), + replacement_binding = _store_rebuilt_input_binding!( + input_bindings, changed_bindings, index, replacement, many_binding_cache, model, ) - input_bindings[index] = replacement_binding - push!(changed_bindings, replacement_binding) push!(rewired_consumer_ids, consumer_id) if binding.carrier_hint == :temporal_stream key = (binding.application_id, consumer_id) From 394ab825c6a18b47e39cc96dda72a68bed80a331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 21:32:53 +0100 Subject: [PATCH 225/324] Index new consumer bindings by the prepared application ID --- src/composite_model/compilation.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index aedc4117e..6a35ac0b9 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3014,7 +3014,7 @@ function _compile_application_consumer_bindings!( distributed_outputs, many_binding_cache, performance, ) _record_consumer_input_bindings!( - recorder, bindings, application, consumer_id, + recorder, bindings, application_id, consumer_id, first_new_binding, length(bindings), ) end @@ -3031,7 +3031,7 @@ struct _AddedConsumerInputBindings{M,C,B,I} end function _record_consumer_input_bindings!( - recorder::_AddedConsumerInputBindings, bindings::AbstractVector{B}, application, consumer_id, + recorder::_AddedConsumerInputBindings, bindings::AbstractVector{B}, application_id::Symbol, consumer_id, first_new_binding, last_new_binding, ) where {B} first_new_binding <= last_new_binding || return nothing @@ -3045,7 +3045,7 @@ function _record_consumer_input_bindings!( push!(new_bindings, binding) end append!(recorder.changed_bindings, new_bindings) - recorder.input_bindings_by_target[(application.id, consumer_id)] = new_bindings + recorder.input_bindings_by_target[(application_id, consumer_id)] = new_bindings return nothing end From 1ccbf811ac31f09fe347a96f7343a7bbc447e1f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 21:44:41 +0100 Subject: [PATCH 226/324] Preserve temporal views within the same application family --- src/composite_model/compilation.jl | 37 ++++++++++++++++++---- test/test-model-output-retention-owners.jl | 12 +++++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 6a35ac0b9..fe38d71ba 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1834,18 +1834,16 @@ function _model_status_view_family_types(V) return families end -# Select the application and its exact view in one generated boundary. The raw -# Any-valued dictionary payload never crosses another metadata callback first. -@generated function _with_model_status_view(f::F, schema::CompiledMetadataTable{T}, - application_id::Symbol, view, args::Vararg{Any,N}, -) where {F,T,N} +# Select the application before admitting its views. Dictionary values reach +# the callback only after crossing the concrete family checks in this branch. +function _model_status_view_dispatch(admission, T) branches = Expr[] for (index, application) in enumerate(fieldnames(T)) Prototype = fieldtype(T, index) Prototype <: AbstractVector || throw(ArgumentError( "Status view family prototypes require vector storage.")) families = _model_status_view_family_types(eltype(Prototype)) - admitted = [:(view isa $V && return f(view::$V, args...)) for V in families] + admitted = admission(families) push!(branches, quote if application_id === $(QuoteNode(application)) prototype = getfield(getfield(schema, :entries), $index) @@ -1861,6 +1859,14 @@ end end end +@generated function _with_model_status_view(f::F, schema::CompiledMetadataTable{T}, + application_id::Symbol, view, args::Vararg{Any,N}, +) where {F,T,N} + return _model_status_view_dispatch(T) do families + [:(view isa $V && return f(view::$V, args...)) for V in families] + end +end + # This hook is also called for newly constructed ephemeral/private views. @inline _admit_model_status_view!(schema, application_id::Symbol, view) = Base.@inline _with_model_status_view(identity, schema, application_id, view) @@ -3813,6 +3819,25 @@ function _preserve_model_status_view_temporal_state!(schema, application_id::Sym return _admit_model_status_view!(schema, application_id, view) end +# The two views belong to the same application. Selecting it once prevents +# specializations for pairs of models that can never share this target. +@generated function _preserve_model_status_view_temporal_state!( + schema::CompiledMetadataTable{T}, application_id::Symbol, current, previous, + previous_temporal_sources, key, +) where {T} + return _model_status_view_dispatch(T) do families + family = Union{families...} + [quote + if current isa $C && previous isa $P + view = _preserve_model_status_view_temporal_state!( + current::$C, previous::$P, previous_temporal_sources, key, + ) + view isa $family && return view + end + end for C in families for P in families] + end +end + function _record_previous_temporal_source!(input::CompiledTemporalInput, sources, key) binding = input.binding source_key = (key..., binding.input) diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl index 3948b812b..a8bf79821 100644 --- a/test/test-model-output-retention-owners.jl +++ b/test/test-model-output-retention-owners.jl @@ -174,6 +174,18 @@ end previous_owner = simulation.model.binding_cache key = (:writer, ObjectId(3)) before = compiled.status_views_by_target[key] + reader_view = compiled.status_views_by_target[(:reader, ObjectId(0))] + previous_sources = PSE._previous_temporal_source_storage(simulation.model) + restored = PSE._preserve_model_status_view_temporal_state!( + schema, :writer, before, before, previous_sources, key, + ) + @test restored.execution_stamp === before.execution_stamp + @test restored.private_outputs.private === before.private_outputs.private + for (current, previous) in ((reader_view, before), (before, reader_view)) + @test_throws "outside its prepared application family" PSE._preserve_model_status_view_temporal_state!( + schema, :writer, current, previous, previous_sources, key, + ) + end invalid = PSE.CompiledMetadataTable((writer=Vector{Union{}}(),)) positions = Dict(id => index for (index, id) in pairs(compiled.application_order)) @test_throws "outside supported prepared application view families" PSE._compile_model_status_view( From c9dd9ac6589df2bdce0038b670e7c57f3093286b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 22:04:57 +0100 Subject: [PATCH 227/324] Reuse prepared refresh state when extending temporal inputs --- src/composite_model/compilation.jl | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index fe38d71ba..f063da90b 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4000,13 +4000,10 @@ function _apply_temporal_many_extensions!(staged::Tuple) return !isnothing(extension) || following_applied end -function _extend_temporal_many_inputs_in_place!(view::CompiledModelStatusView, - model::CompositeModel, key, previous_temporal_sources, applications_by_id, - application_positions, distributed_outputs, status_view_schema, -) - staged = _stage_temporal_many_extensions(view.temporal_inputs, model, key, - previous_temporal_sources, applications_by_id, application_positions, - distributed_outputs, status_view_schema, view.canonical_status) +function _extend_temporal_many_inputs_in_place!(view::CompiledModelStatusView, key, state) + staged = _stage_temporal_many_extensions(view.temporal_inputs, state.model, key, + state.previous_temporal_sources, state.applications_by_id, state.positions, + state.distributed_outputs, state.compiled.status_view_schema, view.canonical_status) isnothing(staged) && return false return _apply_temporal_many_extensions!(staged) end @@ -4135,23 +4132,21 @@ function _extend_model_status_views!( application_id => index for (index, application_id) in pairs(application_order) ) + state = (; model, compiled, views, previous_views, input_bindings_by_target, + applications_by_id, positions, distributed_outputs, previous_temporal_sources) for (application_id, raw_id) in affected_temporal_keys object_id = _index_object_id(model.registry.objects, raw_id) key = (application_id, object_id) view = get(views, key, nothing) isnothing(view) && continue extended = Base.@inline _with_model_status_view(_extend_temporal_many_inputs_in_place!, - compiled.status_view_schema, application_id, view, model, key, - previous_temporal_sources, applications_by_id, positions, distributed_outputs, - compiled.status_view_schema) + compiled.status_view_schema, application_id, view, key, state) if extended current = Base.@inline _with_model_status_view(_status_view_epoch_is_current, compiled.status_view_schema, application_id, view, model, object_id) current && delete!(affected_keys, key) end end - state = (; model, compiled, views, previous_views, input_bindings_by_target, - applications_by_id, positions, distributed_outputs, previous_temporal_sources) for (application_id, object_id) in affected_keys Base.@inline _with_metadata_entry(_refresh_model_status_view_for_target!, applications_by_id, application_id, object_id, state) From ec20cedbaa67c81620528d31bf31eb6cf4a90a36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 23:08:19 +0100 Subject: [PATCH 228/324] Read fresh defaults through the prepared port declarations --- src/composite_model/authored_ports.jl | 29 ++++++ src/composite_model/compilation.jl | 20 ++-- test/test-input-default-values.jl | 138 ++++++++++++++++++++++++++ 3 files changed, 181 insertions(+), 6 deletions(-) diff --git a/src/composite_model/authored_ports.jl b/src/composite_model/authored_ports.jl index 411a032d4..5653a9b11 100644 --- a/src/composite_model/authored_ports.jl +++ b/src/composite_model/authored_ports.jl @@ -96,6 +96,35 @@ function _authored_port_types(type_for, schema::NamedTuple{Names}) where {Names} return NamedTuple{Names,fields}(types) end +# Declaration diagnostics belong to authoring. Fresh values must retain the +# prepared declaration types; only the NamedTuple container may be erased. +@generated function _admit_authored_port_schema(schema, + ::NamedTuple{Names,Types}, kind, +) where {Names,Types} + expected = isempty(Names) ? "(none)" : join(string.(Names), ", ") + reject = :(_changed_authored_port_schema(kind, $expected)) + checks = Any[] + values = Any[] + for (index, field) in enumerate(fieldtypes(Types)) + declaration = field.parameters[1] + value = gensym(:declaration) + push!(checks, :($value = getfield(schema, $(QuoteNode(Names[index]))))) + push!(checks, :($value isa $declaration || return $reject)) + push!(values, :($value::$declaration)) + end + return quote + schema isa NamedTuple{$(QuoteNode(Names))} || return $reject + $(checks...) + NamedTuple{$(QuoteNode(Names))}(($(values...),)) + end +end + +Base.@noinline function _changed_authored_port_schema(::Val{Kind}, expected::String) where {Kind} + hook = Kind === :inputs ? "inputs_" : "outputs_" + throw(ArgumentError("A model default schema changed after preparation. " * + "`" * hook * "` expected variables: " * expected * ".")) +end + # Only real numeric-array defaults have element evidence. Missing fields mean # no initializer value (e.g. Required), whereas Tuple{} means a real empty array. _output_element_types(value) = nothing diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f063da90b..1be79e0a1 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5821,15 +5821,23 @@ function _foreach_configured_variant(f::F, entries::Tuple, args::Vararg{Any,N}) return _foreach_configured_variant(f, Base.tail(entries), args...) end -_read_application_defaults(model, ::Val{:outputs}) = _local_output_schema(model) -_read_application_defaults(model, ::Val{:inputs}) = _input_default_values(_input_schema(model)) +function _read_application_defaults(model, kind::Val{:inputs}, ports) + schema = Base.@inline _admit_authored_port_schema(inputs_(model), + _authored_metadata_value(ports.input_declaration_types), kind) + return _input_default_values(schema) +end +function _read_application_defaults(model, kind::Val{:outputs}, ports) + schema = Base.@inline _admit_authored_port_schema(outputs_(model), + _authored_metadata_value(ports.output_declaration_types), kind) + return _local_output_declarations(schema) +end _variant_defaults_type(ports, ::Val{:outputs}) = ports.defaults_types.outputs _variant_defaults_type(ports, ::Val{:inputs}) = ports.defaults_types.inputs function _application_default_schemas(application, kind) model = model_(application.spec) return model isa ObjectModelOverrides ? IdDict{AbstractModel,NamedTuple}() : - _read_application_defaults(model, kind) + _read_application_defaults(model, kind, _application_ports(application)) end @inline _with_application_defaults(f::F, application, object_id, defaults::NamedTuple, kind, args::Vararg{Any,N}) where {F,N} = f(defaults, args...) @@ -5842,14 +5850,14 @@ end @inline function _call_configured_defaults(model, ports, f::F, cache, kind, args::Vararg{Any,N}, ) where {F,N} - return _with_configured_defaults(f, model, cache, kind, + return _with_configured_defaults(f, model, ports, cache, kind, _variant_defaults_type(ports, kind), args...) end -@inline function _with_configured_defaults(f::F, model, cache, kind, ::Type{S}, +@inline function _with_configured_defaults(f::F, model, ports, cache, kind, ::Type{S}, args::Vararg{Any,N}, ) where {F,S<:NamedTuple,N} schema = get!(cache, model) do - _read_application_defaults(model, kind) + _read_application_defaults(model, kind, ports) end schema isa S || throw(ArgumentError("A model default schema changed after preparation.")) return f(schema::S, args...) diff --git a/test/test-input-default-values.jl b/test/test-input-default-values.jl index 3b1a2cdba..0096d73d2 100644 --- a/test/test-input-default-values.jl +++ b/test/test-input-default-values.jl @@ -157,4 +157,142 @@ PSE.run!(::MutableInputDefaults, status, environment, constants, context) = noth end end +struct AbstractMutableInputDefaults{T,P} <: AbstractTuple_Input_DefaultsModel + payload::P +end +PSE.inputs_(model::AbstractMutableInputDefaults{T}) where {T} = + (selected=Default{T}(model.payload[]),) +PSE.outputs_(::AbstractMutableInputDefaults) = NamedTuple() +PSE.run!(::AbstractMutableInputDefaults, status, environment, constants, context) = nothing + +@testset "fresh abstract defaults preserve values and prepared cells" begin + required = (required=Required(Integer),) + witness = PSE._authored_port_types(typeof, required) + admitted = @inferred PSE._admit_authored_port_schema(required, witness, Val(:inputs)) + @test (@inferred PSE._input_default_values(admitted)) === NamedTuple() + for T in (Real, Any) + payload = Ref{T}(1f0) + process = AbstractMutableInputDefaults{T,typeof(payload)}(payload) + model = CompositeModel(Object(:first; scale=:Leaf); + applications=(ModelSpec(process; name=:defaults, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + application = simulation.compiled.applications_by_id[:defaults] + first = PSE.refvalue(model_status(model, :first), :selected) + @test first[] === 1f0 + payload[] = 3.25 + defaults = PSE._application_default_schemas(application, Val(:inputs)) + @test defaults.selected === payload[] + @test isequal(defaults.selected, payload[]) + @test typeof(defaults.selected) === Float64 + raw = PSE.inputs_(process) + admitted = PSE._admit_authored_port_schema(raw, + PSE._application_ports(application).input_declaration_types, Val(:inputs)) + @test admitted.selected.value === payload[] + # The scene prepared Float32 cells; keep the actual birth in that family. + payload[] = 3.25f0 + register_object!(model, Object(:second; scale=:Leaf)) + step!(simulation) + @test model_status(model, :second).selected == 3.25 + @test PSE.refvalue(model_status(model, :first), :selected) === first + @test first[] === 1f0 + end +end + +struct ErasedAuthoredDeclarations <: AbstractTuple_Input_DefaultsModel + input::Base.RefValue{Any} + output::Base.RefValue{Any} + input_reads::Base.RefValue{Int} + output_reads::Base.RefValue{Int} +end +function PSE.inputs_(model::ErasedAuthoredDeclarations) + model.input_reads[] += 1 + return model.input[] +end +function PSE.outputs_(model::ErasedAuthoredDeclarations) + model.output_reads[] += 1 + return model.output[] +end +PSE.run!(::ErasedAuthoredDeclarations, status, environment, constants, context) = nothing + +@testset "erased configured declarations retain fresh payloads and hook diagnostics" begin + input_name, output_name = Symbol("configured_", "input"), Symbol("configured_", "output") + input_schema = value -> NamedTuple{(input_name,:buffer,:required),Tuple{Any,Any,Any}}( + (Default{Real}(value), Default(Float32[1,2]), Required(Integer))) + output_schema = value -> NamedTuple{(output_name,),Tuple{Any}}((value,)) + process = ErasedAuthoredDeclarations(Ref{Any}(input_schema(1f0)), + Ref{Any}(output_schema(Float32[1])), Ref(0), Ref(0)) + model = CompositeModel(Object(:leaf; scale=:Leaf, status=Status((required=1,))); + applications=(ModelSpec(process; name=:defaults, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:none) + application = simulation.compiled.applications_by_id[:defaults] + process.input[] = input_schema(3.25) + buffer = process.input[].buffer.value + process.input_reads[] = 0 + defaults = PSE._application_default_schemas(application, Val(:inputs)) + @test process.input_reads[] == 1 + @test isequal(getproperty(defaults,input_name), 3.25) + @test typeof(getproperty(defaults,input_name)) === Float64 + @test defaults.buffer === buffer + fresh_output = Float32[4,5] + process.output[] = output_schema(fresh_output) + process.output_reads[] = 0 + @test getproperty(PSE._application_default_schemas(application, Val(:outputs)), output_name) === fresh_output + @test process.output_reads[] == 1 + + caught(operation) = try operation(); nothing catch error; error end + invalid_inputs = (1, NamedTuple{(input_name,:buffer,:required),Tuple{Any,Any,Any}}( + (2, Default(Float32[1]), Required(Integer)))) + for invalid in invalid_inputs + # A malformed declaration at construction keeps its detailed diagnostic + # and is frozen without replaying the hook during activation. + broken = ErasedAuthoredDeclarations(Ref{Any}(invalid), + Ref{Any}(output_schema(Float32[1])), Ref(0), Ref(0)) + expected = caught(() -> PSE._input_schema(broken)) + broken.input_reads[] = 0 + failed = CompositeModel(Object(:leaf; scale=:Leaf, status=Status((required=1,))); + applications=(ModelSpec(broken; name=:defaults, on=Many(scale=:Leaf)),)) + @test broken.input_reads[] == 1 + failure = failed.scenario_plan_cache.failure + @test failure isa PSE.ScenarioPreparationFailure + @test typeof(failure.error) === typeof(expected) + @test sprint(showerror,failure.error) == sprint(showerror,expected) + @test_throws ErrorException run!(failed; steps=0) + @test broken.input_reads[] == 1 + end + changed_name = NamedTuple{(:changed,:buffer,:required),Tuple{Any,Any,Any}}( + (Default{Real}(3.25), Default(Float32[1]), Required(Integer))) + for changed in (invalid_inputs..., changed_name) + process.input[] = changed + process.input_reads[] = 0 + actual = caught(() -> PSE._application_default_schemas(application, Val(:inputs))) + @test process.input_reads[] == 1 + @test actual isa ArgumentError + message = sprint(showerror,actual) + @test occursin("inputs_", message) + @test all(name -> occursin(string(name),message), (input_name,:buffer,:required)) + @test occursin("after preparation", message) + end + broken_output = ErasedAuthoredDeclarations(Ref{Any}(input_schema(1f0)), + Ref{Any}(1), Ref(0), Ref(0)) + broken_spec = ModelSpec(broken_output; name=:defaults, on=Many(scale=:Leaf)) + expected = caught(() -> PSE._output_schema(broken_spec)) + broken_output.output_reads[] = 0 + failed_output = CompositeModel(Object(:leaf; scale=:Leaf); + applications=(broken_spec,)) + @test broken_output.output_reads[] == 1 + failure = failed_output.scenario_plan_cache.failure + @test failure isa PSE.ScenarioPreparationFailure + @test failure.error isa ArgumentError + @test sprint(showerror,failure.error) == sprint(showerror,expected) + @test_throws ArgumentError run!(failed_output; steps=0) + @test broken_output.output_reads[] == 1 + process.output[] = 1 + process.output_reads[] = 0 + actual = caught(() -> PSE._application_default_schemas(application, Val(:outputs))) + @test process.output_reads[] == 1 + @test actual isa ArgumentError + @test occursin("outputs_", sprint(showerror,actual)) + @test occursin(string(output_name), sprint(showerror,actual)) +end + end # module InputDefaultValuesChecks From 6ed3a0d3c4068c349478a663b3c37cb209e5ffb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 23:33:45 +0100 Subject: [PATCH 229/324] Index manual calls using their target identity vectors --- src/composite_model/compilation.jl | 56 +++++++----------------------- 1 file changed, 12 insertions(+), 44 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1be79e0a1..9e5646f2f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2384,7 +2384,7 @@ function _index_observed_manual_call_binding_application_targets!( binding::CompiledModelCallBinding, binding_index::Int, callee_application_id::Symbol, - application, + application_target_ids, ) if binding.multiplicity != :many && length(binding.callee_application_ids) == 1 @@ -2399,38 +2399,14 @@ function _index_observed_manual_call_binding_application_targets!( return index end - application_target_ids = application.target_ids binding_target_ids = binding.callee_object_ids - if length(application_target_ids) <= length(binding_target_ids) - for callee_object_id in application_target_ids - first( - _sorted_object_id_position( - binding_target_ids, - callee_object_id, - ), - ) || continue - _push_observed_manual_call_binding_index!( - index, - callee_application_id, - callee_object_id, - binding_index, - ) - end - else - for callee_object_id in binding_target_ids - first( - _sorted_object_id_position( - application_target_ids, - callee_object_id, - ), - ) || continue - _push_observed_manual_call_binding_index!( - index, - callee_application_id, - callee_object_id, - binding_index, - ) - end + shorter, longer = length(application_target_ids) <= length(binding_target_ids) ? + (application_target_ids, binding_target_ids) : (binding_target_ids, application_target_ids) + for callee_object_id in shorter + first(_sorted_object_id_position(longer, callee_object_id)) || continue + _push_observed_manual_call_binding_index!( + index, callee_application_id, callee_object_id, binding_index, + ) end return index end @@ -2444,13 +2420,9 @@ function _index_observed_manual_call_binding_by_callee_target!( _compiled_call_mode(binding) === :manual || return index _compiled_call_membership_is_observed(binding) || return index for callee_application_id in binding.callee_application_ids - application = applications_by_id[callee_application_id] + target_ids = getfield(applications_by_id[callee_application_id], :target_ids) _index_observed_manual_call_binding_application_targets!( - index, - binding, - binding_index, - callee_application_id, - application, + index, binding, binding_index, callee_application_id, target_ids, ) end return index @@ -2514,13 +2486,9 @@ function _extend_observed_manual_call_binding_callee_target_index!( for application_position in new_application_positions callee_application_id = binding.callee_application_ids[application_position] - application = applications_by_id[callee_application_id] + target_ids = getfield(applications_by_id[callee_application_id], :target_ids) _index_observed_manual_call_binding_application_targets!( - index, - binding, - binding_index, - callee_application_id, - application, + index, binding, binding_index, callee_application_id, target_ids, ) end return index From 718495b8bbdf045f8d4008edaee01109e76ec467 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Thu, 19 Nov 2026 23:43:44 +0100 Subject: [PATCH 230/324] Copy final state through the visible prepared status fields --- src/component_models/Status.jl | 30 ++++++++++++++---- src/composite_model/runtime_outputs.jl | 31 ++++++++++++++++++- .../distributed_producer_birth/src/prepare.jl | 5 +++ test/test-model-output-boundaries.jl | 29 +++++++++++++++++ 4 files changed, 88 insertions(+), 7 deletions(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index a3a74535b..1833fc8e8 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -162,9 +162,6 @@ end end @inline _status_reference(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}, key::Int) = _status_reference(storage, _status_storage_names(storage)[key]) -_status_storage_references(storage::NamedTuple) = values(storage) -_status_storage_references(storage::Union{_FixedStatusStorage,_ProjectedStatusStorage}) = - map(key -> _status_reference(storage, key), _status_storage_names(storage)) # Reference/presence edits invalidate projections; ref[] = value does not. _status_reference_epoch(storage::NamedTuple) = UInt(0) @@ -251,8 +248,29 @@ function Status(nt::NamedTuple{names}) where {names} end _status_vars(status) = getfield(status, :vars) -_status_values(status) = getindex.(refvalues(status)) -_status_namedtuple(status) = NamedTuple{keys(status)}(values(status)) +# Read or transform each concrete reference before selecting the currently +# present fields. A present reference may itself contain nothing. +_map_status_slots(::typeof(identity), slots) = slots +_map_status_slots(f::F, slots) where {F} = + map(slot -> isnothing(slot) ? nothing : f(slot), slots) + +function _map_status_fields(f::F, ::Type{T}, status::Status) where {F,T} + fields = _map_status_slots(f, _initial_status_reference_storage(status)) + names = keys(status) + if names === keys(fields) + return T === Tuple ? Tuple(fields) : fields + end + selected = Vector{Any}(undef, length(names)) + for i in eachindex(names) + selected[i] = getfield(fields, names[i]) + end + data = Tuple(selected) + T === Tuple && return data + return Base.@inline NamedTuple{names}(data) +end + +_status_namedtuple(status) = _map_status_fields(getindex, NamedTuple, status) +_status_values(status) = _map_status_fields(getindex, Tuple, status) _status_tuple(status) = values(status) _status_iterate(status, iter=1) = iterate(values(status), iter) _status_firstindex(status) = 1 @@ -262,7 +280,7 @@ _status_indexed_iterate(status, i::Int, state=1) = Base.indexed_iterate(values(s Base.keys(status::Status) = _status_storage_names(_status_vars(status)) Base.values(st::Status) = _status_values(st) _status_identity(status::Status) = getfield(status, :identity) -refvalues(mnt::Status) = _status_storage_references(_status_vars(mnt)) +refvalues(mnt::Status) = _map_status_fields(identity, Tuple, mnt) Base.@constprop :aggressive @inline refvalue(mnt::Status, key::Symbol) = _status_reference(_status_vars(mnt), key) Base.NamedTuple(mnt::Status) = _status_namedtuple(mnt) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 42db9f58d..b24d0723a 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1549,8 +1549,37 @@ current_step(simulation::Simulation) = simulation.current_step outputs(sim::Simulation) = sim.temporal_streams +# Copy values while the prepared slot types are still known. All fields use +# the same deepcopy memo so shared objects and cycles survive the snapshot. +@inline _snapshot_value(value, memo) = + isbitstype(typeof(value)) ? value : Base.deepcopy_internal(value, memo)::typeof(value) + +# Keep the backing store shared between reshaped or offset arrays in one snapshot. +# Julia's generic Memory deepcopy erases its element type before the copy. +@static if isdefined(Base, :wrap) && isdefined(Core, :Memory) + @inline function _snapshot_value(value::Array{T,N}, memo) where {T,N} + isbitstype(T) || return Base.deepcopy_internal(value, memo)::Array{T,N} + haskey(memo, value) && return memo[value]::Array{T,N} + source = getfield(value, :ref) + memory = get!(() -> copy(source.mem), memo, source.mem)::Memory{T} + offset = Core.memoryrefoffset(source) + first = Core.memoryref(memory) + point = isone(offset) ? first : Core.memoryrefnew(first, offset, false) + result = Base.wrap(Array, point, size(value)) + memo[value] = result + return result + end +end + +function _snapshot_status(status::Status) + memo = IdDict() + return _map_status_fields(ref -> _snapshot_value(ref[], memo), NamedTuple, status) +end + @inline function _final_state_snapshot(simulation::Simulation, object_id) - return deepcopy(NamedTuple(_model_object_status(simulation.model, ObjectId(object_id)))) + model = simulation.model + status = _model_object_status(model, ObjectId(object_id)) + return Base.@inline _with_registered_status(_snapshot_status, model.registry.objects.catalog, status) end """ diff --git a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl index 9232c196d..02c9f3f66 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl @@ -27,12 +27,17 @@ function checkpoint(state, day) object === state.objects[index] && object.scale === :Leaf || return false PSE.refvalue(status, :ordinal) === state.ordinals[index] || return false status.ordinal == index || return false + snapshot = PSE.final_state(sim, id) + snapshot isa NamedTuple && isdefined(snapshot, :ordinal) || return false + getfield(snapshot, :ordinal) === index || return false reference = PSE._initial_status_reference(status, :signal) stream = get(PSE.outputs(sim), (:producer, id, :signal), nothing) if day < 2 + isdefined(snapshot, :signal) && return false isnothing(reference) || return false (isnothing(stream) || (stream isa Vector{Tuple{Float64,Float32}} && isempty(stream))) || return false else + isdefined(snapshot, :signal) && getfield(snapshot, :signal) === Float32(20day) || return false reference isa Base.RefValue{Float32} || return false reference[] === Float32(20day) || return false stream isa Vector{Tuple{Float64,Float32}} || return false diff --git a/test/test-model-output-boundaries.jl b/test/test-model-output-boundaries.jl index 853d0dbef..d5837635a 100644 --- a/test/test-model-output-boundaries.jl +++ b/test/test-model-output-boundaries.jl @@ -94,6 +94,35 @@ end end end +@testset "final state copies the visible fields and preserves shared values" begin + leaf = Object(:leaf; scale=:Leaf, status=Status( + data=zeros(Int, 4), alias=Int[], matrix=zeros(Int, 2, 2), cycle=Any[], nullable=nothing, + )) + simulation = run!(CompositeModel(leaf, Object(:soil; status=Status(water=2.0))); steps=0) + live = model_status(simulation, :leaf) + # Establish the relationships on the registered status after preparation. + live.data .= 1:4 + live.alias = live.data + live.matrix = reshape(live.data, 2, 2) + push!(live.cycle, live.cycle) + + expected = deepcopy(NamedTuple(live)) + snapshot = final_state(simulation, :leaf) + @test typeof(snapshot) === typeof(expected) + @test keys(snapshot) == keys(live) + @test snapshot.nullable === nothing + @test !haskey(snapshot, :water) + @test final_state(simulation, :soil) == (water=2.0,) + @test snapshot.data == expected.data + @test snapshot.data === snapshot.alias + @test snapshot.data !== live.data + @test snapshot.cycle !== live.cycle && only(snapshot.cycle) === snapshot.cycle + # Compare the relationship between reshaped arrays with Julia's own deepcopy. + snapshot.matrix[1] = expected.matrix[1] = 20 + @test snapshot.data == expected.data + @test live.data[1] == 1 +end + @testset "requested mutable initial values survive continuation and reentry" begin model = CompositeModel( Object(:scene; scale=:Scene), From c81510ca70d7665e0935dd36a8ecad2d8d3fde66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 00:12:56 +0100 Subject: [PATCH 231/324] Keep built-in object identity type names out of native runtime sorting --- src/composite_model/selectors.jl | 31 +++++++++++++--------- test/test-structural-delta-intersection.jl | 12 +++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index f683031ae..ba49292b3 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -526,6 +526,17 @@ function _mount_object_instance_applications(instances, instance_ids) return Tuple(mounted) end +# The spelling of built-in key types is fixed. Store it in the compiled method +# so searching mixed identities does not invoke Julia's generic type printer. +@generated function _prepared_type_name(::Type{T}) where {T} + return QuoteNode(string(T)) +end + +const _ObjectIdScalar = Union{Symbol,String,Char,Bool,Base.BitInteger,Float16,Float32,Float64} +_object_id_type_name(T) = string(T) +_object_id_type_name(T::Type{<:Union{_ObjectIdScalar,Tuple{Vararg{_ObjectIdScalar}}}}) = + _prepared_type_name(T) + function _object_id_isless(left::ObjectId, right::ObjectId) left_value = left.value right_value = right.value @@ -533,7 +544,7 @@ function _object_id_isless(left::ObjectId, right::ObjectId) # within a type with string ordering between types is not transitive, and # distinct identities such as `1` and `Symbol("1")` otherwise compare equal. if typeof(left_value) !== typeof(right_value) - return isless(string(typeof(left_value)), string(typeof(right_value))) + return isless(_object_id_type_name(typeof(left_value)), _object_id_type_name(typeof(right_value))) end if hasmethod(isless, Tuple{typeof(left_value),typeof(right_value)}) return isless(left_value, right_value) @@ -1075,12 +1086,6 @@ function _available_selector_labels(model::CompositeModel, candidate_ids) ) end -# Type display is fixed by the schema. Keeping its text constant avoids the -# generic Julia syntax printer in the compiled application's error paths. -@generated function _selector_diagnostic_type_name(::Type{T}) where {T} - return QuoteNode(string(T)) -end - function _print_selector_diagnostic(io, value::T, ancestors) where {T} # Ancestors are inspected only with ===; recursive values remain typed by # this method's argument, never recovered from the identity stack. @@ -1143,7 +1148,7 @@ function _print_selector_diagnostic_value(io, value::ObjectId, ancestors) end function _print_selector_diagnostic_value(io, ::Type{T}, ancestors) where {T} - print(io, _selector_diagnostic_type_name(T)) + print(io, _prepared_type_name(T)) return nothing end @@ -1178,7 +1183,7 @@ function _print_selector_diagnostic_value(io, items::Union{Tuple,AbstractVector} end function _print_selector_diagnostic_value(io, items::AbstractArray, ancestors) - print(io, _selector_diagnostic_type_name(typeof(items)), "(size=") + print(io, _prepared_type_name(typeof(items)), "(size=") _print_selector_diagnostic(io, size(items), ancestors) print(io, ", values=[") for (index, item) in enumerate(items) @@ -1190,7 +1195,7 @@ function _print_selector_diagnostic_value(io, items::AbstractArray, ancestors) end function _print_selector_diagnostic_value(io, items::AbstractDict, ancestors) - print(io, _selector_diagnostic_type_name(typeof(items)), '(') + print(io, _prepared_type_name(typeof(items)), '(') for (index, (key, value)) in enumerate(items) index == 1 || print(io, ", ") _print_selector_diagnostic(io, key, ancestors) @@ -1202,7 +1207,7 @@ function _print_selector_diagnostic_value(io, items::AbstractDict, ancestors) end function _print_selector_diagnostic_value(io, items::AbstractSet, ancestors) - print(io, _selector_diagnostic_type_name(typeof(items)), '(') + print(io, _prepared_type_name(typeof(items)), '(') for (index, item) in enumerate(items) index == 1 || print(io, ", ") _print_selector_diagnostic(io, item, ancestors) @@ -1258,11 +1263,11 @@ end function _print_selector_diagnostic_value(io, value::T, ancestors) where {T} if isprimitivetype(T) - print(io, _selector_diagnostic_type_name(T), "(bytes=") + print(io, _prepared_type_name(T), "(bytes=") _print_selector_diagnostic(io, reinterpret(NTuple{sizeof(T),UInt8}, value), ancestors) print(io, ')') else - _print_selector_diagnostic_record(io, _selector_diagnostic_type_name(T), value, ancestors) + _print_selector_diagnostic_record(io, _prepared_type_name(T), value, ancestors) end return nothing end diff --git a/test/test-structural-delta-intersection.jl b/test/test-structural-delta-intersection.jl index 8cf8bf605..34400f373 100644 --- a/test/test-structural-delta-intersection.jl +++ b/test/test-structural-delta-intersection.jl @@ -13,6 +13,18 @@ struct TiedOrderId end Base.isless(left::TiedOrderId, right::TiedOrderId) = isless(left.group, right.group) +struct CustomSortKey end +Base.show(io::IO, ::Type{CustomSortKey}) = print(io, "AAA custom key") + +@testset "mixed object IDs keep the order of their concrete type names" begin + keys = (:leaf, (:plant, :leaf, 2), 7, (:a, :b), (1.0, 'z'), CustomSortKey()) + for a in keys, b in keys + typeof(a) === typeof(b) && continue + @test PSE._object_id_isless(ObjectId(a), ObjectId(b)) == + isless(string(typeof(a)), string(typeof(b))) + end +end + @testset "structural binding intersections preserve set membership" begin empty_sources = ObjectId[] empty_dirty = Set{ObjectId}() From 04fd694a32ac56d0fe95183a7f00a9b70f0b0b38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 00:21:43 +0100 Subject: [PATCH 232/324] Preserve sorted registry objects and their live status in compiled queries --- src/composite_model/object_families.jl | 2 +- .../prepared_status_manifest.jl | 4 +- src/composite_model/registry_topology.jl | 46 +++++++++++-- test/test-unified-model-object-api.jl | 64 +++++++++++++++++++ 4 files changed, 107 insertions(+), 9 deletions(-) diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index b2285ddfb..1e27e9f81 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -72,7 +72,7 @@ ObjectFamilyStore() = ObjectFamilyStore{ObjectId}() Base.length(store::ObjectFamilyStore) = length(store.locations) Base.haskey(store::ObjectFamilyStore, id) = haskey(store.locations, id) -_prepared_status_context_ids(store::ObjectFamilyStore) = keys(store.locations) +_registry_object_ids(store::ObjectFamilyStore) = keys(store.locations) Base.getindex(store::ObjectFamilyStore, id) = store.locations[id].object function Base.get(store::ObjectFamilyStore, id, default) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index ddd5e4f4a..6bf487e0f 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -457,7 +457,7 @@ end # Registered producers and consumers already belong to the registry's scale # index. A pending object's inherited labels and route still use the full matcher. -_prepared_status_context_ids(objects::AbstractDict) = keys(objects) +_registry_object_ids(objects::AbstractDict) = keys(objects) function _prepared_status_context_ids(model, application, route, object, parent_id) registry = model.registry scope = route.matcher.scope @@ -479,7 +479,7 @@ function _prepared_status_context_ids(model, application, route, object, parent_ end scale = application.target_matcher.scale scale isa Symbol && return get(model.registry.by_scale, scale, ()) - return _prepared_status_context_ids(model.registry.objects) + return _registry_object_ids(model.registry.objects) end # One exact application/permission pair enters the producer/route worker. diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 9dbf6d0b9..2c4a6064b 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1205,9 +1205,22 @@ _object_id_text(id::ObjectId) = string(id.value) _object_id_text(id::ObjectId{<:Tuple}) = sprint(_show_object_id_element, id.value) _show_object_id_element(io, value) = show(io, value) -# Inline Julia's Symbol branch to keep its spelling without compiling expression display. -_show_object_id_element(io, value::Symbol) = - Base.@inline Base.show_unquoted_quote_expr(io, value, 0, 0, 0) +# Preserve Base's quoted-Symbol spelling without its Any-valued Expr branch. +function _show_object_id_element(io, value::Symbol) + if value in Base.quoted_syms + print(io, ":(") + print(io, value) + print(io, ")") + elseif Base.isidentifier(value) || (Base._isoperator(value) && value !== Symbol("'")) + print(io, ':') + print(io, value) + else + print(io, "Symbol(") + show(io, String(value)) + print(io, ')') + end + return nothing +end function _show_object_id_element(io, value::Tuple) print(io, '(') @@ -1852,6 +1865,14 @@ function _geometry_inheriting_descendants(model::CompositeModel, root_id::Object end +function _object_id_sort_order(ids) + labels = Vector{String}(undef, length(ids)) + for index in eachindex(ids) + labels[index] = _object_id_text(ids[index]) + end + return sortperm(labels) +end + function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) ids = _indexed_object_ids( model; @@ -1860,12 +1881,25 @@ function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species= species=_maybe_symbol_collection(species), id=_normalize_object_id_criterion(id), ) - isnothing(ids) && (ids = collect(keys(model.registry.objects))) + isnothing(ids) && (ids = collect(_registry_object_ids(model.registry.objects))) length(ids) < 2 && return ids - return ids[sortperm(map(_object_id_text, ids))] + order = _object_id_sort_order(ids) + sorted = similar(ids) + # sortperm supplies exactly one valid source index for each result slot. + @inbounds for index in eachindex(order) + sorted[index] = ids[order[index]] + end + return sorted end -model_objects(model::CompositeModel; kwargs...) = [_model_object(model, id) for id in object_ids(model; kwargs...)] +function model_objects(model::CompositeModel; kwargs...) + ids = object_ids(model; kwargs...) + objects = Vector{Object}(undef, length(ids)) + for index in eachindex(ids) + objects[index] = _model_object(model, ids[index]) + end + return objects +end function _instance_object_ids(model::CompositeModel, instance::ObjectInstance) root_id = _instance_root_id(instance) diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index ba461785c..da118be07 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -4481,3 +4481,67 @@ end run!(strict_hint_override_scene; steps=2) @test only(model_objects(strict_hint_override_scene; scale=:Leaf)).status.signal == 2.0 end + +@testset "model_objects returns registered objects in selection order" begin + organ = (:leaf, :a, 1) + scene = CompositeModel( + Object(:root; scale=:Scene, kind=:root), + Object(:z; scale=:Leaf, kind=:shoot, species=:alpha, parent=:root, status=Status(x=1.0)), + Object(42; scale=:Leaf, kind=:shoot, species=:beta, parent=:root, status=Status(x=2.0)), + Object(organ; scale=:Leaf, kind=:shoot, species=:alpha, parent=:root, status=Status(x=3.0)), + Object(:a; scale=:Axis, kind=:shoot, species=:alpha, parent=:root, status=Status(x=4.0)), + ) + cases = ( + (NamedTuple(), (organ, 42, :a, :root, :z)), + ((; scale=:Leaf), (organ, 42, :z)), + ((; kind=:shoot, species=:alpha), (organ, :a, :z)), + ((; scale=(:Leaf, :Axis)), (organ, 42, :a, :z)), + ((; id=ObjectId(organ)), (organ,)), + ((; scale=:Missing), ()), + ((; species=:Missing), ()), + ) + for (criteria, expected) in cases + objects = model_objects(scene; criteria...) + ids = object_ids(scene; criteria...) + @test objects isa Vector{Object} + @test Tuple(ids) == map(ObjectId, expected) + @test getfield.(objects, :id) == ids + @test all(i -> objects[i] === model_object(scene, ids[i]), eachindex(ids)) + end + axis = only(model_objects(scene; id=:a)) + @test axis.status === model_status(scene, :a) + axis.geometry = (x=2.0, y=3.0) + @test geometry(model_object(scene, :a)) == axis.geometry + @test model_objects(CompositeModel()) isa Vector{Object} + @test isempty(model_objects(CompositeModel())) + @test_throws MethodError model_objects(scene; unknown_criterion=true) +end + +@testset "ObjectId tuple sort text uses Julia's Symbol spelling" begin + spellings = ["leaf", "a b", "+", ":", "::", ":=", "=", "==", "===", "=>", + "'", "", "\n", "a\"b", "α₁", "⊗"] + for spelling in spellings + symbol = Symbol(spelling) + for value in ((symbol,), (symbol, :nested, 7), ((symbol,), "text", 'x')) + @test PlantSimEngine._object_id_text(ObjectId(value)) == string(value) + end + end +end + +struct ModelObjectsDisplayKey + value::Int +end +Base.show(io::IO, key::ModelObjectsDisplayKey) = print(io, "collection-key-", key.value) + +@testset "sorting preserves arbitrary identities and custom display" begin + ids = ObjectId[ObjectId(ModelObjectsDisplayKey(7)), ObjectId('c'), ObjectId(:c), + ObjectId((:nested, ModelObjectsDisplayKey(3))), ObjectId(0.25)] + before = copy(ids) + expected = sort(ids; by=id -> string(id.value)) + actual = ids[PlantSimEngine._object_id_sort_order(ids)] + @test actual == expected + @test hash.(actual) == hash.(expected) + @test all(i -> actual[i] === expected[i], eachindex(ids)) + @test ids == before + @test PlantSimEngine._object_id_text(first(ids)) == string(ModelObjectsDisplayKey(7)) +end From e78d72e49e8786e38bee1365d5810a76a5cb72e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 00:41:42 +0100 Subject: [PATCH 233/324] Rebuild inputs and resolve hard calls through their prepared families --- src/composite_model/compilation.jl | 190 ++++++++++++++++------------- 1 file changed, 104 insertions(+), 86 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 9e5646f2f..8756a14db 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4664,10 +4664,10 @@ end Base.@noinline function _store_rebuilt_input_binding!( bindings, changed_bindings, index, replacement, cache, model, ) - binding = _share_many_input_binding!(cache, model, only(replacement)) - bindings[index] = binding - push!(changed_bindings, binding) - return binding + replacement[1] = _share_many_input_binding!(cache, model, only(replacement)) + copyto!(bindings, index, replacement, 1, 1) + append!(changed_bindings, replacement) + return nothing end # One existing-binding lifecycle operation; admission precedes this worker. @@ -4789,7 +4789,7 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S get(many_binding_cache.by_query, old_cache_key, nothing) === binding delete!(many_binding_cache.by_query, old_cache_key) end - replacement_binding = _store_rebuilt_input_binding!( + _store_rebuilt_input_binding!( input_bindings, changed_bindings, index, replacement, many_binding_cache, model, ) push!(rewired_consumer_ids, consumer_id) @@ -4804,11 +4804,14 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S target = (binding.application_id, consumer_id) # Replace the membership container so shallow diagnostic snapshots retain # the previous bindings, while all unmodified binding/carrier objects stay shared. - members = valtype(typeof(input_bindings_by_target))() - for existing in get(input_bindings_by_target, target, ()) - push!(members, existing === binding ? replacement_binding : existing) + members = get(input_bindings_by_target, target) do + valtype(typeof(input_bindings_by_target))() end - input_bindings_by_target[target] = members + updated = copy(members) + for i in eachindex(members) + members[i] === binding && copyto!(updated, i, input_bindings, index, 1) + end + input_bindings_by_target[target] = updated return true end @@ -9683,6 +9686,93 @@ function _observe_compiled_call_membership!( return binding end +function _compile_call_plan_binding!( + plan, bindings, model, application_id, consumer_id, application_objects, lookup_applications, +) + call_sym = plan.call + selector = plan.selector + proc = plan.process + app_name = plan.application + mode = _compiled_call_mode(plan) + callee_object_ids, callee_application_ids = if mode === :initializer + # Initializers never cache or track pre-existing target objects. + # Their one scheduled application is statically validated, and + # run_initializer! resolves only its explicit newborn identity. + ( + keytype(model.registry.objects)[], + Symbol[plan.potential_callee_application_ids...], + ) + else + isnothing(application_objects) && + (application_objects = _applications_by_object(lookup_applications, model.registry.objects)) + object_ids = _dependency_object_ids( + model, + selector, + plan.matcher, + consumer_id, + ) + application_ids = Symbol[] + for object_id in object_ids + append!( + application_ids, + _matching_callee_applications( + application_objects, + object_id, + proc, + app_name, + ), + ) + end + unique!(application_ids) + (object_ids, application_ids) + end + if mode === :manual && + isempty(callee_application_ids) && selector isa One + matched_objects = join([_object_id_text(id) for id in callee_object_ids], ", ") + error( + "Call `$(call_sym)` on application `$(application_id)` matched objects ", + "[$(matched_objects)] but no model application", + isnothing(proc) ? "." : " with process `$(proc)`.", + ) + end + if mode === :manual && selector isa One && + length(callee_application_ids) != 1 + callee_applications = join([String(id) for id in callee_application_ids], ", ") + error( + "Call `$(call_sym)` on application `$(application_id)` expected one callee application, ", + "got `[$(callee_applications)]`. Add `application=:name` to disambiguate." + ) + elseif selector isa OptionalOne && length(callee_application_ids) > 1 + callee_applications = join([String(id) for id in callee_application_ids], ", ") + error( + "Call `$(call_sym)` on application `$(application_id)` expected zero or one callee application, ", + "got `[$(callee_applications)]`. Add `application=:name` to disambiguate." + ) + end + push!( + bindings, + CompiledModelCallBinding( + plan, + consumer_id, + _application_target_ids(model, callee_object_ids), + callee_application_ids, + ), + ) + return application_objects +end + +function _compile_application_call_bindings!( + plans, bindings, model, application_id, targets, application_objects, lookup_applications, +) + for consumer_id in targets, slot in eachindex(plans) + application_objects = Base.@inline _with_metadata_entry( + _compile_call_plan_binding!, plans, slot, bindings, model, application_id, + consumer_id, application_objects, lookup_applications, + ) + end + return application_objects +end + function _compile_model_call_bindings( model::CompositeModel, applications, @@ -9705,83 +9795,11 @@ function _compile_model_call_bindings( by_object = Base.@inline _with_model_application( applications_by_id, partial_application, by_object, plans_by_application, ) do application, application_objects, application_plans - for consumer_id in application.target_ids - for plan in _application_plans( - application_plans, - application.id, - ) - call_sym = plan.call - selector = plan.selector - proc = plan.process - app_name = plan.application - mode = _compiled_call_mode(plan) - callee_object_ids, callee_application_ids = if mode === :initializer - # Initializers never cache or track pre-existing target objects. - # Their one scheduled application is statically validated, and - # run_initializer! resolves only its explicit newborn identity. - ( - ObjectId[], - Symbol[plan.potential_callee_application_ids...], - ) - else - isnothing(application_objects) && - (application_objects = _applications_by_object(lookup_applications, model.registry.objects)) - object_ids = _dependency_object_ids( - model, - selector, - plan.matcher, - consumer_id, - ) - application_ids = Symbol[] - for object_id in object_ids - append!( - application_ids, - _matching_callee_applications( - application_objects, - object_id, - proc, - app_name, - ), - ) - end - unique!(application_ids) - (object_ids, application_ids) - end - if mode === :manual && - isempty(callee_application_ids) && selector isa One - matched_objects = join([_object_id_text(id) for id in callee_object_ids], ", ") - error( - "Call `$(call_sym)` on application `$(application.id)` matched objects ", - "[$(matched_objects)] but no model application", - isnothing(proc) ? "." : " with process `$(proc)`.", - ) - end - if mode === :manual && selector isa One && - length(callee_application_ids) != 1 - callee_applications = join([String(id) for id in callee_application_ids], ", ") - error( - "Call `$(call_sym)` on application `$(application.id)` expected one callee application, ", - "got `[$(callee_applications)]`. Add `application=:name` to disambiguate." - ) - elseif selector isa OptionalOne && length(callee_application_ids) > 1 - callee_applications = join([String(id) for id in callee_application_ids], ", ") - error( - "Call `$(call_sym)` on application `$(application.id)` expected zero or one callee application, ", - "got `[$(callee_applications)]`. Add `application=:name` to disambiguate." - ) - end - push!( - bindings, - CompiledModelCallBinding( - plan, - consumer_id, - _application_target_ids(model, callee_object_ids), - callee_application_ids, - ), - ) - end - end - return application_objects + id = application.id + return Base.@inline _with_metadata_entry( + _compile_application_call_bindings!, application_plans, id, + bindings, model, id, application.target_ids, application_objects, lookup_applications, + ) end end return bindings From e933067eb2e05b01b9891457271f0e3e2b8fcd1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 00:47:44 +0100 Subject: [PATCH 234/324] Construct and copy wide organ statuses through their prepared slots --- src/component_models/Status.jl | 20 +++++++++----- .../prepared_status_manifest.jl | 2 +- src/composite_model/registry_topology.jl | 2 +- src/composite_model/status_construction.jl | 2 +- test/fixtures/distributed_growth.jl | 5 ++-- .../distributed_producer_birth/src/prepare.jl | 27 ++++++++++++++++--- 6 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 1833fc8e8..17ffa31e6 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -250,12 +250,18 @@ end _status_vars(status) = getfield(status, :vars) # Read or transform each concrete reference before selecting the currently # present fields. A present reference may itself contain nothing. -_map_status_slots(::typeof(identity), slots) = slots -_map_status_slots(f::F, slots) where {F} = - map(slot -> isnothing(slot) ? nothing : f(slot), slots) +# Preserve each slot type for wide prepared layouts without tuple-map widening. +_map_status_slots(::typeof(identity), slots::NamedTuple) = slots +@generated function _map_status_slots(f::F, slots::NamedTuple{names}) where {F,names} + fields = [:(let slot = getfield(slots, $i) + isnothing(slot) ? nothing : f(slot) + end) for i in 1:length(names)] + data = Expr(:tuple, fields...) + return :(NamedTuple{$(QuoteNode(names))}($data)) +end function _map_status_fields(f::F, ::Type{T}, status::Status) where {F,T} - fields = _map_status_slots(f, _initial_status_reference_storage(status)) + fields = _map_status_slots(f, _status_reference_slots(status)) names = keys(status) if names === keys(fields) return T === Tuple ? Tuple(fields) : fields @@ -349,14 +355,14 @@ Base.copy(status::Status) = Status(_copy_status_storage(_status_vars(status))) # Keep Base's single-IdDict deepcopy: it preserves internal aliases/cycles and # copies refs, owner metadata and the identity token together; no elementwise map. -@inline function _initial_status_reference_storage(source::Status) +@inline function _status_reference_slots(source::Status) storage = _status_vars(source) storage isa NamedTuple && return storage storage isa Union{_FixedStatusStorage,_ProjectedStatusStorage} || throw(ArgumentError("Unknown Status backing.")) return _status_reference_slots(storage) end @inline _initial_status_reference_count(source::Status) = - _initial_status_reference_count(_initial_status_reference_storage(source)) + _initial_status_reference_count(_status_reference_slots(source)) # A newborn may supply any admitted layout. Box its directory once at this # boundary so scanning a wide, mutable Status does not copy it for each field. Base.@noinline Base.@nospecializeinfer function _initial_status_reference_count(@nospecialize(references::NamedTuple)) @@ -367,7 +373,7 @@ Base.@noinline Base.@nospecializeinfer function _initial_status_reference_count( return count end @inline _initial_status_reference(source::Status, name::Symbol) = - _initial_status_reference(_initial_status_reference_storage(source), name) + _initial_status_reference(_status_reference_slots(source), name) @inline function _initial_status_reference(references::NamedTuple, name::Symbol) slot = Base.fieldindex(typeof(references), name, false) return iszero(slot) ? nothing : getfield(references, slot) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 6bf487e0f..c5cdf10ef 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -765,7 +765,7 @@ _object_birth_recipe(manifest, object) = get(manifest.birth_recipes, object.scal isnothing(source_status) && return nothing source_status isa Status || throw(ArgumentError("Prepared initial data must be Status or nothing.")) recipe = _object_birth_recipe(manifest, object) - references = _initial_status_reference_storage(source_status) + references = _status_reference_slots(source_status) allowed = _prepared_status_source_allowed(recipe, model, object, parent_id, references, nothing) allowed && return nothing for raw in recipe.raw_families diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 2c4a6064b..d7f563480 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1504,7 +1504,7 @@ end status = if catalog isa ClosedObjectFamilyCatalog manifest = catalog.status_manifest Base.@inline _validate_prepared_initial_status(manifest, model, object, converted, parent_id) - isnothing(converted) ? nothing : _new_prepared_status(manifest.status_type, converted) + isnothing(converted) ? nothing : (Base.@inline _new_prepared_status(manifest.status_type, converted)) else converted end diff --git a/src/composite_model/status_construction.jl b/src/composite_model/status_construction.jl index 0856deb4f..8bf9616d1 100644 --- a/src/composite_model/status_construction.jl +++ b/src/composite_model/status_construction.jl @@ -72,7 +72,7 @@ end Refs = projected ? fieldtype(Storage, :hot).parameters[2] : _status_schema_references(Result) # Read the reference layout once. Each action indexes this named tuple # directly, including when a field is present only in the full snapshot. - load_refs = Existing === Nothing ? :(NamedTuple()) : :(_initial_status_reference_storage(original)) + load_refs = Existing === Nothing ? :(NamedTuple()) : :(_status_reference_slots(original)) hot = [:( _status_construction_reference(getfield(factory.construction.actions,$i), original_refs, edited)::$(fieldtype(Refs,i)) ) for i in eachindex(Names)] Hot = NamedTuple{Names,Refs} diff --git a/test/fixtures/distributed_growth.jl b/test/fixtures/distributed_growth.jl index df982dbb0..82a3e5002 100644 --- a/test/fixtures/distributed_growth.jl +++ b/test/fixtures/distributed_growth.jl @@ -103,8 +103,9 @@ function PSE.run!(::ProducerBirth, status, environment, constants, context) end producer_birth_leaf_ids() = [PSE.ObjectId((:tree, :leaf, index)) for index in 1:30] -function make_producer_birth_model() - objects = PSE.Object[PSE.Object(:root; scale=:Scene, status=PSE.Status(visits=0))] +function make_producer_birth_model(; extra_root_status=NamedTuple()) + objects = PSE.Object[PSE.Object(:root; scale=:Scene, + status=PSE.Status(; visits=0, extra_root_status...))] for (index, id) in enumerate(producer_birth_leaf_ids()) push!(objects, PSE.Object(id; scale=:Leaf, parent=:root, status=PSE.Status(ordinal=index))) end diff --git a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl index 02c9f3f66..6e2bd3a9b 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl @@ -1,5 +1,25 @@ # Host preparation only: one public scenario, actual finite core owners. const APPLICATION_IDS = (:birth, :producer) +# The existing binary also reads a real wide, heterogeneous Status snapshot. +const WIDE_SNAPSHOT_NAMES = ntuple(i -> Symbol("snapshot_width_", i), 33) +const WIDE_SNAPSHOT_VALUES = ntuple(33) do i + mod(i, 3) == 0 ? iseven(i) : mod(i, 3) == 1 ? i : Float64(i) +end +const WIDE_SNAPSHOT_STATUS = NamedTuple{WIDE_SNAPSHOT_NAMES}(WIDE_SNAPSHOT_VALUES) +make_native_producer_model() = DistributedGrowthFixture.make_producer_birth_model(; + extra_root_status=WIDE_SNAPSHOT_STATUS) + +function wide_snapshot_checkpoint(simulation) + snapshot = PSE.final_state(simulation, :root) + snapshot isa NamedTuple && length(snapshot) == 34 || return false + for index in eachindex(WIDE_SNAPSHOT_NAMES) + value = getfield(snapshot, WIDE_SNAPSHOT_NAMES[index]) + value isa Union{Bool,Int,Float64} || return false + value === WIDE_SNAPSHOT_VALUES[index] || return false + end + return true +end + function state_for(simulation) ids = DistributedGrowthFixture.producer_birth_leaf_ids() S = typeof(PSE.model_status(simulation, first(ids))) @@ -15,6 +35,7 @@ end function checkpoint(state, day) sim, model = state.simulation, state.simulation.model PSE.current_step(sim) == day || return false + wide_snapshot_checkpoint(sim) || return false length(state.ids) == 30 || return false listed = PSE.model_objects(model; scale=:Leaf) length(listed) == 30 || return false @@ -71,13 +92,13 @@ end function prepare_control() # The public ordinary maintained test is independently executed by the host gate. - baseline = state_for(PSE.run!(DistributedGrowthFixture.make_producer_birth_model(); + baseline = state_for(PSE.run!(make_native_producer_model(); steps=0, outputs=:all)) advance_host!(baseline) observed = RuntimeTypes() input_trace = InputTrace(observed) environment = PSE._collecting_environment_binding_schema() - recording = PSE._prepare_simulation!(close_registry(DistributedGrowthFixture.make_producer_birth_model()); + recording = PSE._prepare_simulation!(close_registry(make_native_producer_model()); steps=0, outputs=:all, constants=PSE.Constants(), environment_schema=environment, input_binding_storage=input_trace, status_view_schema=observed) advance_host!(state_for(recording)) @@ -90,7 +111,7 @@ function prepare_control() Vector{Union{types...}}() end)) environment = PSE._freeze_environment_binding_schema(environment) - prepare() = PSE._prepare_simulation!(close_registry(DistributedGrowthFixture.make_producer_birth_model()); + prepare() = PSE._prepare_simulation!(close_registry(make_native_producer_model()); steps=0, outputs=:all, constants=PSE.Constants(), environment_schema=environment, input_binding_storage=prototype, status_view_schema=schema) finite = prepare() From f2b8215a0ebc64c4888be9aa664335d0fd42abef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 01:06:42 +0100 Subject: [PATCH 235/324] Reuse scene indexes when refreshing calls, selectors and distributed outputs --- src/composite_model/compilation.jl | 118 ++++++++---------- src/composite_model/registry_topology.jl | 2 +- src/composite_model/runtime_outputs.jl | 6 +- src/composite_model/selectors.jl | 14 ++- .../status_view_construction.jl | 2 +- 5 files changed, 65 insertions(+), 77 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 8756a14db..48c073a88 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2465,11 +2465,12 @@ function _extend_observed_manual_call_binding_callee_target_index!( (previous_object_count + 1):length(binding.callee_object_ids) for object_position in new_object_positions callee_object_id = binding.callee_object_ids[object_position] - for application in get( + for entry in get( applications_by_object, callee_object_id, (), ) + application = entry::CompiledModelApplication callee_application_id = application.id callee_application_id in binding.callee_application_ids || continue @@ -2687,10 +2688,12 @@ function _compile_scene( ) timeline = scenario_plan.timeline applications_by_id = _applications_by_id(applications) + applications_by_object = _applications_by_object(applications, model.registry.objects) started_at = _runtime_performance_start(performance) call_bindings = _compile_model_call_bindings( model, applications; + by_object=applications_by_object, applications_by_id=applications_by_id, plans_by_application=scenario_plan.call_plans_by_application, ) @@ -2714,6 +2717,8 @@ function _compile_scene( scenario_plan.input_recipes_by_application, distributed_outputs; input_binding_storage, + by_object=applications_by_object, + by_id=applications_by_id, ) many_input_binding_cache = _share_many_input_bindings!(model, input_bindings) @@ -2762,7 +2767,7 @@ function _compile_scene( applications, applications_by_id, ordered_applications, - _applications_by_object(applications, model.registry.objects), + applications_by_object, input_bindings, call_bindings, input_bindings_by_target, @@ -4028,7 +4033,7 @@ function _refresh_model_status_view_for_target!(application, object_id, state) applications_by_id, positions, distributed_outputs, - _status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema), + Base.@inline(_status_view_execution_stamp(model, key, previous_view, compiled.status_view_schema)), compiled.status_view_schema, compiled.input_bindings, ) @@ -4088,7 +4093,7 @@ function _extend_model_status_views!( key = (application.id, object_id) previous_view = get(views, key, nothing) isnothing(previous_view) && return nothing - current = _status_view_key_epoch_is_current(compiled.status_view_schema, + current = Base.@inline _status_view_key_epoch_is_current(compiled.status_view_schema, application.id, previous_view, model, key::Key) current || push!(affected_keys, key) return nothing @@ -4132,7 +4137,8 @@ function _append_added_many_call_targets!( previous_object_count = length(binding.callee_object_ids) previous_application_count = length(binding.callee_application_ids) default_scope = _default_dependency_scope(model, binding.consumer_id) - new_target_ids = ObjectId[ + I = eltype(binding.callee_object_ids) + new_target_ids = I[ object_id for object_id in added_ids if _selector_matches_object_id( model, @@ -4525,7 +4531,6 @@ function _refresh_scene_call_bindings!( _compile_model_call_bindings( model, added_applications, - applications, ; by_object=applications_by_object, applications_by_id=applications_by_id, @@ -4563,8 +4568,7 @@ function _refresh_scene_call_bindings!( similar(compiled.call_bindings, 0) : _compile_model_call_bindings( model, - affected_call_applications, - applications; + affected_call_applications; by_object=applications_by_object, applications_by_id=applications_by_id, plans_by_application=compiled.scenario_plan.call_plans_by_application, @@ -4581,7 +4585,15 @@ function _refresh_scene_call_bindings!( "Incremental hard-call refresh changed the number of declared calls ", "for application `$(first(key))` on object `$(_object_id_text(last(key)))`.", ) - for binding in existing + # Both tuples were indexed against the same ordered declarations by + # _index_model_call_bindings_for_application!. Reuse that position. + for slot in eachindex(existing) + binding = existing[slot]::CompiledModelCallBinding + replacement = replacements[slot]::CompiledModelCallBinding + getfield(binding, :plan) === getfield(replacement, :plan) || error( + "Incremental hard-call refresh changed the declaration at position ", + slot, " for application `$(first(key))` on object `$(_object_id_text(last(key)))`.", + ) binding_index = findfirst( candidate -> candidate === binding, call_bindings, @@ -4590,31 +4602,13 @@ function _refresh_scene_call_bindings!( "Incremental hard-call refresh lost the existing compiled binding ", "for application `$(first(key))` on object `$(_object_id_text(last(key)))`.", ) - replacement_index = findfirst( - candidate -> - _compiled_call_name(candidate) === - _compiled_call_name(binding), - replacements, - ) - isnothing(replacement_index) && error( - "Incremental hard-call refresh lost declared call ", - "`$(_compiled_call_name(binding))` for application ", - "`$(first(key))` on object `$(_object_id_text(last(key)))`.", - ) - replacement = replacements[replacement_index] - if binding.callee_object_ids != replacement.callee_object_ids || - binding.callee_application_ids != - replacement.callee_application_ids - empty!(binding.callee_object_ids) - append!( - binding.callee_object_ids, - replacement.callee_object_ids, - ) - empty!(binding.callee_application_ids) - append!( - binding.callee_application_ids, - replacement.callee_application_ids, - ) + object_ids = getfield(binding, :callee_object_ids)::Vector{I} + updated_ids = getfield(replacement, :callee_object_ids)::Vector{I} + application_ids = getfield(binding, :callee_application_ids) + updated_applications = getfield(replacement, :callee_application_ids) + if object_ids != updated_ids || application_ids != updated_applications + append!(empty!(object_ids), updated_ids) + append!(empty!(application_ids), updated_applications) _mark_compiled_call_membership_changed!( binding, model.revision, @@ -8367,11 +8361,7 @@ function _application_may_output_variable( source_selector, applies_to(application.spec), ) && return true - return any( - plan -> variable in plan.variable_names && - _selector_labels_may_overlap(source_selector, plan.selector), - _application_plans(plans.by_application, application.id), - ) + return _application_declares_distributed_output(application, variable, source_selector, plans) end _application_declares_distributed_output( @@ -8387,13 +8377,17 @@ function _application_declares_distributed_output( source_selector, plans::CompiledDistributedOutputPlans, ) - return any( - plan -> variable in plan.variable_names && - _selector_labels_may_overlap(source_selector, plan.selector), - _application_plans(plans.by_application, application.id), + return Base.@inline _with_metadata_entry( + _any_matching_output_destination, plans.by_application, application.id, variable, source_selector, ) end +function _any_matching_output_destination(plans, variable, selector) + return any(plans) do plan + variable in plan.variable_names && _selector_labels_may_overlap(selector, plan.selector) + end +end + Base.@nospecializeinfer function _potential_call_application_ids( applications, selector, @@ -9009,10 +9003,10 @@ function _compile_model_input_bindings( input_recipes_by_application, distributed_outputs=NoCompiledDistributedOutputs(); input_binding_storage=nothing, + by_object=_applications_by_object(applications, model.registry.objects), + by_id=_applications_by_id(applications), ) bindings = _model_input_binding_storage(input_binding_storage) - by_object = _applications_by_object(applications, model.registry.objects) - by_id = _applications_by_id(applications) for application in applications isempty(application.target_ids) && continue recipe = _application_plans(input_recipes_by_application, application.id) @@ -9687,7 +9681,7 @@ function _observe_compiled_call_membership!( end function _compile_call_plan_binding!( - plan, bindings, model, application_id, consumer_id, application_objects, lookup_applications, + plan, bindings, model, application_id, consumer_id, application_objects, ) call_sym = plan.call selector = plan.selector @@ -9703,8 +9697,6 @@ function _compile_call_plan_binding!( Symbol[plan.potential_callee_application_ids...], ) else - isnothing(application_objects) && - (application_objects = _applications_by_object(lookup_applications, model.registry.objects)) object_ids = _dependency_object_ids( model, selector, @@ -9728,7 +9720,7 @@ function _compile_call_plan_binding!( end if mode === :manual && isempty(callee_application_ids) && selector isa One - matched_objects = join([_object_id_text(id) for id in callee_object_ids], ", ") + matched_objects = join(String[_object_id_text(id) for id in callee_object_ids], ", ") error( "Call `$(call_sym)` on application `$(application_id)` matched objects ", "[$(matched_objects)] but no model application", @@ -9758,47 +9750,39 @@ function _compile_call_plan_binding!( callee_application_ids, ), ) - return application_objects + return nothing end function _compile_application_call_bindings!( - plans, bindings, model, application_id, targets, application_objects, lookup_applications, + plans, bindings, model, application_id, targets, application_objects, ) for consumer_id in targets, slot in eachindex(plans) - application_objects = Base.@inline _with_metadata_entry( + Base.@inline _with_metadata_entry( _compile_call_plan_binding!, plans, slot, bindings, model, application_id, - consumer_id, application_objects, lookup_applications, + consumer_id, application_objects, ) end - return application_objects + return nothing end function _compile_model_call_bindings( model::CompositeModel, - applications, - lookup_applications=applications, - ; - by_object=nothing, + applications; + by_object=_applications_by_object(applications, model.registry.objects), applications_by_id, - plans_by_application=nothing, + plans_by_application, ) - if isnothing(plans_by_application) - plans_by_application = _plans_by_application( - applications, - _compile_model_call_plans(model, applications), - ) - end bindings = _model_call_binding_storage( plans_by_application, keytype(model.registry.objects), ) for partial_application in applications - by_object = Base.@inline _with_model_application( + Base.@inline _with_model_application( applications_by_id, partial_application, by_object, plans_by_application, ) do application, application_objects, application_plans id = application.id return Base.@inline _with_metadata_entry( _compile_application_call_bindings!, application_plans, id, - bindings, model, id, application.target_ids, application_objects, lookup_applications, + bindings, model, id, application.target_ids, application_objects, ) end end diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index d7f563480..440b291d3 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1663,7 +1663,7 @@ function add_organ!( ) registered = register_object!(model, object) adapter.max_node_id[] = max(adapter.max_node_id[], node_id) - return registered.status + return registered.status::Status catch _unregister_mtg_object_identity!(adapter, node) MultiScaleTreeGraph.delete_node!(node) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index b24d0723a..6953ebe4c 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -8595,10 +8595,8 @@ function _model_request_matches_distributed_output(application, request, request concrete_match = any(id -> id in requested_ids, destination_ids) isempty(requested_ids) || return concrete_match isnothing(plans_by_application) && return false - return any( - plan -> request.var in plan.variable_names && - _selector_labels_may_overlap(request.selector, plan.selector), - _application_plans(plans_by_application, application.id), + return Base.@inline _with_metadata_entry( + _any_matching_output_destination, plans_by_application, application.id, request.var, request.selector, ) end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index ba49292b3..5e24fb7c6 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -835,12 +835,18 @@ function _registry_selector_candidates(index, requested) bucket = get(index, requested, ()) return (ids=bucket, estimate=length(bucket)) end - requested_values = requested # Unlabelled objects have no index bucket. Another criterion may still # provide a complete candidate source; otherwise scan the registry. - any(isnothing, requested_values) && return nothing - buckets = map(value -> get(index, value, ()), requested_values) - return (ids=Iterators.flatten(buckets), estimate=sum(length, buckets; init=0)) + buckets = valtype(typeof(index))[] + estimate = 0 + for value in requested + isnothing(value) && return nothing + bucket = get(index, value, nothing) + isnothing(bucket) && continue + push!(buckets, bucket) + estimate += length(bucket) + end + return (ids=Iterators.flatten(buckets), estimate=estimate) end function _smallest_indexed_candidates(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index 860b9ce67..698e17efe 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -265,7 +265,7 @@ function _assemble_model_status_view(canonical_status, model, application, objec parts = (; canonical_status, temporal, private_names, private_values, hot_names, many_names, many_ids, execution_stamp) view = _construct_model_status_view(status_view_schema, application.id, parts) - return _admit_model_status_view!(status_view_schema, application.id, view) + return Base.@inline _admit_model_status_view!(status_view_schema, application.id, view) end # A homogeneous initial snapshot has the same exact schema as before. Matching From 8812561ea11383dac681e61ec0ca5d1fe4c4997e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 01:20:56 +0100 Subject: [PATCH 236/324] Retain the declared weather row type when sampling a Tables row table --- src/composite_model/environment_bindings.jl | 11 +++++++++-- test/test-model-global-environment-sample-schema.jl | 3 +++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 6369b5ef2..4d8477402 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -679,8 +679,15 @@ end ) = @inbounds prepared.rows[step] # These are row-type declarations, not calls to sample arbitrary providers. -_global_environment_raw_sample_type(source) = - DataFormat(source) isa SingletonAlike ? typeof(source) : Any +function _global_environment_raw_sample_type(source) + DataFormat(source) isa SingletonAlike && return typeof(source) + # A Tables.jl row table is its own row iterator. Its declared element type + # also describes a cached row, without reading data during preparation. + if Tables.isrowtable(source) && Base.IteratorEltype(typeof(source)) isa Base.HasEltype + return eltype(source) + end + return Any +end _global_environment_raw_sample_type(source::TimeStepTable) = eltype(source) _global_environment_raw_sample_type(source::PreparedGlobalEnvironmentRows) = eltype(source.rows) diff --git a/test/test-model-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl index ee5c2627f..9610586f4 100644 --- a/test/test-model-global-environment-sample-schema.jl +++ b/test/test-model-global-environment-sample-schema.jl @@ -361,6 +361,9 @@ end @test plan.prepared_source isa PSE.PreparedGlobalEnvironmentRows R = remap ? Any : eltype(rows) @test plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{R} + control_plan = control.environment_bindings.application_plans_by_id[:probe] + @test control_plan.sample_schema isa PSE.GlobalEnvironmentSampleSchema{R} + @test control_plan.prepared_source === rows @test current_step(simulation) == current_step(control) == 3 @test final_state(simulation) == final_state(control) == (seen=4f0, visits=3) @test outputs(simulation)[(:probe, ObjectId(:a), :seen)] == From 1b61cf5381bf76baa18141893f418260f0364981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 01:22:39 +0100 Subject: [PATCH 237/324] Keep the prepared identity and input families for calls on newborn organs --- src/composite_model/compilation.jl | 74 +++++----- src/composite_model/runtime_outputs.jl | 129 ++++++++++-------- test/test-model-input-recipes.jl | 42 ++++++ .../test-model-newborn-context-initializer.jl | 35 +++++ 4 files changed, 186 insertions(+), 94 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 48c073a88..5740f7007 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3051,6 +3051,16 @@ function _compile_consumer_input_plan!( ) end +function _append_inferred_input_route!(plan, bindings, model, application_id, + application_process, consumer_id, sources, applications_by_id, +) + push!(bindings, _materialize_input_route( + model, application_id, application_process, consumer_id, plan, + sources, applications_by_id, + )) + return nothing +end + function _compile_consumer_input_recipe!( bindings, model, @@ -3078,11 +3088,10 @@ function _compile_consumer_input_recipe!( plan = first(group) matches = CompiledModelInputPlan[ candidate for candidate in group - if _application_writes_object_variable( - distributed_outputs, - applications_by_id[candidate.application], - consumer_id, - candidate.source_var, + if Base.@inline _with_metadata_entry( + _application_writes_source_variable, applications_by_id, + candidate.application::Symbol, distributed_outputs, + consumer_id, candidate.source_var, ) ] matches = _final_inferred_output_plans( @@ -3101,10 +3110,12 @@ function _compile_consumer_input_recipe!( _input_binding_source_ids(model.registry.objects, [consumer_id]), Symbol[selected.application], ) - push!(bindings, _materialize_input_route( - model, application_id, application_process, consumer_id, selected, - sources, applications_by_id, - )) + # Filtering preserves members of the authored tuple; admit that same + # selected plan before materialization instead of its abstract vector slot. + slot = something(findfirst(candidate -> candidate === selected, group)) + _with_metadata_entry(_append_inferred_input_route!, group, slot, + bindings, model, application_id, application_process, consumer_id, + sources, applications_by_id) end return bindings end @@ -4809,6 +4820,13 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S return true end +Base.@noinline function _lifecycle_target_count_error(application_id::Symbol, + target_count::Int, selector::String, +) + throw(ErrorException("Lifecycle refresh left application `" * String(application_id) * + "` with " * string(target_count) * " targets for " * selector * " selector.")) +end + function _extend_compiled_scene( model::CompositeModel, compiled::CompiledCompositeModel, @@ -4865,15 +4883,9 @@ function _extend_compiled_scene( if application.id in changed_application_ids_seed target_count = length(application.target_ids) if application.applies_to isa One && target_count != 1 - error( - "Lifecycle refresh left application `$(application.id)` with ", - "$(target_count) targets for a `One` selector.", - ) + _lifecycle_target_count_error(application.id, target_count, "a `One`") elseif application.applies_to isa OptionalOne && target_count > 1 - error( - "Lifecycle refresh left application `$(application.id)` with ", - "$(target_count) targets for an `OptionalOne` selector.", - ) + _lifecycle_target_count_error(application.id, target_count, "an `OptionalOne`") end end return nothing @@ -5101,7 +5113,8 @@ function _extend_compiled_scene( end rewired_applications end - final_input_references = _model_input_status_references(changed_bindings) + final_input_references = _model_input_status_references( + model.registry.objects, changed_bindings) _prepare_model_input_statuses_batched!( model, affected_input_applications, @@ -7727,7 +7740,7 @@ function _force_distributed_producer_rebinds!(forced, model, bindings, by_variab for (raw_destination, producer) in candidates producer in binding.plan.potential_source_application_ids || continue destination = _index_object_id(model.registry.objects, raw_destination) - _selector_matches_object_id( + Base.@inline _selector_matches_object_id( model, binding.matcher, destination, @@ -7747,14 +7760,15 @@ _model_input_status_reference(binding) = binding.carrier isa Ref ? binding.carrier : Ref(binding.carrier) -function _model_input_status_references(bindings) - references = Dict{Tuple{Symbol,ObjectId,Symbol},Any}() +function _model_input_status_references(objects::AbstractDict{I}, bindings) where {I<:ObjectId} + references = _object_key_index(Tuple{Symbol,I,Symbol}, Any) for binding in bindings binding.carrier_hint == :temporal_stream && continue isnothing(binding.carrier) && continue + consumer_id = _index_object_id(objects, binding.consumer_id) references[( binding.application_id, - binding.consumer_id, + consumer_id, binding.input, )] = _model_input_status_reference(binding) end @@ -8340,21 +8354,7 @@ function _application_may_output_variable( variable::Symbol, source_selector, local_output_names, - ::NoCompiledDistributedOutputPlans, -) - return variable in local_output_names && - _selector_labels_may_overlap( - source_selector, - applies_to(application.spec), - ) -end - -function _application_may_output_variable( - application, - variable::Symbol, - source_selector, - local_output_names, - plans::CompiledDistributedOutputPlans, + plans::Union{NoCompiledDistributedOutputPlans,CompiledDistributedOutputPlans}, ) variable in local_output_names && _selector_labels_may_overlap( diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 6953ebe4c..ba2686560 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5776,16 +5776,12 @@ function call_model(context, name::Symbol) ) end -function _call_target_object_id(model::CompositeModel, target) - return object_id(model, target) -end - function _call_target_object_ids(model::CompositeModel, objects) requested = objects isa Union{Tuple,AbstractVector,AbstractSet} ? objects : (objects,) - ids = ObjectId[_call_target_object_id(model, object) for object in requested] - unique!(ids) - return _application_target_ids(model, ids) + I = keytype(model.registry.objects) + ids = I[object_id(model, object)::I for object in requested] + return unique!(ids) end struct _ApplicationsByObjectOverlay{B,O} @@ -5799,18 +5795,15 @@ mutable struct _TargetedApplicationSet{A,B} outputs_prepared::Bool end -mutable struct _TargetedTopologyRuntime{CS,MA} <: +mutable struct _TargetedTopologyRuntime{CS,MA,I,S,O} <: AbstractTargetedTopologyRuntime compiled::CS model_revision::Int application_sets::Dict{ - Tuple{Vararg{ObjectId}}, - Union{Nothing,_TargetedApplicationSet}, - } - added_applications_by_object::Dict{ - ObjectId, - Vector{CompiledModelApplication}, + Tuple{Vararg{I}}, + Union{Nothing,S}, } + added_applications_by_object::O indexed_addition_count::Int manual_application_ids::MA application_positions::Dict{Symbol,Int} @@ -5832,23 +5825,26 @@ function _targeted_topology_runtime!( model::CompositeModel, ) delta = lifecycle_delta(model) + compiled = context.compiled + I = keytype(model.registry.objects) + A = eltype(compiled.applications) + O = Dict{I,Vector{A}} + S = _TargetedApplicationSet{Vector{A},_ApplicationsByObjectOverlay{typeof(compiled.applications_by_object),O}} + manual = compiled.scenario_plan.manual_application_ids + Runtime = _TargetedTopologyRuntime{typeof(compiled),typeof(manual),I,S,O} cached = delta.targeted_topology_runtime - if cached isa _TargetedTopologyRuntime && - cached.compiled === context.compiled && + if cached isa Runtime && + cached.compiled === compiled && cached.model_revision == model.revision return cached end - compiled = context.compiled - runtime = _TargetedTopologyRuntime( + runtime = Runtime( compiled, model.revision, - Dict{ - Tuple{Vararg{ObjectId}}, - Union{Nothing,_TargetedApplicationSet}, - }(), - Dict{ObjectId,Vector{CompiledModelApplication}}(), + Dict{Tuple{Vararg{I}},Union{Nothing,S}}(), + O(), 0, - compiled.scenario_plan.manual_application_ids, + manual, Dict( application_id => index for (index, application_id) in pairs(compiled.application_order) @@ -5864,8 +5860,10 @@ function _new_object_applications( compiled::CompiledCompositeModel, requested_ids, ) - by_object = Dict{ObjectId,Vector{CompiledModelApplication}}() - partial_applications = CompiledModelApplication[] + I = keytype(model.registry.objects) + A = eltype(compiled.applications) + by_object = Dict{I,Vector{A}}() + partial_applications = A[] new_targets = _new_application_targets( model, compiled, @@ -5881,7 +5879,7 @@ function _new_object_applications( push!(partial_applications, partial) for object_id in target_ids applications = get!(by_object, object_id) do - CompiledModelApplication[ + A[ application for application in get( compiled.applications_by_object, object_id, @@ -5897,10 +5895,10 @@ function _new_object_applications( end function _targeted_application_set!( - runtime::_TargetedTopologyRuntime, + runtime::_TargetedTopologyRuntime{CS,MA,I}, model::CompositeModel, requested_ids, -) +) where {CS,MA,I} key = Tuple(requested_ids) application_set = get!(runtime.application_sets, key) do applications = _new_object_applications( @@ -5915,7 +5913,7 @@ function _targeted_application_set!( added_applications_by_object, ) return _TargetedApplicationSet( - Tuple(output_applications), + output_applications, _ApplicationsByObjectOverlay( runtime.compiled.applications_by_object, runtime.added_applications_by_object, @@ -5934,8 +5932,8 @@ function _targeted_application_set!( for index in (runtime.indexed_addition_count + 1):length(added) object_id = added[index].id haskey(runtime.added_applications_by_object, object_id) && continue - isnothing(unindexed_ids) && (unindexed_ids = ObjectId[]) - push!(unindexed_ids, object_id) + isnothing(unindexed_ids) && (unindexed_ids = I[]) + push!(unindexed_ids, object_id::I) end if !isnothing(unindexed_ids) applications = _new_object_applications( @@ -5955,8 +5953,8 @@ function _targeted_callee_applications( requested_ids, partial_applications, ) - applications = CompiledModelApplication[] - unresolved_ids = ObjectId[] + applications = similar(partial_applications, 0) + unresolved_ids = eltype(binding.callee_object_ids)[] for object_id in requested_ids matched = false for application in partial_applications @@ -5979,7 +5977,7 @@ function _targeted_callee_applications( "Hard call `$(binding.call)` from application `$(binding.application_id)` does not ", "resolve requested object(s) `$(Tuple(id.value for id in unresolved_ids))`." ) - return Tuple(applications) + return applications end function _applications_use_only_global_environment( @@ -6164,15 +6162,14 @@ function _targeted_new_object_call_targets( ) end -# Application membership is assembled dynamically, but its finite schema is -# stable for newborns selected by the same application recipe. Keep that tuple -# concrete across the canonical status and binding preparation below. +# A newborn selection borrows its application declarations from the compiled +# model. The number selected depends on the current topology. function _prepare_targeted_newborn_targets( context::RunContext, name::Symbol, targeted_runtime::_TargetedTopologyRuntime, application_set::_TargetedApplicationSet, - callee_applications::Tuple, + callee_applications::AbstractVector, initializer::Bool, batch_schema::ExecutionBatchSchema, ) @@ -6196,7 +6193,8 @@ function _prepare_targeted_newborn_targets( compiled.applications_by_id, compiled.distributed_outputs, ) end - final_input_references = _model_input_status_references(input_bindings) + final_input_references = _model_input_status_references( + model.registry.objects, input_bindings) _prepare_model_input_statuses_batched!( model, callee_applications, @@ -6417,19 +6415,38 @@ function _current_topology_call_targets( (context.application.id, context.object_id), (), ) - binding = findfirst( - candidate -> _compiled_call_name(candidate) === name, - bindings, - ) - if isnothing(binding) - available = Symbol[candidate.call for candidate in bindings] + position = findfirst(eachindex(bindings)) do slot + binding = bindings[slot]::CompiledModelCallBinding + plan = getfield(binding, :plan)::CompiledModelCallPlan + return plan.call === name + end + if isnothing(position) + available = Symbol[(item::CompiledModelCallBinding).call for item in bindings] error( "Application `$(context.application.id)` on object ", "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", "Declared calls: $(available).", ) end - resolved_binding = bindings[binding] + # The refreshed catalog owns the declaration, including any new potential + # callees. Keep its exact plan type when reading the heterogeneous tuple. + return Base.@inline _with_metadata_entry(compiled.scenario_plan.call_plans_by_application, + context.application.id) do plans + Base.@inline _with_metadata_entry(plans, position) do plan + B = CompiledModelCallBinding{typeof(plan),typeof(context.object_id),keytype(model.registry.objects)} + binding = bindings[position]::B + getfield(binding, :plan) === plan || throw(ArgumentError( + "The refreshed hard call belongs to a different declaration.", + )) + _selected_topology_call_targets(binding, cached_targets, context, name, requested_ids, + model, compiled, environment_bindings) + end + end +end + +function _selected_topology_call_targets(resolved_binding, cached_targets, context, name, requested_ids, + model, compiled, environment_bindings, +) _compiled_call_mode(resolved_binding) === :manual || _initializer_requires_dedicated_api(context, name) resolved_binding.multiplicity != :many && length(requested_ids) > 1 && @@ -6438,7 +6455,8 @@ function _current_topology_call_targets( "accepts at most one requested object.", ) default_scope = _default_dependency_scope(model, context.object_id) - unresolved_ids = ObjectId[] + I = keytype(model.registry.objects) + unresolved_ids = I[] callee_application_ids = Symbol[] for object_id in requested_ids if !_selector_matches_object_id( @@ -6495,16 +6513,13 @@ function _current_topology_call_targets( # A previous explicit call may already have consumed the structural # delta. Independently ensure the selected targets' streams exist; # this stays bounded by this call's selection on a clean topology. - selected_target_keys = Tuple{Symbol,ObjectId}[] + selected_target_keys = Tuple{Symbol,I}[] for application_id in callee_application_ids - application = _compiled_application_by_id(compiled, application_id) - for object_id in requested_ids - _call_binding_target_matches( - selected_binding, - application, - object_id, - ) || continue - push!(selected_target_keys, (application_id, object_id)) + _compiled_application_by_id(compiled, application_id) do application + for object_id in requested_ids + _call_binding_target_matches(selected_binding, application, object_id) || continue + push!(selected_target_keys, (application_id, object_id)) + end end end _initialize_model_output_streams!( diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 03f7f3434..82751ede4 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -244,6 +244,48 @@ function closed_registry_model(model) model.revision, model.environment_revision) end +@testset "input refresh references use the closed mixed identity domain" begin + organ = (:tree, :leaf, 1) + model = closed_registry_model(CompositeModel( + Object(:source; scale=:Leaf), Object(:reader; scale=:Reader), + Object(organ; scale=:Reader); + applications=( + ModelSpec(Writer(2f0); name=:source, on=One(id=:source)), + ModelSpec(PairReader{Float32}(); name=:reader, on=Many(scale=:Reader), + inputs=(left=One(SceneScope(); id=:source, var=:x), + right=One(SceneScope(); id=:source, var=:y))), + ), environment=(duration=Hour(1),))) + simulation = run!(model; steps=0, outputs=:all) + bindings = simulation.compiled.input_bindings + references = PSE._model_input_status_references(model.registry.objects, bindings) + I = keytype(model.registry.objects) + @test I === Union{ObjectId{Symbol},ObjectId{Tuple{Symbol,Symbol,Int}}} + @test keytype(references) === Tuple{Symbol,I,Symbol} + @test length(references) == 4 + for binding in bindings + key = (binding.application_id, binding.consumer_id, binding.input) + @test references[key] === input_carrier(binding) + end + continue!(simulation) + @test model_status(model,:reader).total === 6f0 + @test model_status(model,organ).total === 6f0 + newborn = (:tree, :leaf, 2) + register_object!(model, Object(newborn; scale=:Reader)) + step!(simulation) + @test model_status(model,newborn).total === 6f0 + @test outputs(simulation)[(:reader,ObjectId(newborn),:total)] == [(2.0,6f0)] + for (key, reference) in references + @test reference === PSE.refvalue(model_status(model,key[2]),key[3]) + end + refreshed = PSE._model_input_status_references(model.registry.objects, + simulation.compiled.input_bindings) + @test length(refreshed) == 6 + for variable in (:left, :right) + @test refreshed[(:reader,ObjectId(newborn),variable)] === + PSE.refvalue(model_status(model,newborn),variable) + end +end + @testset "prepared routes retain fresh producer policies and closed identity types" begin policy = Ref{PSE.SchedulePolicy}(HoldLast()) model = pair_model(; policy) diff --git a/test/test-model-newborn-context-initializer.jl b/test/test-model-newborn-context-initializer.jl index 77138850b..61befb389 100644 --- a/test/test-model-newborn-context-initializer.jl +++ b/test/test-model-newborn-context-initializer.jl @@ -78,4 +78,39 @@ end @test outputs(simulation)[(:leaf,ObjectId(:born),:draw)] == [(3.0,second_draw)] end +struct BoundLeaf <: AbstractNewborn_Context_LeafModel end +PSE.inputs_(::BoundLeaf) = (day=Required(Int),) +PSE.outputs_(::BoundLeaf) = + (calls=0, draw=0.0, seen_time=0.0, seen_T=0f0, allowed=true, seen=0) +function PSE.run!(::BoundLeaf, status, environment, constants, context) + status.calls += 1 + status.seen = status.day + return nothing +end + +@testset "newborn initializer prepares bound inputs with canonical references" begin + model = CompositeModel(Object(:owner; scale=:Scene, status=Status(seed=12)); + applications=( + ModelSpec(Creator(); name=:creator, on=One(id=:owner), + calls=(initialize=Initializer(One(scale=:Leaf, within=Subtree(), + application=:bound_leaf)),)), + ModelSpec(BoundLeaf(); name=:bound_leaf, on=Many(scale=:Leaf), + inputs=(day=One(scale=:Scene, within=Ancestor(scale=:Scene), + from_status=true, var=:seed),)), + ), environment=(T=3f0,duration=Hour(1))) + simulation = run!(model; steps=2, outputs=:all) + born = model_status(model,:born) + source = PSE.refvalue(model_status(model,:owner),:seed) + @test born.calls == 1 + @test born.seen == 12 + @test PSE.refvalue(born,:day) === source + @test isempty(get(outputs(simulation),(:bound_leaf,ObjectId(:born),:seen),[])) + source[] = 13 + continue!(simulation; steps=1) + @test born.calls == 2 + @test born.seen == 13 + @test PSE.refvalue(born,:day) === source + @test outputs(simulation)[(:bound_leaf,ObjectId(:born),:seen)] == [(3.0,13)] +end + end From 265c1c56c36f819e57cee5806a104764d7a9c05e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 01:39:55 +0100 Subject: [PATCH 238/324] Share input binding preparation across initial, growth and targeted calls --- src/composite_model/compilation.jl | 60 +++++++++++++------------- src/composite_model/runtime_outputs.jl | 46 ++++++-------------- 2 files changed, 43 insertions(+), 63 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 5740f7007..216f77e0c 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5033,25 +5033,14 @@ function _extend_compiled_scene( rebuild_dynamic_input_index |= rebuilt end previous_binding_count = length(input_bindings) - let many_binding_cache = many_binding_cache - recorder = _AddedConsumerInputBindings( - model, many_binding_cache, changed_bindings, input_bindings_by_target, - ) - for partial in added_applications - _with_model_application(applications_by_id, partial) do application - isempty(application.target_ids) && return nothing - _with_metadata_entry( - compiled.scenario_plan.input_recipes_by_application, application.id, - ) do recipe - _compile_application_consumer_bindings!( - input_bindings, model, application, recipe, manual_application_ids, - applications_by_object, applications_by_id, distributed_outputs, - many_binding_cache, performance, recorder, - ) - end - end - end - end + recorder = _AddedConsumerInputBindings( + model, many_binding_cache, changed_bindings, input_bindings_by_target, + ) + _compile_model_input_bindings!( + input_bindings, model, added_applications, manual_application_ids, + compiled.scenario_plan.input_recipes_by_application, distributed_outputs, + applications_by_object, applications_by_id, many_binding_cache, performance, recorder, + ) dynamic_input_binding_indices = if rebuild_dynamic_input_index many_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -9007,13 +8996,24 @@ function _compile_model_input_bindings( by_id=_applications_by_id(applications), ) bindings = _model_input_binding_storage(input_binding_storage) - for application in applications - isempty(application.target_ids) && continue - recipe = _application_plans(input_recipes_by_application, application.id) - _compile_application_consumer_bindings!( - bindings, model, application, recipe, manual_application_ids, - by_object, by_id, distributed_outputs, - ) + return _compile_model_input_bindings!(bindings, model, applications, manual_application_ids, + input_recipes_by_application, distributed_outputs, by_object, by_id) +end + +function _compile_model_input_bindings!(bindings, model, applications, manual_application_ids, + recipes, distributed_outputs, by_object, by_id, many_binding_cache=nothing, + performance=nothing, recorder=nothing, +) + for partial in applications + isempty(partial.target_ids) && continue + _with_model_application(by_id, partial) do application + _with_metadata_entry(recipes, application.id) do recipe + _compile_application_consumer_bindings!( + bindings, model, application, recipe, manual_application_ids, + by_object, by_id, distributed_outputs, many_binding_cache, performance, recorder, + ) + end + end end return bindings end @@ -9575,7 +9575,7 @@ end function _matching_callee_applications(applications, object_id::ObjectId, proc, application_name_filter) matches = Symbol[] - for entry in get(applications, object_id, Any[]) + for entry in get(applications, object_id, ()) application = entry::CompiledModelApplication plan = getfield(application, :plan)::CompiledApplicationPlan isnothing(proc) || getfield(plan, :process) == proc || continue @@ -9697,12 +9697,12 @@ function _compile_call_plan_binding!( Symbol[plan.potential_callee_application_ids...], ) else - object_ids = _dependency_object_ids( + object_ids = _application_target_ids(model, _dependency_object_ids( model, selector, plan.matcher, consumer_id, - ) + )) application_ids = Symbol[] for object_id in object_ids append!( @@ -9746,7 +9746,7 @@ function _compile_call_plan_binding!( CompiledModelCallBinding( plan, consumer_id, - _application_target_ids(model, callee_object_ids), + callee_object_ids, callee_application_ids, ), ) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index ba2686560..318761a87 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5799,10 +5799,7 @@ mutable struct _TargetedTopologyRuntime{CS,MA,I,S,O} <: AbstractTargetedTopologyRuntime compiled::CS model_revision::Int - application_sets::Dict{ - Tuple{Vararg{I}}, - Union{Nothing,S}, - } + application_sets::Dict{Tuple{Vararg{I}},S} added_applications_by_object::O indexed_addition_count::Int manual_application_ids::MA @@ -5841,7 +5838,7 @@ function _targeted_topology_runtime!( runtime = Runtime( compiled, model.revision, - Dict{Tuple{Vararg{I}},Union{Nothing,S}}(), + Dict{Tuple{Vararg{I}},S}(), O(), 0, manual, @@ -5899,15 +5896,13 @@ function _targeted_application_set!( model::CompositeModel, requested_ids, ) where {CS,MA,I} - key = Tuple(requested_ids) + key = Tuple(requested_ids)::Tuple{Vararg{I}} application_set = get!(runtime.application_sets, key) do - applications = _new_object_applications( + output_applications, added_applications_by_object = _new_object_applications( model, runtime.compiled, requested_ids, ) - isnothing(applications) && return nothing - output_applications, added_applications_by_object = applications merge!( runtime.added_applications_by_object, added_applications_by_object, @@ -5921,7 +5916,6 @@ function _targeted_application_set!( false, ) end - isnothing(application_set) && return nothing # A fully initialized source can be registered without an explicit call. # Include its application membership before resolving newborn inputs. The @@ -5930,19 +5924,18 @@ function _targeted_application_set!( added = lifecycle_delta(model).added unindexed_ids = nothing for index in (runtime.indexed_addition_count + 1):length(added) - object_id = added[index].id + object_id = added[index].id::I haskey(runtime.added_applications_by_object, object_id) && continue isnothing(unindexed_ids) && (unindexed_ids = I[]) - push!(unindexed_ids, object_id::I) + push!(unindexed_ids, object_id) end if !isnothing(unindexed_ids) - applications = _new_object_applications( + _, unindexed_applications = _new_object_applications( model, runtime.compiled, unindexed_ids, ) - isnothing(applications) && return nothing - merge!(runtime.added_applications_by_object, last(applications)) + merge!(runtime.added_applications_by_object, unindexed_applications) end runtime.indexed_addition_count = length(added) return application_set @@ -6124,13 +6117,6 @@ function _targeted_new_object_call_targets( model, requested_ids, ) - if isnothing(application_set) - initializer && error( - "Initializer `$(name)` could not compile its newly registered target " * - "against the scheduled application selector.", - ) - return nothing - end output_applications = application_set.applications callee_applications = _targeted_callee_applications( binding, @@ -6182,17 +6168,11 @@ function _prepare_targeted_newborn_targets( application_set.outputs_prepared = true end input_bindings = similar(compiled.input_bindings, 0) - for application in callee_applications - isempty(application.target_ids) && continue - recipe = _application_plans( - compiled.scenario_plan.input_recipes_by_application, application.id, - ) - _compile_application_consumer_bindings!( - input_bindings, model, application, recipe, - targeted_runtime.manual_application_ids, applications_by_object, - compiled.applications_by_id, compiled.distributed_outputs, - ) - end + _compile_model_input_bindings!( + input_bindings, model, callee_applications, targeted_runtime.manual_application_ids, + compiled.scenario_plan.input_recipes_by_application, compiled.distributed_outputs, + applications_by_object, compiled.applications_by_id, + ) final_input_references = _model_input_status_references( model.registry.objects, input_bindings) _prepare_model_input_statuses_batched!( From 6f09dca2d32b1a79ca93ae35ae5a0bb735319a6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 01:40:10 +0100 Subject: [PATCH 239/324] Use the prepared object identity domain for subtree moves and removals --- src/composite_model/registry_topology.jl | 138 +++++++++-------------- test/test-model-api-stabilization.jl | 37 ++++++ 2 files changed, 90 insertions(+), 85 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 440b291d3..39a0a1b6a 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1419,7 +1419,8 @@ function _refresh_object_ancestor_ids!( ancestors = _append_object_ancestor_id(parent_ancestors, object_id) model.registry.ancestor_ids_by_object[object_id] = ancestors object = _model_object(model, object_id) - for child_id in object.children + for raw_child_id in object.children + child_id = _index_object_id(model.registry.objects, raw_child_id) _refresh_object_ancestor_ids!( model, child_id, @@ -1673,60 +1674,42 @@ end function _remove_child_link!(model::CompositeModel, parent_id, child_id::ObjectId) isnothing(parent_id) && return nothing - parent_object = _model_object(model, parent_id) + parent_object = _model_object(model, _index_object_id(model.registry.objects, parent_id)) filter!(!=(child_id), parent_object.children) return nothing end -function _instance_roots_in_subtree( - model::CompositeModel, - root_id::ObjectId, - descendant_ids=_descendant_ids(model, root_id), -) +function _mutable_subtree_ids(model::CompositeModel, root_id::ObjectId, operation::Symbol) + descendant_ids = _descendant_ids(model, root_id) + isempty(model.instances) && return descendant_ids subtree_ids = Set(descendant_ids) - roots = ObjectId[ - _instance_root_id(instance) for instance in model.instances - if _instance_root_id(instance) in subtree_ids - ] - return _sort_object_ids!(roots) -end - -function _validate_mutable_object_subtree!( - model::CompositeModel, - object::Object, - operation::Symbol, - descendant_ids=_descendant_ids(model, object.id), -) - instance_roots = _instance_roots_in_subtree( - model, - object.id, - descendant_ids, - ) - isempty(instance_roots) && return nothing + instance_roots = similar(descendant_ids, 0) + for instance in model.instances + id = _instance_root_id(instance) + id in subtree_ids && push!(instance_roots, _index_object_id(model.registry.objects, id)) + end + isempty(instance_roots) && return descendant_ids + _sort_object_ids!(instance_roots) error( - "Cannot $(operation) object `$(_object_id_text(object.id))` because its subtree contains ", - "immutable ObjectInstance root(s) `$([id.value for id in instance_roots])`. ", + "Cannot $(operation) object `$(_object_id_text(root_id))` because its subtree contains ", + "immutable ObjectInstance root(s) `", join((_object_id_text(id) for id in instance_roots), ", "), "`. ", "Mutate ordinary instance descendants instead.", ) end function remove_object!(model::CompositeModel, id; recursive::Bool=true) object = _model_object(model, id) - descendant_ids = _descendant_ids(model, object.id) - _validate_mutable_object_subtree!( - model, - object, - :remove, - descendant_ids, - ) + objects = model.registry.objects + root_id = _index_object_id(objects, object.id) + descendant_ids = _mutable_subtree_ids(model, root_id, :remove) if !recursive && !isempty(object.children) - error("Cannot remove object `$(_object_id_text(object.id))` with children unless `recursive=true`.") + error("Cannot remove object `$(_object_id_text(root_id))` with children unless `recursive=true`.") end snapshots = LifecycleObjectSnapshot[ _lifecycle_object_snapshot(model, _model_object(model, object_id)) for object_id in descendant_ids ] - _remove_child_link!(model, object.parent, object.id) + _remove_child_link!(model, object.parent, root_id) adapter = model.source_adapter for object_id in Iterators.reverse(descendant_ids) removed = _model_object(model, object_id) @@ -1745,48 +1728,42 @@ end function reparent_object!(model::CompositeModel, id, new_parent) object = _model_object(model, id) - descendant_ids = _descendant_ids(model, object.id) - _validate_mutable_object_subtree!( - model, - object, - :reparent, - descendant_ids, - ) - new_parent_id = isnothing(new_parent) ? nothing : ObjectId(new_parent) - if !isnothing(new_parent_id) - haskey(model.registry.objects, new_parent_id) || error("No model object with id `$(_object_id_text(new_parent_id))`.") - new_parent_id == object.id && error( - "Cannot reparent object `$(_object_id_text(object.id))` to itself.", + objects = model.registry.objects + root_id = _index_object_id(objects, object.id) + descendant_ids = _mutable_subtree_ids(model, root_id, :reparent) + parent = isnothing(new_parent) ? nothing : _model_object(model, new_parent) + new_parent_id = if !isnothing(parent) + parent_id = _index_object_id(objects, parent.id) + parent_id == root_id && error( + "Cannot reparent object `$(_object_id_text(root_id))` to itself.", ) - new_parent_id in descendant_ids && error( - "Cannot reparent object `$(_object_id_text(object.id))` below its descendant `$(_object_id_text(new_parent_id))`.", + parent_id in descendant_ids && error( + "Cannot reparent object `$(_object_id_text(root_id))` below its descendant `$(_object_id_text(parent_id))`.", ) + parent_id end - old_parent_id = object.parent - old_ancestors_by_object = Dict{ObjectId,Tuple}( - descendant_id => Tuple( - _object_ancestor_ids(model.registry, descendant_id), - ) - for descendant_id in descendant_ids - ) - _remove_child_link!(model, old_parent_id, object.id) + old_parent_id = isnothing(object.parent) ? nothing : _index_object_id(objects, object.parent) + old_ancestors_by_object = Dict{ObjectId,Tuple}() + for descendant_id in descendant_ids + old_ancestors_by_object[descendant_id] = Tuple(_object_ancestor_ids(model.registry, descendant_id)) + end + _remove_child_link!(model, old_parent_id, root_id) object.parent = new_parent_id - if !isnothing(new_parent_id) - parent_object = _model_object(model, new_parent_id) - object.id in parent_object.children || push!(parent_object.children, object.id) + if !isnothing(parent) + root_id in parent.children || push!(parent.children, root_id) end parent_ancestors = isnothing(new_parent_id) ? ObjectId[] : _object_ancestor_ids(model.registry, new_parent_id) _refresh_object_ancestor_ids!( model, - object.id, + root_id, parent_ancestors, ) push!( model.lifecycle_delta.reparented, LifecycleReparentEvent( - object.id, + root_id, Tuple(descendant_ids), old_parent_id, new_parent_id, @@ -1803,25 +1780,16 @@ end function update_geometry!(model::CompositeModel, id, geometry_or_position; invalidate_environment::Bool=true) object = _model_object(model, id) + invalidate_environment || return update_geometry!(object, geometry_or_position) + root_id = _index_object_id(model.registry.objects, object.id) + affected_object_ids = keytype(model.registry.objects)[root_id] + _append_geometry_inheriting_descendants!(affected_object_ids, model, root_id) old_geometry = object.geometry - affected_object_ids = ObjectId[object.id] - invalidate_environment && append!( - affected_object_ids, - _geometry_inheriting_descendants(model, object.id), - ) object.geometry = geometry_or_position - if invalidate_environment - push!( - model.lifecycle_delta.moved, - LifecycleMoveEvent( - object.id, - Tuple(affected_object_ids), - old_geometry, - geometry_or_position, - ), - ) - _mark_environment_bindings_dirty!(model, affected_object_ids) - end + push!(model.lifecycle_delta.moved, LifecycleMoveEvent( + root_id, Tuple(affected_object_ids), old_geometry, geometry_or_position, + )) + _mark_environment_bindings_dirty!(model, affected_object_ids) return object end @@ -1853,13 +1821,13 @@ _geometry_bounds(_) = nothing bounds(object::Object) = _geometry_bounds(geometry(object)) bounds(status::Status) = _geometry_bounds(geometry(status)) -function _geometry_inheriting_descendants(model::CompositeModel, root_id::ObjectId) - ids = ObjectId[] - for child_id in _model_object(model, root_id).children +function _append_geometry_inheriting_descendants!(ids, model::CompositeModel, root_id::ObjectId) + for raw_child_id in _model_object(model, root_id).children + child_id = _index_object_id(model.registry.objects, raw_child_id) child = _model_object(model, child_id) isnothing(geometry(child)) || continue push!(ids, child_id) - append!(ids, _geometry_inheriting_descendants(model, child_id)) + _append_geometry_inheriting_descendants!(ids, model, child_id) end return ids end diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index dfbf81b19..ac40b1a0d 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -819,6 +819,43 @@ end @test Advanced.compiled_bindings(model).scenario_plan === scenario_plan end +@testset "moves journal the shared geometry of a mixed-id subtree" begin + original = [1.0] + replacement = [2.0] + model = CompositeModel( + Object(:tree; geometry=original), + Object(12; parent=:tree), + Object(:tip; parent=12), + Object(13; parent=:tree, geometry=(x=0,)), + Object(:other_tip; parent=13), + ) + Advanced.refresh_environment_bindings!(model) + revision = Advanced.environment_revision(model) + move_object!(model, :tree, replacement) + event = only(Advanced.lifecycle_delta(model).moved) + @test event.affected_object_ids == (ObjectId(:tree), ObjectId(12), ObjectId(:tip)) + @test event.old_geometry === original + @test event.new_geometry === replacement + @test Advanced.environment_revision(model) == revision + 1 + + moved = update_geometry!(model, 12, original; invalidate_environment=false) + @test moved.geometry === original + @test only(Advanced.lifecycle_delta(model).moved) === event + @test Advanced.environment_revision(model) == revision + 1 + + reparent_object!(model, 12, 13) + reparented = only(Advanced.lifecycle_delta(model).reparented) + @test reparented.old_ancestors_by_object[ObjectId(:tip)] == + (ObjectId(:tree), ObjectId(12), ObjectId(:tip)) + @test reparented.new_parent == ObjectId(13) + remove_object!(model, 12) + removed = Advanced.lifecycle_delta(model).removed + @test Tuple(snapshot.id for snapshot in removed) == (ObjectId(12), ObjectId(:tip)) + @test first(removed).geometry === original + @test last(removed).ancestors == + (ObjectId(:tree), ObjectId(13), ObjectId(12), ObjectId(:tip)) +end + @testset "lifecycle delta supports partial cache consumption" begin model = CompositeModel( Object(:scene; scale=:Scene); From 358f982a36f11adccc8db3894bd070afed3dc73a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 02:21:55 +0100 Subject: [PATCH 240/324] Reuse current call contexts through one owner and descendant check --- src/composite_model/runtime_outputs.jl | 107 ++++++++------------- test/test-model-prepared-growth-schemas.jl | 5 +- 2 files changed, 42 insertions(+), 70 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 318761a87..d4ae2788a 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6599,14 +6599,6 @@ function commit_environment!(context, state) ) end -# CallTargets store override metadata behind Any; changing the override does -# not change the concrete child-call tuple. Recover the context type without -# erasing the normal no-override execution path. -@inline _call_context_type( - ::RunContext{CS,A,CT,BI,OT,TS,OR,C,OldE,I,EB}, ::E, -) where {CS,A,CT,BI,OT,TS,OR,C,OldE,I,EB,E} = RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I,EB} -@inline _call_context_type(::Nothing, environment) = RunContext - # Metadata already proved current needs only invocation values synchronized. # Keep this small boundary usable when a stale owner's new descendant tuple # differs from its original default type, without reboxing all owner metadata. @@ -6626,7 +6618,7 @@ end return _call_context_bindings_match(Base.tail(calls), Base.tail(bindings)) end -@inline function _call_context_matches( +@inline function _call_context_is_current( context::RunContext, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, environment, @@ -6638,24 +6630,27 @@ end context.temporal_streams === temporal_streams && context.output_retention === output_retention && context.constants === constants && _call_context_bindings_match(context.calls, call_bindings) && - typeof(context.environment) === typeof(environment) + typeof(context.environment) === typeof(environment) && + _call_context_preparation_is_current(context.calls, compiled, environment_bindings, + temporal_streams, output_retention, constants) end -@inline _call_context_matches(::Nothing, args...) = false -@inline function _call_context_clone_is_current( - context::RunContext, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, +@inline function _call_context_clone_is_current(context::RunContext, compiled, environment_bindings, + application, object_id, bound_inputs, output_targets, call_bindings, temporal_streams, + output_retention, constants, ) - # The context identity guard also protects an empty descendant template: - # no per-child stamp exists to prove it still describes another generation. - return _call_context_matches( - context, compiled, environment_bindings, application, object_id, + return _call_context_is_current(context, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, - context.environment, - ) && _call_context_preparation_is_current( - context.calls, compiled, environment_bindings, temporal_streams, - output_retention, constants, - ) + context.environment) +end + +# A cached trial may have a different descendant tuple after growth. Its +# owners, override and empty-call case are all fixed by the current invocation. +@inline function _cached_call_context_type(compiled::CS, bindings::EB, application::A, id::I, + inputs::BI, targets::OT, calls::Tuple, streams::TS, retention::OR, constants::C, environment::E, +) where {CS,EB,A,I,BI,OT,TS,OR,C,E} + isempty(calls) && return RunContext{CS,A,Tuple{},BI,OT,TS,OR,C,E,I,EB} + return RunContext{CS,A,CT,BI,OT,TS,OR,C,E,I,EB} where {CT<:Tuple} end @inline function _prepare_cached_call_context!( @@ -6663,57 +6658,31 @@ end application, object_id, bound_inputs, output_targets, call_bindings::Tuple, temporal_streams, output_retention, time, constants, publication_allowed, environment, ) - Context = _call_context_type(cache.default, environment) - context = reuse ? cache.default : nothing - if !(context isa Context && _call_context_matches( - context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, - environment, - ) && _call_context_preparation_is_current( - context.calls, compiled, environment_bindings, temporal_streams, - output_retention, constants, - )) - context = reuse ? cache.transient : nothing - if context isa RunContext && !(context isa Context) && - _call_context_matches( - context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, - constants, environment, - ) && _call_context_clone_is_current( - context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, - ) - # A stale OptionalOne can have acquired a different descendant tuple - # type. Reuse that current transient rather than forcing the old - # default's Context type and rebuilding it on every invocation. - return _synchronize_current_call_context!( - context, time, publication_allowed, environment, - ) + if reuse + context = cache.default + if context isa RunContext && _call_context_is_current(context, compiled, environment_bindings, + application, object_id, bound_inputs, output_targets, call_bindings, temporal_streams, + output_retention, constants, environment) + return _synchronize_current_call_context!(context, time, publication_allowed, environment) end - if !(context isa Context && _call_context_matches( - context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, constants, - environment, - ) && _call_context_preparation_is_current( - context.calls, compiled, environment_bindings, temporal_streams, - output_retention, constants, - )) - # A reentrant call needs its own descendants as well as its shell: - # child CallTargets carry mutable time, environment and permission. - context = _prepare_model_execution_context!( - cache.default, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, - time, constants, publication_allowed, environment; fresh=true, - ) - reuse && (cache.transient = context) - return context + Context = _cached_call_context_type(compiled, environment_bindings, application, + object_id, bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, + constants, environment) + transient = cache.transient + if transient isa Context && _call_context_is_current(transient, compiled, environment_bindings, + application, object_id, bound_inputs, output_targets, call_bindings, temporal_streams, + output_retention, constants, environment) + return _synchronize_current_call_context!(transient, time, publication_allowed, environment) end end - return _prepare_model_execution_context!( - context::Context, compiled, environment_bindings, application, object_id, + # Reentrant calls need their own descendant views as well as their shell. + fresh = _prepare_model_execution_context!( + cache.default, compiled, environment_bindings, application, object_id, bound_inputs, output_targets, call_bindings, temporal_streams, output_retention, - time, constants, publication_allowed, environment, + time, constants, publication_allowed, environment; fresh=true, ) + reuse && (cache.transient = fresh) + return fresh end @inline function _record_call_execution!(cache) diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index 1bada54dc..5f55b6a5c 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -240,7 +240,10 @@ call_key(target) = (target.application.id, target.object_id.value) @test fieldtype(typeof(context), :environment_bindings) === typeof(current_owner) @test fieldtype(typeof(target.context_cache.default), :environment_bindings) === typeof(partial_owner) - TrialContext = PSE._call_context_type(target.context_cache.default, (T=9f0,)) + TrialContext = PSE._cached_call_context_type(target.compiled, partial_owner, + target.application, target.object_id, target.bound_inputs, target.output_targets, + target.execution_target.call_bindings, target.temporal_streams, target.output_retention, + target.constants, (T=9f0,)) @test fieldtype(TrialContext, :environment_bindings) === typeof(partial_owner) @test context.environment_bindings === current_owner @test only(partial_owner.bindings).object_id == ObjectId(:leaf) From f99bd0a86e9f361afb6ed9a9403eb73dd4e7c4af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 02:22:49 +0100 Subject: [PATCH 241/324] Cover descendants created by an MTG accessor before a newborn is rejected --- test/test-organ-status-assembly.jl | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index aae47895f..5df1a9af7 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -102,6 +102,28 @@ end @test PSE.refvalue(newborn, :seed) === PSE.refvalue(given, :seed) end +@testset "a failing MTG accessor preserves a descendant it already attached" begin + root = MTG.Node(MTG.NodeMTG(:/, :Plant, 1, 1)) + newborn = Ref{typeof(root)}() + tip = Ref{typeof(root)}() + function kind(node) + MTG.symbol(node) === :Leaf || return :plant + @test MTG.parent(node) === root && only(MTG.children(root)) === node + newborn[] = node + tip[] = MTG.Node(MTG.node_id(node) + 1, node, MTG.NodeMTG(:<, :Tip, 1, 2), (;)) + throw(ArgumentError("rejected leaf")) + end + model = CompositeModel(root; kind) + @test_throws "rejected leaf" add_organ!(root, model, :+, :Leaf, 2) + @test isnothing(MTG.parent(newborn[])) && isempty(MTG.children(newborn[])) + @test only(MTG.children(root)) === tip[] + @test MTG.parent(tip[]) === root && MTG.link(tip[]) === :+ + @test isnothing(MTG.get_node(root, MTG.node_id(newborn[]))) + @test MTG.get_node(root, MTG.node_id(tip[])) === tip[] + @test_throws ArgumentError object_id(model, newborn[]) + @test object_id(model, root) == ObjectId(MTG.node_id(root)) +end + @testset "the initial data grammar has one Status construction path" begin payload = Float32[1, 2] for source in ((value=3f0, payload=payload), Dict(:value=>3f0, :payload=>payload), From b99ea687a5a9229119ca87f7b6ef7abd5ee2e7b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 02:23:44 +0100 Subject: [PATCH 242/324] Write coupling and input validation errors with their concrete values --- src/composite_model/compilation.jl | 4 ++-- src/composite_model/environment_bindings.jl | 6 ++++-- src/composite_model/runtime_outputs.jl | 2 +- src/composite_model/selectors.jl | 2 +- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 216f77e0c..3d4f8139d 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8005,8 +8005,8 @@ function _temporal_source_application( return last(sort!(matches; by=application_id -> application_positions[application_id])) end io = IOBuffer() - print(io, "Temporal model input `", binding.input, "` from `", - _object_id_text(source_id), '.', binding.source_var, + print(io, "Temporal model input `", String(binding.input), "` from `", + _object_id_text(source_id), ".", String(binding.source_var), "` has ambiguous source applications `") _print_selector_diagnostic(io, matches, Any[]) print(io, "`. Add `application=...` to the `inputs=...` selector.") diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 4d8477402..cc158bcce 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -665,8 +665,10 @@ function _validate_model_environment_inputs!(bindings, applications_by_id, end end isempty(missing_details) && return nothing - details = join(missing_details, "; ") - error("Composite model environment is missing required source inputs: ", details) + io = IOBuffer() + print(io, "Composite model environment is missing required source inputs: ") + join(io, missing_details, "; ") + error(String(take!(io))) end struct PreparedGlobalEnvironmentRows{R} diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index d4ae2788a..5bd2cc5f0 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -7767,7 +7767,7 @@ function _incremental_output_request_object_ids(delta) end function _continue_scene!(simulation::Simulation, steps::Integer) - steps >= 0 || throw(ArgumentError("`steps` must be non-negative, got $(steps).")) + steps >= 0 || throw(ArgumentError("`steps` must be non-negative, got $(string(steps)).")) if iszero(steps) _refresh_timeline!(simulation, simulation.execution_plan.topology) return simulation diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 5e24fb7c6..530e99ad6 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1301,7 +1301,7 @@ function _selector_resolution_error( ancestors = Any[] print(io, "Expected ", expected, " object for selector `") _print_selector_diagnostic(io, selector, ancestors) - print(io, "`, got ", length(matched_ids), ". context=") + print(io, "`, got ", string(length(matched_ids)), ". context=") _print_selector_diagnostic(io, context_id, ancestors) print(io, ", matched_ids=") _print_selector_diagnostic(io, matched_ids, ancestors) From 5e8359dca775d78426d7b63a453719febcd76df7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 02:23:54 +0100 Subject: [PATCH 243/324] Resolve a subtree parent once when unlinking or moving its root --- src/composite_model/registry_topology.jl | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 39a0a1b6a..6731f4f6d 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1672,11 +1672,13 @@ function add_organ!( end end -function _remove_child_link!(model::CompositeModel, parent_id, child_id::ObjectId) - isnothing(parent_id) && return nothing - parent_object = _model_object(model, _index_object_id(model.registry.objects, parent_id)) +function _unlink_from_parent!(model::CompositeModel, object::Object, child_id::ObjectId) + parent = object.parent + isnothing(parent) && return nothing + parent_id = _index_object_id(model.registry.objects, parent) + parent_object = _model_object(model, parent_id) filter!(!=(child_id), parent_object.children) - return nothing + return parent_id end function _mutable_subtree_ids(model::CompositeModel, root_id::ObjectId, operation::Symbol) @@ -1686,7 +1688,7 @@ function _mutable_subtree_ids(model::CompositeModel, root_id::ObjectId, operatio instance_roots = similar(descendant_ids, 0) for instance in model.instances id = _instance_root_id(instance) - id in subtree_ids && push!(instance_roots, _index_object_id(model.registry.objects, id)) + id isa eltype(descendant_ids) && id in subtree_ids && push!(instance_roots, id) end isempty(instance_roots) && return descendant_ids _sort_object_ids!(instance_roots) @@ -1709,7 +1711,7 @@ function remove_object!(model::CompositeModel, id; recursive::Bool=true) _lifecycle_object_snapshot(model, _model_object(model, object_id)) for object_id in descendant_ids ] - _remove_child_link!(model, object.parent, root_id) + _unlink_from_parent!(model, object, root_id) adapter = model.source_adapter for object_id in Iterators.reverse(descendant_ids) removed = _model_object(model, object_id) @@ -1742,12 +1744,13 @@ function reparent_object!(model::CompositeModel, id, new_parent) ) parent_id end - old_parent_id = isnothing(object.parent) ? nothing : _index_object_id(objects, object.parent) old_ancestors_by_object = Dict{ObjectId,Tuple}() for descendant_id in descendant_ids - old_ancestors_by_object[descendant_id] = Tuple(_object_ancestor_ids(model.registry, descendant_id)) + get!(old_ancestors_by_object, descendant_id) do + Tuple(_object_ancestor_ids(model.registry, descendant_id)) + end end - _remove_child_link!(model, old_parent_id, root_id) + old_parent_id = _unlink_from_parent!(model, object, root_id) object.parent = new_parent_id if !isnothing(parent) root_id in parent.children || push!(parent.children, root_id) From 482cfbfb02d9198aac729994ab18d43b7772309a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 03:31:46 +0100 Subject: [PATCH 244/324] Bind the newborn application cache type on Julia 1.10 --- src/composite_model/runtime_outputs.jl | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 5bd2cc5f0..16d327478 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5795,11 +5795,11 @@ mutable struct _TargetedApplicationSet{A,B} outputs_prepared::Bool end -mutable struct _TargetedTopologyRuntime{CS,MA,I,S,O} <: +mutable struct _TargetedTopologyRuntime{CS,MA,D<:Dict,O} <: AbstractTargetedTopologyRuntime compiled::CS model_revision::Int - application_sets::Dict{Tuple{Vararg{I}},S} + application_sets::D added_applications_by_object::O indexed_addition_count::Int manual_application_ids::MA @@ -5828,7 +5828,8 @@ function _targeted_topology_runtime!( O = Dict{I,Vector{A}} S = _TargetedApplicationSet{Vector{A},_ApplicationsByObjectOverlay{typeof(compiled.applications_by_object),O}} manual = compiled.scenario_plan.manual_application_ids - Runtime = _TargetedTopologyRuntime{typeof(compiled),typeof(manual),I,S,O} + D = Dict{Tuple{Vararg{I}},S} + Runtime = _TargetedTopologyRuntime{typeof(compiled),typeof(manual),D,O} cached = delta.targeted_topology_runtime if cached isa Runtime && cached.compiled === compiled && @@ -5838,7 +5839,7 @@ function _targeted_topology_runtime!( runtime = Runtime( compiled, model.revision, - Dict{Tuple{Vararg{I}},S}(), + D(), O(), 0, manual, @@ -5892,10 +5893,11 @@ function _new_object_applications( end function _targeted_application_set!( - runtime::_TargetedTopologyRuntime{CS,MA,I}, + runtime::_TargetedTopologyRuntime, model::CompositeModel, requested_ids, -) where {CS,MA,I} +) + I = keytype(runtime.added_applications_by_object) key = Tuple(requested_ids)::Tuple{Vararg{I}} application_set = get!(runtime.application_sets, key) do output_applications, added_applications_by_object = _new_object_applications( From 29f8fa66cff65493053bd8a1d859a00e3016f68c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 03:33:30 +0100 Subject: [PATCH 245/324] Preserve the prepared types of newborn statuses and geometry events --- src/composite_model/registry_topology.jl | 10 ++++++++-- test/test-model-api-stabilization.jl | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 6731f4f6d..9b43a528c 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1664,7 +1664,7 @@ function add_organ!( ) registered = register_object!(model, object) adapter.max_node_id[] = max(adapter.max_node_id[], node_id) - return registered.status::Status + return _with_registered_status(identity, model.registry.objects.catalog, registered.status)::Status catch _unregister_mtg_object_identity!(adapter, node) MultiScaleTreeGraph.delete_node!(node) @@ -1784,10 +1784,16 @@ end function update_geometry!(model::CompositeModel, id, geometry_or_position; invalidate_environment::Bool=true) object = _model_object(model, id) invalidate_environment || return update_geometry!(object, geometry_or_position) + return _update_object_geometry!(model, object, object.geometry, geometry_or_position) +end + +# A caller that has already read the old geometry can preserve its concrete +# type in the event. Always journal the actual geometry of the live object. +@inline function _update_object_geometry!(model::CompositeModel, object::Object, old_geometry, geometry_or_position) root_id = _index_object_id(model.registry.objects, object.id) affected_object_ids = keytype(model.registry.objects)[root_id] _append_geometry_inheriting_descendants!(affected_object_ids, model, root_id) - old_geometry = object.geometry + object.geometry === old_geometry || throw(ArgumentError("The object's geometry changed before the update.")) object.geometry = geometry_or_position push!(model.lifecycle_delta.moved, LifecycleMoveEvent( root_id, Tuple(affected_object_ids), old_geometry, geometry_or_position, diff --git a/test/test-model-api-stabilization.jl b/test/test-model-api-stabilization.jl index ac40b1a0d..04fbf6921 100644 --- a/test/test-model-api-stabilization.jl +++ b/test/test-model-api-stabilization.jl @@ -831,6 +831,11 @@ end ) Advanced.refresh_environment_bindings!(model) revision = Advanced.environment_revision(model) + tree = model_object(model, :tree) + @test_throws ArgumentError PlantSimEngine._update_object_geometry!(model, tree, copy(original), replacement) + @test geometry(tree) === original + @test isempty(Advanced.lifecycle_delta(model).moved) + @test Advanced.environment_revision(model) == revision move_object!(model, :tree, replacement) event = only(Advanced.lifecycle_delta(model).moved) @test event.affected_object_ids == (ObjectId(:tree), ObjectId(12), ObjectId(:tip)) From 8124ece43a326db6dca94ccdf4f4901b8d385f95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 03:50:25 +0100 Subject: [PATCH 246/324] Preserve shared backing storage in compiled final-state snapshots --- src/composite_model/runtime_outputs.jl | 56 ++++++++++++++++++++++---- test/test-model-output-boundaries.jl | 37 +++++++++++++++++ 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 16d327478..f03fd38cc 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1554,23 +1554,65 @@ outputs(sim::Simulation) = sim.temporal_streams @inline _snapshot_value(value, memo) = isbitstype(typeof(value)) ? value : Base.deepcopy_internal(value, memo)::typeof(value) -# Keep the backing store shared between reshaped or offset arrays in one snapshot. -# Julia's generic Memory deepcopy erases its element type before the copy. +# Follow the deepcopy memo order while retaining the prepared container types. +# The array wrapper is recorded before its backing memory, so recursive values +# and arrays sharing that memory keep their existing alias relationships. @static if isdefined(Base, :wrap) && isdefined(Core, :Memory) - @inline function _snapshot_value(value::Array{T,N}, memo) where {T,N} - isbitstype(T) || return Base.deepcopy_internal(value, memo)::Array{T,N} + function _snapshot_memory(value::Memory{T}, memo) where {T} + haskey(memo, value) && return memo[value]::Memory{T} + if isbitstype(T) + result = copy(value) + memo[value] = result + return result + end + result = Memory{T}(undef, length(value)) + memo[value] = result + for index in eachindex(value) + if isassigned(value, index) + result[index] = _snapshot_value(value[index], memo) + end + end + return result + end + + function _snapshot_value(value::Array{T,N}, memo) where {T,N} haskey(memo, value) && return memo[value]::Array{T,N} + result = Array{T,N}(undef, ntuple(Returns(0), Val(N))) + memo[value] = result source = getfield(value, :ref) - memory = get!(() -> copy(source.mem), memo, source.mem)::Memory{T} + memory = _snapshot_memory(source.mem, memo) offset = Core.memoryrefoffset(source) first = Core.memoryref(memory) point = isone(offset) ? first : Core.memoryrefnew(first, offset, false) - result = Base.wrap(Array, point, size(value)) - memo[value] = result + setfield!(result, :ref, point) + setfield!(result, :size, size(value)) return result end end +function _snapshot_value(value::Base.RefValue{T}, memo) where {T} + haskey(memo, value) && return memo[value]::Base.RefValue{T} + result = Base.RefValue{T}() + memo[value] = result + isassigned(value) && (result[] = _snapshot_value(value[], memo)) + return result +end + +_snapshot_value(value::RefVector{T}, memo) where {T} = + RefVector{T}(_snapshot_value(parent(value), memo)) + +function _snapshot_value(value::BitArray{N}, memo) where {N} + haskey(memo, value) && return memo[value]::BitArray{N} + result = BitArray{N}(undef, ntuple(Returns(0), Val(N))) + memo[value] = result + setfield!(result, :chunks, _snapshot_value(getfield(value, :chunks), memo)) + setfield!(result, :len, length(value)) + if isdefined(value, :dims) + setfield!(result, :dims, getfield(value, :dims)) + end + return result +end + function _snapshot_status(status::Status) memo = IdDict() return _map_status_fields(ref -> _snapshot_value(ref[], memo), NamedTuple, status) diff --git a/test/test-model-output-boundaries.jl b/test/test-model-output-boundaries.jl index d5837635a..7dc587ea2 100644 --- a/test/test-model-output-boundaries.jl +++ b/test/test-model-output-boundaries.jl @@ -458,3 +458,40 @@ end for membership in target.memberships ] == [(0.0, 2.0), (5.0, 6.0)] end + +@testset "final state preserves shared reference cells and packed array storage" begin + leaf = Object(:leaf; status=Status( + columns=PlantSimEngine.RefVector{Float64}([Ref(0.0), Ref(0.0)]), + cells=Base.RefValue{Float64}[], + flags=falses(4), + matrix_flags=falses(2, 2), + chunks=UInt64[], + )) + simulation = run!(CompositeModel(leaf); steps=0) + live = model_status(simulation, :leaf) + cell = Ref(3.5) + live.columns = PlantSimEngine.RefVector{Float64}([cell, cell]) + live.cells = parent(live.columns) + live.matrix_flags = reshape(live.flags, 2, 2) + live.chunks = getfield(live.flags, :chunks) + + expected = deepcopy(NamedTuple(live)) + snapshot = final_state(simulation, :leaf) + @test typeof(snapshot) === typeof(expected) + @test snapshot.columns == expected.columns + @test snapshot.flags == expected.flags + @test snapshot.matrix_flags == expected.matrix_flags + @test parent(snapshot.columns) === snapshot.cells + @test snapshot.cells[1] === snapshot.cells[2] + @test snapshot.cells[1] !== cell + @test getfield(snapshot.flags, :chunks) === snapshot.chunks + @test getfield(snapshot.matrix_flags, :chunks) === snapshot.chunks + @test snapshot.chunks !== live.chunks + snapshot.cells[1][] = 23.0 + @test snapshot.columns[1] == snapshot.columns[2] == 23.0 + @test cell[] == 3.5 + snapshot.matrix_flags[1] = true + @test snapshot.flags[1] + @test !live.flags[1] + @test current_step(simulation) == 0 +end From 8ddcf698465e2c7654cfa46d82eb51c4e6c5ba63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 03:50:53 +0100 Subject: [PATCH 247/324] Keep producer and destination diagnostics concrete during scene preparation --- src/composite_model/compilation.jl | 112 +++++++++++++------------ src/composite_model/runtime_outputs.jl | 2 +- 2 files changed, 58 insertions(+), 56 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 3d4f8139d..ff24e4f3e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3098,13 +3098,7 @@ function _compile_consumer_input_recipe!( distributed_outputs, consumer_id, plan.source_var, matches, ) isempty(matches) && return nothing - if length(matches) > 1 - error( - "Input `$(plan.input)` on application `$(application_id)` for object `$(_object_id_text(consumer_id))` " * - "has ambiguous same-object producers: `$([match.application for match in matches])`. " * - "Add `inputs=(:$(plan.input) => One(...),)` to disambiguate." - ) - end + length(matches) > 1 && _ambiguous_input_producers(plan.input, application_id, consumer_id, matches) selected = only(matches) sources = ResolvedInputSources( _input_binding_source_ids(model.registry.objects, [consumer_id]), @@ -3127,6 +3121,18 @@ _final_inferred_output_plans( matches, ) = matches +function _ambiguous_input_producers(input::Symbol, application::Symbol, object::ObjectId, matches) + io = IOBuffer() + print(io, "Input `", String(input), "` on application `", String(application), "` for object `", + _object_id_text(object), "` has ambiguous same-object producers: ") + for (i, candidate) in enumerate(matches) + i == 1 || print(io, ", ") + print(io, "`", String(candidate.application::Symbol), "`") + end + print(io, ". Add `inputs=(:", String(input), " => One(...),)` to disambiguate.") + error(String(take!(io))) +end + function _final_inferred_output_plans( distributed_outputs::CompiledDistributedOutputs, object_id::ObjectId, @@ -5951,14 +5957,14 @@ function _validate_model_writer_groups!(writer_groups, applications_by_id) union!(labels, Base.@inline _with_metadata_entry( _application_match_labels, applications_by_id, previous_id)) end - previous_labels = join(sort!([String(label) for label in labels]), ", ") - error( - "Ambiguous canonical writers for variable `$(variable)` on object ", - "`$(_object_id_text(object_id))`. ", - "applications. Application `$(application.id)` must declare ", - "`Updates(:$(variable); after=...)` matching one of the previous writers ", - "`$(previous_labels)`." - ) + io = IOBuffer() + print(io, "Ambiguous canonical writers for variable `", String(variable), + "` on object `", _object_id_text(object_id), "`. Application `", + String(application.id), "` must declare `Updates(:", String(variable), + "; after=...)` matching one of the previous writers `") + join(io, sort!([String(label) for label in labels]), ", ") + print(io, "`.") + error(String(take!(io))) end if !isempty(previous) && !_updates_after_previous_writer(application.spec, variable, (last(previous),)) @@ -6754,15 +6760,17 @@ Base.@noinline function _status_reference_directory(::Type{T}, cells::Vector{Uni return Base._new_NamedTuple(T, Tuple(cells)) end +function _invalid_object_status(id::ObjectId, type_name::Symbol) + error("Model object `", _object_id_text(id), "` uses model applications but its status has type `", + String(type_name), "`. Use `Status(...)` or leave status as `nothing`.") +end + function _model_object_status_for_preparation( model::CompositeModel, object_id::ObjectId, ) status = model_status(model, object_id) - (isnothing(status) || status isa Status) || error( - "Model object `$(_object_id_text(object_id))` uses model applications but its status has type " * - "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." - ) + (isnothing(status) || status isa Status) || _invalid_object_status(object_id, nameof(typeof(status))) return status end @@ -6864,10 +6872,7 @@ end replacement = Base.@inline _new_prepared_status(S, nothing) status = _replace_model_object_status!(model, object, replacement) end - status isa Status || error( - "Model object `$(_object_id_text(object_id))` uses model applications but its status has type ", - "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`." - ) + status isa Status || _invalid_object_status(object_id, nameof(typeof(status))) status isa S || throw(ArgumentError( "The status schema is outside the prepared object family catalog.", )) @@ -6954,7 +6959,7 @@ function _validate_required_model_output_destinations!( model::CompositeModel, resolved_destinations, ) - missing = String[] + details = nothing for resolved in resolved_destinations for destination_id in resolved.destination_ids for (variable_, declaration) in pairs(resolved.declarations) @@ -6971,20 +6976,21 @@ function _validate_required_model_output_destinations!( )) continue end - push!(missing, - "`$(resolved.plan.application_id).$(resolved.plan.group)` requires " * - "`$(variable)` on destination object `$(_object_id_text(destination_id))`") + if isnothing(details) + details = IOBuffer() + print(details, "Missing required distributed-output destination variable(s): ") + else + print(details, "; ") + end + print(details, '`', String(resolved.plan.application_id), '.', String(resolved.plan.group), + "` requires `", String(variable), "` on destination object `", _object_id_text(destination_id), '`') end end end - isempty(missing) && return nothing - details = join(missing, "; ") - error( - "Missing required distributed-output destination variable(s): ", - details, - ". Add the variable to each destination `Status` or declare it with ", - "`Distributed(Default(value))` in the model's `outputs_`.", - ) + isnothing(details) && return nothing + print(details, ". Add the variable to each destination `Status` or declare it with ", + "`Distributed(Default(value))` in the model's `outputs_`.") + error(String(take!(details))) end function _validate_model_output_destination_statuses!( @@ -6995,11 +7001,10 @@ function _validate_model_output_destination_statuses!( for destination_id in resolved.destination_ids status = _model_object(model, destination_id).status (isnothing(status) || status isa Status) && continue - error( - "Output destination `$(resolved.plan.application_id).$(resolved.plan.group)` " * - "selected object `$(_object_id_text(destination_id))` with status type " * - "`$(typeof(status))`. Use `Status(...)` or leave status as `nothing`.", - ) + error("Output destination `", String(resolved.plan.application_id), ".", + String(resolved.plan.group), "` selected object `", _object_id_text(destination_id), + "` with status type `", String(nameof(typeof(status))), + "`. Use `Status(...)` or leave status as `nothing`.") end end return nothing @@ -9367,8 +9372,8 @@ function _validate_model_input_source!( ] isempty(status_source_ids) && return nothing io = IOBuffer() - print(io, "Input binding `", input_sym, "` on application `", application_id, - "` for object `", _object_id_text(consumer_id), "` reads `", source_var, "` from objects `[") + print(io, "Input binding `", String(input_sym), "` on application `", String(application_id), + "` for object `", _object_id_text(consumer_id), "` reads `", String(source_var), "` from objects `[") for (index, source_id) in pairs(status_source_ids) index == 1 || print(io, ", ") _print_selector_diagnostic(io, source_id.value, Any[]) @@ -9426,19 +9431,16 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a end end isempty(missing) && return nothing - details = join( - [ - "`$(row.application_id)` on object `$(_object_id_text(row.object_id))` requires `$(row.input)`" - for row in missing - ], - "; ", - ) - error( - "Missing required composite-model/object input(s): ", - details, - ". Provide the variable on object `Status`, add a `ModelSpec(...; inputs=...)` binding, ", - "or add an unambiguous same-object producer." - ) + io = IOBuffer() + print(io, "Missing required composite-model/object input(s): ") + for (index, row) in pairs(missing) + index == 1 || print(io, "; ") + print(io, "`", String(row.application_id), "` on object `", _object_id_text(row.object_id), + "` requires `", String(row.input), "`") + end + print(io, ". Provide the variable on object `Status`, add a `ModelSpec(...; inputs=...)` binding, ", + "or add an unambiguous same-object producer.") + error(String(take!(io))) end function _applications_by_object(applications, ::ObjectFamilyStore{I}) where {I<:ObjectId} diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f03fd38cc..c8b1d94c3 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4631,7 +4631,7 @@ _missing_previous_execution_group(f, ::AbstractVector, application) = function _missing_previous_execution_group(f, ::Tuple, application) throw(ArgumentError( "The prepared execution-group schema has no matching application " * - "`$(application.id)` at slot $(application.slot). Prepare its group before execution.", + "`$(String(application.id))` at slot $(string(application.slot)). Prepare its group before execution.", )) end From 6cf01c24370d3afce2b6761f4486b055045c1417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 04:31:07 +0100 Subject: [PATCH 248/324] Keep the simulation schedule error compilable with JuliaC safe --- src/composite_model/runtime_outputs.jl | 3 ++- test/test-model-refreshed-schedule.jl | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index c8b1d94c3..998b2a59c 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1391,7 +1391,8 @@ function _due_application_schedule_entries!( step::Int, ) step > schedule.last_step || error( - "Application schedule expected a step after $(schedule.last_step), got $(step).", + "Application schedule expected a step after " * string(schedule.last_step) * + ", got " * string(step) * ".", ) due = schedule.due_entry_indices empty!(due) diff --git a/test/test-model-refreshed-schedule.jl b/test/test-model-refreshed-schedule.jl index dc6b1b1a3..747ca391c 100644 --- a/test/test-model-refreshed-schedule.jl +++ b/test/test-model-refreshed-schedule.jl @@ -96,8 +96,10 @@ end step!(copied) @test model_status(copied.model, :scene).ticks == 2 @test model_status(model, :scene).ticks == 1 - @test schedule.last_step == 2 @test copied.execution_plan.schedule.last_step == 3 + rewind_error = ErrorException("Application schedule expected a step after 2, got 1.") + @test_throws rewind_error PSE._due_application_schedule_entries!(schedule, definition, 1) + @test schedule.last_step == 2 end PSE.@process "schedule_force_midstep" verbose=false From c21dca1072119589dfae13caf40ef87aff724c7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 04:33:15 +0100 Subject: [PATCH 249/324] Run hard calls while their selected targets are concrete --- src/composite_model/runtime_outputs.jl | 28 +++++++++++++++----------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 998b2a59c..0f8e01d74 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5230,14 +5230,16 @@ end ) end -@inline function _selected_call_targets(targets, context::RunContext, name::Symbol, requested_ids) +@inline function _with_selected_call_targets( + targets, context::RunContext, name::Symbol, requested_ids, consume::F, args::Vararg{Any,N}, +) where {F,N} if isnothing(requested_ids) _compiled_call_mode(targets.binding) === :manual || _initializer_requires_dedicated_api(context, name) - return _synchronized_named_call(targets, context, name) + return consume(_synchronized_named_call(targets, context, name), args...) end return _current_topology_call_targets( - _synchronized_named_call(targets, context, name), context, name, requested_ids, + _synchronized_named_call(targets, context, name), context, name, requested_ids, consume, args..., ) end @@ -5746,7 +5748,7 @@ Base.@constprop :aggressive function call_targets( ) requested_ids = isnothing(objects) ? nothing : _call_target_object_ids(runtime_model(context), objects) - return _with_named_call(_selected_call_targets, context.calls, name, context, requested_ids) + return _with_named_call(_with_selected_call_targets, context.calls, name, context, requested_ids, identity) end @inline function _single_call_model(targets::CallTargets, batches::Tuple{B}) where {B} @@ -6419,7 +6421,9 @@ function _current_topology_call_targets( context::RunContext, name::Symbol, requested_ids, -) + consume::F, + args::Vararg{Any,N}, +) where {F,N} model = runtime_model(context) targeted = _targeted_new_object_call_targets( context, @@ -6427,7 +6431,7 @@ function _current_topology_call_targets( requested_ids, cached_targets, ) - isnothing(targeted) || return targeted + isnothing(targeted) || return consume(targeted, args...) compiled = _refresh_runtime_bindings!(model, context.compiled) environment_bindings = _refresh_environment_bindings!( model, @@ -6463,8 +6467,9 @@ function _current_topology_call_targets( getfield(binding, :plan) === plan || throw(ArgumentError( "The refreshed hard call belongs to a different declaration.", )) - _selected_topology_call_targets(binding, cached_targets, context, name, requested_ids, + selected = _selected_topology_call_targets(binding, cached_targets, context, name, requested_ids, model, compiled, environment_bindings) + consume(selected, args...) end end end @@ -7196,13 +7201,12 @@ function run_call!( end requested_ids = isnothing(objects) ? nothing : _call_target_object_ids(runtime_model(context), objects) - return _with_named_call(_selected_run_call!, context.calls, name, context, - requested_ids, publish, sampled_environment, environment) + return _with_named_call(_with_selected_call_targets, context.calls, name, context, + requested_ids, _run_selected_call_targets!, context, publish, sampled_environment, environment) end -@inline function _selected_run_call!(cached_targets, context::RunContext, name::Symbol, - requested_ids, publish, sampled_environment, environment) - targets = _selected_call_targets(cached_targets, context, name, requested_ids) +@inline function _run_selected_call_targets!(targets, context::RunContext, publish, + sampled_environment, environment) selected_environment = environment isa NoEnvironmentOverride ? context.environment : environment return _run_call_targets!(targets, publish, sampled_environment, selected_environment) From 32cdff2c56c653f1e420f022178b85dc9edc74b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 04:45:26 +0100 Subject: [PATCH 250/324] Use the prepared local output fields when constructing status views --- src/composite_model/compilation.jl | 4 +++- src/composite_model/status_view_construction.jl | 16 ++++++++++------ test/test-model-authored-port-inventory.jl | 7 +++++++ 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index ff24e4f3e..acd426a31 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5802,8 +5802,10 @@ end function _read_application_defaults(model, kind::Val{:outputs}, ports) schema = Base.@inline _admit_authored_port_schema(outputs_(model), _authored_metadata_value(ports.output_declaration_types), kind) - return _local_output_declarations(schema) + return NamedTuple{_prepared_local_output_names(ports)}(schema) end +_prepared_local_output_names(ports::AuthoredPortInventory) = ports.outputs.local_names +_prepared_local_output_names(ports::NamedTuple) = fieldnames(ports.defaults_types.outputs) _variant_defaults_type(ports, ::Val{:outputs}) = ports.defaults_types.outputs _variant_defaults_type(ports, ::Val{:inputs}) = ports.defaults_types.inputs diff --git a/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl index 698e17efe..67305284b 100644 --- a/src/composite_model/status_view_construction.jl +++ b/src/composite_model/status_view_construction.jl @@ -231,7 +231,7 @@ function _assemble_model_status_view(canonical_status, model, application, objec NamedTuple() else defaults = Base.@inline _with_application_variant(application, object_id) do effective_model, ports - _local_output_schema(effective_model) + _read_application_defaults(effective_model, Val(:outputs), ports) end for variable in keys(defaults) _publish_mode_for_output(application.spec, variable) == :stream_only && @@ -248,11 +248,8 @@ function _assemble_model_status_view(canonical_status, model, application, objec end private_values = Any[] for name in private_names - initial, _, _ = _materialize_status_value(model, name, - getproperty(output_defaults, name); object_id, - application_id=application.id, origin=:stream_only_private_default, - private_copy=true, reuse=true) - push!(private_values, initial) + Base.@inline _with_metadata_entry(_append_private_status_default!, output_defaults, name, + private_values, model, name, object_id, application.id) end seen_many = Set{Symbol}() for name in many_names @@ -268,6 +265,13 @@ function _assemble_model_status_view(canonical_status, model, application, objec return Base.@inline _admit_model_status_view!(status_view_schema, application.id, view) end +function _append_private_status_default!(value, private_values, model, name, object_id, application) + initial, _, _ = _materialize_status_value(model, name, value; object_id, + application_id=application, origin=:stream_only_private_default, private_copy=true, reuse=true) + push!(private_values, initial) + return nothing +end + # A homogeneous initial snapshot has the same exact schema as before. Matching # never constructs a type from an Any value in the finite construction path. _status_view_initial_mode(::Type{B}) where {B<:CompiledModelInputBinding} = diff --git a/test/test-model-authored-port-inventory.jl b/test/test-model-authored-port-inventory.jl index db737de3f..32abf8a17 100644 --- a/test/test-model-authored-port-inventory.jl +++ b/test/test-model-authored-port-inventory.jl @@ -142,6 +142,13 @@ PSE.run!(::DeclarationProbe, status, environment, constants, context) = nothing @test inventory_is_value_free(variant) @test probe.empty == Real[3f0] @test probe.mixed == Real[1f0, 2.0, 1//2, 4] + for owner in (ports, variant) + before = probe.counter[].outputs + defaults = @inferred PSE._read_application_defaults(probe, Val(:outputs), owner) + @test keys(defaults) === (:direct,) + @test defaults.direct === probe.empty + @test probe.counter[].outputs == before + 1 + end end @testset "constructor owns one instance-specific value-free port inventory" begin From 01b0041ae39831187bcd728d039a3aa82284317b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 05:21:23 +0100 Subject: [PATCH 251/324] Reuse prepared update declarations when checking writer order --- src/composite_model/compilation.jl | 21 +++++++-------------- test/test-model-spec-normalization.jl | 8 ++++++++ 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index acd426a31..47ab98bcd 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -5889,17 +5889,13 @@ end _update_matches_application(label::Symbol, application) = label == application.id -function _update_variables(update) - return Tuple(Symbol(variable) for variable in getproperty(update, :variables)) -end +_update_symbols(values::Tuple{Vararg{Symbol}}) = values +_update_symbols(values) = Tuple(Symbol(value) for value in values) +_update_variables(update) = _update_symbols(update.variables) +_update_after(update) = _update_symbols(update.after) -function _update_after(update) - return Tuple(Symbol(label) for label in getproperty(update, :after)) -end - -function _matching_updates(spec, variable::Symbol) - return [update for update in updates(spec) if variable in _update_variables(update)] -end +_matching_updates(spec, variable::Symbol) = + Iterators.filter(update -> variable in _update_variables(update), updates(spec)) function _update_after_labels(spec, variable::Symbol) labels = Symbol[] @@ -5911,11 +5907,8 @@ function _update_after_labels(spec, variable::Symbol) end function _updates_after_previous_writer(spec, variable::Symbol, previous_application_ids) - matching = _matching_updates(spec, variable) - isempty(matching) && return false - for update in matching + for update in _matching_updates(spec, variable) after = _update_after(update) - isempty(after) && continue any(label -> label in previous_application_ids, after) && return true end return false diff --git a/test/test-model-spec-normalization.jl b/test/test-model-spec-normalization.jl index 595fab985..f755c6bbe 100644 --- a/test/test-model-spec-normalization.jl +++ b/test/test-model-spec-normalization.jl @@ -41,6 +41,14 @@ struct TestWindow <: PlantMeteo.AbstractSamplingWindow end @test spec.calls.start === initializer @test spec.input_origins === (value=:model_default,) @test spec.call_origins === (leaf=:model_default, start=:model_default) + update = only(PSE.updates(spec)) + @test (@inferred PSE._update_variables(update)) === (:trace,) + @test (@inferred PSE._update_after(update)) === (:producer,) + @test PSE._updates_after_previous_writer(spec, :trace, (:other, :producer)) + @test !PSE._updates_after_previous_writer(spec, :value, (:producer,)) + stored = Updates(["trace", "value"], ["producer"]) + @test PSE._update_variables(stored) == (:trace, :value) + @test PSE._update_after(stored) == (:producer,) # Environment resolution has no authority to reconstruct already-authored # dependencies, replace model defaults, or change their origin. From 30b9a080efde14d50378bd40aa9c027563cceaa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 05:29:51 +0100 Subject: [PATCH 252/324] Keep the prepared identity type for hard-call growth deltas --- src/composite_model/runtime_outputs.jl | 2 +- test/test-model-finite-call-extension-intents.jl | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 0f8e01d74..fb8182e13 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4367,7 +4367,7 @@ function _pure_addition_changed_call_target_ids( compiled::CompiledCompositeModel, ) application_ids = binding.callee_application_ids - changed_ids = ObjectId[] + changed_ids = similar(binding.callee_object_ids, 0) affected_application_ids = Symbol[] for (application_id, object_id) in compiled.changed_execution_target_ids application_id in application_ids || continue diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl index 174f40ac7..ec13700d2 100644 --- a/test/test-model-finite-call-extension-intents.jl +++ b/test/test-model-finite-call-extension-intents.jl @@ -182,6 +182,16 @@ random_state(rng) = rand(copy(rng), UInt64, 8) add_leaves!(ordinary) owners = refreshed_owners(data) @test owners.compiled.status_view_refresh_is_pure_addition + if algorithm === :pure_addition + bindings = owners.compiled.call_bindings_by_target[(:root, ObjectId(1))] + binding = only(b for b in bindings if b.call === :a) + closed = PSE.CompiledModelCallBinding(binding.plan, binding.consumer_id, + ObjectId{Int}[id for id in binding.callee_object_ids], binding.callee_application_ids) + changed, affected = PSE._pure_addition_changed_call_target_ids(closed, owners.compiled) + @test eltype(changed) === ObjectId{Int} + @test changed == [ObjectId(101)] + @test affected == [:leaf_a] + end before_state = state(data.model) @test extend!(algorithm, target, owners, simulation) === true @test state(data.model) == before_state From 5c99524b1aa3a2fbd53c444632c0406ace4a3463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 06:08:31 +0100 Subject: [PATCH 253/324] Read freshly included initializer bindings in their defining world --- test/test-model-runtime-call-names.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test-model-runtime-call-names.jl b/test/test-model-runtime-call-names.jl index 725e2325b..289659e9a 100644 --- a/test/test-model-runtime-call-names.jl +++ b/test/test-model-runtime-call-names.jl @@ -224,7 +224,7 @@ end write(path, source) generated_module = Module(gensym(:RuntimeNamedInitializers)) Base.include(generated_module, path) - generated_run = getfield(generated_module, :runtime_named_initializers!) + generated_run = Base.invokelatest(getfield, generated_module, :runtime_named_initializers!) generated = Base.invokelatest(generated_run, fixture.model; steps=1, outputs=:all) @test model_status(runtime_model(generated), :born_a).value === 2f0 @test model_status(runtime_model(generated), :born_b).value === 7.0 From 8e9e6cadd11163fde1a5f74a9ee0f7ce26b21a45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 06:33:13 +0100 Subject: [PATCH 254/324] Resolve selected and retained calls from the current declaration --- .../execution_batch_schemas.jl | 42 ++++++++++-------- src/composite_model/runtime_outputs.jl | 44 ++++++------------- test/test-model-authored-call-plans.jl | 3 +- test/test-model-call-cohort-retirement.jl | 32 ++++++++++---- 4 files changed, 62 insertions(+), 59 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index ea69e4822..9e6e3b2db 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -695,33 +695,39 @@ function _execution_batch_type_with_call_schemas(::Type{B}, schemas::NamedTuple) fieldtype(B,:environment_provider),fieldtype(B,:output_publication)} end -@generated function _current_call_binding_for_application(compiled::CS, - application::CompiledModelApplication, binding::B, -) where {CS<:CompiledCompositeModel,B<:CompiledModelCallBinding} - Owner = fieldtype(fieldtype(CS, :scenario_plan), :call_plans_by_application) - Entries = fieldtype(Owner, :entries) - Plan = fieldtype(B, :plan) - CallerId = fieldtype(B, :consumer_id) - CalleeId = eltype(fieldtype(B, :callee_object_ids)) +# Resolve the name against the current owner's declarations. A retained view +# also checks that the resulting binding still fits its original representation. +@generated function _current_named_call_binding(compiled::CS, application_id::Symbol, + object_id::I, ::B, ::Type{J}, +) where {CS<:CompiledCompositeModel,I<:ObjectId,B<:CompiledModelCallBinding,J<:ObjectId} + Table = fieldtype(fieldtype(CS, :scenario_plan), :call_plans_by_application) + Entries = fieldtype(Table, :entries) + name = _prepared_call_name(B) branches = Expr[] - for (position, application_id) in enumerate(fieldnames(Entries)) - Plans = fieldtype(Entries, position) - index = findfirst(==(Plan), fieldtypes(Plans)) + for (slot, id) in enumerate(fieldnames(Entries)) + Plans = fieldtype(Entries, slot) + index = findfirst(P -> _prepared_call_plan_name(P) === name, fieldtypes(Plans)) isnothing(index) && continue - Bindings = Tuple{[CompiledModelCallBinding{T,CallerId,CalleeId} for T in fieldtypes(Plans)]...} + Plan = fieldtype(Plans, index) + Binding = CompiledModelCallBinding{Plan,I,J} + Bindings = Tuple{[CompiledModelCallBinding{P,I,J} for P in fieldtypes(Plans)]...} push!(branches, quote - if application_id === $(QuoteNode(application_id)) - bindings = get(compiled.call_bindings_by_target, - (application_id, binding.consumer_id), ()) + if application_id === $(QuoteNode(id)) + bindings = get(compiled.call_bindings_by_target, (application_id, object_id), ()) + isempty(bindings) && return nothing bindings isa $Bindings || _unprepared_runtime_configuration() - return getfield(bindings::$Bindings, $index)::$B + binding = getfield(bindings::$Bindings, $index)::$Binding + plans = getfield(getfield(compiled.scenario_plan.call_plans_by_application, :entries), $slot) + getfield(binding, :plan) === getfield(plans, $index) || throw(ArgumentError( + "The refreshed hard call belongs to a different declaration.", + )) + return binding end end) end return quote - application_id = getfield(getfield(application, :plan), :id)::Symbol $(branches...) - throw(ArgumentError("A retained call no longer has its prepared declaration.")) + return nothing end end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index fb8182e13..6c8b809f4 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -816,11 +816,12 @@ end end function _current_call_binding_for_retained_view(compiled::CompiledCompositeModel, - binding::CompiledModelCallBinding, -) - return _compiled_application_by_id(compiled,binding.application_id) do application - _current_call_binding_for_application(compiled,application,binding) - end + binding::B, +) where {B<:CompiledModelCallBinding} + current = _current_named_call_binding(compiled, binding.application_id, binding.consumer_id, + binding, eltype(binding.callee_object_ids)) + current isa B || throw(ArgumentError("A retained call no longer has its prepared declaration.")) + return current::B end @inline function _environment_bindings_match_compiled( @@ -6439,17 +6440,10 @@ function _current_topology_call_targets( _current_environment_binding_owner(model, context.environment_bindings); environment_schema=context.environment_bindings.environment_schema, ) - bindings = get( - compiled.call_bindings_by_target, - (context.application.id, context.object_id), - (), - ) - position = findfirst(eachindex(bindings)) do slot - binding = bindings[slot]::CompiledModelCallBinding - plan = getfield(binding, :plan)::CompiledModelCallPlan - return plan.call === name - end - if isnothing(position) + binding = _current_named_call_binding(compiled, context.application.id, context.object_id, + cached_targets.binding, keytype(model.registry.objects)) + if isnothing(binding) + bindings = get(compiled.call_bindings_by_target, (context.application.id, context.object_id), ()) available = Symbol[(item::CompiledModelCallBinding).call for item in bindings] error( "Application `$(context.application.id)` on object ", @@ -6457,21 +6451,9 @@ function _current_topology_call_targets( "Declared calls: $(available).", ) end - # The refreshed catalog owns the declaration, including any new potential - # callees. Keep its exact plan type when reading the heterogeneous tuple. - return Base.@inline _with_metadata_entry(compiled.scenario_plan.call_plans_by_application, - context.application.id) do plans - Base.@inline _with_metadata_entry(plans, position) do plan - B = CompiledModelCallBinding{typeof(plan),typeof(context.object_id),keytype(model.registry.objects)} - binding = bindings[position]::B - getfield(binding, :plan) === plan || throw(ArgumentError( - "The refreshed hard call belongs to a different declaration.", - )) - selected = _selected_topology_call_targets(binding, cached_targets, context, name, requested_ids, - model, compiled, environment_bindings) - consume(selected, args...) - end - end + selected = _selected_topology_call_targets(binding, cached_targets, context, name, + requested_ids, model, compiled, environment_bindings) + return consume(selected, args...) end function _selected_topology_call_targets(resolved_binding, cached_targets, context, name, requested_ids, diff --git a/test/test-model-authored-call-plans.jl b/test/test-model-authored-call-plans.jl index f2f89427c..ce933e264 100644 --- a/test/test-model-authored-call-plans.jl +++ b/test/test-model-authored-call-plans.jl @@ -81,8 +81,7 @@ end @test only(runtime_plans[:driver]) === resolved binding = only(simulation.compiled.call_bindings) @test binding.plan === resolved - @test PSE._current_call_binding_for_application(simulation.compiled, - simulation.compiled.applications_by_id[:driver], binding) === binding + @test PSE._current_call_binding_for_retained_view(simulation.compiled, binding) === binding # Same type, different resolved scope: only the actual runtime declaration # may own a binding, even when the current target set happens to overlap. diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl index 7468a6409..c88643d4a 100644 --- a/test/test-model-call-cohort-retirement.jl +++ b/test/test-model-call-cohort-retirement.jl @@ -22,7 +22,7 @@ end PSE.run!(::Leaf, status, environment, constants, context) = (status.leaf_visits += 1; nothing) # Real authored bindings: the caller has a Symbol identity, its callees Int IDs. -function fixture(; transform=identity, outputs=:none) +function fixture(; transform=identity, outputs=:none, left_selector=Many(scale=:Leaf, application=:leaf)) capture = Ref{Any}(nothing) model = CompositeModel( Object(:caller; scale=:Scene, status=Status(caller_visits=0)), @@ -30,8 +30,7 @@ function fixture(; transform=identity, outputs=:none) Object(2; scale=:Leaf, parent=:caller, status=Status(leaf_visits=0)); applications=( ModelSpec(Caller(capture); name=:caller, on=One(id=:caller, scale=:Scene), - calls=(left=Many(scale=:Leaf, application=:leaf), - right=Many(scale=:Leaf, application=:leaf))), + calls=(left=left_selector, right=Many(scale=:Leaf, application=:leaf))), ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), )) model = transform(model) @@ -58,15 +57,13 @@ end @testset "caller identity remains independent from the callee schema" begin data = fixture() - application = data.simulation.compiled.applications_by_id[:caller] for calls in (data.left, data.right) binding = calls.binding @test fieldtype(typeof(binding), :consumer_id) === ObjectId{Symbol} @test binding.consumer_id === ObjectId(:caller) @test eltype(binding.callee_object_ids) === ObjectId @test all(id -> id isa ObjectId{Int}, binding.callee_object_ids) - @test PSE._current_call_binding_for_application(data.simulation.compiled, - application, binding) === binding + @test PSE._current_call_binding_for_retained_view(data.simulation.compiled, binding) === binding @test PSE._prepared_call_mode(typeof(binding)) === :manual @test PSE._prepared_call_name(typeof(binding)) in (:left, :right) end @@ -180,6 +177,7 @@ function with_finite_registry(model) end current_target(simulation) = only(only(only(simulation.execution_plan.groups).batches).targets) view_ids(values) = [target.object_id for target in values] + live_state(model) = Dict(object.id => deepcopy(NamedTuple(object.status)) for object in model_objects(model)) stream_values(simulation) = Dict(key => collect(stream) for (key, stream) in outputs(simulation)) @@ -209,6 +207,25 @@ function publish_current_left!(data) return context end +@testset "an explicitly selected call follows the current declaration after a forced refresh" begin + select_leaf(id) = Many(id=id, within=SceneScope(), application=:leaf) + data = fixture(; left_selector=select_leaf(1)) + context = data.target.context + @test view_ids(call_targets(context, :left; objects=(1,))) == [ObjectId(1)] + + specification = data.model.applications[1] + data.model.applications[1] = ModelSpec(PSE.model_(specification); name=:caller, + on=One(id=:caller, scale=:Scene), + calls=(left=select_leaf(2), right=Many(scale=:Leaf, application=:leaf))) + current = Advanced.refresh_bindings!(data.model; force=true) + @test current !== data.simulation.compiled + @test typeof(current) === typeof(data.simulation.compiled) + selected = call_targets(context, :left; objects=(2,)) + @test view_ids(selected) == [ObjectId(2)] + @test selected.binding.plan === current.call_bindings_by_target[(:caller, ObjectId(:caller))][1].plan + @test_throws "does not resolve requested object" call_targets(context, :left; objects=(1,)) +end + @testset "closed memberships use the global future identity schema" begin data = fixture(; transform=with_finite_registry) I = Union{ObjectId{Symbol},ObjectId{Int}} @@ -221,8 +238,7 @@ end for calls in (data.left, data.right) @test fieldtype(typeof(calls.binding), :consumer_id) === ObjectId{Symbol} @test eltype(calls.binding.callee_object_ids) === I - @test PSE._current_call_binding_for_application(data.simulation.compiled, - applications[:caller], calls.binding) === calls.binding + @test PSE._current_call_binding_for_retained_view(data.simulation.compiled, calls.binding) === calls.binding end partial = PSE._partial_model_application(applications[:leaf], ObjectId{Int}[ObjectId(1)]) @test eltype(partial.target_ids) === I From 0bcebac864d4ad7bc5d318343a5d4b3785b862db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 06:46:41 +0100 Subject: [PATCH 255/324] Load the generated weather dependency through PlantSimEngine --- src/composite_model/source_compilation.jl | 2 +- test/test-model-runtime-call-names.jl | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/composite_model/source_compilation.jl b/src/composite_model/source_compilation.jl index 4fe2b45d5..af62bbbe1 100644 --- a/src/composite_model/source_compilation.jl +++ b/src/composite_model/source_compilation.jl @@ -619,7 +619,7 @@ function _compiled_source_concrete_type_name(model) end function _compiled_source_imports(kernels) - imports = String["import PlantSimEngine\n", "import PlantMeteo\n"] + imports = String["import PlantSimEngine\n", "import PlantSimEngine: PlantMeteo\n"] roots = Set{Module}() for kernel in kernels root = _compiled_source_root_module(kernel.source_module) diff --git a/test/test-model-runtime-call-names.jl b/test/test-model-runtime-call-names.jl index 289659e9a..c24b9da12 100644 --- a/test/test-model-runtime-call-names.jl +++ b/test/test-model-runtime-call-names.jl @@ -223,7 +223,18 @@ end path = joinpath(directory, "RuntimeNamedInitializers.jl") write(path, source) generated_module = Module(gensym(:RuntimeNamedInitializers)) - Base.include(generated_module, path) + # Load the generated file as a consumer whose only dependency is PSE. + write(joinpath(directory, "Project.toml"), + "[deps]\nPlantSimEngine = \"$(Base.PkgId(PSE).uuid)\"\n") + saved_load_path = copy(LOAD_PATH) + try + empty!(LOAD_PATH) + append!(LOAD_PATH, (directory, "@stdlib")) + Base.include(generated_module, path) + finally + empty!(LOAD_PATH) + append!(LOAD_PATH, saved_load_path) + end generated_run = Base.invokelatest(getfield, generated_module, :runtime_named_initializers!) generated = Base.invokelatest(generated_run, fixture.model; steps=1, outputs=:all) @test model_status(runtime_model(generated), :born_a).value === 2f0 From 6fe904973fc61e2908ef420297eef0fdff48f4d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 06:54:05 +0100 Subject: [PATCH 256/324] Use the trim-safe Libiconv wrapper in the compiled example --- docs/src/guides/compile_scenario.md | 5 +++++ examples/compiled_scenario/Project.toml | 3 +++ 2 files changed, 8 insertions(+) diff --git a/docs/src/guides/compile_scenario.md b/docs/src/guides/compile_scenario.md index 78d671a85..21c7aa3d6 100644 --- a/docs/src/guides/compile_scenario.md +++ b/docs/src/guides/compile_scenario.md @@ -48,6 +48,11 @@ julia --project=examples/compiled_scenario -e 'using Pkg; Pkg.instantiate()' ``` The app project points to the local PlantSimEngine checkout in `[sources]`. +The example pins `Libiconv_jll` to 1.18.0 in the app's `Project.toml`. +With version 1.18.1 on Linux, JuliaC 0.3.12 reports unresolved calls to +`string` and `convert` in `Libiconv_jll.__init__`. If your build reports +these errors, use the same dependency and compatibility entries in your app. + Use a separate environment for the build tools. From the repository root, start Julia and run: diff --git a/examples/compiled_scenario/Project.toml b/examples/compiled_scenario/Project.toml index 9aa7f5dec..a10145ac9 100644 --- a/examples/compiled_scenario/Project.toml +++ b/examples/compiled_scenario/Project.toml @@ -3,10 +3,13 @@ uuid = "ac67530e-c1dc-4bfe-8d89-6dced94d41bf" version = "0.1.0" [deps] +Libiconv_jll = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" [sources] PlantSimEngine = {path = "../.."} [compat] +# JuliaC 0.3.12 cannot trim the lazy library paths in Libiconv_jll 1.18.1. +Libiconv_jll = "=1.18.0" julia = "1.13" From bda0b81920c7351c3ec25c2b09f45abdd371e347 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 06:55:54 +0100 Subject: [PATCH 257/324] Resolve the same native library for both growth fixtures --- test/fixtures/local_palm_leaf_birth/Project.toml | 2 ++ .../fixtures/distributed_producer_birth/Project.toml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/test/fixtures/local_palm_leaf_birth/Project.toml b/test/fixtures/local_palm_leaf_birth/Project.toml index 3257e080c..2a8f0fe57 100644 --- a/test/fixtures/local_palm_leaf_birth/Project.toml +++ b/test/fixtures/local_palm_leaf_birth/Project.toml @@ -4,10 +4,12 @@ version = "0.1.0" [deps] Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" +Libiconv_jll = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" [sources] PlantSimEngine = {path = "../../.."} [compat] +Libiconv_jll = "=1.18.0" julia = "1.13" diff --git a/test/integration/fixtures/distributed_producer_birth/Project.toml b/test/integration/fixtures/distributed_producer_birth/Project.toml index 812ae9a60..abeff5f4e 100644 --- a/test/integration/fixtures/distributed_producer_birth/Project.toml +++ b/test/integration/fixtures/distributed_producer_birth/Project.toml @@ -3,10 +3,12 @@ uuid = "3c96ca4e-58bc-4f40-935b-d8fae20d6519" version = "0.1.0" [deps] +Libiconv_jll = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" [sources] PlantSimEngine = {path = "../../../.."} [compat] +Libiconv_jll = "=1.18.0" julia = "1.13" From 572676c47e2bf800d891d9f2c6ee7cb056b47fd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 07:23:54 +0100 Subject: [PATCH 258/324] Copy interned symbol arrays when initializing organ defaults --- src/input_schema.jl | 6 +++--- test/test-model-status-type-conversion.jl | 26 ++++++++++++++++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/input_schema.jl b/src/input_schema.jl index 288f02c19..7ba17aca7 100644 --- a/src/input_schema.jl +++ b/src/input_schema.jl @@ -42,9 +42,9 @@ end _private_initial_value(value) = deepcopy(value) function _private_initial_value(value::Array{T}) where {T} - # Isbits elements contain no mutable identities; a fresh dense copy has the - # same private-value semantics without entering Base's erased Memory helper. - return isbitstype(T) ? copy(value) : deepcopy(value) + # Bits values and interned symbols keep their identities under deepcopy. + # Other element types may provide a custom deepcopy for the whole array. + return isbitstype(T) || T === Symbol ? copy(value) : deepcopy(value) end @noinline function _invalid_input_schema_error(model, schema) diff --git a/test/test-model-status-type-conversion.jl b/test/test-model-status-type-conversion.jl index 5c838fc5e..47a4812a9 100644 --- a/test/test-model-status-type-conversion.jl +++ b/test/test-model-status-type-conversion.jl @@ -38,7 +38,15 @@ PlantSimEngine.inputs_(model::OwnedArrayDefaultModel) = (payload=Default(model.d PlantSimEngine.outputs_(::OwnedArrayDefaultModel) = NamedTuple() PlantSimEngine.run!(::OwnedArrayDefaultModel, status, environment, constants, context) = nothing -@testset "private array defaults retain bits and independent mutable graphs" begin +mutable struct ModelOwnedDefaultCell + value::Int +end + +# A model may define how its non-bits array defaults are privately copied. +Base.deepcopy_internal(values::Vector{ModelOwnedDefaultCell}, ::IdDict) = + [ModelOwnedDefaultCell(cell.value + 1) for cell in values] + +@testset "private array defaults retain symbols, bits and independent mutable graphs" begin function prepared_defaults(value) model = CompositeModel( Object(:first; scale=:Scene), Object(:second; scale=:Scene); @@ -58,6 +66,22 @@ PlantSimEngine.run!(::OwnedArrayDefaultModel, status, environment, constants, co left[3] = 9f0 @test right[3] === source[3] === 3f0 + states = [:undetermined] + first_states, second_states = prepared_defaults(states) + first_states[1] = :female + @test second_states == states == [:undetermined] + @test first_states !== second_states && second_states !== states + + unfilled = Matrix{Symbol}(undef, 1, 2) + unfilled[1] = :male + copied = PlantSimEngine._private_initial_value(unfilled) + @test size(copied) == size(unfilled) + @test copied[1] === :male && !isassigned(copied, 2) + + owned = [ModelOwnedDefaultCell(2)] + copied_owned = PlantSimEngine._private_initial_value(owned) + @test only(copied_owned).value == 3 && only(owned).value == 2 + shared = Float32[1, 2] nested = [shared, shared] first_graph, second_graph = prepared_defaults(nested) From f746e9343155f49308d5d9b3a6e2fd51bdcf3ce3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 07:39:11 +0100 Subject: [PATCH 259/324] Keep declared input and call types when refreshing live bindings --- src/composite_model/compilation.jl | 54 +++++++++++++++----------- src/composite_model/runtime_outputs.jl | 5 ++- 2 files changed, 34 insertions(+), 25 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 47ab98bcd..46f199800 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -7718,29 +7718,37 @@ end function _force_distributed_producer_rebinds!(forced, model, bindings, by_variable) for binding in bindings - binding.origin === :inferred_same_object && continue - (binding.carrier_hint === :temporal_stream || - !isnothing(binding.process) || !isnothing(binding.application)) || - continue - candidates = get(by_variable, binding.source_var, ()) - isempty(candidates) && continue - consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) - default_scope = _default_dependency_scope(model, consumer_id) - for (raw_destination, producer) in candidates - producer in binding.plan.potential_source_application_ids || continue - destination = _index_object_id(model.registry.objects, raw_destination) - Base.@inline _selector_matches_object_id( - model, - binding.matcher, - destination, - consumer_id, - true, - default_scope, - false, - ) || continue - push!(forced, (binding.application_id, consumer_id, binding.input)) - break - end + Base.@inline _with_model_input_binding( + _force_distributed_producer_rebind!, bindings, binding, + forced, model, by_variable, + ) + end + return nothing +end + +function _force_distributed_producer_rebind!(binding, forced, model, by_variable) + binding.origin === :inferred_same_object && return nothing + (binding.carrier_hint === :temporal_stream || + !isnothing(binding.process) || !isnothing(binding.application)) || + return nothing + candidates = get(by_variable, binding.source_var, ()) + isempty(candidates) && return nothing + consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) + default_scope = _default_dependency_scope(model, consumer_id) + for (raw_destination, producer) in candidates + producer in binding.plan.potential_source_application_ids || continue + destination = _index_object_id(model.registry.objects, raw_destination) + Base.@inline _selector_matches_object_id( + model, + binding.matcher, + destination, + consumer_id, + true, + default_scope, + false, + ) || continue + push!(forced, (binding.application_id, consumer_id, binding.input)) + break end return nothing end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 6c8b809f4..f73f09423 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1129,7 +1129,7 @@ end function _call_bindings_signature(call_bindings) signature = hash(length(call_bindings)) for binding in call_bindings - signature = hash(_compiled_call_name(binding), signature) + signature = hash(_compiled_call_name(binding)::Symbol, signature) # Lifecycle code advances this generation whenever either callee # vector changes, so signature refresh remains independent of the # number of organs selected by the call. @@ -5793,7 +5793,8 @@ execution target and remains valid until a lifecycle refresh barrier. end @noinline function _missing_named_call(context, name) - available = Symbol[targets.binding.call for targets in context.calls] + available = Symbol[_with_metadata_entry(targets -> targets.binding.call, context.calls, slot) + for slot in eachindex(context.calls)] error( "Application `$(context.application.id)` on object ", "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", From 8c51f2a477ccba96df4d7666fa02b98e9bb6d106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 08:02:56 +0100 Subject: [PATCH 260/324] Reconcile each local environment plan once and preserve provider identity --- src/composite_model/environment_bindings.jl | 42 +++++++++------- ...test-model-environment-binding-identity.jl | 50 +++++++++++++++++++ 2 files changed, 74 insertions(+), 18 deletions(-) diff --git a/src/composite_model/environment_bindings.jl b/src/composite_model/environment_bindings.jl index cc158bcce..2c9891510 100644 --- a/src/composite_model/environment_bindings.jl +++ b/src/composite_model/environment_bindings.jl @@ -179,7 +179,7 @@ function _update_model_environment_indices_for_objects!( seen = Set{UInt}() for application_id in application_ids plan = cached.application_plans_by_id[application_id] - _with_environment_plan(cached.environment_schema, plan) do admitted_plan + Base.@inline _with_environment_plan(cached.environment_schema, plan) do admitted_plan backend = admitted_plan.backend isnothing(backend) && return nothing id = objectid(backend) @@ -191,7 +191,7 @@ function _update_model_environment_indices_for_objects!( # Plans are immutable snapshots. Index callbacks may replace the owner's # dictionary entries, so consume these selected plans without rereading it. return _update_model_environment_indices!(model, plans, dirty_object_ids) do consume, plan - _with_environment_plan(cached.environment_schema, plan) do admitted_plan + Base.@inline _with_environment_plan(cached.environment_schema, plan) do admitted_plan consume(admitted_plan.backend) end end @@ -647,7 +647,7 @@ function _validate_model_environment_inputs!(bindings, applications_by_id, for binding in bindings plan = getfield(binding, :plan)::CompiledEnvironmentApplicationPlan object_id = getfield(binding, :object_id)::I - _with_environment_plan(environment_schema, plan) do plan + Base.@inline _with_environment_plan(environment_schema, plan) do plan application_id = getfield(plan, :application_id) no_inputs = _with_metadata_entry(applications_by_id, application_id) do application isempty(_model_environment_input_names(application)) @@ -869,7 +869,7 @@ function _reconciled_environment_application_plans( compiled::CompiledCompositeModel, cached::CompiledEnvironmentBindings, ) - candidates, candidates_by_id = _compile_environment_application_plans( + candidates, _ = _compile_environment_application_plans( model, compiled.applications, compiled.applications_by_id; @@ -880,25 +880,31 @@ function _reconciled_environment_application_plans( plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() environment_schema = cached.environment_schema for candidate in candidates - application_id = candidate.application_id - old = get(cached.application_plans_by_id, application_id, nothing) - plan = if isnothing(old) - _with_environment_plan(identity, environment_schema, candidates_by_id[application_id]) - else - admitted_old = _with_environment_plan(identity, environment_schema, old) - admitted_candidate = _with_environment_plan(identity, environment_schema, candidates_by_id[application_id]) - _same_environment_plan_configuration(admitted_old, admitted_candidate) || - return nothing - _same_environment_application_plan(admitted_old, admitted_candidate) ? - admitted_old : _with_environment_plan(identity, environment_schema, candidates_by_id[application_id]) + accepted = Base.@inline _with_environment_plan(environment_schema, candidate) do admitted_candidate + old = get(cached.application_plans_by_id, admitted_candidate.application_id, nothing) + if isnothing(old) + return _append_reconciled_environment_plan!(admitted_candidate, plans, plans_by_id) + end + Base.@inline _with_environment_plan(environment_schema, old) do admitted_old + _same_environment_plan_configuration(admitted_old, admitted_candidate) || + return false + if _same_environment_application_plan(admitted_old, admitted_candidate) + return _append_reconciled_environment_plan!(admitted_old, plans, plans_by_id) + end + _append_reconciled_environment_plan!(admitted_candidate, plans, plans_by_id) + end end - isnothing(plan) && return nothing - push!(plans, plan) - plans_by_id[plan.application_id] = plan + accepted || return nothing end return plans, plans_by_id end +function _append_reconciled_environment_plan!(plan, plans, plans_by_id) + push!(plans, plan) + plans_by_id[plan.application_id] = plan + return true +end + function _reconcile_environment_binding_values(schema, old, old_plan, plan, object_id, context, geometry_source_object_id, geometry_source, ::Type{I}, ) where {I<:ObjectId} diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl index 5efea875b..5e262edb3 100644 --- a/test/test-model-environment-binding-identity.jl +++ b/test/test-model-environment-binding-identity.jl @@ -1025,4 +1025,54 @@ end end end +@testset "metadata reconciliation detects a replacement local provider of the same type" begin + observed = prepare_policy(policy_model(); schema=PSE._collecting_environment_binding_schema()) + fixed = PSE._freeze_environment_binding_schema(observed.environment_bindings.environment_schema) + traces = [] + for policy in (PSE.EnvironmentBindingSchema(), fixed) + data = policy_model() + simulation = prepare_policy(data; schema=policy) + owner = simulation.environment_bindings + old_plan = only(owner.application_plans) + old_backend = data.backend + old_handles = Dict(id => owner.by_target[(:policy_probe, id)].handle + for id in (ObjectId(:leaf), ObjectId(1))) + replacement = PlanPolicyBackend(old_backend.values, 0, 0) + @test typeof(replacement) === typeof(old_backend) + @test replacement !== old_backend + @test replacement.values == old_backend.values + data.source.backend = replacement + data.model.applications[1] = policy_spec(:T) + alternate = PSE.Advanced.refresh_bindings!(data.model; force=true) + @test !PSE.lifecycle_delta(data.model).full_environment + @test alternate.applications !== owner.compiled_applications + normalizations = data.source.normalizations + # This is the metadata path, not the full-dirty shortcut. Candidate + # type equality cannot justify preserving a different local backend. + @test isnothing(PSE._reconciled_environment_application_plans(data.model, alternate, owner)) + @test data.model.environment_binding_cache === owner + @test replacement.binds == replacement.samples == 0 + current = PSE.Advanced.refresh_environment_bindings!(data.model, alternate) + @test current !== owner + @test current.environment_schema === policy + @test typeof(only(current.application_plans)) === typeof(old_plan) + @test only(current.application_plans).backend === replacement + @test replacement.binds == 2 + @test old_backend.binds == 2 + for id in (ObjectId(:leaf), ObjectId(1)) + binding = current.by_target[(:policy_probe, id)] + @test binding.backend === replacement + @test binding.handle !== old_handles[id] + end + replacement.values = (T=71f0, U=82f0) + step!(simulation) + @test model_status(data.model, :leaf).seen === 71f0 + @test model_status(data.model, 1).seen === 71f0 + @test old_backend.samples == 0 + push!(traces, (data.source.normalizations - normalizations, + replacement.binds, replacement.samples, old_backend.binds, old_backend.samples)) + end + @test traces[1] == traces[2] +end + end From 1c5a16c7696c2b0b151c890fdb65c62744094aea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 08:24:37 +0100 Subject: [PATCH 261/324] Share temporal input materialization across growth and ordinary steps --- src/composite_model/runtime_outputs.jl | 128 +++++-------------------- test/test-model-initializers.jl | 19 +++- 2 files changed, 40 insertions(+), 107 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index f73f09423..df6c2e4b9 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2535,96 +2535,29 @@ function _model_assign_private_temporal_value!( return temporal_input end -function _materialize_model_temporal_input!( - status::Status, - temporal_input::CompiledTemporalInput, - application::CompiledModelApplication, - streams, - time::Real, - timeline, -) - binding = temporal_input.binding - plan = getfield(binding, :plan) - source_ids = getfield(binding, :source_ids) - policy = getfield(binding, :policy) - window_steps = _model_input_window_steps(binding, application, timeline) - t_start = float(time) - float(window_steps) + 1.0 - if plan.multiplicity == :many - storage = temporal_input.reference[] - storage isa AbstractVector || error( - "Temporal `Many` input `$(plan.input)` on application ", - "`$(plan.application_id)` has non-vector private storage ", - "`$(typeof(storage))`.", - ) - length(storage) == length(source_ids) || error( - "Temporal `Many` input `$(plan.input)` on application ", - "`$(plan.application_id)` has $(length(storage)) private values for ", - "$(length(source_ids)) resolved source objects. Refresh the ", - "compiled lifecycle bindings before execution.", - ) - for index in eachindex(source_ids) - value = _model_temporal_source_value( - streams, - temporal_input.source_applications[index], - source_ids[index], - plan.source_var, - time, - policy, - t_start, - timeline, - ) - if isnothing(value) - policy isa PreviousTimeStep || error( - "No temporal model value available for input ", - "`$(plan.input)` from ", - "`$(_object_id_text(source_ids[index])).$(plan.source_var)` ", - "at t=$(time).", - ) - value = temporal_input.initial[index] - end - storage[index] = _private_temporal_value(value) - end - return status - end - source_id = only(source_ids) - value = _model_temporal_source_value( - streams, - only(temporal_input.source_applications), - source_id, - plan.source_var, - time, - policy, - t_start, - timeline, - ) - if isnothing(value) - policy isa PreviousTimeStep || error( - "No temporal model value available for input `$(plan.input)` from ", - "`$(_object_id_text(source_id)).$(plan.source_var)` at t=$(time).", - ) - value = temporal_input.initial - end - _model_assign_private_temporal_value!(temporal_input, value) - return status +@inline _compiled_temporal_input(input::CompiledTemporalInput) = input +@inline _compiled_temporal_input(input::RuntimeTemporalInput) = input.compiled + +@inline function _temporal_input_sample(input::CompiledTemporalInput, sources, index, + source_id, plan, time, policy, t_start, timeline) + application_id = isnothing(index) ? only(input.source_applications) : input.source_applications[index] + return _model_temporal_source_value(sources, application_id, source_id, plan.source_var, + time, policy, t_start, timeline) +end + +@inline function _temporal_input_sample(input::RuntimeTemporalInput, sources, index, + source_id, plan, time, policy, t_start, timeline) + stream = isnothing(index) ? input.source_streams : input.source_streams[index] + return _evaluated_temporal_sample_value(stream, time, policy, t_start, timeline) end function _materialize_model_temporal_input!( - status::Status, - runtime_input::RuntimeTemporalInput, - application::CompiledModelApplication, - streams, - time::Real, - timeline, + status::Status, input::Union{CompiledTemporalInput,RuntimeTemporalInput}, + application::CompiledModelApplication, streams, time::Real, timeline, ) - return _materialize_model_temporal_input!( - status, - runtime_input, - application, - streams, - time, - timeline, - getfield(runtime_input.compiled.binding, :policy), - ) + policy = getfield(_compiled_temporal_input(input).binding, :policy) + return _materialize_model_temporal_input!(status, input, application, + streams, time, timeline, policy) end @inline function _previous_time_step_sample(samples, time::Real) @@ -2710,18 +2643,17 @@ end function _materialize_model_temporal_input!( status::Status, - runtime_input::RuntimeTemporalInput, + input::Union{CompiledTemporalInput,RuntimeTemporalInput}, application::CompiledModelApplication, streams, time::Real, timeline, policy, ) - temporal_input = runtime_input.compiled + temporal_input = _compiled_temporal_input(input) binding = temporal_input.binding plan = getfield(binding, :plan) source_ids = getfield(binding, :source_ids) - policy = getfield(binding, :policy) window_steps = _model_input_window_steps(binding, application, timeline) t_start = float(time) - float(window_steps) + 1.0 if plan.multiplicity == :many @@ -2738,13 +2670,8 @@ function _materialize_model_temporal_input!( "compiled lifecycle bindings before execution.", ) for index in eachindex(source_ids) - value = _evaluated_temporal_sample_value( - runtime_input.source_streams[index], - time, - policy, - t_start, - timeline, - ) + value = _temporal_input_sample(input, streams, index, source_ids[index], plan, + time, policy, t_start, timeline) if isnothing(value) policy isa PreviousTimeStep || error( "No temporal model value available for input ", @@ -2759,13 +2686,8 @@ function _materialize_model_temporal_input!( return status end source_id = only(source_ids) - value = _evaluated_temporal_sample_value( - runtime_input.source_streams, - time, - policy, - t_start, - timeline, - ) + value = _temporal_input_sample(input, streams, nothing, source_id, plan, + time, policy, t_start, timeline) if isnothing(value) policy isa PreviousTimeStep || error( "No temporal model value available for input `$(plan.input)` from ", diff --git a/test/test-model-initializers.jl b/test/test-model-initializers.jl index 2a4000b3e..2c5c8818e 100644 --- a/test/test-model-initializers.jl +++ b/test/test-model-initializers.jl @@ -911,7 +911,7 @@ end ) == [4.0] end -@testset "initializer resolves distributed current and prior sources" begin +@testset "initializer resolves distributed current and prior sources" for replaced_history in (false, true) model = CompositeModel( Object(:scene; scale=:Scene), Object(:plant_a; name=:plant_a, scale=:Plant, parent=:scene), @@ -989,14 +989,25 @@ end @test findfirst(==(:writer_b), compiled.application_order) < findfirst(==(:distributed_creator), compiled.application_order) - run!(model; steps=2, outputs=:all) + sim = run!(model; steps=1, outputs=:all) + if replaced_history + key = (:writer_a, ObjectId(:plant_a), :incident_par) + original = outputs(sim)[key] + @test original == [(1.0, 10.0)] + # The ordinary output directory accepts an independently supplied history. + restored = Tuple{Float64,Real}[(1.0, 13.0)] + outputs(sim)[key] = restored + @test outputs(sim)[key] === restored + end + continue!(sim; steps=1) + lagged_total = replaced_history ? 113.0 : 110.0 creator = model_status(model, :scene) leaf = model_status(model, :distributed_new_leaf) @test creator.created @test creator.direct_seen == 20.0 - @test creator.lagged_total == 110.0 + @test creator.lagged_total == lagged_total @test leaf.direct_seen == 20.0 - @test leaf.lagged_total == 110.0 + @test leaf.lagged_total == lagged_total @test model_status(model, :plant_a).incident_par == 20.0 @test model_status(model, :plant_b).incident_par == 200.0 end From fb4066bada90e6fc81a8e313bcef6f7aa9bb6b7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 08:37:27 +0100 Subject: [PATCH 262/324] Own ordered newborn selections and preserve hard-call diagnostics --- src/composite_model/runtime_outputs.jl | 38 +++++++++++-------- test/test-model-concrete-object-identities.jl | 30 +++++++++++++++ 2 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index df6c2e4b9..9a090307b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5797,7 +5797,7 @@ function _targeted_topology_runtime!( O = Dict{I,Vector{A}} S = _TargetedApplicationSet{Vector{A},_ApplicationsByObjectOverlay{typeof(compiled.applications_by_object),O}} manual = compiled.scenario_plan.manual_application_ids - D = Dict{Tuple{Vararg{I}},S} + D = Dict{Vector{I},S} Runtime = _TargetedTopologyRuntime{typeof(compiled),typeof(manual),D,O} cached = delta.targeted_topology_runtime if cached isa Runtime && @@ -5867,7 +5867,9 @@ function _targeted_application_set!( requested_ids, ) I = keytype(runtime.added_applications_by_object) - key = Tuple(requested_ids)::Tuple{Vararg{I}} + # Own the ordered key so later changes to the caller's selection cannot + # alter dictionary equality or hashing. Its type is independent of length. + key = collect(I, requested_ids) application_set = get!(runtime.application_sets, key) do output_applications, added_applications_by_object = _new_object_applications( model, @@ -5912,6 +5914,20 @@ function _targeted_application_set!( return application_set end +@noinline function _unresolved_call_objects(name::Symbol, application_id::Symbol, ids) + io = IOBuffer() + write(io, "Hard call `", String(name), "` from application `", String(application_id), + "` does not resolve requested object(s) `(") + context = IOContext(io, :typeinfo => Any) + for (index, object_id) in pairs(ids) + index == firstindex(ids) || print(io, ", ") + _show_object_id_element(context, object_id.value) + end + length(ids) == 1 && print(io, ',') + print(io, ")`.") + throw(ErrorException(String(take!(io)))) +end + function _targeted_callee_applications( binding::CompiledModelCallBinding, requested_ids, @@ -5937,10 +5953,7 @@ function _targeted_callee_applications( end matched || push!(unresolved_ids, object_id) end - isempty(unresolved_ids) || error( - "Hard call `$(binding.call)` from application `$(binding.application_id)` does not ", - "resolve requested object(s) `$(Tuple(id.value for id in unresolved_ids))`." - ) + isempty(unresolved_ids) || _unresolved_call_objects(binding.call, binding.application_id, unresolved_ids) return applications end @@ -6053,7 +6066,8 @@ function _targeted_new_object_call_targets( "accepts at most one requested object.", ) default_scope = _default_dependency_scope(model, context.object_id) - unresolved_ids = ObjectId[ + I = keytype(model.registry.objects) + unresolved_ids = I[ object_id for object_id in requested_ids if !_selector_matches_object_id( model, @@ -6065,10 +6079,7 @@ function _targeted_new_object_call_targets( false, ) ] - isempty(unresolved_ids) || error( - "Hard call `$(name)` from application `$(context.application.id)` does not ", - "resolve requested object(s) `$(Tuple(id.value for id in unresolved_ids))`." - ) + isempty(unresolved_ids) || _unresolved_call_objects(name, context.application.id, unresolved_ids) if !initializer && binding.multiplicity != :many # A targeted newborn does not relax the authored singular selector. # Resolve its complete live scope before compiling or preparing any @@ -6418,10 +6429,7 @@ function _selected_topology_call_targets(resolved_binding, cached_targets, conte end append!(callee_application_ids, matching_applications) end - isempty(unresolved_ids) || error( - "Hard call `$(name)` from application `$(context.application.id)` does not ", - "resolve requested object(s) `$(Tuple(id.value for id in unresolved_ids))`." - ) + isempty(unresolved_ids) || _unresolved_call_objects(name, context.application.id, unresolved_ids) unique!(callee_application_ids) selected_binding = CompiledModelCallBinding( resolved_binding.plan, diff --git a/test/test-model-concrete-object-identities.jl b/test/test-model-concrete-object-identities.jl index 8414b5a51..f0193d73d 100644 --- a/test/test-model-concrete-object-identities.jl +++ b/test/test-model-concrete-object-identities.jl @@ -107,4 +107,34 @@ end end end +@testset "Newborn application selections own their ordered cache keys" begin + data = fixture(Float64, (:existing,)) + run!(data.model; steps=1, outputs=:none) + first_id, second_id = ObjectId(:new_a), ObjectId(:new_b) + for id in (first_id, second_id) + register_object!(data.model, Object(id; kind=:identity_leaf, parent=data.owner_id)) + end + runtime = PSE._targeted_topology_runtime!(data.capture[], data.model) + selection = [first_id, second_id] + ordered = PSE._targeted_application_set!(runtime, data.model, selection) + reverse!(selection) + reversed = PSE._targeted_application_set!(runtime, data.model, selection) + @test reversed !== ordered + @test PSE._targeted_application_set!(runtime, data.model, (first_id, second_id)) === ordered + @test PSE._targeted_application_set!(runtime, data.model, [second_id, first_id]) === reversed +end + +@testset "Unresolved hard calls preserve the display of user identifiers" begin + selections = ( + [ObjectId(:a)], + [ObjectId((:plant, 2)), ObjectId(3)], + [ObjectId(Symbol("one leaf")), ObjectId(Symbol("if"))], + ) + for ids in selections + values = Tuple(id.value for id in ids) + message = "Hard call `leaves` from application `caller` does not resolve requested object(s) `$values`." + @test_throws ErrorException(message) PSE._unresolved_call_objects(:leaves, :caller, ids) + end +end + end # module ConcreteRuntimeIdentityChecks From b138aad57e51d51899788e9429192bdd3dcfcf7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 08:37:41 +0100 Subject: [PATCH 263/324] Resolve distributed output selectors through their declared plan types --- src/composite_model/compilation.jl | 32 +++++++++++++++++------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 46f199800..679ccffc3 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8274,18 +8274,17 @@ _selector_constraint_values(value) = # Object-level multiplicity and writer ambiguity are still validated when # concrete targets exist. function _selector_labels_may_overlap(left, right) - for key in (:scale, :kind, :species, :id) - left_values = _selector_constraint_values( - _criteria_value(criteria(left), key), - ) - right_values = _selector_constraint_values( - _criteria_value(criteria(right), key), - ) - isempty(left_values) && continue - isempty(right_values) && continue - any(value -> value in right_values, left_values) || return false - end - return true + a, b = criteria(left), criteria(right) + return _selector_constraints_overlap(a, b, :scale) && + _selector_constraints_overlap(a, b, :kind) && + _selector_constraints_overlap(a, b, :species) && + _selector_constraints_overlap(a, b, :id) +end + +@inline function _selector_constraints_overlap(left, right, key) + a = _selector_constraint_values(_criteria_value(left, key)) + b = _selector_constraint_values(_criteria_value(right, key)) + return isempty(a) || isempty(b) || any(in(b), a) end function _potential_input_source_application_ids( @@ -8379,10 +8378,15 @@ function _application_declares_distributed_output( ) end +@inline _matching_output_destination(plan, variable, selector) = + variable in plan.variable_names && _selector_labels_may_overlap(selector, plan.selector) + function _any_matching_output_destination(plans, variable, selector) - return any(plans) do plan - variable in plan.variable_names && _selector_labels_may_overlap(selector, plan.selector) + for index in eachindex(plans) + (Base.@inline _with_metadata_entry(_matching_output_destination, plans, index, + variable, selector)) && return true end + return false end Base.@nospecializeinfer function _potential_call_application_ids( From 7bbcfadcb8eb00ede2a36e6298798bedfce84f48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 10:22:01 +0100 Subject: [PATCH 264/324] Use the registered object location to bind input cells --- src/composite_model/compilation.jl | 3 ++- src/composite_model/object_families.jl | 9 +++++++++ src/composite_model/registry_topology.jl | 11 +++++------ test/test-model-input-binding-storage.jl | 21 +++++++++++++++++++++ 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 679ccffc3..d8bfd13f5 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6492,8 +6492,9 @@ function _input_carrier( model::CompositeModel, selector::AbstractObjectMultiplicity, source_ids::AbstractVector{<:ObjectId}, source_var, reference_types::Type{<:Tuple}, ) + objects = model.registry.objects reference_for = source_id -> - _status_ref_or_nothing(model_status(model, source_id), source_var) + _status_ref_or_nothing(_registered_object_status(objects, source_id), source_var) return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end diff --git a/src/composite_model/object_families.jl b/src/composite_model/object_families.jl index 1e27e9f81..5e8ee90a5 100644 --- a/src/composite_model/object_families.jl +++ b/src/composite_model/object_families.jl @@ -143,6 +143,15 @@ end _object_family_status(store::ObjectFamilyStore, id) = _object_family_status_at(store.catalog, store.locations[id]) +function _require_object_location(store::ObjectFamilyStore, id::ObjectId) + location = get(store.locations, id, nothing) + isnothing(location) && error("No model object with id `", _object_id_text(id), "`.") + return location +end + +_registered_object_status(store::ObjectFamilyStore, id::ObjectId) = + _object_family_status_at(store.catalog, _require_object_location(store, id)) + function _validate_object_family_status_owner!(store::ObjectFamilyStore, status, id) status isa Status || return nothing existing = get(store.status_owners, _status_identity(status), nothing) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 9b43a528c..d31388e76 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1233,12 +1233,8 @@ function _show_object_id_element(io, value::Tuple) return nothing end -function _model_object(model::CompositeModel, id) - oid = ObjectId(id) - object = get(model.registry.objects, oid, nothing) - isnothing(object) && error("No model object with id `", _object_id_text(oid), "`.") - return object -end +_model_object(model::CompositeModel, id) = + _require_object_location(model.registry.objects, ObjectId(id)).object """ model_object(model::CompositeModel, id) -> Object @@ -1328,6 +1324,9 @@ model registry and is not stored in MTG attributes. model_status(model::CompositeModel, source) = _object_family_status(model.registry.objects, object_id(model, source)) +model_status(model::CompositeModel, id::ObjectId) = + _registered_object_status(model.registry.objects, id) + """ source_node(model::CompositeModel, source) -> MultiScaleTreeGraph.Node diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 967c95745..25adeb2d9 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -605,4 +605,25 @@ end check_carriers(data, simulation) end +@testset "an input reference belongs to the live registry of its simulation" begin + model, other = fixture().model, fixture().model + simulation = prepare(model) + id = ObjectId(:anchor) + selector = One(id=:anchor) + types = binding(simulation, :a, :single).plan.reference_types + carrier(m) = PSE._input_carrier(m, selector, [id], :x, types) + + reference = carrier(model) + @test reference === PSE.refvalue(model_status(model, id), :x) + @test carrier(other) === PSE.refvalue(model_status(other, id), :x) + @test carrier(other) !== reference + @test_throws ArgumentError model_status(other, model_object(model, id)) + @test_throws ArgumentError model_status(other, model_status(model, id)) + + remove_object!(model, id) + @test_throws "No model object with id `anchor`." model_status(model, id) + @test_throws "No model object with id `anchor`." carrier(model) + @test reference[] === 3f0 +end + end # module ModelInputBindingStorageChecks From a9d4b8dced1d5a9ec8331222a89dd01b9b513737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 10:22:19 +0100 Subject: [PATCH 265/324] Rebuild singular hard calls when their sole target changes --- src/composite_model/runtime_outputs.jl | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 9a090307b..0f7bdb9ec 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4251,6 +4251,9 @@ function _extend_execution_target_call_batches_by_prefix!( existing_count = next_count end existing_count == length(current_ids) && return true + # Existing batches own nonempty runs. A singular call can retain + # its one row or rebuild it when the callee changes. + binding.plan.selector isa Union{One,OptionalOne} && return false admission = _call_cohort_admission(application_schema, OpenExecutionCohortSchema()) first_new_index = existing_count + 1 return _with_execution_batch(application_schema, last(batches)) do destination_batch @@ -4353,6 +4356,8 @@ function _extend_execution_target_call_batches_for_pure_addition!( isempty(changed_ids) && return true length(affected_application_ids) == 1 || return nothing length(binding.callee_application_ids) == 1 || return nothing + # No singular membership contains both the old boundary and a later ID. + binding.plan.selector isa Union{One,OptionalOne} && return false application_id = only(affected_application_ids) return _compiled_application_by_id(compiled, application_id) do application application_schema = _call_batch_schema_for_application(schema, application) From def1cca92f80725ff701e59be8662a7af7e64c25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 10:31:04 +0100 Subject: [PATCH 266/324] Format hard-call diagnostics without compiling the Julia expression printer --- src/composite_model/registry_topology.jl | 3 ++- src/composite_model/runtime_outputs.jl | 27 ++++++++++++++++++------ test/test-model-runtime-call-names.jl | 10 ++++++++- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index d31388e76..b1b3cedbe 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -1205,8 +1205,9 @@ _object_id_text(id::ObjectId) = string(id.value) _object_id_text(id::ObjectId{<:Tuple}) = sprint(_show_object_id_element, id.value) _show_object_id_element(io, value) = show(io, value) +_show_object_id_element(io, value::Symbol) = _show_quoted_symbol(io, value) # Preserve Base's quoted-Symbol spelling without its Any-valued Expr branch. -function _show_object_id_element(io, value::Symbol) +function _show_quoted_symbol(io, value::Symbol) if value in Base.quoted_syms print(io, ":(") print(io, value) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 0f7bdb9ec..b2325c5c8 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5722,10 +5722,27 @@ end @noinline function _missing_named_call(context, name) available = Symbol[_with_metadata_entry(targets -> targets.binding.call, context.calls, slot) for slot in eachindex(context.calls)] + return _missing_named_call(context, name, available) +end + +function _diagnostic_symbol_list(names::Vector{Symbol}; as_tuple=false) + isempty(names) && return as_tuple ? "()" : "Symbol[]" + io = IOBuffer() + print(io, as_tuple ? '(' : '[') + for (i, name) in pairs(names) + i == firstindex(names) || print(io, ", ") + _show_quoted_symbol(io, name) + end + as_tuple && length(names) == 1 && print(io, ',') + print(io, as_tuple ? ')' : ']') + return String(take!(io)) +end + +@noinline function _missing_named_call(context, name, available) error( "Application `$(context.application.id)` on object ", "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", - "Declared calls: $(available).", + "Declared calls: ", _diagnostic_symbol_list(available), ".", ) end @@ -6183,7 +6200,7 @@ function _prepare_targeted_newborn_targets( if !isempty(unsupported_temporal_inputs) initializer && error( "Initializer `$(name)` target requires unsupported temporal input(s) " * - "`$(Tuple(unsupported_temporal_inputs))`; only `PreviousTimeStep` has " * + "`$(_diagnostic_symbol_list(unsupported_temporal_inputs; as_tuple=true))`; only `PreviousTimeStep` has " * "defined newborn initialization semantics.", ) return nothing @@ -6384,11 +6401,7 @@ function _current_topology_call_targets( if isnothing(binding) bindings = get(compiled.call_bindings_by_target, (context.application.id, context.object_id), ()) available = Symbol[(item::CompiledModelCallBinding).call for item in bindings] - error( - "Application `$(context.application.id)` on object ", - "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", - "Declared calls: $(available).", - ) + _missing_named_call(context, name, available) end selected = _selected_topology_call_targets(binding, cached_targets, context, name, requested_ids, model, compiled, environment_bindings) diff --git a/test/test-model-runtime-call-names.jl b/test/test-model-runtime-call-names.jl index c24b9da12..5ea103d33 100644 --- a/test/test-model-runtime-call-names.jl +++ b/test/test-model-runtime-call-names.jl @@ -70,6 +70,14 @@ function manual_fixture() return (; model, capture) end +@testset "diagnostics preserve Julia's spelling of declared names" begin + for names in (Symbol[], [:first], [:first, :second], + [Symbol("a b"), Symbol(":"), Symbol("'"), Symbol("a\"b"), :énergie]) + @test PSE._diagnostic_symbol_list(names) == string(names) + @test PSE._diagnostic_symbol_list(names; as_tuple=true) == string(Tuple(names)) + end +end + @testset "runtime Symbol calls keep finite heterogeneous target branches" begin @test_throws ArgumentError cli_name(String[]) @test_throws ArgumentError cli_name(["a", "b"]) @@ -95,7 +103,7 @@ end @test outputs(simulation)[(:target_b, ObjectId(:second), :value)] == [(1.0, 7.0)] @test isempty(cli_run(context, ["empty"]; publish=true)) @test_throws ArgumentError cli_model(context, ["empty"]) - @test_throws ErrorException cli_targets(context, ["missing"]) + @test_throws "Declared calls: [:a, :b, :empty]." cli_targets(context, ["missing"]) @test_throws ErrorException cli_model(context, ["missing"]) @test_throws ErrorException cli_run(context, ["missing"]) @test_throws ErrorException cli_run(context, a_args; objects=:second) From 32f70c373c1d2ef4890dc9c86a930fa2b75b7c69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 11:01:19 +0100 Subject: [PATCH 267/324] Keep prepared output histories in their declared storage family --- src/composite_model/execution_storage.jl | 12 +- src/composite_model/runtime_outputs.jl | 6 +- test/test-model-runtime-stream-extensions.jl | 109 +++++++++++++++++++ 3 files changed, 122 insertions(+), 5 deletions(-) diff --git a/src/composite_model/execution_storage.jl b/src/composite_model/execution_storage.jl index 673d074cb..f4ab7c1dc 100644 --- a/src/composite_model/execution_storage.jl +++ b/src/composite_model/execution_storage.jl @@ -21,12 +21,18 @@ RuntimeStorage(streams::AbstractDict, registry::ObjectFamilyStore) = Base.length(storage::RuntimeStorage) = length(storage.streams) Base.iterate(storage::RuntimeStorage, state...) = iterate(storage.streams, state...) Base.getindex(storage::RuntimeStorage, key) = storage.streams[key] -Base.setindex!(storage::RuntimeStorage, value, key) = setindex!(storage.streams, value, key) +function _runtime_storage_history(storage::RuntimeStorage{K,H}, value) where {K,H} + value isa H || throw(ArgumentError("The output stream is outside the prepared history family.")) + return value::H +end +Base.setindex!(storage::RuntimeStorage, value, key) = + setindex!(storage.streams, _runtime_storage_history(storage, value), key) Base.haskey(storage::RuntimeStorage, key) = haskey(storage.streams, key) Base.get(storage::RuntimeStorage, key, default) = get(storage.streams, key, default) -Base.get!(storage::RuntimeStorage, key, default) = get!(storage.streams, key, default) +Base.get!(storage::RuntimeStorage, key, default) = + get!(() -> _runtime_storage_history(storage, default), storage.streams, key) Base.get!(default::Union{Function,Type}, storage::RuntimeStorage, key) = - get!(default, storage.streams, key) + get!(() -> _runtime_storage_history(storage, default()), storage.streams, key) Base.delete!(storage::RuntimeStorage, key) = (delete!(storage.streams, key); storage) Base.empty!(storage::RuntimeStorage) = (empty!(storage.streams); storage) Base.empty(storage::RuntimeStorage) = RuntimeStorage(empty(storage.streams), typeof(storage.cohorts)()) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index b2325c5c8..848efb10f 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -8192,7 +8192,8 @@ function _prepare_simulation!( environment_schema=_environment_schema(getfield(model, :environment_binding_cache)), input_binding_storage=nothing, status_view_schema=nothing, -) + output_stream_type::Type{H}=Any, +) where {H} performance_counters = performance ? RuntimePerformanceCounters() : nothing initial_composite_started_at = _runtime_performance_start(performance_counters) @@ -8288,7 +8289,8 @@ function _prepare_simulation!( :initial_output_retention_compile, started_at, ) - temporal_streams = RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},Any}(), model.registry.objects) + # The simulation owns its history directory; ordinary execution keeps Any. + temporal_streams = RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},H}(), model.registry.objects) _initialize_model_output_streams!( temporal_streams, compiled, diff --git a/test/test-model-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl index 8b0ff4f55..32ca4cd9d 100644 --- a/test/test-model-runtime-stream-extensions.jl +++ b/test/test-model-runtime-stream-extensions.jl @@ -376,4 +376,113 @@ end @test reader_runs[] == 2 end +@testset "simulation history families preserve streams through continuation" begin + make_model() = CompositeModel(Object(0; scale=:Leaf); + applications=(ModelSpec(Source(Ref(0)); name=:source, on=One(id=0)),)) + ordinary = run!(make_model(); steps=0, outputs=:all) + H = Union{Vector{Tuple{Float64,Real}}, map(typeof, values(outputs(ordinary)))...} + finite = PSE._prepare_simulation!(make_model(); steps=0, outputs=:all, + constants=PSE.Constants(), output_stream_type=H) + @test valtype(typeof(outputs(ordinary))) === Any + @test valtype(typeof(outputs(finite))) === H + @test outputs(ordinary) !== outputs(finite) + @test all(key -> outputs(ordinary)[key] !== outputs(finite)[key], keys(outputs(ordinary))) + continue!(ordinary; steps=1) + continue!(finite; steps=1) + key = (:source, ObjectId(0), :z) + restored = map((ordinary, finite)) do simulation + history = Tuple{Float64,Real}[(1.0, 13.0)] + outputs(simulation)[key] = history + @test outputs(simulation)[key] === history + history + end + continue!(ordinary; steps=0) + continue!(finite; steps=0) + continue!(ordinary; steps=1) + continue!(finite; steps=1) + @test current_step(ordinary) == current_step(finite) == 2 + @test histories(ordinary) == histories(finite) + @test NamedTuple(model_status(ordinary.model, 0)) == NamedTuple(model_status(finite.model, 0)) + @test all(pair -> outputs(pair[1])[key] === pair[2], zip((ordinary, finite), restored)) + @test valtype(typeof(outputs(finite))) === H + + # Exercise both creation sites with a real status/ref and retention plan. + # Vector{Tuple{Float64,Float64}} is convertible to this single family, but + # conversion would disconnect the stored history from the runtime stream. + F = Vector{Tuple{Float64,Float32}} + storage = PSE.RuntimeStorage(Dict{Tuple{Symbol,ObjectId,Symbol},F}(), ordinary.model.registry.objects) + status = model_status(ordinary.model, 0) + a_key = (:source, ObjectId(0), :a) + z_key = (:source, ObjectId(0), :z) + PSE._initialize_model_output_stream_from_reference!(PSE.refvalue(status, :a), storage, + ordinary.output_retention, :source, a_key, :a, 0, 1) + original = storage[a_key] + before = copy(original) + @test_throws ArgumentError PSE._initialize_model_output_stream_from_reference!( + PSE.refvalue(status, :z), storage, ordinary.output_retention, :source, z_key, :z, 0, 1) + @test !haskey(storage, z_key) + @test_throws ArgumentError PSE._initialize_model_output_stream_from_reference!( + PSE.refvalue(status, :z), storage, ordinary.output_retention, :source, a_key, :a, 0, 1) + @test storage[a_key] === original + @test original == before + application = only(ordinary.compiled.applications) + @test_throws ArgumentError PSE._runtime_model_output_streams(status, application, + ObjectId(0), storage, ordinary.output_retention, true) + @test !haskey(storage, z_key) + @test storage[a_key] === original + @test original == before + + target = execution_target(ordinary, :source, 0) + a_output = only(output for output in target.output_bindings if PSE._runtime_output_variable(output) === :a) + z_output = only(output for output in target.output_bindings if PSE._runtime_output_variable(output) === :z) + @test_throws ArgumentError PSE._prepared_local_runtime_output(typeof(z_output), + status, application, ObjectId(0), storage, ordinary.output_retention, true) + @test !haskey(storage, z_key) + accepted = PSE._prepared_local_runtime_output(typeof(a_output), + status, application, ObjectId(0), storage, ordinary.output_retention, true) + @test accepted.stream === storage[a_key] === original + @test accepted.reference === PSE.refvalue(status, :a) + + # Restoration uses the same write boundary, even when Dict could convert. + unexpected = Tuple{Float64,Float64}[(3.0, 123.0)] + @test unexpected isa Vector{Tuple{Float64,Float64}} + @test_throws ArgumentError setindex!(storage, unexpected, a_key) + @test storage[a_key] === original + @test original == before + @test_throws ArgumentError setindex!(storage, unexpected, z_key) + @test !haskey(storage, z_key) + @test get!(storage, a_key, unexpected) === original + @test_throws ArgumentError get!(storage, z_key, unexpected) + @test !haskey(storage, z_key) + + calls = Ref(0) + bad_default() = (calls[] += 1; unexpected) + @test get!(bad_default, storage, a_key) === original + @test calls[] == 0 + @test_throws ArgumentError get!(bad_default, storage, z_key) + @test calls[] == 1 + @test !haskey(storage, z_key) + good = F() + good_default() = (calls[] += 1; good) + @test get!(good_default, storage, z_key) === good + @test storage[z_key] === good + @test calls[] == 2 + @test get!(bad_default, storage, z_key) === good + @test calls[] == 2 + delete!(storage, z_key) + @test get!(storage, z_key, good) === good + @test setindex!(storage, good, z_key) === storage.streams + delete!(storage, z_key) + from_type = get!(F, storage, z_key) + @test from_type isa F + @test storage[z_key] === from_type + + # Ordinary H=Any still accepts an independently supplied history by identity. + any_storage = ordinary.temporal_streams + @test setindex!(any_storage, unexpected, z_key) === any_storage.streams + @test outputs(ordinary)[z_key] === unexpected + @test storage[a_key] === original + @test original == before +end + end From e14bef17912e179128348c908365b73f226c61d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 11:56:26 +0100 Subject: [PATCH 268/324] Use the admitted application and bindings when preparing newborn calls --- src/composite_model/compilation.jl | 10 +-- src/composite_model/runtime_outputs.jl | 87 ++++++++++++-------------- 2 files changed, 44 insertions(+), 53 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index d8bfd13f5..82b947536 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3021,7 +3021,7 @@ function _record_consumer_input_bindings!( recorder.many_binding_cache, recorder.model, bindings[binding_index], ) bindings[binding_index] = binding - push!(new_bindings, binding) + push!(new_bindings, bindings[binding_index]) end append!(recorder.changed_bindings, new_bindings) recorder.input_bindings_by_target[(application_id, consumer_id)] = new_bindings @@ -4633,7 +4633,7 @@ function _refresh_scene_call_bindings!( pure_addition && _index_observed_manual_call_binding_by_callee_target!( observed_manual_call_binding_indices_by_callee_target, - binding, + call_bindings[binding_index], binding_index, applications_by_id, ) @@ -6161,7 +6161,7 @@ function _compile_model_writer_ownership( ownership = _object_key_index(Tuple{I,Symbol}, Vector{CompiledWriterOwner}) for partial in applications getfield(getfield(partial, :plan), :id) in manual_application_ids && continue - _with_model_application(_record_application_writers!, applications_by_id, partial, + Base.@inline _with_model_application(_record_application_writers!, applications_by_id, partial, ownership, nothing, partial.target_ids) end _record_destination_writers!(ownership, nothing, resolved_destinations) @@ -9019,7 +9019,7 @@ function _compile_model_input_bindings!(bindings, model, applications, manual_ap ) for partial in applications isempty(partial.target_ids) && continue - _with_model_application(by_id, partial) do application + Base.@inline _with_model_application(by_id, partial) do application _with_metadata_entry(recipes, application.id) do recipe _compile_application_consumer_bindings!( bindings, model, application, recipe, manual_application_ids, @@ -9418,7 +9418,7 @@ function _validate_model_required_inputs!(model::CompositeModel, applications, a I = keytype(model.registry.objects) missing = NamedTuple{(:application_id, :object_id, :input),Tuple{Symbol,I,Symbol}}[] for partial in applications - _with_model_application(applications_by_id, partial) do application + Base.@inline _with_model_application(applications_by_id, partial) do application required_names = _required_input_names(_application_ports(application)) for object_id in application.target_ids for input in required_names diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 848efb10f..791ae5571 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5979,17 +5979,9 @@ function _targeted_callee_applications( return applications end -function _applications_use_only_global_environment( - model::CompositeModel, - applications, -) - return all(applications) do application - backend = _environment_backend_from_config( - model, - environment_config(application.spec), - ) - return isnothing(backend) || backend isa GlobalConstant - end +function _application_uses_global_environment(application, model) + backend = _environment_backend_from_config(model, environment_config(application.spec)) + return isnothing(backend) || backend isa GlobalConstant end function _targeted_call_environment_bindings( @@ -5999,8 +5991,11 @@ function _targeted_call_environment_bindings( applications, applications_by_id, ) - _applications_use_only_global_environment(model, applications) || - return nothing + for partial in applications + uses_global = Base.@inline _with_model_application(_application_uses_global_environment, + applications_by_id, partial, model) + uses_global || return nothing + end partial = _compile_environment_bindings_for_applications( model, applications, @@ -6227,10 +6222,9 @@ function _prepare_targeted_newborn_targets( targets = _targeted_newborn_target_buffer(batch_schema, context) for partial_application in callee_applications - _append_targeted_newborn_targets!( - targets, context, targeted_runtime, partial_application, - targeted_input_bindings, environment_bindings, batch_schema, - ) + Base.@inline _with_model_application(_append_targeted_newborn_targets!, + compiled.applications_by_id, partial_application, targets, context, + targeted_runtime, targeted_input_bindings, environment_bindings, batch_schema) end if initializer length(targets) == 1 || error( @@ -6242,44 +6236,41 @@ function _prepare_targeted_newborn_targets( end function _append_targeted_newborn_targets!( - targets, + partial_application::A, targets, context::RunContext, targeted_runtime::_TargetedTopologyRuntime, - partial_application::CompiledModelApplication, targeted_input_bindings, environment_bindings::CompiledEnvironmentBindings, batch_schema::ExecutionBatchSchema, -) +) where {A<:CompiledModelApplication} compiled = context.compiled - # Partial applications share the genuine authored application plan. - _compiled_application_by_id(compiled,partial_application.id) do application - application_schema = _call_batch_schema_for_application(batch_schema,application) - admission = _call_cohort_admission(application_schema,OpenExecutionCohortSchema()) - for object_id in partial_application.target_ids - key = (application.id,object_id) - cache = get(targeted_runtime.call_context_caches,key,nothing)::Union{Nothing,CallContextCache} - stamp = isnothing(cache) ? Ref(UInt64(0)) : - (getfield(cache,:execution_stamp)::Base.RefValue{UInt64}) - status_view = _compile_model_status_view(runtime_model(context),partial_application, - object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, - targeted_runtime.application_positions,compiled.distributed_outputs, - stamp, compiled.status_view_schema, - compiled.input_bindings)::CompiledModelStatusView - output_groups = _runtime_model_output_groups(compiled,application,object_id) - environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) - call_bindings = () # targeted admission has rejected nested callees - model = _application_model(application,object_id) - owners = (compiled=compiled,environment_bindings=environment_bindings, - temporal_streams=context.temporal_streams, - output_retention=context.output_retention,constants=context.constants, - environment=context.environment) - Base.@inline _with_execution_target_type(admission,application,status_view,object_id,model, - output_groups,call_bindings,environment_binding,owners) do target_type,actual_application,actual,owner,call_schema - _append_targeted_newborn_target!(target_type,actual_application,actual,owner, - call_schema,targets,context,cache,stamp,targeted_runtime,key) - end + # The selection owns the requested IDs. Contexts retain the registered application. + application = compiled.applications_by_id[partial_application.id]::A + application_schema = _call_batch_schema_for_application(batch_schema,application) + admission = _call_cohort_admission(application_schema,OpenExecutionCohortSchema()) + for object_id in partial_application.target_ids + key = (application.id,object_id) + cache = get(targeted_runtime.call_context_caches,key,nothing)::Union{Nothing,CallContextCache} + stamp = isnothing(cache) ? Ref(UInt64(0)) : + (getfield(cache,:execution_stamp)::Base.RefValue{UInt64}) + status_view = _compile_model_status_view_for_application(partial_application, runtime_model(context), + object_id,get(targeted_input_bindings,key,()),compiled.applications_by_id, + targeted_runtime.application_positions,compiled.distributed_outputs, + stamp, compiled.status_view_schema, + compiled.input_bindings)::CompiledModelStatusView + output_groups = _runtime_model_output_groups(compiled,application,object_id) + environment_binding = _environment_binding_for(environment_bindings,application.id,object_id) + call_bindings = () # targeted admission has rejected nested callees + model = _application_model(application,object_id) + owners = (compiled=compiled,environment_bindings=environment_bindings, + temporal_streams=context.temporal_streams, + output_retention=context.output_retention,constants=context.constants, + environment=context.environment) + Base.@inline _with_execution_target_type(admission,application,status_view,object_id,model, + output_groups,call_bindings,environment_binding,owners) do target_type,actual_application,actual,owner,call_schema + _append_targeted_newborn_target!(target_type,actual_application,actual,owner, + call_schema,targets,context,cache,stamp,targeted_runtime,key) end - return nothing end return targets end From 031e0c145274e1a06c1f8580399a3f087d47e2ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:04:51 +0100 Subject: [PATCH 269/324] Make nested call storage available to the schema generator --- src/composite_model/execution_batch_schemas.jl | 11 ++++++----- test/test-model-prepared-call-schemas.jl | 4 ++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 9e6e3b2db..1f3c585c9 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -52,6 +52,12 @@ end _prepared_call_mode(::Type{<:CompiledModelCallBinding{P}}) where {P} = _prepared_call_plan_mode(P) _prepared_call_plan_mode(::Type{<:CompiledModelCallPlan{NAME,MODE}}) where {NAME,MODE} = MODE +function _prepared_call_batch_storage_type(::Type{B}, ::Type{BT}) where {B, BT} + _prepared_call_mode(B) === :initializer && return Tuple{} + Selector = fieldtype(fieldtype(B, :plan), :selector) + return BT <: Tuple && Selector <: Many ? Union{Nothing, BT} : BT +end + function _validate_prepared_context_calls(::Type{C}) where {C<:Tuple} isconcretetype(C) || throw(ArgumentError("Prepared context calls require a concrete finite tuple.")) for CT in fieldtypes(C) @@ -264,11 +270,6 @@ end @inline _materialize_call_execution_batches!(::OpenExecutionBatchSchema, targets::CallTargets) = _materialize_open_call_execution_batches!(targets) -function _prepared_call_batch_storage_type(::Type{B}, ::Type{BT}) where {B, BT} - _prepared_call_mode(B) === :initializer && return Tuple{} - Selector = fieldtype(fieldtype(B, :plan), :selector) - return BT <: Tuple && Selector <: Many ? Union{Nothing, BT} : BT -end @inline _call_execution_batch_storage_type(::OpenExecutionBatchSchema, binding, batches) = typeof(batches) @inline _call_execution_batch_storage_type(::PreparedExecutionBatchSchema{BT}, binding, batches) where {BT} = _prepared_call_batch_storage_type(typeof(binding), BT) diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl index e2f8122f6..c5fd23ebf 100644 --- a/test/test-model-prepared-call-schemas.jl +++ b/test/test-model-prepared-call-schemas.jl @@ -183,6 +183,10 @@ end original_root = root_target(data.simulation) streams = Dict(key => stream for (key, stream) in outputs(data.simulation)) learned = observed_schemas(data.simulation) + # A nested call exercises the generator's view of its schema helpers. + cohort = PSE._execution_cohort_schema(learned.schemas.root) + @test cohort isa PSE.ClosedExecutionCohortSchema + @test only(fieldtypes(only(typeof(cohort).parameters))) === eltype(fieldtype(learned.RootB, :targets)) @test data.kernels == Dict(:root => 0, :middle => 0, :leaf => 0) @test scientific_state(data.model) == before @test rng_probe(data.rng) == random_state From 0996eb0c4fe4f6e7a5162e9bdc99a4829535716e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:10:56 +0100 Subject: [PATCH 270/324] Use public MTG edits for tree-backed organ growth and rollback --- src/composite_model/registry_topology.jl | 76 ++++++++++++++---------- test/test-organ-status-assembly.jl | 71 ++++++++++++++++------ 2 files changed, 99 insertions(+), 48 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index b1b3cedbe..810337e22 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -249,7 +249,7 @@ struct MTGObjectAccessors{I,S,K,SP,N,G,ST} status::ST end -struct MTGObjectAdapter{R,I,S,K,SP,N,G,ST,FI,RI} +struct MTGObjectAdapter{R,I,S,K,SP,N,G,ST,FI,RI,E} root::R id::I scale::S @@ -261,11 +261,19 @@ struct MTGObjectAdapter{R,I,S,K,SP,N,G,ST,FI,RI} max_node_id::Base.RefValue{Int} object_ids_by_node::FI nodes_by_object_id::RI + node_edits::E +end + +# An open tree admits new column types. A prepared adapter also retains +# the edit plan of its source tree when the MTG version supports it. +function _prepared_mtg_edits(root) + if isdefined(MultiScaleTreeGraph, :prepare_node_edits) && + applicable(MultiScaleTreeGraph.prepare_node_edits, root) + return (MultiScaleTreeGraph.prepare_node_edits(root),) + end + return () end -# Close only identity carrier types, preserving the source tree and every -# accessor. A closed execution schema can still create arbitrary numbers of -# nodes and call the same registration/removal operations. function _closed_mtg_object_adapter(adapter::MTGObjectAdapter, ::Type{I}) where {I<:ObjectId} R = typeof(adapter.root) return MTGObjectAdapter( @@ -273,6 +281,7 @@ function _closed_mtg_object_adapter(adapter::MTGObjectAdapter, ::Type{I}) where adapter.name, adapter.geometry, adapter.status, adapter.max_node_id, IdDict{R,I}(adapter.object_ids_by_node), Dict{I,R}(adapter.nodes_by_object_id), + _prepared_mtg_edits(adapter.root), ) end @@ -811,8 +820,21 @@ function CompositeModel( ) end -_mtg_attribute(node, key::Symbol, default=nothing) = - get(MultiScaleTreeGraph.node_attributes(node), key, default) +struct _MTGAttribute + key::Symbol +end +(accessor::_MTGAttribute)(node) = MultiScaleTreeGraph.attribute(node, accessor.key, nothing) + +_mtg_birth_attribute(accessor, node, edits) = accessor(node) +_mtg_birth_attribute(accessor::_MTGAttribute, node, edits) = + MultiScaleTreeGraph.attribute(edits..., node, accessor.key, nothing) + +# The open MTG API also accepts dictionary-backed attributes. Its prepared +# overload takes named rows, whose values retain the caller's objects. +_mtg_birth_attributes(::Tuple{}, attributes) = attributes +_mtg_birth_attributes(::Tuple{P}, attributes::NamedTuple) where {P} = attributes +_mtg_birth_attributes(::Tuple{P}, attributes) where {P} = + (; (Symbol(key) => value for (key, value) in pairs(attributes))...) _no_mtg_status(_) = nothing @@ -832,10 +854,10 @@ function objects_from_mtg( root::MultiScaleTreeGraph.Node; id=node_id, scale=symbol, - kind=node -> _mtg_attribute(node, :kind, nothing), - species=node -> _mtg_attribute(node, :species, nothing), - name=node -> _mtg_attribute(node, :name, nothing), - geometry=node -> _mtg_attribute(node, :geometry, nothing), + kind=_MTGAttribute(:kind), + species=_MTGAttribute(:species), + name=_MTGAttribute(:name), + geometry=_MTGAttribute(:geometry), status=_no_mtg_status, ) accessors = MTGObjectAccessors( @@ -914,10 +936,10 @@ function CompositeModel( environment=nothing, id=node_id, scale=symbol, - kind=node -> _mtg_attribute(node, :kind, nothing), - species=node -> _mtg_attribute(node, :species, nothing), - name=node -> _mtg_attribute(node, :name, nothing), - geometry=node -> _mtg_attribute(node, :geometry, nothing), + kind=_MTGAttribute(:kind), + species=_MTGAttribute(:species), + name=_MTGAttribute(:name), + geometry=_MTGAttribute(:geometry), status=_no_mtg_status, type_promotion=nothing, status_transform=nothing, @@ -934,6 +956,7 @@ function CompositeModel( Ref(MultiScaleTreeGraph.new_id(root) - 1), IdDict{typeof(root),ObjectId}(), Dict{ObjectId,typeof(root)}(), + (), ) objects = _objects_from_mtg(root, adapter) return CompositeModel( @@ -1639,27 +1662,20 @@ function add_organ!( explicit_id end - node = MultiScaleTreeGraph.Node( - node_id, - parent_node, - MultiScaleTreeGraph.NodeMTG( - Symbol(link), - Symbol(organ_symbol), - Int(index), - Int(mtg_scale), - ), - attributes, - ) + edits = adapter.node_edits + encoding = MultiScaleTreeGraph.NodeMTG(Symbol(link), Symbol(organ_symbol), Int(index), Int(mtg_scale)) + node = MultiScaleTreeGraph.addchild!(edits..., parent_node, node_id, encoding, + _mtg_birth_attributes(edits, attributes)) try new_object_id = _register_mtg_object_identity!(adapter, node) object = Object( new_object_id; scale=adapter.scale(node), - kind=isnothing(kind) ? adapter.kind(node) : kind, - species=isnothing(species) ? adapter.species(node) : species, - name=isnothing(name) ? adapter.name(node) : name, + kind=isnothing(kind) ? _mtg_birth_attribute(adapter.kind, node, edits) : kind, + species=isnothing(species) ? _mtg_birth_attribute(adapter.species, node, edits) : species, + name=isnothing(name) ? _mtg_birth_attribute(adapter.name, node, edits) : name, parent=parent_id, - geometry=adapter.geometry(node), + geometry=_mtg_birth_attribute(adapter.geometry, node, edits), status=status, ) registered = register_object!(model, object) @@ -1667,7 +1683,7 @@ function add_organ!( return _with_registered_status(identity, model.registry.objects.catalog, registered.status)::Status catch _unregister_mtg_object_identity!(adapter, node) - MultiScaleTreeGraph.delete_node!(node) + MultiScaleTreeGraph.delete_node!(edits..., node) rethrow() end end diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index 5df1a9af7..d4cc100a1 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -102,26 +102,61 @@ end @test PSE.refvalue(newborn, :seed) === PSE.refvalue(given, :seed) end +@testset "a prepared MTG adapter keeps scientific inputs separate from node annotations" begin + root = MTG.Node(1, MTG.NodeMTG(:/, :Plant, 1, 1), + (kind=:plant, note="plant", seed=0f0, geometry=Float32[])) + adapter = PSE._closed_mtg_object_adapter(CompositeModel(root).source_adapter, ObjectId{Int}) + if isdefined(MTG, :prepare_node_edits) + @test length(adapter.node_edits) == 1 + end + model = CompositeModel(only(objects_from_mtg(root)); source_adapter=adapter, + applications=(ModelSpec(Probe(2f0); name=:probe, on=Many(scale=:Leaf)),)) + simulation = run!(model; steps=0, outputs=:all) + geometry = Float32[1, 2] + given = Status(seed=3f0, payload=Float32[]) + leaf = add_organ!(root, simulation, :+, :Leaf, 2; + attributes=Dict{Symbol,Any}(:kind=>:expanding, :note=>"first", :geometry=>geometry, :seed=>99f0), + initial_status=given) + node = source_node(model, leaf) + @test only(MTG.children(root)) === node + @test model_object(model, node).kind === :expanding + @test model_object(model, node).geometry === geometry + @test node[:note] == "first" && node[:seed] === 99f0 + @test !hasproperty(leaf, :geometry) && !hasproperty(leaf, :note) + @test PSE.refvalue(leaf, :seed) === PSE.refvalue(given, :seed) + bare = add_organ!(root, simulation, :+, :Leaf, 2; initial_status=(seed=4f0,)) + @test isnothing(model_object(model, source_node(model, bare)).kind) + continue!(simulation; steps=1) + @test leaf.value === 5f0 && bare.value === 6f0 + @test only(outputs(simulation)[(:probe, object_id(model, leaf), :value)]) == (1.0, 5f0) +end + @testset "a failing MTG accessor preserves a descendant it already attached" begin - root = MTG.Node(MTG.NodeMTG(:/, :Plant, 1, 1)) - newborn = Ref{typeof(root)}() - tip = Ref{typeof(root)}() - function kind(node) - MTG.symbol(node) === :Leaf || return :plant - @test MTG.parent(node) === root && only(MTG.children(root)) === node - newborn[] = node - tip[] = MTG.Node(MTG.node_id(node) + 1, node, MTG.NodeMTG(:<, :Tip, 1, 2), (;)) - throw(ArgumentError("rejected leaf")) + for prepared in (false, true) + root = MTG.Node(MTG.NodeMTG(:/, :Plant, 1, 1)) + newborn = Ref{typeof(root)}() + tip = Ref{typeof(root)}() + function kind(node) + MTG.symbol(node) === :Leaf || return :plant + @test MTG.parent(node) === root && only(MTG.children(root)) === node + newborn[] = node + tip[] = MTG.Node(MTG.node_id(node) + 1, node, MTG.NodeMTG(:<, :Tip, 1, 2), (;)) + throw(ArgumentError("rejected leaf")) + end + model = CompositeModel(root; kind) + if prepared + adapter = PSE._closed_mtg_object_adapter(model.source_adapter, ObjectId{Int}) + model = CompositeModel(only(objects_from_mtg(root; kind)); source_adapter=adapter) + end + @test_throws "rejected leaf" add_organ!(root, model, :+, :Leaf, 2) + @test isnothing(MTG.parent(newborn[])) && isempty(MTG.children(newborn[])) + @test only(MTG.children(root)) === tip[] + @test MTG.parent(tip[]) === root && MTG.link(tip[]) === :+ + @test isnothing(MTG.get_node(root, MTG.node_id(newborn[]))) + @test MTG.get_node(root, MTG.node_id(tip[])) === tip[] + @test_throws ArgumentError object_id(model, newborn[]) + @test object_id(model, root) == ObjectId(MTG.node_id(root)) end - model = CompositeModel(root; kind) - @test_throws "rejected leaf" add_organ!(root, model, :+, :Leaf, 2) - @test isnothing(MTG.parent(newborn[])) && isempty(MTG.children(newborn[])) - @test only(MTG.children(root)) === tip[] - @test MTG.parent(tip[]) === root && MTG.link(tip[]) === :+ - @test isnothing(MTG.get_node(root, MTG.node_id(newborn[]))) - @test MTG.get_node(root, MTG.node_id(tip[])) === tip[] - @test_throws ArgumentError object_id(model, newborn[]) - @test object_id(model, root) == ObjectId(MTG.node_id(root)) end @testset "the initial data grammar has one Status construction path" begin From 3b03f0ab82a80e812a19806ecf3fffe86b569197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:11:19 +0100 Subject: [PATCH 271/324] Keep the prepared cohort schema visible at hard-call growth sites --- src/composite_model/execution_cohort_refresh.jl | 7 +++++++ src/composite_model/runtime_outputs.jl | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index f99261a96..1f5470b3d 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -244,6 +244,13 @@ function refresh_cohort_membership!( owner=nothing, schema=isnothing(previous) ? OpenExecutionCohortSchema() : previous.schema, ) + return refresh_cohort_membership!(build_target, store, application_id, current_ids, + changed_ids, previous, owner, schema) +end + +function refresh_cohort_membership!(build_target::F, store::ExecutionCohortStore, + application_id::Symbol, current_ids, changed_ids, previous, owner, schema, +) where {F} owner = _execution_store_owner(store, owner) if !isnothing(previous) previous.store === store && previous.application_id === application_id && diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 791ae5571..b3affd0f5 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3768,8 +3768,8 @@ function _compiled_call_execution_batches( application_schema = _call_batch_schema_for_application(batch_schema,application) current_ids = [object_id for object_id in binding.callee_object_ids if _call_binding_target_matches(binding,application,object_id)] - refreshed = refresh_cohort_membership!(cohorts,application.id,current_ids, - nothing;owner,schema=admission) do object_id, previous_target + refreshed = Base.@inline refresh_cohort_membership!(cohorts, application.id, + current_ids, nothing, nothing, owner, admission) do object_id, previous_target _compiled_model_execution_target_from_previous(previous_target, compiled,env_bindings,application,object_id,temporal_streams, output_retention,constants;target_schema=admission) From 0c9c55973e960a655265c63d213f224ee1617b7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:27:55 +0100 Subject: [PATCH 272/324] Normalize newborn object fields independently of the MTG column family --- src/composite_model/registry_topology.jl | 21 +++++++++--------- test/test-organ-status-assembly.jl | 27 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 810337e22..d5ab008fd 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -205,6 +205,12 @@ function Object( status=nothing, applications=(), ) + return _new_object(id, scale, kind, species, name, parent, children, geometry, status, applications) +end + +# Each field is converted independently, including when the MTG carries +# heterogeneous geometry and label columns. +@inline function _new_object(id, scale, kind, species, name, parent, children, geometry, status, applications) return Object( ObjectId(id), _maybe_symbol(scale), @@ -1668,16 +1674,11 @@ function add_organ!( _mtg_birth_attributes(edits, attributes)) try new_object_id = _register_mtg_object_identity!(adapter, node) - object = Object( - new_object_id; - scale=adapter.scale(node), - kind=isnothing(kind) ? _mtg_birth_attribute(adapter.kind, node, edits) : kind, - species=isnothing(species) ? _mtg_birth_attribute(adapter.species, node, edits) : species, - name=isnothing(name) ? _mtg_birth_attribute(adapter.name, node, edits) : name, - parent=parent_id, - geometry=_mtg_birth_attribute(adapter.geometry, node, edits), - status=status, - ) + object = _new_object(new_object_id, adapter.scale(node), + isnothing(kind) ? _mtg_birth_attribute(adapter.kind, node, edits) : kind, + isnothing(species) ? _mtg_birth_attribute(adapter.species, node, edits) : species, + isnothing(name) ? _mtg_birth_attribute(adapter.name, node, edits) : name, + parent_id, (), _mtg_birth_attribute(adapter.geometry, node, edits), status, ()) registered = register_object!(model, object) adapter.max_node_id[] = max(adapter.max_node_id[], node_id) return _with_registered_status(identity, model.registry.objects.catalog, registered.status)::Status diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index d4cc100a1..af082f5b2 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -131,6 +131,33 @@ end @test only(outputs(simulation)[(:probe, object_id(model, leaf), :value)]) == (1.0, 5f0) end +@testset "new organs inherit declared MTG labels and geometry" begin + for prepared in (false, true) + root = MTG.Node(1, MTG.NodeMTG(:/, :Plant, 1, 1), (annotation=:existing,)) + geometry = Float32[1, 2] + MTG.add_column!(root, :Leaf, :kind, Int; default=3) + MTG.add_column!(root, :Leaf, :species, Symbol; default=:guineensis) + MTG.add_column!(root, :Leaf, :name, String; default="young leaf") + MTG.add_column!(root, :Leaf, :geometry, typeof(geometry); default=geometry) + model = CompositeModel(root) + if prepared + adapter = PSE._closed_mtg_object_adapter(model.source_adapter, ObjectId{Int}) + model = CompositeModel(only(objects_from_mtg(root)); source_adapter=adapter) + end + leaf = add_organ!(root, model, :+, :Leaf, 2) + object = model_object(model, source_node(model, leaf)) + @test (object.kind, object.species, object.name) == (Symbol(3), :guineensis, "young leaf") + @test object.geometry === geometry + + MTG.add_column!(root, :Tip, :kind, Int; default=7) + tip = add_organ!(root, model, :+, :Tip, 2) + @test model_object(model, source_node(model, tip)).kind === Symbol(7) + fruit = add_organ!(root, model, :+, :Fruit, 2; attributes=(kind=:green,)) + @test model_object(model, source_node(model, fruit)).kind === :green + @test !hasproperty(fruit, :kind) + end +end + @testset "a failing MTG accessor preserves a descendant it already attached" begin for prepared in (false, true) root = MTG.Node(MTG.NodeMTG(:/, :Plant, 1, 1)) From d6fe43096ad91f8aee6ee798cf523a061c2b9cfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:40:15 +0100 Subject: [PATCH 273/324] Share prepared registry construction with authored application fixtures --- src/composite_model/registry_topology.jl | 26 +++++++++++- test/integration/native_preparation.jl | 13 ++---- test/test-model-binding-index-identities.jl | 42 ++++++------------- ...test-model-environment-index-identities.jl | 23 ++-------- test/test-organ-status-assembly.jl | 21 +++++----- 5 files changed, 53 insertions(+), 72 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index d5ab008fd..448144b2c 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -703,17 +703,39 @@ function _install_prepared_canonical_registry(model, manifest, ::Type{S}) where for (object, status) in pending setfield!(object, :status, status) end + return _model_with_object_store(model, store, model.source_adapter, model.scenario_plan_cache) +end + +function _model_with_object_store(model, store, adapter, preparation) + previous = model.registry registry = ObjectRegistry(store, previous.by_scale, previous.by_kind, previous.by_species, previous.ancestor_ids_by_object) fields = map(fieldnames(typeof(model))) do name - name === :registry ? registry : getfield(model, name) + name === :registry && return registry + name === :source_adapter && return adapter + return getfield(model, name) end prepared = CompositeModel(fields...) - preparation = model.scenario_plan_cache _model_owned_scenario_preparation(prepared, preparation) return prepared end +# An authored executable can fix its object ID types while keeping the status +# cells, applications and source nodes prepared by the original CompositeModel. +function _with_object_id_domain(model::CompositeModel, id_type=nothing) + isnothing(model.binding_cache) && isnothing(model.environment_binding_cache) || + throw(ArgumentError("Prepare object ID types before binding a simulation.")) + preparation = _scenario_preparation(model) + objects = model.registry.objects + store = isnothing(id_type) ? _closed_object_family_store(objects) : + _closed_object_family_store(objects, id_type) + adapter = model.source_adapter + if adapter isa MTGObjectAdapter + adapter = _closed_mtg_object_adapter(adapter, keytype(store)) + end + return _model_with_object_store(model, store, adapter, preparation) +end + """ CompositeModel(template::CompositeModelTemplate; root, objects=(), name=nothing, overrides=NamedTuple(), diff --git a/test/integration/native_preparation.jl b/test/integration/native_preparation.jl index 30e79baef..d46d05492 100644 --- a/test/integration/native_preparation.jl +++ b/test/integration/native_preparation.jl @@ -3,7 +3,6 @@ import PlantSimEngine as PSE export close_registry, RuntimeTypes, InputTrace, remember!, batch_schema function close_registry(model, id_type=nothing) - previous = model.registry manifest = PSE._scenario_preparation(model).status_manifest for object in PSE.model_objects(model) status = PSE.model_status(model, object) @@ -11,14 +10,10 @@ function close_registry(model, id_type=nothing) error("Fresh objects lost the prepared canonical Status owner.") status === object.status || error("The facade lost its canonical status.") end - store = isnothing(id_type) ? PSE._closed_object_family_store(previous.objects) : - PSE._closed_object_family_store(previous.objects, id_type) - store.catalog.status_manifest === manifest || error("Registry closure changed the manifest.") - registry = PSE.ObjectRegistry(store, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - # Build-time reconstruction retains every field of this exact model. - return PSE.CompositeModel(registry, - (getfield(model, index) for index in 2:fieldcount(typeof(model)))...) + prepared = PSE._with_object_id_domain(model, id_type) + prepared.registry.objects.catalog.status_manifest === manifest || + error("Registry closure changed the manifest.") + return prepared end mutable struct RuntimeTypes diff --git a/test/test-model-binding-index-identities.jl b/test/test-model-binding-index-identities.jl index 3dbb38b91..f92c43d67 100644 --- a/test/test-model-binding-index-identities.jl +++ b/test/test-model-binding-index-identities.jl @@ -38,27 +38,9 @@ function PSE.run!(::ManyReader, status, environment, constants, context) return nothing end -# Close only the actual complete schemas already present in this call fixture. -# This introduces no scientific object, default evaluation, or type probe. -function close_registry(model::CompositeModel) - previous = model.registry - registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), - previous.by_scale, previous.by_kind, previous.by_species, - previous.ancestor_ids_by_object) - return PSE.CompositeModel(registry, model.applications, model.environment, - model.instances, model.source_adapter, model.status_conversion, - model.status_conversion_records, model.status_source_owners, - model.status_source_identities, model.scenario_plan_cache, - model.binding_cache, model.environment_binding_cache, model.bindings_dirty, - model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, - model.revision, model.environment_revision) -end - - @testset "registration admits object and parent identities before status conversion" begin root = Object(:root; status=Status(x=1f0)) - model = close_registry(CompositeModel(root; type_promotion=Dict(Float64 => Float32))) + model = PSE._with_object_id_domain(CompositeModel(root; type_promotion=Dict(Float64 => Float32))) records = copy(model.status_conversion_records) revision = model.revision children = copy(root.children) @@ -116,7 +98,7 @@ end end model = CompositeModel(Object(:seed; status=Status(x=1.0)); type_promotion=Dict(Float64 => Float32), status_transform=transform) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) before = calls[] source = Status(x=2.0) @test_throws "already contains object id" register_object!(model, @@ -147,7 +129,7 @@ end @test instance.root === (form === :object ? root : root.id) items = form === :object ? (branch,) : (root, branch) model = CompositeModel(items...; instances=(instance,)) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) @test PSE._instance_root_id(instance) === root.id @test PSE._instance_for_object(model, branch.id) === instance @@ -190,7 +172,7 @@ function call_fixture(closed) many=Many(scale=:Leaf, within=Subtree(), application=:leaf))), ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)), )) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) simulation = run!(model; steps=0, outputs=:all) target = only(only(only(simulation.execution_plan.groups).batches).targets) return (; model, simulation, capture, context=target.context) @@ -457,7 +439,7 @@ end catch error sprint(showerror, error) end - mixed = close_registry(CompositeModel( + mixed = PSE._with_object_id_domain(CompositeModel( Object(:root; scale=:Scene), Object((:tree, :leaf, 2); scale=:Leaf, parent=:root))) I = keytype(mixed.registry.objects) for ids in (I[], I[ObjectId(:root)], collect(keys(mixed.registry.objects))) @@ -563,7 +545,7 @@ end Object(1; scale=:Leaf, parent=Symbol("plante α")), Object(Symbol("1"); scale=:Leaf, parent=Symbol("plante α")), Object(Symbol("feuille α"); scale=:Leaf, parent=Symbol("plante α"))) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) message = try resolve_object_ids(model, One(Subtree(); scale=:Leaf); context=Symbol("plante α")) @@ -642,7 +624,7 @@ end Object(:root; scale=:Plant, status=Status(visits=0)), Object(1; scale=:Leaf, parent=:root, status=Status(x=3f0)); applications=()) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) I = keytype(model.registry.objects) authored = PSE._compile_model_applications(model, PSE._model_timeline(model)) prepared = PSE._prepare_scenario_plan(model) @@ -689,7 +671,7 @@ end applications=(ModelSpec(Reader(); name=:reader, on=One(id=:root), inputs=(single=One(id=1, within=Subtree(), var=:x, from_status=true),)),)) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) simulation = run!(model; steps=0, outputs=:none) bindings = simulation.compiled.input_bindings erased_inputs = PSE.CompiledModelInputBinding[bindings...] @@ -752,7 +734,7 @@ PSE.EnvironmentAPI.bind_environment(::GeometryOwnerBackend, object::Object, cont Object(:blank_branch; scale=:Branch, parent=:no_geometry, status=Status()); applications=(ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)),), environment=GeometryOwnerBackend()) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) simulation = run!(model; steps=0, outputs=:none) leaf = model_object(model, :leaf) reference = PSE.refvalue(leaf.status, :x) @@ -799,7 +781,7 @@ end Object(:feuille; scale=:Leaf, parent=:root, status=Status(values=Float64[], total=0.0)); applications=(ModelSpec(Reader(); name=:reader, on=Many(scale=:Leaf)),)) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) error = try run!(model; steps=0, outputs=:none) nothing @@ -825,7 +807,7 @@ end ModelSpec(Reader(); name=:reader, on=One(id=ObjectId(consumer)), inputs=(single=One(id=:source, within=SceneScope(), application=:leaf, var=:x),)), )) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) simulation = run!(model; steps=0, outputs=:none) bound = PSE._bound_model_inputs(simulation.compiled.input_bindings, model.registry.objects) @test eltype(bound) === Tuple{Symbol,keytype(model.registry.objects),Symbol} @@ -842,7 +824,7 @@ end direct = CompositeModel(Object(:root; scale=:Plant), Object(consumer; scale=:Leaf, parent=:root, status); applications=(ModelSpec(Reader(); name=:reader, on=One(id=ObjectId(consumer))),)) - closed && (direct = close_registry(direct)) + closed && (direct = PSE._with_object_id_domain(direct)) if provided direct_simulation = run!(direct; steps=0, outputs=:none) direct_bound = PSE._bound_model_inputs(direct_simulation.compiled.input_bindings, diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl index 6ef3e83e0..8360c4cf9 100644 --- a/test/test-model-environment-index-identities.jl +++ b/test/test-model-environment-index-identities.jl @@ -51,22 +51,6 @@ function PSE.run!(::Probe, status, environment, constants, context) return nothing end -function close_registry(model::CompositeModel) - previous = model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - return PSE.CompositeModel( - registry, model.applications, model.environment, model.instances, - model.source_adapter, model.status_conversion, model.status_conversion_records, - model.status_source_owners, model.status_source_identities, - model.scenario_plan_cache, model.binding_cache, model.environment_binding_cache, - model.bindings_dirty, model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, model.revision, - model.environment_revision, - ) -end - function fixture(closed::Bool; environment_schema=PSE.EnvironmentBindingSchema(), first_id=1) backend = Backend(Dict(:a => 10.0f0, :b => 20.0f0), 0, Any[], nothing) model = CompositeModel( @@ -77,7 +61,7 @@ function fixture(closed::Bool; environment_schema=PSE.EnvironmentBindingSchema() status=Status(seen=0.0f0, visits=0)); applications=(ModelSpec(Probe(); name=:probe, on=Many(scale=:Leaf), environment=Environment(provider=:identity_probe)),), environment=backend) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) simulation = PSE._prepare_simulation!(model; steps=1, outputs=:all, constants=PSE.Constants(), environment_schema) PSE._continue_scene!(simulation, 1) @@ -127,7 +111,7 @@ function index_discovery_fixture(closed::Bool; extra_applications::Int=0, extra_objects...; applications=applications, environment=backend_a) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) return (; model, backend_a, backend_b, events) end @@ -623,7 +607,6 @@ end module SwitchingBackendRepro using PlantSimEngine, Dates, Test -import ..EnvironmentIndexIdentityChecks: close_registry const PSE = PlantSimEngine const EA = PSE.EnvironmentAPI @@ -675,7 +658,7 @@ function fixture(closed::Bool) applications=(ModelSpec(Probe(); name=:probe, on=One(id=:root), every=Dates.Hour(1), environment=Environment(backend=source)),), environment=b) - closed && (model = close_registry(model)) + closed && (model = PSE._with_object_id_domain(model)) return (; model, source, a, b, events) end diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index af082f5b2..e85412c11 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -105,13 +105,18 @@ end @testset "a prepared MTG adapter keeps scientific inputs separate from node annotations" begin root = MTG.Node(1, MTG.NodeMTG(:/, :Plant, 1, 1), (kind=:plant, note="plant", seed=0f0, geometry=Float32[])) - adapter = PSE._closed_mtg_object_adapter(CompositeModel(root).source_adapter, ObjectId{Int}) + source = CompositeModel(root; + applications=(ModelSpec(Probe(2f0); name=:probe, on=Many(scale=:Leaf)),)) + model = PSE._with_object_id_domain(source, ObjectId{Int}) + adapter = model.source_adapter + @test model.scenario_plan_cache.owner === model + @test model.scenario_plan_cache.status_manifest === source.scenario_plan_cache.status_manifest + @test source_node(model, 1) === root if isdefined(MTG, :prepare_node_edits) @test length(adapter.node_edits) == 1 end - model = CompositeModel(only(objects_from_mtg(root)); source_adapter=adapter, - applications=(ModelSpec(Probe(2f0); name=:probe, on=Many(scale=:Leaf)),)) simulation = run!(model; steps=0, outputs=:all) + @test_throws "before binding a simulation" PSE._with_object_id_domain(model) geometry = Float32[1, 2] given = Status(seed=3f0, payload=Float32[]) leaf = add_organ!(root, simulation, :+, :Leaf, 2; @@ -140,10 +145,7 @@ end MTG.add_column!(root, :Leaf, :name, String; default="young leaf") MTG.add_column!(root, :Leaf, :geometry, typeof(geometry); default=geometry) model = CompositeModel(root) - if prepared - adapter = PSE._closed_mtg_object_adapter(model.source_adapter, ObjectId{Int}) - model = CompositeModel(only(objects_from_mtg(root)); source_adapter=adapter) - end + prepared && (model = PSE._with_object_id_domain(model, ObjectId{Int})) leaf = add_organ!(root, model, :+, :Leaf, 2) object = model_object(model, source_node(model, leaf)) @test (object.kind, object.species, object.name) == (Symbol(3), :guineensis, "young leaf") @@ -171,10 +173,7 @@ end throw(ArgumentError("rejected leaf")) end model = CompositeModel(root; kind) - if prepared - adapter = PSE._closed_mtg_object_adapter(model.source_adapter, ObjectId{Int}) - model = CompositeModel(only(objects_from_mtg(root; kind)); source_adapter=adapter) - end + prepared && (model = PSE._with_object_id_domain(model, ObjectId{Int})) @test_throws "rejected leaf" add_organ!(root, model, :+, :Leaf, 2) @test isnothing(MTG.parent(newborn[])) && isempty(MTG.children(newborn[])) @test only(MTG.children(root)) === tip[] From a5e87998aaae120c23f40587682fbbd46c1f457f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:49:04 +0100 Subject: [PATCH 274/324] Document scientific initial values for MTG growth and native preparation scope --- docs/src/guides/compile_scenario.md | 10 ++++++++- docs/src/guides/multiscale/import_mtg.md | 28 +++++++++++++++++------- src/native_compilation.jl | 4 ++-- 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/docs/src/guides/compile_scenario.md b/docs/src/guides/compile_scenario.md index 21c7aa3d6..d253a4a5b 100644 --- a/docs/src/guides/compile_scenario.md +++ b/docs/src/guides/compile_scenario.md @@ -96,7 +96,7 @@ entry point. Use the entry point to parse arguments, advance the program, and write the result. JuliaC loads the module during the build, so put the fixed scenario in `make_model()` and handle runtime data in the entry point. -This compiler admits one ordinary object with at least one scheduled +`Compilation.prepare` admits one ordinary object with at least one scheduled application, and same-object scalar inputs and outputs. All scheduled applications run at every base step. Status values must be numeric bits values such as `Float32`, `Float64` or `Int`, and model and @@ -117,6 +117,14 @@ inputs, hard calls, initializers, distributed or stream-only outputs, topology edits, or retained histories can run through the ordinary PlantSimEngine API. +`Compilation.compile` takes an **application project**. A multi-object +application can prepare a PSE `Simulation` at build time and advance it with +the same `step!` or `continue!` as an ordinary run. For example, a growing +plant also needs the types of the organs and model calls that can appear +after the first step. The multi-object growth tests currently supply these +types using internal preparation functions. Automatic preparation through +the public API covers the fixed scenario described above. + If preparation rejects a model, read the reported application or feature and check it against this list. If JuliaC's safe verifier rejects a call, start with the first unresolved call in its error output. Check the types diff --git a/docs/src/guides/multiscale/import_mtg.md b/docs/src/guides/multiscale/import_mtg.md index 1f98b42e3..b7ff597f8 100644 --- a/docs/src/guides/multiscale/import_mtg.md +++ b/docs/src/guides/multiscale/import_mtg.md @@ -73,14 +73,26 @@ plant_area ## Keep the link to the MTG when the plant grows -`CompositeModel(root; ...)` keeps the relationship between MTG nodes and -simulation objects. Use `object_id(model, leaf_1)` to find the object for a -node. For a new organ, pass its scientific initial values explicitly, for -example `add_organ!(parent_node, model, :+, :Leaf, 1; -initial_status=(carbon_biomass=0.0,))`. The import function is not called -during growth. The new organ uses the numeric conversion and field types -prepared for its model configuration. MTG attributes remain annotations -and geometry; use `source_node(model, object)` to retrieve its source node. +`add_organ!` creates the new node and returns its model status. Give the +leaf its starting biomass through `initial_status`. Use `attributes` for +tree data such as a field tag or geometry. + +```@example import_mtg +young = add_organ!(root, model, "/", :Leaf, 1; index=3, + initial_status=(carbon_biomass=25.0,), attributes=(tag="leaf 3",)) +continue!(simulation; steps=1) +node = source_node(model, young) +@assert node[:tag] == "leaf 3" # hide +@assert young.surface ≈ 0.5 # hide +(area=young.surface, tag=node[:tag]) +``` + +The original import callback runs when you construct the model. During +growth, each new leaf uses the field types and numerical conversions +prepared for its models. `source_node(model, young)` returns the live MTG +node, and `object_id(model, node)` gives its simulation identifier. +Use a key such as `tag` for field notes. The default MTG adapter uses +`kind` and `species` to select model objects, and `name` for display. See [Growth within a time step](../../tutorials/growing_plant/part1_growth.md). Use `objects_from_mtg(root; status=initial_status)` when you only want a diff --git a/src/native_compilation.jl b/src/native_compilation.jl index 5c64d1fa9..8aa15e377 100644 --- a/src/native_compilation.jl +++ b/src/native_compilation.jl @@ -134,8 +134,8 @@ PSE.final_state(program::PreparedSimulation) = NamedTuple(program.status) Build a named Julia application project with an `@main` entry point as a JuliaC `safe` executable. Load `JuliaC` and PlantSimEngine in the build -session. The build requires Julia 1.13 or later and a C toolchain. Use -[`prepare`](@ref) in the application's source to prepare its scenario. +session. The build requires Julia 1.13 or later and a C toolchain. +For a fixed one-object scenario, use [`prepare`](@ref) in the application's source. `destination` must be a new directory. Return a named tuple containing the absolute `directory` and `executable` paths. Keep the full bundle together From b8131fdc30660868ac3143cf85d97b566d398b72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:55:21 +0100 Subject: [PATCH 275/324] Exercise rollback and reuse of live tree organs in the native growth suite --- .../local_palm_leaf_birth/Project.toml | 1 + .../src/PSELocalPalmLeafBirth.jl | 5 +++ .../local_palm_leaf_birth/src/tree_birth.jl | 35 +++++++++++++++++++ test/integration/native_fixture_apps.jl | 18 +++++++--- test/integration/native_growth.jl | 4 +++ 5 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 test/fixtures/local_palm_leaf_birth/src/tree_birth.jl diff --git a/test/fixtures/local_palm_leaf_birth/Project.toml b/test/fixtures/local_palm_leaf_birth/Project.toml index 2a8f0fe57..322b82943 100644 --- a/test/fixtures/local_palm_leaf_birth/Project.toml +++ b/test/fixtures/local_palm_leaf_birth/Project.toml @@ -5,6 +5,7 @@ version = "0.1.0" [deps] Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" Libiconv_jll = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" +MultiScaleTreeGraph = "dd4a991b-8a45-4075-bede-262ee62d5583" PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" [sources] diff --git a/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl b/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl index 2edbad519..aaa262dd9 100644 --- a/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl +++ b/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl @@ -6,6 +6,7 @@ include("prepare.jl") using .LocalPalmLeafBirth using .LocalPalmLeafBirthPreparation: prepare_native_scene import PlantSimEngine as PSE +include("tree_birth.jl") # A alone is the only retained payload. The native count is command-line data. const STATE = prepare_native_scene() @@ -90,6 +91,10 @@ end function (@main)(args) length(args)==1 || return 2 + if only(args) == "tree" + isnothing(TREE_BIRTH) && return 2 + return check_tree_birth!(TREE_BIRTH) ? 0 : 1 + end neighbours=parse(Int,args[1]) neighbours in (0,100) || return 2 result=native_run!(STATE,neighbours) diff --git a/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl new file mode 100644 index 000000000..17c13382d --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl @@ -0,0 +1,35 @@ +# This grows the source tree and the PSE registry in the same transaction. +const MTG = PSE.MultiScaleTreeGraph + +function prepare_tree_birth() + root = MTG.Node(1, MTG.NodeMTG(:/, :Plant, 1, 1), + (age=0, parameters=Dict{String,Any}("leaf" => [1, 2]),)) + edits = MTG.prepare_node_edits(root) + kind(node) = MTG.attribute(edits, node, :kind, nothing)::Union{Int,Nothing} + species(node) = MTG.attribute(edits, node, :species, nothing)::Nothing + name(node) = MTG.attribute(edits, node, :name, nothing)::Nothing + model = PSE.CompositeModel(root; kind, species, name) + return PSE._with_object_id_domain(model, PSE.ObjectId{Int}) +end + +const TREE_BIRTH = isdefined(MTG, :prepare_node_edits) ? prepare_tree_birth() : nothing + +function check_tree_birth!(model) + root = PSE.source_node(model, 1) + try + PSE.add_organ!(root, model, :+, :Leaf, 2; initial_status=(undeclared=4,)) + return false + catch err + err isa ArgumentError || rethrow() + end + isempty(MTG.children(root)) && isnothing(MTG.get_node(root, 2)) || return false + first_leaf = PSE.add_organ!(root, model, :+, :Leaf, 2) + first_node = PSE.source_node(model, first_leaf) + MTG.node_id(first_node) == 2 && PSE.model_status(model, 2) === first_leaf || return false + new_leaf = PSE.add_organ!(first_node, model, :+, :Leaf, 2; attributes=(kind=3,)) + new_node = PSE.source_node(model, new_leaf) + MTG.parent(new_node) === first_node && MTG.node_id(new_node) == 3 || return false + PSE.model_object(model, new_node).kind === Symbol(3) || return false + last_leaf = PSE.add_organ!(root, model, :+, :Leaf, 2) + return isnothing(PSE.model_object(model, PSE.source_node(model, last_leaf)).kind) +end diff --git a/test/integration/native_fixture_apps.jl b/test/integration/native_fixture_apps.jl index 86de54060..f21ca0920 100644 --- a/test/integration/native_fixture_apps.jl +++ b/test/integration/native_fixture_apps.jl @@ -6,7 +6,7 @@ export stage_native_fixture """Stage a self-contained test app from canonical source files. Project.toml, src and an optional Manifest.toml are copied. Source paths resolve against the original -project, and PSE is the package actually loaded by this integration test. +project. Direct PSE and MTG dependencies use the packages loaded by the integration test. """ function stage_native_fixture(template; fixture_sources=()) template = abspath(template) @@ -26,7 +26,14 @@ function stage_native_fixture(template; fixture_sources=()) haskey(source, "path") || continue source["path"] = abspath(joinpath(template, source["path"])) end - sources["PlantSimEngine"] = Dict("path" => realpath(pkgdir(PSE))) + checkouts = Dict{String,String}() + for package in (PSE, PSE.MultiScaleTreeGraph) + name = string(nameof(package)) + haskey(project["deps"], name) || continue + path = realpath(pkgdir(package)) + sources[name] = Dict("path" => path) + checkouts[project["deps"][name]] = path + end open(joinpath(app, "Project.toml"), "w") do io TOML.print(io, project) end @@ -34,8 +41,11 @@ function stage_native_fixture(template; fixture_sources=()) if isfile(manifest) lock = TOML.parsefile(manifest) for entries in values(lock["deps"]), entry in entries - if entry["uuid"] == project["deps"]["PlantSimEngine"] - entry["path"] = realpath(pkgdir(PSE)) + if haskey(checkouts, entry["uuid"]) + entry["path"] = checkouts[entry["uuid"]] + for key in ("git-tree-sha1", "registries", "repo-url", "repo-rev") + delete!(entry, key) + end elseif haskey(entry, "path") entry["path"] = entry["uuid"] == project["uuid"] ? app : abspath(joinpath(template, entry["path"])) diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl index 129ddb1e0..7b5f8819f 100644 --- a/test/integration/native_growth.jl +++ b/test/integration/native_growth.jl @@ -58,6 +58,10 @@ end palm = Compilation.compile(_palm_growth_app; destination=joinpath(directory, "palm")) @test isfile(palm.executable) digest = sha256(read(palm.executable)) + if !isnothing(PSELocalPalmLeafBirth.TREE_BIRTH) + @test PSELocalPalmLeafBirth.main(["tree"]) == 0 + @test success(`$(palm.executable) tree`) + end zero = _native_palm_growth_report(palm.executable, 0, directory) hundred = _native_palm_growth_report(palm.executable, 100, directory) @test sha256(read(palm.executable)) == digest From cdebbe8b7ee3fcb3919e72568e3507de8a226def Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 12:56:59 +0100 Subject: [PATCH 276/324] Reconnect status change watchers to their live registries when restoring a simulation --- Project.toml | 3 +++ ext/PlantSimEngineSerializationExt.jl | 23 +++++++++++++++++ test/test-status-fixed-storage.jl | 36 +++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 ext/PlantSimEngineSerializationExt.jl diff --git a/Project.toml b/Project.toml index 0a3dcbc9a..232a62256 100644 --- a/Project.toml +++ b/Project.toml @@ -19,10 +19,12 @@ Term = "22787eb5-b846-44ae-b979-8e399b8463ab" [weakdeps] HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" JuliaC = "acedd4c2-ced6-4a15-accc-2607eb759ba2" +Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [extensions] PlantSimEngineGraphEditorExt = "HTTP" PlantSimEngineJuliaCExt = "JuliaC" +PlantSimEngineSerializationExt = "Serialization" [compat] CSV = "0.10, 1.0" @@ -35,6 +37,7 @@ Markdown = "1.10" MultiScaleTreeGraph = "0.16.0" PlantMeteo = "0.9.0" Random = "1.10" +Serialization = "1.10" Statistics = "1.10" Tables = "1" Term = "2" diff --git a/ext/PlantSimEngineSerializationExt.jl b/ext/PlantSimEngineSerializationExt.jl new file mode 100644 index 000000000..b17269b1d --- /dev/null +++ b/ext/PlantSimEngineSerializationExt.jl @@ -0,0 +1,23 @@ +module PlantSimEngineSerializationExt + +import PlantSimEngine: _WeakStatusChangeSink, ObjectId +import Serialization + +# The registry owns the vector. Register the weak reference with the GC again +# on restore, and keep aliases when several statuses watch the same registry. +function Serialization.serialize(s::Serialization.AbstractSerializer, sink::_WeakStatusChangeSink) + Serialization.serialize_cycle_header(s, sink) && return + ids = sink.ids.value::Union{Nothing,Vector{ObjectId}} + Serialization.serialize(s, ids) + return nothing +end + +function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{_WeakStatusChangeSink}) + weak = WeakRef(nothing) + sink = _WeakStatusChangeSink(weak) + Serialization.deserialize_cycle(s, sink) + weak.value = Serialization.deserialize(s)::Union{Nothing,Vector{ObjectId}} + return sink +end + +end diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index e94c5f76b..5595a379e 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -1,5 +1,6 @@ module FixedStatusStorageChecks using PlantSimEngine, Test +using Serialization const PSE = PlantSimEngine const RF32 = Base.RefValue{Float32} const RF64 = Base.RefValue{Float64} @@ -172,6 +173,41 @@ end @test PSE.refvalue(state, first(names))[] === 2f0 end +function restore_watched_status(owners_first, keep_both) + original = CompositeModel(Object(:leaf; status=Status(x=1f0))) + prepared = PSE._with_object_id_domain(original) + status = model_status(prepared, :leaf) + owners = keep_both ? (original, prepared) : (prepared,) + packet = owners_first ? (; owners, status) : (; status, owners) + io = IOBuffer() + GC.@preserve original serialize(io, packet) + seekstart(io) + return deserialize(io) +end + +@testset "restored status references notify only their live registries" begin + for owners_first in (false, true), keep_both in (false, true) + restored = restore_watched_status(owners_first, keep_both) + GC.gc(true) + watches = PSE._status_vars(restored.status).watchers + @test length(watches) == 2 + @test count(watch -> isnothing(PSE._watch_ids(watch)), watches) == !keep_both + for model in restored.owners + store = model.registry.objects + @test model_status(model, :leaf) === restored.status + watch = only(w for w in watches if w.sink.ids === store.change_sink.ids) + @test PSE._watch_ids(watch) === store.changed_status_ids + empty!(store.changed_status_ids) + end + cell = Ref(2f0) + PSE._set_status_reference!(restored.status, :x, cell) + for model in restored.owners + @test PSE.refvalue(model_status(model, :leaf), :x) === cell + @test model.registry.objects.changed_status_ids == [ObjectId(:leaf)] + end + end +end + @testset "deepcopy preserves internal ref aliases, RefAny and RefReal stay exact" begin S = PSE._fixed_status_type((:a,:b,:abstract,:opaque),Tuple{RF32,RF32,Base.RefValue{Real},Base.RefValue{Any}}) reference = Ref(1f0) From 9195e82a20114dfcb3fe7232e2ce5b7198140eac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 13:19:33 +0100 Subject: [PATCH 277/324] Give supplied status fields the same slots across independent preparations --- .../prepared_status_manifest.jl | 20 +++++++++++++++--- test/test-fixed-status-manifest.jl | 21 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index c5cdf10ef..1ce658793 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -304,6 +304,22 @@ function _prepared_status_raw_configured_references(model, object, names, refere return configured end +function _add_supplied_status_fields!(names, refs, raw) + first_supplied = length(names) + 1 + for family in raw, (name, R) in zip(family.names, family.reference_types) + _prepared_status_add_type!(names, refs, name, R) + end + # Registry iteration can differ between processes. Keep authored ports first + # and give extra fields the same slots when an application is restored. + supplied = first_supplied:lastindex(names) + if !issorted(view(names, supplied)) + order = sort!(collect(supplied); by=i -> names[i]) + names[supplied] = names[order] + refs[supplied] = refs[order] + end + return nothing +end + function _prepare_status_manifest(model, authored, program, raw_basis) # Host traversal uses scalar records; freeze exact owner tuples only once # the namespace and all RAW permissions have been prepared. @@ -350,9 +366,7 @@ function _prepare_status_manifest(model, authored, program, raw_basis) # new RAW permissions. Preserve the genuine constructor-owned evidence. raw_basis end - for family in raw, (name, R) in zip(family.names, family.reference_types) - _prepared_status_add_type!(names, refs, name, R) - end + _add_supplied_status_fields!(names, refs, raw) for permission in permissions for variant in permission.variants, (name, R) in variant.canonical _prepared_status_add_type!(names, refs, name, R) diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl index f9db4ebf0..f7265ff26 100644 --- a/test/test-fixed-status-manifest.jl +++ b/test/test-fixed-status-manifest.jl @@ -19,6 +19,27 @@ PSE.inputs_(::Reader) = (x=Default(0f0),) PSE.outputs_(::Reader) = (;) PSE.run!(::Reader, status, environment, constants, context) = nothing +@testset "independent preparations keep the same slots for supplied fields" begin + function prepare_leaves(reverse_order) + value = Ref(3f0) + data = reverse_order ? (; zeta=Ref(7), alpha=value) : (; alpha=value, zeta=Ref(7)) + leaf = Object(:leaf; scale=:Leaf, status=Status(data)) + soil = Object(:soil; scale=:Soil, status=Status(depth=2.0)) + objects = reverse_order ? (leaf, soil) : (soil, leaf) + model = CompositeModel(objects...; applications=( + ModelSpec(Source(1f0, 2.0, Ref(0)); name=:source, on=Many(scale=:Leaf)),)) + return model, value + end + a, original = prepare_leaves(false) + b, other = prepare_leaves(true) + schema(m) = PSE._prepared_status_manifest(m).status_type + @test schema(a) === schema(b) + @test PSE._status_schema_names(schema(a)) == (:x, :y, :alpha, :depth, :zeta) + @test PSE.refvalue(model_status(a, :leaf), :alpha) === original + @test PSE.refvalue(model_status(b, :leaf), :alpha) === other + @test typeof(PSE.refvalue(model_status(b, :leaf), :zeta)) === Base.RefValue{Int} +end + function _wide_leaf_admission_bytes(model, leaf, status) return @allocated PSE._validate_prepared_initial_status(model, leaf, status, leaf.parent) end From 6d545250492a8bfaf93e02123907db5777d02e4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 13:19:33 +0100 Subject: [PATCH 278/324] Infer default MTG routing label types for native organ growth --- docs/src/guides/multiscale/import_mtg.md | 6 ++ src/composite_model/registry_topology.jl | 56 ++++++++++++++----- .../local_palm_leaf_birth/src/tree_birth.jl | 6 +- test/test-organ-status-assembly.jl | 11 ++++ 4 files changed, 59 insertions(+), 20 deletions(-) diff --git a/docs/src/guides/multiscale/import_mtg.md b/docs/src/guides/multiscale/import_mtg.md index b7ff597f8..65445c89b 100644 --- a/docs/src/guides/multiscale/import_mtg.md +++ b/docs/src/guides/multiscale/import_mtg.md @@ -93,6 +93,12 @@ prepared for its models. `source_node(model, young)` returns the live MTG node, and `object_id(model, node)` gives its simulation identifier. Use a key such as `tag` for field notes. The default MTG adapter uses `kind` and `species` to select model objects, and `name` for display. +A native application using prepared MTG edits derives the types of its default +`kind`, `species` and `name` accessors from the tree. Declare a column before +preparation if future organs will inherit its default, for example +`add_column!(root, :Leaf, :kind, Symbol; default=:expanding)`. An application +can also supply the label at birth with `attributes=(kind=:expanding,)`. + See [Growth within a time step](../../tutorials/growing_plant/part1_growth.md). Use `objects_from_mtg(root; status=initial_status)` when you only want a diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 448144b2c..55c517e4f 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -282,12 +282,14 @@ end function _closed_mtg_object_adapter(adapter::MTGObjectAdapter, ::Type{I}) where {I<:ObjectId} R = typeof(adapter.root) + edits = _prepared_mtg_edits(adapter.root) + kind, species, name = _prepared_mtg_labels(adapter, edits) return MTGObjectAdapter( - adapter.root, adapter.id, adapter.scale, adapter.kind, adapter.species, - adapter.name, adapter.geometry, adapter.status, adapter.max_node_id, + adapter.root, adapter.id, adapter.scale, kind, species, + name, adapter.geometry, adapter.status, adapter.max_node_id, IdDict{R,I}(adapter.object_ids_by_node), Dict{I,R}(adapter.nodes_by_object_id), - _prepared_mtg_edits(adapter.root), + edits, ) end @@ -848,14 +850,38 @@ function CompositeModel( ) end -struct _MTGAttribute - key::Symbol +struct _MTGAttribute{K,T} end +_MTGAttribute(key::Symbol) = _MTGAttribute{key,Any}() +(accessor::_MTGAttribute{K})(node) where {K} = MultiScaleTreeGraph.attribute(node, K, nothing) + +function _prepared_mtg_labels(adapter, edits) + labels = (adapter.kind, adapter.species, adapter.name) + # Custom accessors may change the new node before the next label is read. + isempty(edits) && return labels + adapter.id === MultiScaleTreeGraph.node_id && adapter.scale === MultiScaleTreeGraph.symbol && + all(f -> f isa _MTGAttribute, (labels..., adapter.geometry)) || return labels + columns = MultiScaleTreeGraph.to_table(adapter.root; vars=(:kind, :species, :name)) + return map(labels) do accessor + _prepared_mtg_label(accessor, columns) + end +end + +function _prepared_mtg_label(::_MTGAttribute{K}, columns) where {K} + T = eltype(Tables.getcolumn(columns, K)) + # Preserve true missing values as well as the default for absent attributes. + return _MTGAttribute{K,Union{Nothing,T}}() end -(accessor::_MTGAttribute)(node) = MultiScaleTreeGraph.attribute(node, accessor.key, nothing) -_mtg_birth_attribute(accessor, node, edits) = accessor(node) -_mtg_birth_attribute(accessor::_MTGAttribute, node, edits) = - MultiScaleTreeGraph.attribute(edits..., node, accessor.key, nothing) +_mtg_birth_attribute(accessor, node, edits, row) = accessor(node) +_mtg_birth_attribute(::_MTGAttribute{K}, node, edits, row) where {K} = + MultiScaleTreeGraph.attribute(edits..., node, K, nothing) + +@inline function _mtg_birth_attribute(::_MTGAttribute{K,T}, node, edits::Tuple{P}, row::NamedTuple) where {K,T,P} + value = MultiScaleTreeGraph.attribute(only(edits), node, K, nothing) + accepted = hasfield(typeof(row), K) ? Union{T,fieldtype(typeof(row), K)} : T + value isa accepted && return value + throw(ArgumentError("A new MTG label type must be declared before preparing the tree or supplied in the organ attributes.")) +end # The open MTG API also accepts dictionary-backed attributes. Its prepared # overload takes named rows, whose values retain the caller's objects. @@ -1692,15 +1718,15 @@ function add_organ!( edits = adapter.node_edits encoding = MultiScaleTreeGraph.NodeMTG(Symbol(link), Symbol(organ_symbol), Int(index), Int(mtg_scale)) - node = MultiScaleTreeGraph.addchild!(edits..., parent_node, node_id, encoding, - _mtg_birth_attributes(edits, attributes)) + row = _mtg_birth_attributes(edits, attributes) + node = MultiScaleTreeGraph.addchild!(edits..., parent_node, node_id, encoding, row) try new_object_id = _register_mtg_object_identity!(adapter, node) object = _new_object(new_object_id, adapter.scale(node), - isnothing(kind) ? _mtg_birth_attribute(adapter.kind, node, edits) : kind, - isnothing(species) ? _mtg_birth_attribute(adapter.species, node, edits) : species, - isnothing(name) ? _mtg_birth_attribute(adapter.name, node, edits) : name, - parent_id, (), _mtg_birth_attribute(adapter.geometry, node, edits), status, ()) + isnothing(kind) ? _mtg_birth_attribute(adapter.kind, node, edits, row) : kind, + isnothing(species) ? _mtg_birth_attribute(adapter.species, node, edits, row) : species, + isnothing(name) ? _mtg_birth_attribute(adapter.name, node, edits, row) : name, + parent_id, (), _mtg_birth_attribute(adapter.geometry, node, edits, row), status, ()) registered = register_object!(model, object) adapter.max_node_id[] = max(adapter.max_node_id[], node_id) return _with_registered_status(identity, model.registry.objects.catalog, registered.status)::Status diff --git a/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl index 17c13382d..4dc65613f 100644 --- a/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl +++ b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl @@ -4,11 +4,7 @@ const MTG = PSE.MultiScaleTreeGraph function prepare_tree_birth() root = MTG.Node(1, MTG.NodeMTG(:/, :Plant, 1, 1), (age=0, parameters=Dict{String,Any}("leaf" => [1, 2]),)) - edits = MTG.prepare_node_edits(root) - kind(node) = MTG.attribute(edits, node, :kind, nothing)::Union{Int,Nothing} - species(node) = MTG.attribute(edits, node, :species, nothing)::Nothing - name(node) = MTG.attribute(edits, node, :name, nothing)::Nothing - model = PSE.CompositeModel(root; kind, species, name) + model = PSE.CompositeModel(root) return PSE._with_object_id_domain(model, PSE.ObjectId{Int}) end diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index e85412c11..ce18692b8 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -154,6 +154,17 @@ end MTG.add_column!(root, :Tip, :kind, Int; default=7) tip = add_organ!(root, model, :+, :Tip, 2) @test model_object(model, source_node(model, tip)).kind === Symbol(7) + MTG.add_column!(root, :Bud, :kind, Symbol; default=:dormant) + if prepared && isdefined(MTG, :prepare_node_edits) + @test_throws "new MTG label type" add_organ!(root, model, :+, :Bud, 2) + @test isnothing(MTG.get_node(root, 4)) + bud = add_organ!(root, model, :+, :Bud, 2; attributes=(kind=:dormant,)) + else + bud = add_organ!(root, model, :+, :Bud, 2) + end + @test MTG.node_id(source_node(model, bud)) == 4 + @test model_object(model, source_node(model, bud)).kind === :dormant + fruit = add_organ!(root, model, :+, :Fruit, 2; attributes=(kind=:green,)) @test model_object(model, source_node(model, fruit)).kind === :green @test !hasproperty(fruit, :kind) From 27a9ed5a88fe4919848693f49f110f40614dd512 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 13:25:33 +0100 Subject: [PATCH 279/324] Use the common model preparation in ten registry and call test suites --- test/test-model-call-cohort-retirement.jl | 18 ++++---------- test/test-model-cohort-store-identities.jl | 13 +--------- test/test-model-distributed-output-runtime.jl | 24 ++++--------------- test/test-model-input-binding-storage.jl | 13 +--------- test/test-model-input-recipes.jl | 19 ++------------- test/test-model-prepared-growth-schemas.jl | 13 +--------- test/test-object-families.jl | 6 ++--- test/test-prepared-status-registration.jl | 7 +----- test/test-registered-status-dispatch.jl | 21 ++++------------ test/test-selector-candidate-empty-scope.jl | 17 +------------ 10 files changed, 22 insertions(+), 129 deletions(-) diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl index c88643d4a..b5de4f5a6 100644 --- a/test/test-model-call-cohort-retirement.jl +++ b/test/test-model-call-cohort-retirement.jl @@ -165,16 +165,6 @@ end # Freeze only the real identity domain. The canonical Status schema is already # prepared at CompositeModel construction, even when no Leaf remains active. -function with_finite_registry(model) - previous = model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - fields = map(fieldnames(typeof(model))) do name - name === :registry ? registry : getfield(model, name) - end - return PSE.CompositeModel(fields...) -end current_target(simulation) = only(only(only(simulation.execution_plan.groups).batches).targets) view_ids(values) = [target.object_id for target in values] @@ -227,7 +217,7 @@ end end @testset "closed memberships use the global future identity schema" begin - data = fixture(; transform=with_finite_registry) + data = fixture(; transform=PSE._with_object_id_domain) I = Union{ObjectId{Symbol},ObjectId{Int}} @test keytype(data.model.registry.objects) === I applications = data.simulation.compiled.applications_by_id @@ -261,8 +251,8 @@ end end @testset "ordinary and prepared public calls retain state histories and membership through birth and removal" begin - ordinary = fixture(; transform=with_finite_registry, outputs=:all) - prepared = prepared_tree(fixture(; transform=with_finite_registry, outputs=:all)) + ordinary = fixture(; transform=PSE._with_object_id_domain, outputs=:all) + prepared = prepared_tree(fixture(; transform=PSE._with_object_id_domain, outputs=:all)) fixtures = (ordinary, prepared) references = [PSE.refvalue(model_status(data.model, 2), :leaf_visits) for data in fixtures] held = [data.left for data in fixtures] @@ -314,7 +304,7 @@ end @testset "an initially empty Many retains its prepared Status and real Symbol identity family" begin function empty_closed(model) - closed = with_finite_registry(model) + closed = PSE._with_object_id_domain(model) remove_object!(closed, 1) remove_object!(closed, 2) return closed diff --git a/test/test-model-cohort-store-identities.jl b/test/test-model-cohort-store-identities.jl index 844785a41..8618df0fb 100644 --- a/test/test-model-cohort-store-identities.jl +++ b/test/test-model-cohort-store-identities.jl @@ -36,18 +36,7 @@ function fixture(closed) alias=Many(within=Subtree(), scale=:Leaf, application=:leaf))), ModelSpec(Leaf(); name=:leaf, on=Many(scale=:Leaf)))) if closed - previous = model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - model = PSE.CompositeModel(registry, model.applications, model.environment, - model.instances, model.source_adapter, model.status_conversion, - model.status_conversion_records, model.status_source_owners, - model.status_source_identities, model.scenario_plan_cache, model.binding_cache, - model.environment_binding_cache, model.bindings_dirty, - model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, - model.revision, model.environment_revision) + model = PSE._with_object_id_domain(model) end return (;model,capture) end diff --git a/test/test-model-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index 4959284c4..f5eb8dbdb 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1230,22 +1230,6 @@ end # Same closure mechanism used by the maintained finite-registry fixtures. Every # status family here is an actual fully initialized object in this small scene. -function _distributed_runtime_closed_destination_registry(model::CompositeModel) - PSE = PlantSimEngine - previous = model.registry - registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), - previous.by_scale, previous.by_kind, previous.by_species, - previous.ancestor_ids_by_object) - return PSE.CompositeModel(registry, model.applications, model.environment, - model.instances, model.source_adapter, model.status_conversion, - model.status_conversion_records, model.status_source_owners, - model.status_source_identities, model.scenario_plan_cache, - model.binding_cache, model.environment_binding_cache, model.bindings_dirty, - model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, - model.revision, model.environment_revision) -end - @testset "Closed distributed memberships retain the registry ID domain and live carriers" begin PSE = PlantSimEngine for (scene, leaves, added) in ((10, (20,), 30), @@ -1257,7 +1241,7 @@ end name=:closed_destination_writer, on=One(id=scene), outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope()); vars=(:incident_par,)),)),), environment=(duration=Hour(1),)) - model = _distributed_runtime_closed_destination_registry(model) + model = PSE._with_object_id_domain(model) simulation = run!(model; steps=0, outputs=:all, performance=true) I = keytype(model.registry.objects) binding = only(simulation.compiled.distributed_outputs.bindings) @@ -1307,7 +1291,7 @@ end applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); name=:closed_context_writer, on=One(id=scene), outputs_to=(OutputTo(selector; vars=(:incident_par,)),)),)) - model = _distributed_runtime_closed_destination_registry(model) + model = PSE._with_object_id_domain(model) simulation = run!(model; steps=0, outputs=:all) binding = only(simulation.compiled.distributed_outputs.bindings) I = keytype(model.registry.objects) @@ -1331,7 +1315,7 @@ end applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); name=:closed_empty_writer, on=One(id=1), outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope()); vars=(:incident_par,)),)),)) - empty_model = _distributed_runtime_closed_destination_registry(empty_model) + empty_model = PSE._with_object_id_domain(empty_model) simulation = run!(empty_model; steps=0, outputs=:all) binding = only(simulation.compiled.distributed_outputs.bindings) @test isempty(binding.destination_ids) @@ -1354,7 +1338,7 @@ end applications=(ModelSpec(DistributedRuntimeStatefulWriterModel(); name=:closed_merged_writer, on=Many(scale=:Plant), outputs_to=(OutputTo(Many(scale=:Leaf, within=Subtree()); vars=(:incident_par,)),)),)) - merged_model = _distributed_runtime_closed_destination_registry(merged_model) + merged_model = PSE._with_object_id_domain(merged_model) simulation = run!(merged_model; steps=0, outputs=:all) bindings = simulation.compiled.distributed_outputs.bindings combined = simulation.compiled.distributed_outputs.destination_ids_by_application_variable[ diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 25adeb2d9..1a6cfbec9 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -461,19 +461,8 @@ end expected_index = baseline.compiled.observed_manual_call_binding_indices_by_callee_target data = fixture(; called=true) - prepare(data.model) # Close only the actual complete statuses on these objects. - previous = data.model.registry - registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), - previous.by_scale, previous.by_kind, previous.by_species, - previous.ancestor_ids_by_object) original = data.model - model = PSE.CompositeModel(registry, original.applications, original.environment, - original.instances, original.source_adapter, original.status_conversion, - original.status_conversion_records, original.status_source_owners, - original.status_source_identities, nothing, nothing, nothing, true, - true, original.lifecycle_delta, - original.input_default_status_variables, original.runtime_revision, - original.revision, original.environment_revision) + model = PSE._with_object_id_domain(original) @test all(model_object(model, id) === model_object(original, id) for id in (:scene, :anchor, :a, :b)) closed = merge(data, (; model)) diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 82751ede4..f97bec42e 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -229,24 +229,9 @@ function materialize_reader(model, compiled, application, recipe) return bindings end -function closed_registry_model(model) - previous = model.registry - registry = PSE.ObjectRegistry(PSE._closed_object_family_store(previous.objects), - previous.by_scale, previous.by_kind, previous.by_species, - previous.ancestor_ids_by_object) - return PSE.CompositeModel(registry, model.applications, model.environment, - model.instances, model.source_adapter, model.status_conversion, - model.status_conversion_records, model.status_source_owners, - model.status_source_identities, model.scenario_plan_cache, - model.binding_cache, model.environment_binding_cache, model.bindings_dirty, - model.environment_bindings_dirty, model.lifecycle_delta, - model.input_default_status_variables, model.runtime_revision, - model.revision, model.environment_revision) -end - @testset "input refresh references use the closed mixed identity domain" begin organ = (:tree, :leaf, 1) - model = closed_registry_model(CompositeModel( + model = PSE._with_object_id_domain(CompositeModel( Object(:source; scale=:Leaf), Object(:reader; scale=:Reader), Object(organ; scale=:Reader); applications=( @@ -289,6 +274,7 @@ end @testset "prepared routes retain fresh producer policies and closed identity types" begin policy = Ref{PSE.SchedulePolicy}(HoldLast()) model = pair_model(; policy) + closed = PSE._with_object_id_domain(model) simulation = run!(model; outputs=:none) compiled = simulation.compiled application, recipe = reader_recipe(compiled) @@ -301,7 +287,6 @@ end @test all(binding.policy isa HoldLast for binding in first) @test all(input_carrier(old) === input_carrier(new) for (old, new) in zip(first, next)) - closed = closed_registry_model(model) bindings = materialize_reader(closed, compiled, application, recipe) @test all(binding.source_ids isa Vector{ObjectId{Int}} for binding in bindings) @test all(binding.consumer_id isa ObjectId{Int} for binding in bindings) diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index 5f55b6a5c..adc267a22 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -98,17 +98,6 @@ function make_growth(; environment=nothing, fail_initializer=false) return (; model, birth_day, seed) end -function with_finite_registry(model::PSE.CompositeModel) - previous = model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - fields = map(fieldnames(typeof(model))) do name - name === :registry ? registry : getfield(model, name) - end - return PSE.CompositeModel(fields...) -end - function future_leaf_batch_type(simulation) compiled = simulation.compiled application = compiled.applications_by_id[:leaf] @@ -144,7 +133,7 @@ end function prepare_schema_growth(; environment=nothing, fail_initializer=false) setup = make_growth(; environment, fail_initializer) - model = with_finite_registry(setup.model) + model = PSE._with_object_id_domain(setup.model) simulation = run!(model;steps=0,outputs=:none) controller = only(simulation.execution_plan.groups) controller_batch = only(controller.batches) diff --git a/test/test-object-families.jl b/test/test-object-families.jl index 49534b0c9..713504ebd 100644 --- a/test/test-object-families.jl +++ b/test/test-object-families.jl @@ -467,10 +467,8 @@ end admitted_watchers = snapshot_watchers() @test PSE._closed_object_family_store(store, I) === store @test snapshot_watchers() == admitted_watchers - registry = PSE.ObjectRegistry(store, model.registry.by_scale, model.registry.by_kind, - model.registry.by_species, model.registry.ancestor_ids_by_object) - closed = PSE.CompositeModel(registry, - (getfield(model, index) for index in 2:fieldcount(typeof(model)))...) + closed = PSE._model_with_object_store(model, store, model.source_adapter, + PSE._scenario_preparation(model)) @test model_object(closed, :plant) === parent @test model_status(closed, :plant) === original @test PSE.refvalue(model_status(closed, :plant), :value) === reference diff --git a/test/test-prepared-status-registration.jl b/test/test-prepared-status-registration.jl index af97d74e7..a5aebf8f9 100644 --- a/test/test-prepared-status-registration.jl +++ b/test/test-prepared-status-registration.jl @@ -22,12 +22,7 @@ function fixture(second_id=17; finite_ids=false) ObjectInstance(:a, template(0f0); root=first, objects=(a,)), ObjectInstance(:b, template(0.0); root=second, objects=(b,))) if finite_ids - previous = model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - model = PSE.CompositeModel(registry, - (getfield(model, index) for index in 2:fieldcount(typeof(model)))...) + model = PSE._with_object_id_domain(model) end return (; model, first, second, a, b) end diff --git a/test/test-registered-status-dispatch.jl b/test/test-registered-status-dispatch.jl index 24bfc304a..f01ee522e 100644 --- a/test/test-registered-status-dispatch.jl +++ b/test/test-registered-status-dispatch.jl @@ -3,17 +3,6 @@ module RegisteredStatusDispatchChecks using PlantSimEngine, Test const PSE = PlantSimEngine -function with_finite_registry(model) - previous = model.registry - objects = PSE._closed_object_family_store(previous.objects) - registry = PSE.ObjectRegistry(objects, previous.by_scale, previous.by_kind, - previous.by_species, previous.ancestor_ids_by_object) - fields = map(fieldnames(typeof(model))) do name - name === :registry ? registry : getfield(model, name) - end - return PSE.CompositeModel(fields...) -end - @testset "erased statuses share one prepared schema and retain their real references" begin supplied = [Status(value=Float32(index), payload=ntuple(identity, index)) for index in 1:8] model = CompositeModel((Object(index; status=status) for (index,status) in enumerate(supplied))...) @@ -46,7 +35,7 @@ PSE.outputs_(::Finisher) = (value=0.5, visits=0) PSE.run!(::Finisher, status, environment, constants, context) = nothing @testset "ensuring a required status admits root and registered parent identities" begin - model = with_finite_registry(CompositeModel( + model = PSE._with_object_id_domain(CompositeModel( Object(:root; scale=:Leaf),Object(:child; scale=:Leaf,parent=:root); applications=(ModelSpec(Finisher();name=:finish,on=Many(scale=:Leaf)),))) I = keytype(model.registry.objects) @@ -80,7 +69,7 @@ end Status((seed=Ref{Real}(3f0), value=Ref(0.5), visits=Ref(0))), Status((seed=Ref{Any}(4f0), value=Ref(0.5), visits=Ref(0))), ) - model = with_finite_registry(CompositeModel( + model = PSE._with_object_id_domain(CompositeModel( Object(:owner; status=Status(count=0)), (Object(Symbol(:existing_, index); parent=:owner, scale=:Leaf, status=status) for (index,status) in enumerate(existing))...; @@ -149,7 +138,7 @@ end source = CompositeModel(Object(:leaf; status=Status(seed=1.0)); applications=(ModelSpec(PrivateWriter(); name=:private_writer, on=One(id=:leaf), output_routing=(x=:stream_only,)),)) - model = with_finite_registry(source) + model = PSE._with_object_id_domain(source) canonical = model_status(model, :leaf) @test propertynames(canonical) == (:seed,) @test !hasproperty(canonical, :x) @@ -166,7 +155,7 @@ end push!(seen, (name,typeof(value))) value end - model = with_finite_registry(CompositeModel( + model = PSE._with_object_id_domain(CompositeModel( Object(:owner; status=Status(count=0)), Object(:existing; parent=:owner, scale=:Leaf, status=Status(seed=1.0)); type_promotion=Dict(Float64=>Float32), status_transform=transform)) @@ -189,7 +178,7 @@ end @testset "incompatible edited references fail before changing live cells" begin supplied = Status(seed=2.0) - model = with_finite_registry(CompositeModel(Object(:leaf; scale=:Leaf, status=supplied); + model = PSE._with_object_id_domain(CompositeModel(Object(:leaf; scale=:Leaf, status=supplied); applications=(ModelSpec(Finisher(); name=:finish, on=Many(scale=:Leaf)),))) official = model_status(model, :leaf) seed_ref = PSE.refvalue(official, :seed) diff --git a/test/test-selector-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 46b706e3c..b716b5494 100644 --- a/test/test-selector-candidate-empty-scope.jl +++ b/test/test-selector-candidate-empty-scope.jl @@ -101,21 +101,6 @@ end end # Close only the actual existing fixture families. No future family is invented. -function _closed_selector_candidate_fixture(model) - previous = model.registry - registry = PlantSimEngine.ObjectRegistry( - PlantSimEngine._closed_object_family_store(previous.objects), - previous.by_scale, previous.by_kind, previous.by_species, - previous.ancestor_ids_by_object) - fields = map(fieldnames(typeof(model))) do name - name === :registry && return registry - name in (:scenario_plan_cache, :binding_cache, :environment_binding_cache) && return nothing - name in (:bindings_dirty, :environment_bindings_dirty) && return true - getfield(model, name) - end - return CompositeModel(fields...) -end - @testset "Typed selector buckets preserve numeric and mixed identities" begin for ids in ((10, 11, 12, 13), (0, :plant, "axis", 17)), closed in (false, true) scene_id, plant_id, axis_id, leaf_id = ids @@ -126,7 +111,7 @@ end Object(axis_id; scale=:Axis, parent=plant_id), Object(leaf_id; scale=:Leaf, kind, species, parent=axis_id), ) - closed && (model = _closed_selector_candidate_fixture(model)) + closed && (model = PlantSimEngine._with_object_id_domain(model)) @test model.registry.objects.catalog isa PlantSimEngine.ClosedObjectFamilyCatalog I = keytype(model.registry.objects) expected_id_type = closed ? Union{map(id -> typeof(ObjectId(id)), ids)...} : ObjectId From ab7d038f50172265925ab6ca27f54de75a0f2651 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 13:30:07 +0100 Subject: [PATCH 280/324] Keep the prepared history type when newborn initializers sample earlier steps --- src/composite_model/runtime_outputs.jl | 24 ++++++++++++++++-- test/test-model-temporal-initial-typing.jl | 29 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index b3affd0f5..a24857539 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2461,8 +2461,8 @@ function _model_temporal_source_value( timeline, ) samples = get(streams, _model_stream_key(application_id, source_id, source_var), nothing) - return _model_temporal_sample_value( - samples, + return _sample_model_history( + streams, samples, time, policy, t_start, @@ -2470,6 +2470,26 @@ function _model_temporal_source_value( ) end +# An initializer reads its input directly from the simulation history directory. +# Keep the concrete stream type through sampling, as for a cached runtime input. +@inline _sample_model_history(streams, samples, time, policy, t_start, timeline) = + _model_temporal_sample_value(samples, time, policy, t_start, timeline) + +@generated function _sample_model_history(::RuntimeStorage{K,H}, samples, time, policy, + t_start, timeline, +) where {K,H} + histories = Base.uniontypes(H) + all(isconcretetype, histories) || return :(_model_temporal_sample_value(samples, + time, policy, t_start, timeline)) + branches = [:(samples isa $S && return _model_temporal_sample_value(samples::$S, + time, policy, t_start, timeline)) for S in histories] + return quote + isnothing(samples) && return _model_temporal_sample_value(nothing, time, policy, t_start, timeline) + $(branches...) + throw(ArgumentError("The sampled history is outside the prepared history family.")) + end +end + function _model_temporal_sample_value( samples, time::Real, diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 95b26f98c..0d3d0332b 100644 --- a/test/test-model-temporal-initial-typing.jl +++ b/test/test-model-temporal-initial-typing.jl @@ -505,4 +505,33 @@ end @test rng_probe(current) == before_rng end +@testset "initializers sample retained and bounded histories in their prepared type family" begin + id = ObjectId(1) + H = Union{Vector{Tuple{Float64,Int}},Vector{Tuple{Float64,Float64}},PSE.TemporalDependencyBuffer{Float64}} + storage = PSE.RuntimeStorage(Dict{Tuple{Symbol,typeof(id),Symbol},H}()) + ring = PSE.TemporalDependencyBuffer{Float64}(2) + for (t,x) in ((1.0,0.25), (2.0,0.5), (3.0,1.5)) + push!(ring, (t,x)) + end + storage[(:source,id,:ratio)] = ring + storage[(:source,id,:count)] = [(1.0,1), (2.0,2), (3.0,3)] + storage[(:source,id,:area)] = [(1.0,0.25), (2.0,0.5), (3.0,1.5)] + timeline = (; base_step_seconds=1.0) + previous(x,t) = PSE._model_temporal_source_value(storage,:source,id,x,t,PreviousTimeStep(:value),1.0,timeline) + @test previous(:ratio,2.0) === nothing + @test previous(:missing,4.0) === nothing + @test previous(:ratio,3.0) === 0.5 + @test previous(:count,3.0) === 2 + @test previous(:area,3.0) === 0.5 + @test PSE._model_temporal_source_value(storage,:source,id,:missing,3.0,Aggregate(),1.0,timeline) === 0.0 + @test PSE._model_temporal_source_value(storage,nothing,id,:ratio,3.0,PreviousTimeStep(:value),1.0,timeline) === nothing + @test_throws ErrorException PSE._model_temporal_source_value(storage,nothing,id,:ratio,3.0,HoldLast(),1.0,timeline) + for (name, history) in ((:ratio,ring), (:count,storage[(:source,id,:count)]), (:area,storage[(:source,id,:area)])) + for policy in (PreviousTimeStep(:value),HoldLast(),Interpolate(),Aggregate()) + @test PSE._model_temporal_source_value(storage,:source,id,name,2.5,policy,2.0,timeline) === + PSE._model_temporal_sample_value(history,2.5,policy,2.0,timeline) + end + end +end + end From 06e2f0feaebec62ec3046edbb02dbf6ef38a15d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 13:31:45 +0100 Subject: [PATCH 281/324] Keep callee application types through ordered growth and share suffix staging --- src/composite_model/runtime_outputs.jl | 119 ++++++++++-------- ...est-model-finite-call-extension-intents.jl | 6 + 2 files changed, 71 insertions(+), 54 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index a24857539..17de63868 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4217,6 +4217,41 @@ function _model_execution_batch_accepts_target( return isequal(provider, batch.environment_provider) end +# Only admission needs the closed batch types. The registered application +# supplies its current target IDs for the same ordered-prefix check. +@inline _call_prefix_application(compiled, id, ::OpenExecutionBatchSchema) = + _compiled_application_by_id(compiled, id) + +@generated function _call_prefix_application(compiled, id, ::PreparedExecutionBatchSchema{BT}) where {BT} + owners = unique(fieldtype(batch, :application) for batch in _prepared_execution_batch_types(BT)) + A = Union{owners...} + return quote + application = _compiled_application_by_id(compiled, id) + application isa $A || throw(ArgumentError("A callee application is outside its prepared batch schema.")) + return application::$A + end +end + +function _stage_call_execution_suffix!(staged, scope, call_targets, binding, + destination_batch, admission, application, ids, first_new, compiled, env_bindings, + temporal_streams, output_retention, constants) + for index in first_new:lastindex(ids) + object_id = ids[index] + execution_target = _compiled_model_execution_target( + compiled, env_bindings, application, object_id, + temporal_streams, output_retention, constants; + owner=_execution_call_owner(binding), cohort_schema=admission) + accepted = _with_execution_cohort_target(admission, execution_target) do actual + _model_execution_batch_accepts_target(destination_batch, + actual, env_bindings, application) || return false + return _stage_execution_append!(staged, scope, call_targets, + binding, destination_batch.targets, actual) + end + accepted || return false + end + return true +end + function _extend_execution_target_call_batches_by_prefix!( target::CompiledExecutionTarget, compiled::CompiledCompositeModel, @@ -4253,46 +4288,33 @@ function _extend_execution_target_call_batches_by_prefix!( _execution_call_batches_match_applications(schema, execution_batches, binding.callee_application_ids) || return false for application_id in binding.callee_application_ids - matched = _compiled_application_by_id(compiled, application_id) do application - application_schema = _call_batch_schema_for_application(schema, application) - batches = _execution_call_batches_for_application(schema, application_schema, - execution_batches, application_id) - isempty(batches) && return false - current_ids = [object_id for object_id in binding.callee_object_ids - if _call_binding_target_matches(binding, application, object_id)] - # Preserve the existing ordered-prefix algorithm. Only the - # count leaves each admitted concrete batch operation. - existing_count = 0 - for raw_batch in batches - next_count = _execution_call_prefix_end(application_schema, - raw_batch, current_ids, existing_count, - compiled.changed_execution_target_ids, application.id) - isnothing(next_count) && return false - existing_count = next_count - end - existing_count == length(current_ids) && return true - # Existing batches own nonempty runs. A singular call can retain - # its one row or rebuild it when the callee changes. - binding.plan.selector isa Union{One,OptionalOne} && return false - admission = _call_cohort_admission(application_schema, OpenExecutionCohortSchema()) - first_new_index = existing_count + 1 - return _with_execution_batch(application_schema, last(batches)) do destination_batch - for index in first_new_index:lastindex(current_ids) - object_id = current_ids[index] - execution_target = _compiled_model_execution_target( - compiled, env_bindings, application, object_id, - temporal_streams, output_retention, constants; - owner=_execution_call_owner(binding), cohort_schema=admission) - accepted = _with_execution_cohort_target(admission, execution_target) do actual - _model_execution_batch_accepts_target(destination_batch, - actual, env_bindings, application) || return false - return _stage_execution_append!(staged, scope, call_targets, - binding, destination_batch.targets, actual) - end - accepted || return false - end - return true - end + application = _call_prefix_application(compiled, application_id, schema) + application_schema = _call_batch_schema_for_application(schema, application) + batches = _execution_call_batches_for_application(schema, application_schema, + execution_batches, application_id) + isempty(batches) && return false + current_ids = [object_id for object_id in binding.callee_object_ids + if _call_binding_target_matches(binding, application, object_id)] + # Preserve the existing ordered-prefix algorithm. Only the + # count leaves each admitted concrete batch operation. + existing_count = 0 + for raw_batch in batches + next_count = _execution_call_prefix_end(application_schema, + raw_batch, current_ids, existing_count, + compiled.changed_execution_target_ids, application.id) + isnothing(next_count) && return false + existing_count = next_count + end + existing_count == length(current_ids) && continue + # Existing batches own nonempty runs. A singular call can retain + # its one row or rebuild it when the callee changes. + binding.plan.selector isa Union{One,OptionalOne} && return false + admission = _call_cohort_admission(application_schema, OpenExecutionCohortSchema()) + first_new_index = existing_count + 1 + matched = _with_execution_batch(application_schema, last(batches)) do destination_batch + return _stage_call_execution_suffix!(staged, scope, call_targets, binding, + destination_batch, admission, application, current_ids, first_new_index, compiled, + env_bindings, temporal_streams, output_retention, constants) end matched || return false end @@ -4395,20 +4417,9 @@ function _extend_execution_target_call_batches_for_pure_addition!( first(_sorted_object_id_position(application.target_ids, object_id)) || continue first(_sorted_object_id_position(changed_ids, object_id)) || return false end - for object_id in changed_ids - execution_target = _compiled_model_execution_target( - compiled, env_bindings, application, object_id, - temporal_streams, output_retention, constants; - owner=_execution_call_owner(binding), cohort_schema=admission) - accepted = _with_execution_cohort_target(admission, execution_target) do actual - _model_execution_batch_accepts_target(destination_batch, - actual, env_bindings, application) || return false - return _stage_execution_append!(staged, scope, call_targets, - binding, destination_batch.targets, actual) - end - accepted || return false - end - return true + return _stage_call_execution_suffix!(staged, scope, call_targets, binding, + destination_batch, admission, application, changed_ids, firstindex(changed_ids), compiled, + env_bindings, temporal_streams, output_retention, constants) end end end diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl index ec13700d2..8881da941 100644 --- a/test/test-model-finite-call-extension-intents.jl +++ b/test/test-model-finite-call-extension-intents.jl @@ -230,6 +230,12 @@ end simulation = data.simulation target = root_target(simulation) materialize_manual_calls!(target) + if prepared + schema = call_targets(target.context, :a).batch_schema + compiled = simulation.compiled + @test PSE._call_prefix_application(compiled, :leaf_a, schema) === compiled.applications_by_id[:leaf_a] + @test_throws ArgumentError PSE._call_prefix_application(compiled, :root, schema) + end add_leaves!(data) @test extend!(:prefix, target, refreshed_owners(data), simulation) === true rows = [only(call_targets(target.context, name).execution_batches).targets From 0decf72babe1096e416a8baceddf0df6d11661a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 13:49:31 +0100 Subject: [PATCH 282/324] Document and exercise setting a new organ label independently of its tree columns --- docs/src/guides/multiscale/import_mtg.md | 10 +++++++--- test/fixtures/local_palm_leaf_birth/src/tree_birth.jl | 4 +++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/src/guides/multiscale/import_mtg.md b/docs/src/guides/multiscale/import_mtg.md index 65445c89b..11ca6280c 100644 --- a/docs/src/guides/multiscale/import_mtg.md +++ b/docs/src/guides/multiscale/import_mtg.md @@ -93,11 +93,15 @@ prepared for its models. `source_node(model, young)` returns the live MTG node, and `object_id(model, node)` gives its simulation identifier. Use a key such as `tag` for field notes. The default MTG adapter uses `kind` and `species` to select model objects, and `name` for display. -A native application using prepared MTG edits derives the types of its default -`kind`, `species` and `name` accessors from the tree. Declare a column before +To grow an MTG in a native application, use a version of MultiScaleTreeGraph +that provides `prepare_node_edits`. PSE infers the types of the default +`kind`, `species` and `name` labels from the tree. Declare a column before preparation if future organs will inherit its default, for example `add_column!(root, :Leaf, :kind, Symbol; default=:expanding)`. An application -can also supply the label at birth with `attributes=(kind=:expanding,)`. +can also supply the label at birth with `attributes=(kind=:expanding,)` +when the prepared tree supports that column type. On a tree with only numeric +columns, declare the symbol column first. To set only the simulation object's +label, pass `kind=:expanding` directly to `add_organ!`. See [Growth within a time step](../../tutorials/growing_plant/part1_growth.md). diff --git a/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl index 4dc65613f..c99f6b86f 100644 --- a/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl +++ b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl @@ -27,5 +27,7 @@ function check_tree_birth!(model) MTG.parent(new_node) === first_node && MTG.node_id(new_node) == 3 || return false PSE.model_object(model, new_node).kind === Symbol(3) || return false last_leaf = PSE.add_organ!(root, model, :+, :Leaf, 2) - return isnothing(PSE.model_object(model, PSE.source_node(model, last_leaf)).kind) + isnothing(PSE.model_object(model, PSE.source_node(model, last_leaf)).kind) || return false + labelled_leaf = PSE.add_organ!(root, model, :+, :Leaf, 2; kind=:young) + return PSE.model_object(model, PSE.source_node(model, labelled_leaf)).kind === :young end From 4765ae1da35f2f82869914eadc3d83c926d18492 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 14:21:16 +0100 Subject: [PATCH 283/324] Preserve the exact union of declared MTG label types across organ scales --- src/composite_model/registry_topology.jl | 10 +++------- test/test-organ-status-assembly.jl | 11 +++++++++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/composite_model/registry_topology.jl b/src/composite_model/registry_topology.jl index 55c517e4f..e3dcdf8b6 100644 --- a/src/composite_model/registry_topology.jl +++ b/src/composite_model/registry_topology.jl @@ -860,15 +860,11 @@ function _prepared_mtg_labels(adapter, edits) isempty(edits) && return labels adapter.id === MultiScaleTreeGraph.node_id && adapter.scale === MultiScaleTreeGraph.symbol && all(f -> f isa _MTGAttribute, (labels..., adapter.geometry)) || return labels - columns = MultiScaleTreeGraph.to_table(adapter.root; vars=(:kind, :species, :name)) - return map(labels) do accessor - _prepared_mtg_label(accessor, columns) - end + return map(f -> _prepared_mtg_label(f, adapter.root), labels) end -function _prepared_mtg_label(::_MTGAttribute{K}, columns) where {K} - T = eltype(Tables.getcolumn(columns, K)) - # Preserve true missing values as well as the default for absent attributes. +function _prepared_mtg_label(::_MTGAttribute{K}, root) where {K} + T = MultiScaleTreeGraph.attribute_type(root, K) return _MTGAttribute{K,Union{Nothing,T}}() end diff --git a/test/test-organ-status-assembly.jl b/test/test-organ-status-assembly.jl index ce18692b8..c389178e3 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -141,6 +141,8 @@ end root = MTG.Node(1, MTG.NodeMTG(:/, :Plant, 1, 1), (annotation=:existing,)) geometry = Float32[1, 2] MTG.add_column!(root, :Leaf, :kind, Int; default=3) + MTG.add_column!(root, :Flower, :kind, String; default="pistillate") + MTG.add_column!(root, :Plant, :quality, Missing; default=missing) MTG.add_column!(root, :Leaf, :species, Symbol; default=:guineensis) MTG.add_column!(root, :Leaf, :name, String; default="young leaf") MTG.add_column!(root, :Leaf, :geometry, typeof(geometry); default=geometry) @@ -168,6 +170,15 @@ end fruit = add_organ!(root, model, :+, :Fruit, 2; attributes=(kind=:green,)) @test model_object(model, source_node(model, fruit)).kind === :green @test !hasproperty(fruit, :kind) + flower = add_organ!(root, model, :+, :Flower, 2) + @test model_object(model, source_node(model, flower)).kind === :pistillate + MTG.add_column!(root, :Seed, :kind, Missing; default=missing) + if prepared && isdefined(MTG, :prepare_node_edits) + @test_throws "new MTG label type" add_organ!(root, model, :+, :Seed, 2) + else + seed = add_organ!(root, model, :+, :Seed, 2) + @test model_object(model, source_node(model, seed)).kind === Symbol(missing) + end end end From fc7fdec5e3b1287bcb0d520540381988ed7f915f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 17:23:18 +0100 Subject: [PATCH 284/324] Preserve empty self-scoped status collections through organ growth --- docs/src/guides/multiscale/value_coupling.md | 7 +++ src/composite_model/compilation.jl | 23 ++++++++- .../prepared_status_manifest.jl | 1 - src/composite_model/selectors.jl | 7 +++ .../local_palm_leaf_birth/src/fixture.jl | 13 +++-- test/test-resolved-input-materialization.jl | 48 +++++++++++++++++++ 6 files changed, 92 insertions(+), 7 deletions(-) diff --git a/docs/src/guides/multiscale/value_coupling.md b/docs/src/guides/multiscale/value_coupling.md index e990bf18a..15703fdc2 100644 --- a/docs/src/guides/multiscale/value_coupling.md +++ b/docs/src/guides/multiscale/value_coupling.md @@ -20,6 +20,13 @@ diagnostics. Use `Diagnostics.input_value` to read the values, `Diagnostics.input_carrier` to inspect their container, and `Diagnostics.explain_bindings` to see where they come from. +For a model running on a plant, an input such as +`areas=Many(Self(); scale=:Leaf, var=:area, from_status=true)` stays empty +even after leaves appear. Use `within=Subtree()` to read those leaves. If +neither a source nor the input supplies a concrete element type, the empty +collection has element type `Union{}`. For example, +`sum(status.areas; init=0.0)` then returns `0.0`. + !!! note "Reading the model examples" The examples below show code inside a model. A model stores its parameters in a Julia `struct`, declares its variables with `inputs_` and `outputs_`, diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 82b947536..53ca8f6ee 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6424,7 +6424,7 @@ end # Type-only projection shared by the canonical Many constructor and manifest. function _many_input_carrier_type(::Type{RT}) where {RT<:Tuple} types = fieldtypes(RT) - isempty(types) && throw(ArgumentError("A Many input requires a prepared reference family.")) + isempty(types) && return RefVector{Union{}} all(R -> R <: Ref && isconcretetype(R), types) || throw(ArgumentError("A Many input requires exact prepared reference types.")) R = Union{types...} @@ -6477,10 +6477,13 @@ end ::Many, source_ids, reference_for::F, ::Type{RT}, ) where {F,RT<:Tuple} types = fieldtypes(RT) - isempty(types) && return :(throw(ArgumentError("A Many input requires a prepared reference family."))) all(R -> R <: Ref && isconcretetype(R), types) || return :(throw(ArgumentError("A Many input requires exact prepared reference types."))) C = _many_input_carrier_type(RT) + isempty(types) && return quote + isempty(source_ids) || throw(ArgumentError("A Many input selected a source outside its empty prepared reference family.")) + return $C() + end return quote references = _collect_reference_family(source_ids, reference_for, $RT) isnothing(references) && return nothing @@ -8490,6 +8493,18 @@ function _add_status_writer_reference_types!(references, model, selector, variab return references end +# Self can only select the consumer itself. An unscoped input defaults to Self +# on ordinary objects, but to SceneScope on scene objects. +function _disjoint_self_status_input(model, consumer, selector::Many) + _selector_from_status(selector) || return false + _selector_labels_may_overlap(applies_to(consumer.spec), selector) && return false + matcher = _authored_selector_matcher(selector) + (matcher.scope isa Self || matcher.relation isa Val{:self}) && return true + isnothing(matcher.scope) && isnothing(matcher.relation) || return false + targets = _many_current_application_targets(model, consumer) + return !isempty(targets) && all(id -> _default_dependency_scope(model, id) isa Self, targets) +end + function _prepare_input_reference_types(model, consumer, input, selector, source_var, producer_ids, applications_by_id, writer_applications, distributed_output_plans) references = Any[] @@ -8559,6 +8574,10 @@ function _prepare_input_reference_types(model, consumer, input, selector, # Existing complete references remain valid evidence; no transform # is called here to manufacture an additional type witness. if isempty(candidates) + if selector isa Many && isempty(current) && isempty(references) && + _disjoint_self_status_input(model, consumer, selector) + return Tuple{} + end (current_complete || (isnothing(producer) && !isempty(references)) || (selector isa OptionalOne && isempty(current))) && continue end diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 1ce658793..3e8ad65db 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -165,7 +165,6 @@ end # constructor. A seed Vector value is not a RefVector carrier. function _prepared_status_input_reference(plan) refs = fieldtypes(plan.reference_types) - isempty(refs) && return Union{} if !(plan.selector isa Many) return Union{refs...} end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 530e99ad6..9c3d3bc76 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1697,6 +1697,13 @@ function _prepared_status_route_matches(model, object, parent_id, application, id = _index_object_id(model.registry.objects, object.id) topology = _prepared_status_topology(model, object, id, parent_id) matcher = destination_plan.matcher + if topology isa _PreparedStatusObjectTopology + return _prepared_status_route_matches_id(model, topology, matcher, id, execution_id) + end + return _prepared_status_route_matches_id(model, model, matcher, id, execution_id) +end + +function _prepared_status_route_matches_id(model, topology, matcher::CompiledSelectorMatcher, id, execution_id) _prepared_status_scope_is_current(model, topology, matcher.scope, execution_id) || return false default_scope = isnothing(matcher.scope) && isnothing(matcher.relation) ? _default_dependency_scope(topology, execution_id) : nothing diff --git a/test/fixtures/local_palm_leaf_birth/src/fixture.jl b/test/fixtures/local_palm_leaf_birth/src/fixture.jl index 0edaba979..ce55eb9f4 100644 --- a/test/fixtures/local_palm_leaf_birth/src/fixture.jl +++ b/test/fixtures/local_palm_leaf_birth/src/fixture.jl @@ -25,7 +25,8 @@ PSE.inputs_(::LeafAssimilation{T}) where {T} = PSE.outputs_(::LeafAssimilation{T}) where {T} = (assimilation=zero(T), water_seen=zero(T), previous_seen=zero(T), visits=Int64(0)) PSE.environment_inputs_(::LeafAssimilation{T}) where {T} = (par=zero(T),) -PSE.inputs_(::PalmCarbon{T}) where {T} = (leaf_assimilations=PSE.Default(T[]),) +PSE.inputs_(::PalmCarbon{T}) where {T} = (leaf_assimilations=PSE.Default(T[]), + self_leaf_losses=PSE.Required(AbstractVector{<:Real})) PSE.outputs_(::PalmCarbon{T}) where {T} = (carbon=zero(T), reserve=zero(T), leaf_count=Int64(0)) @@ -42,7 +43,8 @@ PSE.variable_contracts_(::LeafAssimilation) = (area=AREA, water=WATER, previous_assimilation=LEAF_CARBON, assimilation=LEAF_CARBON, water_seen=WATER, previous_seen=LEAF_CARBON) PSE.variable_contracts_(::PalmCarbon) = - (leaf_assimilations=LEAF_CARBON, carbon=PALM_CARBON, reserve=PALM_CARBON) + (leaf_assimilations=LEAF_CARBON, self_leaf_losses=LEAF_CARBON, + carbon=PALM_CARBON, reserve=PALM_CARBON) function PSE.run!(::PalmSupply, status, environment, constants, context) status.supply = status.soil_water @@ -57,7 +59,8 @@ function PSE.run!(model::LeafAssimilation, status, environment, constants, conte return nothing end function PSE.run!(::PalmCarbon, status, environment, constants, context) - status.carbon = sum(status.leaf_assimilations; init=zero(status.carbon)) + status.carbon = sum(status.leaf_assimilations; init=zero(status.carbon)) - + sum(status.self_leaf_losses; init=zero(status.carbon)) status.reserve += status.carbon status.leaf_count = length(status.leaf_assimilations) return nothing @@ -117,7 +120,9 @@ function make_scene(neighbours::Integer; T::Type{<:AbstractFloat}=Float32) application=:leaf_assimilation, var=:assimilation))), PSE.ModelSpec(PalmCarbon{T}(); name=:palm_carbon, on=PSE.Many(scale=:Palm), inputs=(leaf_assimilations=PSE.Many(within=PSE.Subtree(), scale=:Leaf, - application=:leaf_assimilation, var=:assimilation),)), + application=:leaf_assimilation, var=:assimilation), + # The default Self scope keeps this input empty after a leaf is born. + self_leaf_losses=PSE.Many(scale=:Leaf, var=:loss, from_status=true))), ), environment=(duration=Day(1), par=T(8))) newborn = leaf_cells(T, T(1) / T(4)) object = PSE.Object(NEW_LEAF; scale=:Leaf, kind=:leaf, species=:Elaeis_guineensis, diff --git a/test/test-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl index 09a817316..9cf4e8ab1 100644 --- a/test/test-resolved-input-materialization.jl +++ b/test/test-resolved-input-materialization.jl @@ -609,6 +609,54 @@ end @test_throws "no concrete configured source type" run!(ambiguous; steps=0, outputs=:none) end +@testset "a plant's self-scoped leaf input stays empty when a leaf is born" begin + function plant_model(selector, objects...) + CompositeModel(objects...; applications=( + ModelSpec(ManyReader{AbstractVector{<:Real},Float64}(0.0); name=:reader, + on=Many(scale=:Plant), inputs=(x=selector,)),), + environment=(duration=Hour(1),)) + end + for selector in (Many(scale=:Leaf, var=:area, from_status=true), + Many(Self(); scale=:Leaf, var=:area, from_status=true)) + model = plant_model(selector, Object(:p; scale=:Plant)) + simulation = run!(model; steps=1, outputs=:none) + status = model_status(model, :p) + @test status.x isa AbstractVector{<:Real} + @test eltype(status.x) === Union{} + @test isempty(status.x) && status.seen == 0.0 + register_object!(model, Object(:leaf; scale=:Leaf, parent=:p)) + continue!(simulation; steps=1) + @test isempty(status.x) && status.seen == 0.0 + @test !hasproperty(model_status(model, :leaf), :area) + end + + # A scene's unscoped input can select other objects, irrespective of its scale. + unscoped = Many(scale=:Leaf, var=:area, from_status=true) + scene = plant_model(unscoped, Object(:p; scale=:Plant, kind=:scene)) + @test_throws "no concrete configured source type" run!(scene; steps=0, outputs=:none) + future = plant_model(unscoped, Object(:root; scale=:Scene)) + @test_throws "no concrete configured source type" run!(future; steps=0, outputs=:none) + self = Many(Self(); scale=:Leaf, var=:area, from_status=true) + future = plant_model(self, Object(:root; scale=:Scene)) + simulation = run!(future; steps=0, outputs=:none) + register_object!(future, Object(:p; scale=:Plant, parent=:root)) + continue!(simulation; steps=1) + @test isempty(model_status(future, :p).x) && model_status(future, :p).seen == 0.0 + @test_throws "empty prepared reference family" PSE._input_reference_carrier( + Many(), [ObjectId(:leaf)], _ -> Ref(1.0), Tuple{}) + + # A known source cell remains eligible for a future scene-wide consumer. + model = plant_model(unscoped, Object(:p; scale=:Plant), + Object(:leaf; scale=:Leaf, parent=:p, status=Status(area=3f0))) + simulation = run!(model; steps=1, outputs=:none) + @test isempty(model_status(model, :p).x) + register_object!(model, Object(:whole; scale=:Plant, kind=:scene)) + continue!(simulation; steps=1) + @test model_status(model, :whole).seen == 3.0 + @test eltype(model_status(model, :whole).x) === Float32 + @test only(parent(model_status(model, :whole).x)) === PSE.refvalue(model_status(model, :leaf), :area) +end + struct VariantInputDefaults{T} <: AbstractResolved_Endpoint_ReaderModel seed::Base.RefValue{Float64} input_reads::Base.RefValue{Int} From 6f4433fcaf21e859d77dd8b9354ed561be75a0d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 20:58:50 +0100 Subject: [PATCH 285/324] Check the retained newborn context before constructing its execution target --- .../execution_batch_schemas.jl | 22 ++++++++++++++----- src/composite_model/runtime_outputs.jl | 13 ++++------- test/test-model-prepared-growth-schemas.jl | 14 ++++++++++++ 3 files changed, 34 insertions(+), 15 deletions(-) diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl index 1f3c585c9..3708b20b6 100644 --- a/src/composite_model/execution_batch_schemas.jl +++ b/src/composite_model/execution_batch_schemas.jl @@ -180,21 +180,25 @@ end # the same existing finite target schema before assembling the same fields. @inline function _with_execution_target_type(f::F, ::OpenExecutionCohortSchema, application, status_view::V, object_id, model, output_groups, call_bindings, - environment_binding, owners, + environment_binding, owners, args..., ) where {F,V<:CompiledModelStatusView} actual_fields = (object_id=object_id, model=model, status_view=status_view, bound_inputs=status_view.bound_inputs, output_targets=_runtime_model_output_targets(output_groups), call_bindings=call_bindings, environment_binding=environment_binding) - return f(Val{nothing}(), application, actual_fields, owners, OpenContextCallSchema()) + if isempty(args) + return f(Val{nothing}(), application, actual_fields, owners, OpenContextCallSchema()) + end + return f(Val{nothing}(), application, actual_fields, owners, OpenContextCallSchema(), + args[1], args[2], args[3], args[4], args[5], args[6]) end # Incoming metadata can be abstract: callers inline these finite checks before # dispatching the typed factory, without a runtime generated-method fallback. @generated function _with_execution_target_type(f, ::ClosedExecutionCohortSchema{T}, application, status_view::CompiledModelStatusView, object_id, model, output_groups, - call_bindings, environment_binding, owners, -) where {T} + call_bindings, environment_binding, owners, args::Vararg{Any,N}, +) where {T,N} branches = Expr[] names = (:object_id, :model, :status_view, :bound_inputs, :output_targets, :call_bindings, :environment_binding) @@ -234,12 +238,19 @@ end owner_names = (:compiled, :environment_bindings, :temporal_streams, :output_retention, :constants, :environment) owner_values = Expr(:tuple, [:(getproperty(owners, $(QuoteNode(name)))::$(fieldtype(Context,name))) for name in owner_names]...) A = fieldtype(Context, :application) + # Only newborn targets carry a retained context cache. Check its concrete + # type here and emit a direct call with each of the six existing operands. + arguments = [:(args[$i]) for i in 1:N] + if !isempty(arguments) + length(arguments) == 6 || error("Unexpected newborn target factory arguments.") + arguments[1] = :(_admit_newborn_context_cache($Target, args[1])) + end push!(branches, quote if $condition actual_fields = NamedTuple{$(QuoteNode(names))}($(Expr(:tuple,values...))) actual_owners = NamedTuple{$(QuoteNode(owner_names))}($owner_values) return f(Val{$Target}(), application::$A, actual_fields, actual_owners, - $CallSchema()) + $CallSchema(), $(arguments...)) end end) end @@ -732,7 +743,6 @@ end end end -@inline _admit_newborn_context_cache(::Nothing,cache) = cache @inline function _admit_newborn_context_cache(::Type{T},cache) where {T<:CompiledExecutionTarget} isnothing(cache) && return nothing Cache = CallContextCache{fieldtype(T,:context)} diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 17de63868..a55745b49 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -6297,17 +6297,15 @@ function _append_targeted_newborn_targets!( temporal_streams=context.temporal_streams, output_retention=context.output_retention,constants=context.constants, environment=context.environment) - Base.@inline _with_execution_target_type(admission,application,status_view,object_id,model, - output_groups,call_bindings,environment_binding,owners) do target_type,actual_application,actual,owner,call_schema - _append_targeted_newborn_target!(target_type,actual_application,actual,owner, - call_schema,targets,context,cache,stamp,targeted_runtime,key) - end + Base.@inline _with_execution_target_type(_append_targeted_newborn_target!, admission, + application, status_view, object_id, model, output_groups, call_bindings, + environment_binding, owners, cache, targets, context, stamp, targeted_runtime, key) end return targets end function _append_targeted_newborn_target!(::Val{Target}, actual_application, actual, owner, - call_schema, targets, context, cache, stamp, targeted_runtime, key, + call_schema, prepared_cache, targets, context, stamp, targeted_runtime, key, ) where {Target} outputs = isnothing(Target) ? _runtime_model_output_streams(actual.status_view.status,actual_application, @@ -6316,9 +6314,6 @@ function _append_targeted_newborn_target!(::Val{Target}, actual_application, act actual.status_view,actual.output_targets,actual_application, actual.object_id,owner.temporal_streams, owner.output_retention,true) - # Narrow a retained cache before use; no new owner is published - # until all real fields have passed the same target admission. - prepared_cache = _admit_newborn_context_cache(Target,cache) if isnothing(prepared_cache) prepared_cache = _newborn_call_context_cache(context,actual_application, actual.object_id,actual.bound_inputs,actual.output_targets, diff --git a/test/test-model-prepared-growth-schemas.jl b/test/test-model-prepared-growth-schemas.jl index adc267a22..798ea94f3 100644 --- a/test/test-model-prepared-growth-schemas.jl +++ b/test/test-model-prepared-growth-schemas.jl @@ -258,6 +258,20 @@ call_key(target) = (target.application.id, target.object_id.value) target.object_id, target.model, PSE._runtime_model_output_groups(target.compiled, target.application, target.object_id), target.execution_target.call_bindings, target.environment_binding, owners) + + # A controller's retained context cannot initialize the new leaf. + caches = PSE.lifecycle_delta(simulation.model).targeted_topology_runtime.call_context_caches + key = (target.application.id, target.object_id) + leaf_cache = caches[key] + controller_cache = only(only(controller.batches).targets).call_context_cache + caches[key] = controller_cache + try + @test_throws "A retained newborn context is outside its prepared schema" PSE._targeted_new_object_call_targets( + context, :initialize, [target.object_id], cached; initializer=true) + @test caches[key] === controller_cache + finally + caches[key] = leaf_cache + end @test canonical.visits == 0 && canonical.value == 0.0 @test isempty(PSE.lifecycle_delta(simulation.model).initialized_targets) end From 3d5a1b68627d95d3860cbd248b17c00ed6398bee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Fri, 20 Nov 2026 21:12:59 +0100 Subject: [PATCH 286/324] Split the long macOS manual-call test groups into a fifth shard --- .github/workflows/CI.yml | 7 +++++-- test/runtests.jl | 3 +-- test/test_groups.jl | 14 +++++++++++--- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 67d59a74c..1b5b9e9bb 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -20,7 +20,7 @@ concurrency: jobs: test: if: ${{ github.event_name != 'workflow_dispatch' || !inputs.juliac_safe }} - name: Julia ${{ matrix.version }} - ${{ matrix.os }} - shard ${{ matrix.shard }}/4 - ${{ github.event_name }} + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - shard ${{ matrix.shard }}/${{ matrix.os == 'macOS-latest' && 5 || 4 }} - ${{ github.event_name }} runs-on: ${{ matrix.os }} # Cold compilation of the nested call tests can take 170 minutes on macOS 1.10. timeout-minutes: ${{ matrix.os == 'macOS-latest' && matrix.version == '1.10' && 225 || 180 }} @@ -39,6 +39,9 @@ jobs: - macOS-latest - windows-latest shard: [1, 2, 3, 4] + include: + - { os: macOS-latest, version: "1", shard: 5 } + - { os: macOS-latest, version: "1.10", shard: 5 } steps: - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 @@ -49,7 +52,7 @@ jobs: - uses: julia-actions/julia-runtest@v1 env: JULIA_NUM_THREADS: 4 - PSE_TEST_SHARD_COUNT: "4" + PSE_TEST_SHARD_COUNT: ${{ matrix.os == 'macOS-latest' && 5 || 4 }} PSE_TEST_SHARD_INDEX: ${{ matrix.shard }} - uses: julia-actions/julia-processcoverage@v1 - uses: codecov/codecov-action@v7 diff --git a/test/runtests.jl b/test/runtests.jl index c2613af4d..054a02633 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -38,8 +38,7 @@ else shard_index = parse(Int, get(ENV, "PSE_TEST_SHARD_INDEX", "1")) 1 <= shard_index <= shard_count <= length(TEST_GROUPS) || error("Test shard index/count must satisfy 1 <= index <= count <= $(length(TEST_GROUPS)).") - group_indices = shard_count == length(CI_TEST_SHARDS) ? - CI_TEST_SHARDS[shard_index] : (shard_index:shard_count:length(TEST_GROUPS)) + group_indices = test_group_indices(shard_index, shard_count) @info "Test partition" shard_index shard_count groups=length(group_indices) @testset "Testing PlantSimEngine" begin diff --git a/test/test_groups.jl b/test/test_groups.jl index 2f41d9b13..b66dd84e6 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -306,13 +306,21 @@ const TEST_GROUPS = ( # Prepared execution alone can take over two hours on Julia 1.10. On macOS # the reusable scenario tests also need a separate share of the three-hour job budget. -const CI_TEST_SHARDS = let +function test_group_indices(index, count) + count in (4, 5) || return index:count:length(TEST_GROUPS) group_index(name) = only(findall(group -> first(group) == name, TEST_GROUPS)) prepared = group_index("Prepared execution schemas") reusable = group_index("Reusable scenario plans") newborn = group_index("Newborn retained manual calls") identities = group_index("Identity-aware Many inputs") @assert prepared < reusable < newborn < identities - (filter(i -> i != prepared && i != reusable, 1:(newborn - 1)), prepared:prepared, - newborn:(identities - 1), [reusable; identities:lastindex(TEST_GROUPS)]) + early = filter(i -> i != prepared && i != reusable, 1:(newborn - 1)) + other = (prepared:prepared, newborn:(identities - 1), [reusable; identities:lastindex(TEST_GROUPS)]) + if count == 4 + return (early, other...)[index] + end + # The manual-call groups can use a separate macOS runner while keeping + # every group's test files in their original order and Julia process. + calls = group_index("Accepted call evaluations") + return (filter(<(calls), early), other..., filter(>=(calls), early))[index] end From c9b4e6c38ecb25d5c650a4c697de760b576f1c23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 00:08:08 +0100 Subject: [PATCH 287/324] Explain abstract vector defaults in JuliaC safe builds --- docs/src/guides/compile_scenario.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/src/guides/compile_scenario.md b/docs/src/guides/compile_scenario.md index d253a4a5b..4c5eb4c77 100644 --- a/docs/src/guides/compile_scenario.md +++ b/docs/src/guides/compile_scenario.md @@ -125,6 +125,14 @@ after the first step. The multi-object growth tests currently supply these types using internal preparation functions. Automatic preparation through the public API covers the fixed scenario described above. +For a multi-object app that reads values from other organs, declare what the +reader needs. For example, `ages=Required(Vector{Real})` with +`Many(scale=(:Leaf, :Flower), var=:birth, from_status=true)` lets the reader +use a leaf's `Float64` value and a flower's `Float32` value. Writing +`ages=Default(Real[])` also asks PSE to make a private copy of the default. +With Julia 1.13.3 and JuliaC 0.3.12, the safe verifier reports unresolved +calls in `deepcopy(::Vector{Real})` even when that array starts empty. + If preparation rejects a model, read the reported application or feature and check it against this list. If JuliaC's safe verifier rejects a call, start with the first unresolved call in its error output. Check the types From 5ba2a9a4d295d2f440c3e0c585de71618b2c0285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 00:17:30 +0100 Subject: [PATCH 288/324] Balance the plan reuse tests across the existing macOS shards --- test/test_groups.jl | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/test_groups.jl b/test/test_groups.jl index b66dd84e6..406670c24 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -315,12 +315,15 @@ function test_group_indices(index, count) identities = group_index("Identity-aware Many inputs") @assert prepared < reusable < newborn < identities early = filter(i -> i != prepared && i != reusable, 1:(newborn - 1)) - other = (prepared:prepared, newborn:(identities - 1), [reusable; identities:lastindex(TEST_GROUPS)]) + schemas = prepared:prepared + growth = newborn:(identities - 1) + remaining = identities:lastindex(TEST_GROUPS) if count == 4 - return (early, other...)[index] + return (early, schemas, growth, [reusable; remaining])[index] end - # The manual-call groups can use a separate macOS runner while keeping - # every group's test files in their original order and Julia process. + # Plan reuse takes about half an hour on macOS. Run it alongside the + # manual-call groups so the last group finishes within the job budget. calls = group_index("Accepted call evaluations") - return (filter(<(calls), early), other..., filter(>=(calls), early))[index] + return (filter(<(calls), early), schemas, growth, remaining, + [reusable; filter(>=(calls), early)])[index] end From 70c3f00d330fdc8aba60f0830f88d2a7dc9d807d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 01:51:03 +0100 Subject: [PATCH 289/324] Resolve dependency scopes with concrete selector arguments and registry IDs --- src/composite_model/compilation.jl | 8 ++++---- src/composite_model/selectors.jl | 16 +++++++++++++-- test/test-selector-construction-inference.jl | 21 ++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 53ca8f6ee..b84f1f7a1 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6357,10 +6357,10 @@ function _dependency_object_ids( return _resolve_object_ids( model, selector, - matcher; - context=context, - default_to_context=true, - default_scope=_default_dependency_scope(model, context), + matcher, + context, + true, + _default_dependency_scope(model, context), ) end diff --git a/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 9c3d3bc76..0b16f4a34 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -1456,6 +1456,17 @@ function _resolve_object_ids( context=nothing, default_to_context::Bool=false, default_scope=nothing, +) + return _resolve_object_ids(model, selector, matcher, context, default_to_context, default_scope) +end + +function _resolve_object_ids( + model::CompositeModel, + selector::AbstractObjectMultiplicity, + matcher::CompiledSelectorMatcher, + context, + default_to_context::Bool, + default_scope, ) relation = isnothing(matcher.relation) ? nothing : _compiled_relation_symbol(matcher.relation) @@ -1472,11 +1483,13 @@ function _resolve_object_ids( kind = matcher.kind species = matcher.species requested_id = matcher.id + I = keytype(model.registry.objects) if default_to_context && matcher.defaults_to_context && !isnothing(context) - return ObjectId[_object_id_from_context(context)] + id = _object_id_from_context(context) + return id isa I ? I[id] : ObjectId[id] end indexed = _smallest_indexed_candidates( @@ -1498,7 +1511,6 @@ function _resolve_object_ids( else nothing end - I = keytype(model.registry.objects) local_ids = if !isnothing(subtree_root) if !(subtree_root isa I) || !haskey(model.registry.objects, subtree_root::I) I[] diff --git a/test/test-selector-construction-inference.jl b/test/test-selector-construction-inference.jl index a03e45a67..0e684da07 100644 --- a/test/test-selector-construction-inference.jl +++ b/test/test-selector-construction-inference.jl @@ -24,3 +24,24 @@ end @test scoped.relation === nothing @test resolve_object_ids(model, One(id=:leaf)) == [ObjectId(:leaf)] end + +@testset "Scene-wide and relative dependency selectors share the object's ID type" begin + model = PlantSimEngine._with_object_id_domain(CompositeModel( + Object(:scene; scale=:Scene), + Object(:east; scale=:Crown, kind=:crown, parent=:scene), + Object(:west; scale=:Crown, kind=:crown, parent=:scene), + ), ObjectId{Symbol}) + crowns = Many(scale=:Crown, kind=:crown, id=(:east, :west), + within=SceneScope(), process=:light) + relative = Many() + crown_matcher = PlantSimEngine._compile_selector_matcher(model, crowns) + relative_matcher = PlantSimEngine._compile_selector_matcher(model, relative) + for context in (ObjectId(:scene), ObjectId(:west)) + ids = @inferred PlantSimEngine._dependency_object_ids(model, crowns, crown_matcher, context) + @test ids == [ObjectId(:east), ObjectId(:west)] + own = @inferred PlantSimEngine._dependency_object_ids(model, relative, relative_matcher, context) + @test own == [context] + end + @test_throws "No model object with id" PlantSimEngine._dependency_object_ids( + model, crowns, crown_matcher, ObjectId(:absent)) +end From 59fff7216b19c5d79bb3d2b65281b9050eb068a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 02:14:59 +0100 Subject: [PATCH 290/324] Compile scene-wide and relative dependency queries in the native growth tests --- .../fixtures/scene_dependencies/Project.toml | 14 ++++++++++ .../src/PSESceneDependencyControl.jl | 28 +++++++++++++++++++ test/integration/native_growth.jl | 14 ++++++++++ 3 files changed, 56 insertions(+) create mode 100644 test/integration/fixtures/scene_dependencies/Project.toml create mode 100644 test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl diff --git a/test/integration/fixtures/scene_dependencies/Project.toml b/test/integration/fixtures/scene_dependencies/Project.toml new file mode 100644 index 000000000..5525b8d90 --- /dev/null +++ b/test/integration/fixtures/scene_dependencies/Project.toml @@ -0,0 +1,14 @@ +name = "PSESceneDependencyControl" +uuid = "da54703d-0512-40a5-b97a-cb09ac178e21" +version = "0.1.0" + +[deps] +Libiconv_jll = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" +PlantSimEngine = "9a576370-710b-4269-adf9-4f603a9c6423" + +[sources] +PlantSimEngine = {path = "../../../.."} + +[compat] +Libiconv_jll = "=1.18.0" +julia = "1.13" diff --git a/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl b/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl new file mode 100644 index 000000000..2d4c7dabf --- /dev/null +++ b/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl @@ -0,0 +1,28 @@ +module PSESceneDependencyControl + +import PlantSimEngine as PSE + +const SCENE = PSE._with_object_id_domain(PSE.CompositeModel( + PSE.Object(:scene; scale=:Scene, kind=:scene), + PSE.Object(:crown_1; scale=:Crown, kind=:crown, parent=:scene), + PSE.Object(:crown_2; scale=:Crown, kind=:crown, parent=:scene), +), PSE.ObjectId{Symbol}) +const CROWNS = PSE.Many(PSE.SceneScope(); scale=:Crown, kind=:crown, + id=(:crown_1, :crown_2), process=:crown_process) +const MATCHER = PSE._compile_selector_matcher(SCENE, CROWNS) +const RELATIVE = PSE.Many() +const RELATIVE_MATCHER = PSE._compile_selector_matcher(SCENE, RELATIVE) + +Base.@noinline function both_crowns(model, selector, matcher, context) + ids = PSE._dependency_object_ids(model, selector, matcher, context) + return length(ids) == 2 && ids[1] == PSE.ObjectId(:crown_1) && ids[2] == PSE.ObjectId(:crown_2) +end + +function (@main)(args) + context = isempty(args) ? PSE.ObjectId(:scene) : PSE.ObjectId(:crown_1) + both_crowns(SCENE, CROWNS, MATCHER, context) || return Cint(1) + ids = PSE._dependency_object_ids(SCENE, RELATIVE, RELATIVE_MATCHER, context) + return length(ids) == 1 && ids[1] === context ? Cint(0) : Cint(2) +end + +end diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl index 7b5f8819f..529de49a3 100644 --- a/test/integration/native_growth.jl +++ b/test/integration/native_growth.jl @@ -14,6 +14,10 @@ const _producer_growth_app = stage_native_fixture(joinpath(_growth_root, Base.include(@__MODULE__, joinpath(_palm_growth_app, "src", "PSELocalPalmLeafBirth.jl")) Base.include(@__MODULE__, joinpath(_producer_growth_app, "src", "PSEThirtyProducerControl.jl")) +const _scene_dependency_app = stage_native_fixture(joinpath(_growth_root, + "test", "integration", "fixtures", "scene_dependencies")) +Base.include(@__MODULE__, joinpath(_scene_dependency_app, "src", "PSESceneDependencyControl.jl")) + function _split_neighbour_report(words) length(words) >= 8 || error("Incomplete native neighbour report.") words[end-5] == 0x50484153454e5343 || error("Missing native phase timing tag.") @@ -88,3 +92,13 @@ end end end end + +@testset "Native scene and relative model-call selectors" begin + mktempdir() do directory + scene = Compilation.compile(_scene_dependency_app; destination=joinpath(directory, "scene")) + for args in (String[], ["crown"]) + @test PSESceneDependencyControl.main(args) == 0 + @test success(`$(scene.executable) $args`) + end + end +end From 09c506778e302d6c163fd3d388d6d6d8bff95eab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 02:53:12 +0100 Subject: [PATCH 291/324] Document the Julia series used by the standalone Linux check --- docs/src/guides/compile_scenario.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/src/guides/compile_scenario.md b/docs/src/guides/compile_scenario.md index 4c5eb4c77..40a28587d 100644 --- a/docs/src/guides/compile_scenario.md +++ b/docs/src/guides/compile_scenario.md @@ -39,9 +39,9 @@ to inspect it, and `continue!` or `step!` to advance it. ## Build the example executable -Use Julia 1.13.1, JuliaC 0.3.12 and a working C compiler to match the qualified -build. From the root of a PlantSimEngine checkout, instantiate the named app -project once: +The Linux CI job builds this example with Julia 1.13 and JuliaC 0.3.12. You +also need a C compiler. From the root of a PlantSimEngine checkout, instantiate +the app project once. ```sh julia --project=examples/compiled_scenario -e 'using Pkg; Pkg.instantiate()' From 9fe00c5b3b4faccafa74f5aab70c0c4ffcf03070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 02:56:05 +0100 Subject: [PATCH 292/324] Reuse unchanged execution groups before specializing the refresh callback Select the unchanged application before capturing its simulation owners in the rebuilding callback. A birth affecting one of eight applications now specializes the group builder twice instead of sixteen times. Preserve group identity, schedule order and the full refresh when an application changes. --- src/composite_model/runtime_outputs.jl | 25 +++++++++++++++++++------ test/test-model-slot-group-refresh.jl | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index a55745b49..eaf7464de 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4670,6 +4670,17 @@ function _preflight_execution_group_layout!(previous, compiled, slots::Tuple) return nothing end +function _reuse_unchanged_execution_group!(application, previous_slots, visited, groups, batches) + return _with_previous_execution_group(previous_slots, application, visited) do previous_group + if isnothing(previous_group) || previous_group.application !== application + return (0, 0, 0) + end + push!(groups, previous_group) + append!(batches, previous_group.batches) + return (0, 0, 1) + end +end + function _refresh_model_execution_plan( previous::CompiledExecutionPlan, compiled::CompiledCompositeModel, @@ -4699,16 +4710,18 @@ function _refresh_model_execution_plan( # These are the compiler's existing dependency-ordered root entries; # call-only applications are already excluded by that same schedule. for entry in compiled.scenario_plan.application_schedule.entries + if !isnothing(changed_application_ids) && !(entry.application_id in changed_application_ids) + reused = _with_metadata_entry(_reuse_unchanged_execution_group!, compiled.applications_by_id, + entry.application_id, previous_slots, visited_slots, groups, batches) + if !iszero(reused[3]) + groups_reused += 1 + continue + end + end counts = _with_metadata_entry(compiled.applications_by_id, entry.application_id) do application _with_previous_execution_group(previous_slots, application, visited_slots, ) do previous_group - if !isnothing(previous_group) && !isnothing(changed_application_ids) && - !(application.id in changed_application_ids) - push!(groups, previous_group) - append!(batches, previous_group.batches) - return (0, 0, 1) - end changed_ids = isnothing(changed_by_application) ? nothing : get(changed_by_application, application.id, ()) return _refresh_model_execution_group!( diff --git a/test/test-model-slot-group-refresh.jl b/test/test-model-slot-group-refresh.jl index 7260358ba..0b6acfca3 100644 --- a/test/test-model-slot-group-refresh.jl +++ b/test/test-model-slot-group-refresh.jl @@ -97,4 +97,24 @@ end simulation.execution_plan.groups) end +@testset "a new leaf and a replaced model reach the same timestep" begin + leaves = ModelSpec(SlotCounter(1); name=:leaves, on=Many(scale=:Leaf)) + axis(amount) = ModelSpec(SlotCounter(amount); name=:axis, on=One(id=:axis)) + model = CompositeModel(Object(:first; scale=:Leaf, status=Status(count=0)), + Object(:axis; scale=:Axis, status=Status(count=0)); applications=(leaves, axis(2))) + simulation = run!(model; steps=1, outputs=:all) + cell = PSE.refvalue(model_status(model, :axis), :count) + + register_object!(model, Object(:new; scale=:Leaf, status=Status(count=0))) + model.applications[2] = axis(7) + Advanced.refresh_bindings!(model; force=true) + step!(simulation) + + @test PSE.refvalue(model_status(model, :axis), :count) === cell + retained = outputs(simulation) + @test retained[(:axis, ObjectId(:axis), :count)] == [(1.0, 2), (2.0, 9)] + @test retained[(:leaves, ObjectId(:first), :count)] == [(1.0, 1), (2.0, 2)] + @test retained[(:leaves, ObjectId(:new), :count)] == [(2.0, 1)] +end + end From 3cdc6092789a0d2a1a261967dfae3b13cfeb598c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 04:15:40 +0100 Subject: [PATCH 293/324] Validate new leaf input bindings before publishing growth --- docs/src/journeys/users/structure_changes.md | 8 + src/composite_model/compilation.jl | 385 +++++++++++------- .../lifecycle_input_changes.jl | 228 +++++++++++ src/composite_model/runtime_outputs.jl | 19 +- test/fixtures/raw_status_readers.jl | 15 + test/test-input-source-matching.jl | 4 +- test/test-model-distributed-output-runtime.jl | 100 +++++ test/test-model-input-binding-storage.jl | 4 +- test/test-model-input-recipes.jl | 226 +++++++++- 9 files changed, 797 insertions(+), 192 deletions(-) create mode 100644 src/composite_model/lifecycle_input_changes.jl create mode 100644 test/fixtures/raw_status_readers.jl diff --git a/docs/src/journeys/users/structure_changes.md b/docs/src/journeys/users/structure_changes.md index 674167e66..4ff69c260 100644 --- a/docs/src/journeys/users/structure_changes.md +++ b/docs/src/journeys/users/structure_changes.md @@ -101,6 +101,14 @@ targets_after_refresh = only( ) ``` +A model that reads measured area directly from every leaf with +`Many(scale=:Leaf, within=SceneScope(), from_status=true, var=:measured_area)` +needs a `measured_area` value on each new leaf. If a leaf registered between steps is +missing that value, `step!` reports the missing input before advancing the +clock or recording another sample. The leaf is still in the model. You can +remove it with `remove_object!`, register a leaf with its measured area, +and retry the step. + You can also create organs inside a model's `run!` function, for example in a growth model. In that case, PlantSimEngine updates the simulation after that model finishes. The new organ can take part in calculations scheduled diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b84f1f7a1..f650695f8 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3002,6 +3002,27 @@ end _record_consumer_input_bindings!(::Nothing, args...) = nothing +# Read a proposal over an existing index without touching the committed +# entries. Used for application membership, source writers and conversions. +struct _LookupOverlay{B,O} + base::B + overlay::O +end + +@inline function Base.get( + table::_LookupOverlay, + key, + default, +) + overlay = get(table.overlay, key, nothing) + isnothing(overlay) || return overlay + return get(table.base, key, default) +end + +@inline Base.setindex!(table::_LookupOverlay, value, key) = setindex!(table.overlay, value, key) + +include("lifecycle_input_changes.jl") + struct _AddedConsumerInputBindings{M,C,B,I} model::M many_binding_cache::C @@ -3039,7 +3060,7 @@ function _compile_consumer_input_plan!( many_binding_cache, model, plan, consumer_id, ) if !isnothing(shared_binding) - push!(bindings, shared_binding) + _push_shared_many_input!(bindings, shared_binding) _runtime_performance_count!(performance, :many_input_binding_precompile_reuses) return nothing end @@ -3056,7 +3077,7 @@ function _append_inferred_input_route!(plan, bindings, model, application_id, ) push!(bindings, _materialize_input_route( model, application_id, application_process, consumer_id, plan, - sources, applications_by_id, + sources, applications_by_id, _route_cells(bindings), )) return nothing end @@ -3451,42 +3472,39 @@ end end end -function _append_stable_many_source_references!( +@inline function _staged_stable_source_reference(::Nothing, model, id, variable, ::Type{R}) where {R} + return _registered_source_reference(model.registry.objects.catalog, _model_object(model, id).status, variable, R) +end +@inline function _staged_stable_source_reference(statuses, model, id, variable, ::Type{R}) where {R} + reference = _input_source_cell(statuses, model.registry.objects, id, variable) + return reference isa R ? reference::R : nothing +end + +function _prepare_stable_many_source_references( model::CompositeModel, binding::CompiledModelInputBinding, new_source_ids, - performance, + statuses, ) - _can_append_stable_many_sources(binding) || return false + _can_append_stable_many_sources(binding) || return nothing existing_references = parent(binding.carrier) added_references = eltype(existing_references)[] sizehint!(added_references, length(new_source_ids)) for object_id in new_source_ids - reference = _registered_source_reference( - model.registry.objects.catalog, _model_object(model, object_id).status, - _input_route_source(binding.plan.route), eltype(existing_references), - ) - isnothing(reference) && return false + reference = _staged_stable_source_reference(statuses, model, object_id, + _input_route_source(binding.plan.route), eltype(existing_references)) + isnothing(reference) && return nothing push!(added_references, reference) end - # Resolve every fallible reference before mutating the vectors shared by - # all consumers in this same-rate `Many(...)` group. - append!(existing_references, added_references) - append!(binding.source_ids, new_source_ids) - _runtime_performance_count!( - performance, - :lifecycle_many_input_binding_direct_appends, - ) - _runtime_performance_count!( - performance, - :lifecycle_many_input_binding_direct_sources_appended, - length(new_source_ids), - ) - return true + return CompiledModelInputBinding(binding.plan, binding.consumer_id, new_source_ids, + binding.source_application_ids, binding.policy, binding.carrier_hint, + typeof(binding.carrier)(added_references)) end -function _append_added_many_sources!( +struct _UnchangedManyInput end + +function _prepare_added_many_sources( model::CompositeModel, binding::CompiledModelInputBinding, added_ids, @@ -3494,9 +3512,9 @@ function _append_added_many_sources!( applications_by_id, distributed_outputs, ; - performance=nothing, + statuses=nothing, ) - binding.multiplicity == :many || return false + binding.multiplicity == :many || return nothing default_scope = _default_dependency_scope(model, binding.consumer_id) matcher = binding.matcher matching_matcher = matcher @@ -3522,7 +3540,7 @@ function _append_added_many_sources!( first(_sorted_object_id_position(source_ids, object_id)) || push!(new_source_ids, object_id) end - isempty(new_source_ids) && return true + isempty(new_source_ids) && return _UnchangedManyInput() _sort_object_ids!(new_source_ids) _filter_many_input_sources_by_writer!( new_source_ids, @@ -3534,28 +3552,24 @@ function _append_added_many_sources!( distributed_outputs, applications_by_object, ) - isempty(new_source_ids) && return true + isempty(new_source_ids) && return _UnchangedManyInput() # The growth path allocates monotonically increasing IDs. Appending preserves the # selector's stable order and, critically, keeps the carrier already installed in # the consumer status. Non-monotonic explicit IDs use the general rebuild path. if !isempty(binding.source_ids) && !_object_id_isless(last(binding.source_ids), first(new_source_ids)) - return false + return nothing end - _append_stable_many_source_references!( - model, - binding, - new_source_ids, - performance, - ) && return true + direct = _prepare_stable_many_source_references(model, binding, new_source_ids, statuses) + isnothing(direct) || return direct - new_carrier = _input_carrier(model, binding.selector, new_source_ids, _input_route_source(binding.plan.route), binding.plan.reference_types) - isnothing(new_carrier) && return false + new_carrier = _input_carrier(model, binding.selector, new_source_ids, _input_route_source(binding.plan.route), binding.plan.reference_types, statuses) + isnothing(new_carrier) && return nothing existing_refs = parent(binding.carrier) new_refs = parent(new_carrier) - eltype(new_refs) <: eltype(existing_refs) || return false + eltype(new_refs) <: eltype(existing_refs) || return nothing source_application_ids = if _selector_from_status(binding.selector) Symbol[] @@ -3604,15 +3618,31 @@ function _append_added_many_sources!( end end - # Resolve every fallible piece before mutating the shared carrier/binding. - # Several consumers may share these vectors through `many_binding_cache`. - append!(existing_refs, new_refs) - append!(binding.source_ids, new_source_ids) - empty!(binding.source_application_ids) - append!(binding.source_application_ids, source_application_ids) + return CompiledModelInputBinding(binding.plan, binding.consumer_id, new_source_ids, + source_application_ids, binding.policy, binding.carrier_hint, new_carrier) +end + +function _apply_added_many_sources!(binding, delta, performance) + append!(parent(binding.carrier), parent(delta.carrier)) + append!(binding.source_ids, delta.source_ids) + if delta.source_application_ids === binding.source_application_ids + _runtime_performance_count!(performance, :lifecycle_many_input_binding_direct_appends) + _runtime_performance_count!(performance, :lifecycle_many_input_binding_direct_sources_appended, + length(delta.source_ids)) + else + empty!(binding.source_application_ids) + append!(binding.source_application_ids, delta.source_application_ids) + end return true end +function _append_added_many_sources!(model, binding, added, by_object, by_id, outputs; performance=nothing) + delta = _prepare_added_many_sources(model, binding, added, by_object, by_id, outputs) + isnothing(delta) && return false + delta isa _UnchangedManyInput && return true + return _apply_added_many_sources!(binding, delta, performance) +end + function _update_structural_many_sources!( model::CompositeModel, binding::CompiledModelInputBinding, @@ -4682,7 +4712,7 @@ Base.@noinline function _store_rebuilt_input_binding!( end # One existing-binding lifecycle operation; admission precedes this worker. -function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S) where {B<:CompiledModelInputBinding,S} +function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S, admissions) where {B<:CompiledModelInputBinding,S} (; model, input_bindings, input_bindings_by_target, many_binding_cache, changed_bindings, rewired_consumer_ids, affected_temporal_keys, previous_temporal_sources, @@ -4741,7 +4771,13 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S default_scope, ) || return false end - appended_sources = if force_rebuild + prepared = _pending_input_update(admissions, index) + appended_sources = if !isnothing(prepared) && first(prepared) === :append && !force_rebuild + delta = admissions.bindings[last(prepared)] + _apply_added_many_sources!(binding, delta, performance) + elseif !isnothing(prepared) && first(prepared) === :unchanged && !force_rebuild + true + elseif !isnothing(prepared) || force_rebuild false else _append_added_many_sources!( @@ -4783,18 +4819,22 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S end application = applications_by_id[binding.application_id] replacement = similar(input_bindings, 0) - _resolve_materialize_input_route!( - replacement, - model, - application.id, - application.process, - consumer_id, - binding.plan, - applications_by_object, - applications_by_id, - nothing, - distributed_outputs, - ) + if !isnothing(prepared) && first(prepared) === :replace + push!(replacement, admissions.bindings[last(prepared)]) + else + _resolve_materialize_input_route!( + replacement, + model, + application.id, + application.process, + consumer_id, + binding.plan, + applications_by_object, + applications_by_id, + nothing, + distributed_outputs, + ) + end old_cache_key = _many_binding_share_key(many_binding_cache, model, binding) if !isnothing(old_cache_key) && get(many_binding_cache.by_query, old_cache_key, nothing) === binding @@ -4906,8 +4946,31 @@ function _extend_compiled_scene( return nothing end end + added_applications = CompiledModelApplication[] + for application_id in new_target_application_ids + Base.@inline _with_metadata_entry(applications_by_id, application_id) do application + push!(added_applications, + _partial_model_application(application, new_targets[application.id])) + return nothing + end + end + candidate_binding_indices = Set{Int}() + for target_id in added_ids + object_id = _index_object_id(model.registry.objects, target_id) + _union_selector_candidates!( + candidate_binding_indices, + compiled.dynamic_input_binding_indices, + model, + object_id, + ) + end + staged = _new_consumer_input_storage(compiled, model, added_applications, added_ids, pure_addition, candidate_binding_indices) + before_publish!(outputs, destinations, output_applications=added_applications) = + _stage_added_scene_inputs!(compiled, model, added_applications, output_applications, + outputs, destinations, staged, performance) manual_application_ids = compiled.scenario_plan.manual_application_ids - distributed_outputs, changed_distributed_output_target_ids, changed_writers_by_variable = + distributed_outputs, changed_distributed_output_target_ids, changed_writers_by_variable = try + _validate_model_writers_for_objects!(compiled, added_ids) _refresh_model_distributed_outputs( model, compiled.distributed_outputs, @@ -4917,8 +4980,12 @@ function _extend_compiled_scene( compiled.scenario_plan.distributed_output_plans, added_ids, new_targets, - pure_addition, + pure_addition, before_publish!, ) + catch + _discard_added_memberships!(compiled, new_targets) + rethrow() + end for (application_id, raw_id) in changed_distributed_output_target_ids object_id = _index_object_id(model.registry.objects, raw_id) push!(changed_target_ids_seed, (application_id, object_id)) @@ -4931,14 +4998,6 @@ function _extend_compiled_scene( ) started_at = _runtime_performance_start(performance) - added_applications = CompiledModelApplication[] - for application_id in new_target_application_ids - Base.@inline _with_metadata_entry(applications_by_id, application_id) do application - push!(added_applications, - _partial_model_application(application, new_targets[application.id])) - return nothing - end - end new_call_bindings, changed_call_target_keys, observed_manual_call_binding_indices_by_callee_target = _refresh_scene_call_bindings!( model, @@ -4951,13 +5010,6 @@ function _extend_compiled_scene( ) call_bindings = compiled.call_bindings dynamic_call_binding_indices = compiled.dynamic_call_binding_indices - _validate_model_writers_for_objects!(compiled, added_ids) - _prepare_model_output_statuses!( - model, - added_applications, - applications_by_id; - performance=performance, - ) _runtime_performance_finish!( performance, :call_binding_refresh, @@ -4977,7 +5029,6 @@ function _extend_compiled_scene( processed_many_sources = IdDict{Any,Nothing}() previous_shared_many_sources = IdDict{Any,Vector{I}}() rebuild_dynamic_input_index = !pure_addition - candidate_binding_indices = Set{Int}() # Keep one key schema; the inactive alias is never queried as writer evidence. writer_rebind_keys = forced_input_binding_keys has_writer_rebinds = false @@ -5003,15 +5054,6 @@ function _extend_compiled_scene( push!(candidate_binding_indices, binding_index) end end - for target_id in added_ids - object_id = _index_object_id(model.registry.objects, target_id) - _union_selector_candidates!( - candidate_binding_indices, - compiled.dynamic_input_binding_indices, - model, - object_id, - ) - end _runtime_performance_count!( performance, :selector_input_binding_candidates, @@ -5020,6 +5062,7 @@ function _extend_compiled_scene( queued_binding_indices = copy(candidate_binding_indices) pending_binding_indices = sort!(collect(candidate_binding_indices)) pending_binding_position = 1 + admissions = isnothing(staged) ? nothing : staged.existing binding_refresh = (; model, input_bindings, input_bindings_by_target, many_binding_cache, changed_bindings, rewired_consumer_ids, affected_temporal_keys, previous_temporal_sources, @@ -5034,7 +5077,7 @@ function _extend_compiled_scene( raw_binding = input_bindings[index] rebuilt = Base.@inline _with_model_input_binding( _refresh_existing_scene_input_binding!, input_bindings, - raw_binding, index, binding_refresh, + raw_binding, index, binding_refresh, admissions, ) rebuild_dynamic_input_index |= rebuilt end @@ -5042,11 +5085,8 @@ function _extend_compiled_scene( recorder = _AddedConsumerInputBindings( model, many_binding_cache, changed_bindings, input_bindings_by_target, ) - _compile_model_input_bindings!( - input_bindings, model, added_applications, manual_application_ids, - compiled.scenario_plan.input_recipes_by_application, distributed_outputs, - applications_by_object, applications_by_id, many_binding_cache, performance, recorder, - ) + _publish_added_consumer_bindings!(recorder, input_bindings, staged, model, + many_binding_cache, previous_binding_count) dynamic_input_binding_indices = if rebuild_dynamic_input_index many_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -6491,13 +6531,25 @@ end end end +_route_cells(::Any) = nothing +_route_cells(bindings::_StagedConsumerBindings) = bindings.statuses + +_input_source_cell(::Nothing, objects, id, variable) = + _status_ref_or_nothing(_registered_object_status(objects, id), variable) +function _input_source_cell(statuses, objects, id, variable) + recipe = get(statuses.recipes, id, nothing) + isnothing(recipe) && return _input_source_cell(nothing, objects, id, variable) + name = _input_reference_name(variable) + return _status_recipe_has_variable(recipe, name) ? _status_recipe_reference(recipe, name) : nothing +end + function _input_carrier( model::CompositeModel, selector::AbstractObjectMultiplicity, - source_ids::AbstractVector{<:ObjectId}, source_var, reference_types::Type{<:Tuple}, + source_ids::AbstractVector{<:ObjectId}, source_var, reference_types::Type{<:Tuple}, statuses=nothing, ) objects = model.registry.objects reference_for = source_id -> - _status_ref_or_nothing(_registered_object_status(objects, source_id), source_var) + _input_source_cell(statuses, objects, source_id, source_var) return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end @@ -6522,7 +6574,7 @@ function _stream_only_initial_reference( application::CompiledModelApplication, model::CompositeModel, source_id::ObjectId, - source_var::Symbol, + source_var::Symbol, conversions=model.status_conversion_records, ) _has_stream_only_output(application, source_var) || return nothing return Base.@inline _with_application_variant(application, source_id) do effective_model, ports @@ -6534,7 +6586,7 @@ function _stream_only_initial_reference( application_id=application.id, origin=:stream_only_source_default, private_copy=true, - reuse=true, + reuse=true, conversion_records=conversions, ) return Ref(initial) end @@ -6545,7 +6597,7 @@ function _stream_only_initial_reference( source_id::ObjectId, source_application_ids, source_var::Symbol, - applications_by_id, + applications_by_id, statuses=nothing, ) matching_application_ids = Symbol[ application_id for application_id in source_application_ids @@ -6554,13 +6606,11 @@ function _stream_only_initial_reference( ] if length(matching_application_ids) == 1 reference = Base.@inline _with_metadata_entry(_stream_only_initial_reference, - applications_by_id, only(matching_application_ids), model, source_id, source_var) + applications_by_id, only(matching_application_ids), model, source_id, source_var, + isnothing(statuses) ? model.status_conversion_records : statuses.conversion_records) isnothing(reference) || return reference end - return _status_ref_or_nothing( - _model_object(model, source_id).status, - source_var, - ) + return _input_source_cell(statuses, model.registry.objects, source_id, source_var) end function _stream_only_initial_carrier( @@ -6570,10 +6620,10 @@ function _stream_only_initial_carrier( source_application_ids, source_var::Symbol, applications_by_id, - reference_types::Type{<:Tuple}, + reference_types::Type{<:Tuple}, statuses=nothing, ) reference_for = source_id -> _stream_only_initial_reference( - model, source_id, source_application_ids, source_var, applications_by_id, + model, source_id, source_application_ids, source_var, applications_by_id, statuses, ) return _input_reference_carrier(selector, source_ids, reference_for, reference_types) end @@ -6904,18 +6954,16 @@ Base.@noinline function _stage_model_output_default!(value, recipe, variable, co return nothing end -function _prepare_model_output_statuses!( - model::CompositeModel, - applications, - applications_by_id; - performance=nothing, -) - isempty(applications) && return model +function _output_status_preparation(model) I = keytype(model.registry.objects) recipes = _canonical_status_recipe_storage(model, I) - recipe_order = I[] - record_conversions = !_no_status_conversion(model.status_conversion) - conversion_records = record_conversions ? Dict{Any,Any}() : model.status_conversion_records + records = _no_status_conversion(model.status_conversion) ? model.status_conversion_records : + _LookupOverlay(model.status_conversion_records, empty(model.status_conversion_records)) + return (; recipes, recipe_order=I[], conversion_records=records) +end + +function _stage_model_output_statuses!(statuses, model, applications, applications_by_id) + (; recipes, recipe_order, conversion_records) = statuses for partial in applications Base.@inline _with_model_application(applications_by_id, partial) do application schemas = _application_default_schemas(application, Val(:outputs)) @@ -6942,16 +6990,21 @@ function _prepare_model_output_statuses!( end end end - # Publish each final canonical Status and its conversion records after the - # ordered defaults have all been staged, in every lifecycle mode. - result = _apply_status_recipes!( - model, - recipes, - recipe_order; - performance=performance, - ) - record_conversions && merge!(model.status_conversion_records, conversion_records) - return result + return statuses +end + +function _commit_model_output_statuses!(model, statuses; performance=nothing) + _apply_status_recipes!(model, statuses.recipes, statuses.recipe_order; performance) + records = statuses.conversion_records + _no_status_conversion(model.status_conversion) || merge!(model.status_conversion_records, records.overlay) + return model +end + +function _prepare_model_output_statuses!(model::CompositeModel, applications, applications_by_id; performance=nothing) + isempty(applications) && return model + statuses = _output_status_preparation(model) + _stage_model_output_statuses!(statuses, model, applications, applications_by_id) + return _commit_model_output_statuses!(model, statuses; performance) end function _validate_required_model_output_destinations!( @@ -7009,7 +7062,7 @@ function _validate_model_output_destination_statuses!( return nothing end -function _stage_model_output_destination_statuses!(model, record, recipes, recipe_order) +function _stage_model_output_destination_statuses!(model, record, recipes, recipe_order, conversion_records=model.status_conversion_records) for destination_id in record.destination_ids preparation = _status_preparation_for_object!( recipes, @@ -7036,7 +7089,7 @@ function _stage_model_output_destination_statuses!(model, record, recipes, recip variable, _input_default(declaration); application_id=record.plan.application_id, - origin=:distributed_output_default, + origin=:distributed_output_default, conversion_records, ) end end @@ -7304,7 +7357,7 @@ function _compile_model_distributed_outputs( applications, applications_by_id, manual_application_ids, - plans::CompiledDistributedOutputPlans, + plans::CompiledDistributedOutputPlans, before_publish! = nothing, ) resolved = _resolve_model_output_destinations( model, @@ -7323,8 +7376,14 @@ function _compile_model_distributed_outputs( # destination state behind. _validate_model_output_destination_statuses!(model, resolved) _validate_required_model_output_destinations!(model, resolved) - _prepare_model_output_statuses!(model, applications, applications_by_id) - _prepare_model_output_destination_statuses!(model, resolved) + if isnothing(before_publish!) + _prepare_model_output_statuses!(model, applications, applications_by_id) + _prepare_model_output_destination_statuses!(model, resolved) + else + # Input source resolution consults only the ordered writer ownership. + prospective = CompiledDistributedOutputs((), nothing, ownership, nothing) + before_publish!(prospective, resolved, applications) + end bindings, by_execution_target = _compile_model_output_destination_bindings(model, resolved, plans) return CompiledDistributedOutputs( @@ -7371,8 +7430,9 @@ function _refresh_model_distributed_outputs( plans, added_ids, new_targets, - pure_addition, + pure_addition, before_publish!, ) + before_publish!(previous, ()) return previous, _object_key_set(Tuple{Symbol,keytype(model.registry.objects)}), nothing end @@ -7411,7 +7471,7 @@ end for binding in Base.uniontypes(B) C = fieldtype(binding, :columns) IDs = fieldtype(binding, :destination_ids) - records = Union{records,NamedTuple{(:binding, :destination_ids, :columns),Tuple{binding,IDs,C}}} + records = Union{records,NamedTuple{(:binding, :destination_ids, :columns, :replace_columns),Tuple{binding,IDs,C,Bool}}} end return :(Vector{$records}()) end @@ -7419,7 +7479,7 @@ end # The binding and its columns are one correlated alternative from the existing # staging vector. Admit them together before constructing that exact record. @generated function _append_model_output_column_addition!( - additions::Vector{A}, binding, destination_ids, columns, + additions::Vector{A}, binding, destination_ids, columns, replace_columns::Bool, ) where {A} branches = Expr[] for record in Base.uniontypes(A) @@ -7427,7 +7487,7 @@ end fieldtype(record, :columns) push!(branches, quote if binding isa $B && destination_ids isa $IDs && columns isa $C - push!(additions, $record((binding::$B, destination_ids::$IDs, columns::$C))) + push!(additions, $record((binding::$B, destination_ids::$IDs, columns::$C, replace_columns))) return nothing end end) @@ -7438,6 +7498,15 @@ end end end +function _can_append_model_output_columns(existing, additions) + for name in keys(existing) + references = parent(getproperty(additions, name)) + R = eltype(parent(getproperty(existing, name))) + eltype(references) <: R || all(ref -> ref isa R, references) || return false + end + return true +end + function _incremental_distributed_output_addition!( model::CompositeModel, previous::CompiledDistributedOutputs, @@ -7446,7 +7515,7 @@ function _incremental_distributed_output_addition!( manual_application_ids, plans::CompiledDistributedOutputPlans, added_ids, - new_targets, + new_targets, before_publish!, ) for (application_id, object_ids) in new_targets isempty(object_ids) && continue @@ -7475,7 +7544,10 @@ function _incremental_distributed_output_addition!( end _record_destination_writers!(staged_ownership, previous, resolved_additions) _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) - _prepare_model_output_destination_statuses!(model, resolved_additions) + prospective = CompiledDistributedOutputs(previous.bindings, previous.by_execution_target, + _LookupOverlay(previous.writer_ownership, staged_ownership), + previous.destination_ids_by_application_variable) + before_publish!(prospective, resolved_additions) column_additions = _model_output_column_additions(previous.bindings) for resolved in resolved_additions @@ -7485,15 +7557,14 @@ function _incremental_distributed_output_addition!( columns = _model_output_destination_columns( model, resolved.plan, resolved.destination_ids, ) - for variable in binding.plan.variable_names - existing_references = parent(getproperty(binding.columns, variable)) - added_references = parent(getproperty(columns, variable)) - eltype(added_references) <: eltype(existing_references) || - all(reference -> reference isa eltype(existing_references), added_references) || - return nothing + replace_columns = !_can_append_model_output_columns(binding.columns, columns) + if replace_columns && !isempty(binding.destination_ids) + # Widen this group with the same status cells used at preparation. + columns = _model_output_destination_columns(model, resolved.plan, + [binding.destination_ids; resolved.destination_ids]) end _append_model_output_column_addition!(column_additions, binding, - resolved.destination_ids, columns) + resolved.destination_ids, columns, replace_columns) end for (key, owners) in staged_ownership @@ -7502,12 +7573,13 @@ function _incremental_distributed_output_addition!( for addition in column_additions binding = addition.binding destination_ids = addition.destination_ids + addition.replace_columns && setfield!(binding, :columns, addition.columns) for variable_ in binding.plan.variable_names variable = Symbol(variable_) - append!( - parent(getproperty(binding.columns, variable)), - parent(getproperty(addition.columns, variable)), - ) + if !addition.replace_columns + append!(parent(getproperty(binding.columns, variable)), + parent(getproperty(addition.columns, variable))) + end indexed_ids = previous.destination_ids_by_application_variable[ (binding.application_id, variable) ] @@ -7537,7 +7609,7 @@ function _refresh_model_distributed_outputs( plans::CompiledDistributedOutputPlans, added_ids, new_targets, - pure_addition, + pure_addition, before_publish!, ) if pure_addition incremental = _incremental_distributed_output_addition!( @@ -7548,7 +7620,7 @@ function _refresh_model_distributed_outputs( manual_application_ids, plans, added_ids, - new_targets, + new_targets, before_publish!, ) isnothing(incremental) || return incremental end @@ -7557,7 +7629,7 @@ function _refresh_model_distributed_outputs( applications, applications_by_id, manual_application_ids, - plans, + plans, before_publish!, ) changed_targets = _changed_distributed_output_target_ids(previous, current) changed_writers_by_variable = if pure_addition @@ -9162,7 +9234,7 @@ function _materialize_input_route( consumer_id::ObjectId, plan::CompiledModelInputPlan, sources::ResolvedInputSources, - applications_by_id, + applications_by_id, statuses=nothing, ) input_sym = _input_route_input(plan.route) selector = plan.selector @@ -9198,10 +9270,10 @@ function _materialize_input_route( source_application_ids, source_var, applications_by_id, - plan.reference_types, + plan.reference_types, statuses, ) else - _input_carrier(model, selector, source_ids, source_var_tag, plan.reference_types) + _input_carrier(model, selector, source_ids, source_var_tag, plan.reference_types, statuses) end carrier_hint = if isempty(source_ids) && selector isa OptionalOne :optional_default @@ -9218,7 +9290,7 @@ function _materialize_input_route( source_var, source_ids, carrier, - carrier_hint, + carrier_hint, statuses, ) return CompiledModelInputBinding( plan, consumer_id, source_ids, source_application_ids, @@ -9246,7 +9318,7 @@ function _resolve_materialize_input_route!( ) push!(bindings, _materialize_input_route( model, application_id, application_process, consumer_id, plan, - sources, applications_by_id, + sources, applications_by_id, _route_cells(bindings), )) return bindings end @@ -9390,12 +9462,13 @@ function _validate_model_input_source!( source_var::Symbol, source_ids::AbstractVector{I}, carrier, - carrier_hint::Symbol, + carrier_hint::Symbol, statuses=nothing, ) where {I<:ObjectId} !isnothing(carrier) && return nothing status_source_ids = I[ source_id for source_id in source_ids - if _model_object(model, source_id).status isa Status + if _model_object(model, source_id).status isa Status || + (!isnothing(statuses) && haskey(statuses.recipes, source_id)) ] isempty(status_source_ids) && return nothing io = IOBuffer() diff --git a/src/composite_model/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl new file mode 100644 index 000000000..eaad5176b --- /dev/null +++ b/src/composite_model/lifecycle_input_changes.jl @@ -0,0 +1,228 @@ +# Binding changes across a lifecycle barrier. The registered objects already +# exist. New consumer bindings and fallible changes to existing source groups +# borrow the normal resolver, then publish the admitted cells and memberships. + +struct _StagedManyInputCache{L,P,I,S} + local_cache::L + published::P + added::I + statuses::S + pure_addition::Bool +end + +function _shared_many_input_binding(staged::_StagedManyInputCache, model, plan, consumer) + shared = _shared_many_input_binding(staged.local_cache, model, plan, consumer) + isnothing(shared) || return shared + # A settled source and a single writer keep the prepared Many carrier + # family stable on addition. Borrow the cell and recover its final + # membership from the live cache after the ordinary refresh has run. + staged.pure_addition && (plan.application !== nothing || + _input_route_from_status(plan.route) || length(plan.potential_source_application_ids) == 1) || + return nothing + previous = _shared_many_input_binding(staged.published, model, plan, consumer) + isnothing(previous) && return nothing + if isempty(previous.source_ids) + # An empty live group can receive its first column. Check only the + # incoming cells against the existing carrier's admitted element type. + scope = _default_dependency_scope(model, consumer) + R = eltype(parent(previous.carrier)) + for id in staged.added + _selector_matches_object_id(model, plan.matcher, id, consumer, true, scope, false) || continue + ref = _input_source_cell(staged.statuses, model.registry.objects, id, _input_route_source(plan.route)) + ref isa R || return nothing + end + end + return previous +end + +struct _PendingStatusInputChanges{B,I} + candidates::Vector{Int} + added::I + bindings::B + updates::Dict{Int,Tuple{Symbol,Int}} +end + +struct _StagedConsumerBindings{B,S,R,C,M,A} + entries::B + statuses::S + ranges::R + cache::Union{Nothing,C} + model::M + existing::Union{Nothing,_PendingStatusInputChanges{B,A}} + reused::BitSet +end +Base.length(bindings::_StagedConsumerBindings) = length(bindings.entries) +Base.push!(bindings::_StagedConsumerBindings, binding) = push!(bindings.entries, binding) + +_push_shared_many_input!(bindings, binding) = push!(bindings, binding) +function _push_shared_many_input!(staged::_StagedConsumerBindings, binding) + push!(staged.entries, binding) + push!(staged.reused, length(staged.entries)) + return nothing +end + +function _record_consumer_input_bindings!(staged::_StagedConsumerBindings, bindings, + application_id::Symbol, object_id, first_binding, last_binding) + first_binding <= last_binding || return nothing + range = first_binding:last_binding + push!(staged.ranges, (application_id, object_id, range)) + for i in range + staged.entries[i] = _share_many_input_binding!(staged.cache.local_cache, + staged.model, staged.entries[i]) + end + return nothing +end + +@inline _has_consumer_input_routes(recipe, manual::Bool) = + !isempty(recipe.explicit) || (!manual && !isempty(recipe.inferred)) + +function _new_consumer_input_storage(compiled, model, applications, added, pure_addition, candidates) + plan = compiled.scenario_plan + any_routes = false + for application in applications + id = application.id + if _with_metadata_entry(_has_consumer_input_routes, plan.input_recipes_by_application, id, + id in plan.manual_application_ids) + any_routes = true + break + end + end + existing = _pending_status_input_changes(compiled, candidates, added, pure_addition) + any_routes || !isnothing(existing) || return nothing + I = keytype(model.registry.objects) + entries = similar(compiled.input_bindings, 0) + statuses = _output_status_preparation(model) + # Only new consumers need a writable query cache. A refresh of existing + # readers needs its storage type, which the published cache already supplies. + local_cache = any_routes ? _empty_many_input_binding_cache(I, entries) : compiled.many_input_binding_cache + cache = _StagedManyInputCache(local_cache, + compiled.many_input_binding_cache, added, statuses, pure_addition) + ranges = Tuple{Symbol,I,UnitRange{Int}}[] + return _StagedConsumerBindings{typeof(entries),typeof(statuses),typeof(ranges), + typeof(cache),typeof(model),typeof(added)}(entries, statuses, ranges, + any_routes ? cache : nothing, model, existing, BitSet()) +end + +function _stage_added_scene_inputs!(compiled, model, applications, output_applications, + outputs, destinations, ::Nothing, performance) + _prepare_model_output_statuses!(model, output_applications, compiled.applications_by_id; performance) + isempty(destinations) || _prepare_model_output_destination_statuses!(model, destinations) + return nothing +end + +function _stage_added_scene_inputs!(compiled, model, applications, output_applications, + outputs, destinations, staged::_StagedConsumerBindings, performance) + empty!(staged.entries) + empty!(staged.ranges) + empty!(staged.reused) + if !isnothing(staged.cache) + empty!(staged.cache.local_cache.by_query) + empty!(staged.cache.local_cache.by_plan) + end + _stage_model_output_statuses!(staged.statuses, model, output_applications, compiled.applications_by_id) + for record in destinations + _stage_model_output_destination_statuses!(model, record, staged.statuses.recipes, + staged.statuses.recipe_order, staged.statuses.conversion_records) + end + if !isnothing(staged.cache) + _compile_model_input_bindings!(staged, model, applications, + compiled.scenario_plan.manual_application_ids, compiled.scenario_plan.input_recipes_by_application, + outputs, compiled.applications_by_object, compiled.applications_by_id, staged.cache, performance, staged) + end + _stage_existing_status_inputs!(staged.existing, compiled, model, outputs, staged.statuses, performance) + _commit_model_output_statuses!(model, staged.statuses; performance) + return nothing +end + +_publish_added_consumer_bindings!(recorder, input_bindings, ::Nothing, args...) = nothing + +function _publish_added_consumer_bindings!(recorder, input_bindings, staged::_StagedConsumerBindings, + model, many_binding_cache, previous_binding_count) + for (id, consumer, range) in staged.ranges + for index in range + binding = staged.entries[index] + if index in staged.reused + shared = _shared_many_input_binding(many_binding_cache, model, binding.plan, consumer) + isnothing(shared) || (binding = shared) + end + push!(input_bindings, binding) + end + _record_consumer_input_bindings!(recorder, input_bindings, id, consumer, + previous_binding_count + first(range), previous_binding_count + last(range)) + end + return nothing +end + +# A raw status reader can select a new object with no cell for its variable. +# A singular route can also acquire a second source. Stage those fallible +# changes in the same barrier as the new consumers, without copying old IDs. + +function _pending_status_input_changes(compiled, candidates, added, pure_addition) + pure_addition && !isempty(candidates) || return nothing + indices = Int[] + for index in candidates + raw = compiled.input_bindings[index] + needed = _with_model_input_binding(compiled.input_bindings, raw) do binding + binding.multiplicity !== :many || _input_route_from_status(binding.plan.route) + end + needed && push!(indices, index) + end + isempty(indices) && return nothing + return _PendingStatusInputChanges(sort!(indices), added, similar(compiled.input_bindings, 0), + Dict{Int,Tuple{Symbol,Int}}()) +end + +_stage_existing_status_inputs!(::Nothing, args...) = nothing +function _stage_existing_status_inputs!(pending, compiled, model, outputs, statuses, performance) + empty!(pending.bindings) + empty!(pending.updates) + for index in pending.candidates + _with_model_input_binding(_stage_existing_status_input!, compiled.input_bindings, + compiled.input_bindings[index], pending, index, compiled, model, outputs, statuses, performance) + end + return nothing +end + +function _stage_existing_status_input!(binding, pending, index, compiled, model, outputs, statuses, performance) + if binding.multiplicity === :many && binding.carrier isa Union{RefVector,ObjectRefVector} + delta = _prepare_added_many_sources(model, binding, pending.added, + compiled.applications_by_object, compiled.applications_by_id, outputs; statuses) + if delta isa _UnchangedManyInput + pending.updates[index] = (:unchanged, 0) + return nothing + elseif !isnothing(delta) + push!(pending.bindings, delta) + pending.updates[index] = (:append, length(pending.bindings)) + return nothing + end + elseif binding.multiplicity !== :many + scope = _default_dependency_scope(model, binding.consumer_id) + _selector_matches_any_object_id(model, binding.matcher, pending.added, binding.consumer_id, + true, scope) || return nothing + end + sources = _resolve_input_sources(model, binding.consumer_id, binding.plan, + compiled.applications_by_object, compiled.applications_by_id, nothing, outputs) + replacement = _materialize_input_route(model, binding.application_id, + compiled.applications_by_id[binding.application_id].process, binding.consumer_id, binding.plan, + sources, compiled.applications_by_id, statuses) + push!(pending.bindings, replacement) + pending.updates[index] = (:replace, length(pending.bindings)) + return nothing +end + +_pending_input_update(::Nothing, index) = nothing +_pending_input_update(pending, index) = get(pending.updates, index, nothing) + +function _discard_added_memberships!(compiled, new_targets) + for (id, targets) in new_targets + _with_metadata_entry(compiled.applications_by_id, id) do application + for object_id in targets + found, position = _sorted_object_id_position(application.target_ids, object_id) + found && deleteat!(application.target_ids, position) + delete!(compiled.applications_by_object, object_id) + end + return nothing + end + end + return nothing +end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index eaf7464de..a5687854e 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -5819,11 +5819,6 @@ function _call_target_object_ids(model::CompositeModel, objects) return unique!(ids) end -struct _ApplicationsByObjectOverlay{B,O} - base::B - overlay::O -end - mutable struct _TargetedApplicationSet{A,B} applications::A applications_by_object::B @@ -5842,16 +5837,6 @@ mutable struct _TargetedTopologyRuntime{CS,MA,D<:Dict,O} <: call_context_caches::Dict{Tuple{Symbol,ObjectId},CallContextCache} end -@inline function Base.get( - applications::_ApplicationsByObjectOverlay, - object_id, - default, -) - overlay = get(applications.overlay, object_id, nothing) - isnothing(overlay) || return overlay - return get(applications.base, object_id, default) -end - function _targeted_topology_runtime!( context::RunContext, model::CompositeModel, @@ -5861,7 +5846,7 @@ function _targeted_topology_runtime!( I = keytype(model.registry.objects) A = eltype(compiled.applications) O = Dict{I,Vector{A}} - S = _TargetedApplicationSet{Vector{A},_ApplicationsByObjectOverlay{typeof(compiled.applications_by_object),O}} + S = _TargetedApplicationSet{Vector{A},_LookupOverlay{typeof(compiled.applications_by_object),O}} manual = compiled.scenario_plan.manual_application_ids D = Dict{Vector{I},S} Runtime = _TargetedTopologyRuntime{typeof(compiled),typeof(manual),D,O} @@ -5948,7 +5933,7 @@ function _targeted_application_set!( ) return _TargetedApplicationSet( output_applications, - _ApplicationsByObjectOverlay( + _LookupOverlay( runtime.compiled.applications_by_object, runtime.added_applications_by_object, ), diff --git a/test/fixtures/raw_status_readers.jl b/test/fixtures/raw_status_readers.jl new file mode 100644 index 000000000..80b0289f2 --- /dev/null +++ b/test/fixtures/raw_status_readers.jl @@ -0,0 +1,15 @@ +PSE.@process "input_recipe_aggregate" verbose=false +PSE.@process "input_recipe_empty" verbose=false + +struct AggregateReader <: AbstractInput_Recipe_AggregateModel end +PSE.inputs_(::AggregateReader) = (values=Default(Float64[]),) +PSE.outputs_(::AggregateReader) = (total=0.0,) +function PSE.run!(::AggregateReader, status, environment, constants, context) + status.total = sum(bound_input(context, :values); init=0.0) + return nothing +end + +struct EmptyModel <: AbstractInput_Recipe_EmptyModel end +PSE.inputs_(::EmptyModel) = NamedTuple() +PSE.outputs_(::EmptyModel) = NamedTuple() +PSE.run!(::EmptyModel, status, environment, constants, context) = nothing diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl index d263a9c26..1d60869d2 100644 --- a/test/test-input-source-matching.jl +++ b/test/test-input-source-matching.jl @@ -105,7 +105,7 @@ end compiled.applications_by_id[:a].spec.applies_to) partial = PSE._partial_model_application(compiled.applications_by_id[:a], ObjectId[ObjectId(7)]) - overlay = PSE._ApplicationsByObjectOverlay(compiled.applications_by_object, + overlay = PSE._LookupOverlay(compiled.applications_by_object, Dict(ObjectId(7) => PSE.CompiledModelApplication[partial])) @test !(ObjectId(7) in compiled.applications_by_id[:a].target_ids) @test PSE._matching_input_source_applications(overlay, ObjectId[ObjectId(7)], @@ -158,7 +158,7 @@ end newborn = register_object!(model, Object(5; kind=:local, status=Status(x=5f0))) reference = PSE.refvalue(newborn.status, :x) partial = PSE._partial_model_application(shared, ObjectId[ObjectId(5)]) - overlay = PSE._ApplicationsByObjectOverlay(compiled.applications_by_object, + overlay = PSE._LookupOverlay(compiled.applications_by_object, Dict(ObjectId(5) => PSE.CompiledModelApplication[partial])) @test PSE._matching_input_source_applications(overlay, ObjectId.([5, 2, 1, 3]), :x, nothing, nothing, distributed; diff --git a/test/test-model-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index f5eb8dbdb..590427f62 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1483,3 +1483,103 @@ end end end end + +struct DistributedRuntimeRealWriter <: AbstractDistributed_Runtime_Stateful_WriterModel end +PlantSimEngine.inputs_(::DistributedRuntimeRealWriter) = NamedTuple() +PlantSimEngine.outputs_(::DistributedRuntimeRealWriter) = (incident_par=Distributed(Required(Real)),) +function PlantSimEngine.run!(::DistributedRuntimeRealWriter, status, environment, constants, context) + column = output_targets(context, (:incident_par,)).columns.incident_par + for index in eachindex(column) + column[index] = 100.0 + context.time + end + return nothing +end + +@testset "The first destination and a widened column retain the actual leaf cells" begin + PSE = PlantSimEngine + events = DistributedRuntimeEvent[] + model = CompositeModel(Object(:scene; scale=:Scene); + applications=_distributed_runtime_applications(events), + environment=(duration=Hour(1),)) + sim = run!(model; steps=0, outputs=:all) + @test isempty(only(sim.compiled.distributed_outputs.bindings).destination_ids) + + register_object!(model, Object(:leaf_a; scale=:Leaf, parent=:scene)) + step!(sim) + binding = only(sim.compiled.distributed_outputs.bindings) + column = binding.columns.incident_par + leaf = model_status(model, :leaf_a) + @test binding.destination_ids == [ObjectId(:leaf_a)] + @test only(parent(column)) === PSE.refvalue(leaf, :incident_par) + @test leaf.seen === 10.0 + @test length(sim.compiled.input_bindings) == 1 + + register_object!(model, Object(:leaf_z; scale=:Leaf, parent=:scene)) + step!(sim) + @test binding.columns.incident_par === column + @test last(parent(column)) === PSE.refvalue(model_status(model, :leaf_z), :incident_par) + @test model_status(model, :leaf_z).seen === 60.0 + @test outputs(sim)[(:distributed_runtime_writer, ObjectId(:leaf_a), :incident_par)] == + [(1.0, 10.0), (2.0, 20.0)] + + # The canonical manifest admits both precisions. A new Float32 destination + # widens the previous homogeneous column while preserving its Float64 cell. + supplied = Status(incident_par=0.0) + mixed = CompositeModel(Object(:scene; scale=:Scene), + Object(:leaf_a; scale=:Leaf, parent=:scene, status=supplied), + Object(:sample; scale=:Leaf, parent=:scene, status=Status(incident_par=0f0)); + applications=(ModelSpec(DistributedRuntimeRealWriter(); name=:writer, + on=One(id=:scene), outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope()); + vars=(:incident_par,)),)),)) + mixed_sim = run!(mixed; steps=0, outputs=:all) + remove_object!(mixed, :sample) + step!(mixed_sim) + homogeneous = only(mixed_sim.compiled.distributed_outputs.bindings) + @test homogeneous.columns.incident_par isa PSE.RefVector{Float64} + before = PSE.refvalue(supplied, :incident_par) + added = Status(incident_par=0f0) + register_object!(mixed, Object(:leaf_z; scale=:Leaf, parent=:scene, status=added)) + step!(mixed_sim) + after = PSE.refvalue(added, :incident_par) + group = only(mixed_sim.compiled.distributed_outputs.bindings) + @test group.destination_ids == ObjectId.([:leaf_a, :leaf_z]) + @test parent(group.columns.incident_par)[1] === before + @test parent(group.columns.incident_par)[2] === after + @test before[] === 102.0 && after[] === 102f0 + @test only(outputs(mixed_sim)[(:writer, ObjectId(:leaf_z), :incident_par)]) == (2.0, 102f0) +end + +@testset "A rejected first destination can be retried after its reader acquires a source" begin + model = CompositeModel(Object(:scene; scale=:Scene), + Object(:sample; scale=:Gate, parent=:scene, status=Status(permit=[0.0])); + applications=( + ModelSpec(DistributedRuntimeStatefulWriterModel(); name=:writer, on=One(id=:scene), + outputs_to=(OutputTo(Many(scale=:Leaf, within=SceneScope()); vars=(:incident_par,)),)), + ModelSpec(DistributedRuntimePlantIntegratorModel(); name=:reader, on=Many(scale=:Leaf), + inputs=(integrated_incident_par=One(SceneScope(); scale=:Gate, from_status=true, var=:permit),)), + )) + remove_object!(model, :sample) + sim = run!(model; steps=0, outputs=:all) + leaf_id = ObjectId(:leaf_a) + group = only(sim.compiled.distributed_outputs.bindings) + register_object!(model, Object(leaf_id; scale=:Leaf, parent=:scene)) + initial = model_status(model, leaf_id) + for attempt in 1:2 + @test_throws "Expected exactly one object" step!(sim) + @test current_step(sim) == 0 + @test model_status(model, leaf_id) === initial + @test isempty(group.destination_ids) + @test isempty(group.columns.incident_par) + @test isempty(sim.compiled.input_bindings) + @test !haskey(sim.compiled.distributed_outputs.writer_ownership, (leaf_id, :incident_par)) + @test !haskey(outputs(sim), (:writer, leaf_id, :incident_par)) + end + register_object!(model, Object(:gate; scale=:Gate, parent=:scene, status=Status(permit=[7.0]))) + step!(sim) + @test current_step(sim) == 1 + @test group.destination_ids == [leaf_id] + @test only(parent(group.columns.incident_par)) === PlantSimEngine.refvalue(model_status(model, leaf_id), :incident_par) + @test only(sim.compiled.input_bindings).carrier === PlantSimEngine.refvalue(model_status(model, :gate), :permit) + @test model_status(model, leaf_id).integrated_total === 7.0 + @test outputs(sim)[(:writer, leaf_id, :incident_par)] == [(1.0, 101.0)] +end diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 1a6cfbec9..e33569acf 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -167,8 +167,8 @@ end register_object!(data.model,Object(:second;scale=:Leaf,parent=:scene)) @test model_status(data.model,:second) === nothing # A valid first reference followed by genuine absence must not append either. - @test !PSE._append_stable_many_source_references!(data.model, current, - ObjectId[ObjectId(:first), ObjectId(:second)], nothing) + @test isnothing(PSE._prepare_stable_many_source_references(data.model, current, + ObjectId[ObjectId(:first), ObjectId(:second)], nothing)) @test parent(current.carrier) === references @test current.source_ids === source_ids @test isempty(references) && isempty(source_ids) diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index f97bec42e..d43e83088 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -6,8 +6,7 @@ const PSE = PlantSimEngine PSE.@process "input_recipe_writer" verbose=false PSE.@process "input_recipe_pair_reader" verbose=false -PSE.@process "input_recipe_aggregate" verbose=false -PSE.@process "input_recipe_empty" verbose=false +include("fixtures/raw_status_readers.jl") struct Writer{T,P} <: AbstractInput_Recipe_WriterModel value::T @@ -40,19 +39,6 @@ function PSE.run!(::InferredReader, status, environment, constants, context) return nothing end -struct AggregateReader <: AbstractInput_Recipe_AggregateModel end -PSE.inputs_(::AggregateReader) = (values=Default(Float64[]),) -PSE.outputs_(::AggregateReader) = (total=0.0,) -function PSE.run!(::AggregateReader, status, environment, constants, context) - status.total = sum(bound_input(context, :values); init=0.0) - return nothing -end - -struct EmptyModel <: AbstractInput_Recipe_EmptyModel end -PSE.inputs_(::EmptyModel) = NamedTuple() -PSE.outputs_(::EmptyModel) = NamedTuple() -PSE.run!(::EmptyModel, status, environment, constants, context) = nothing - function pair_model(; policy=nothing) return CompositeModel(Object(0; scale=:Scene), Object(1; scale=:Leaf), Object(2; scale=:Reader), Object(3; scale=:Other); @@ -299,4 +285,214 @@ end [ObjectId(:unadmitted_identity_type)]) end +@testset "Retry a pending leaf after its required writer appears" begin + model = CompositeModel(Object(1; scale=:Scene); applications=( + ModelSpec(Writer(2f0); name=:source, on=One(id=1)), + ModelSpec(Writer(4f0); name=:later, on=Many(scale=:Extra)), + ModelSpec(PairReader{Float32}(); name=:reader, on=Many(scale=:Leaf), + inputs=(left=One(SceneScope(); id=1, var=:x, application=:source), + right=One(SceneScope(); scale=:Extra, var=:y, application=:later))), + )) + simulation = run!(model; steps=0, outputs=:all) + compiled = simulation.compiled + reader = compiled.applications_by_id[:reader] + root = model_status(model, 1) + source = PSE.refvalue(root, :x) + leaf = ObjectId(2) + register_object!(model, Object(leaf; scale=:Leaf, parent=1)) + initial_leaf = model_status(model, leaf) + for attempt in 1:2 + @test_throws "Expected exactly one object" PSE.continue!(simulation; steps=1) + @test current_step(simulation) == 0 + @test simulation.compiled === compiled + @test isempty(reader.target_ids) + @test isempty(get(compiled.applications_by_object, leaf, ())) + @test isempty(compiled.input_bindings) + @test !haskey(compiled.input_bindings_by_target, (:reader, leaf)) + @test !haskey(compiled.status_views_by_target, (:reader, leaf)) + @test model_status(model, leaf) === initial_leaf + @test PSE.refvalue(model_status(model, 1), :x) === source + end + register_object!(model, Object(3; scale=:Extra, parent=1)) + step!(simulation) + @test current_step(simulation) == 1 + @test reader.target_ids == [leaf] + @test only(simulation.compiled.applications_by_object[leaf]).id === :reader + current = simulation.compiled + bindings = current.input_bindings_by_target[(:reader, leaf)] + @test getproperty.(bindings, :input) == [:left, :right] + @test all(i -> current.input_bindings[i] === bindings[i], eachindex(bindings)) + @test bindings[1].carrier === source + @test bindings[2].carrier === PSE.refvalue(model_status(model, 3), :y) + @test PSE.refvalue(current.status_views_by_target[(:reader, leaf)].status, :left) === source + @test model_status(model, leaf).total === 10f0 +end + +@testset "A refused carrier leaves no writer or binding to the new leaf" begin + function make_scene(populated) + objects = Object[Object(1; scale=:Scene)] + populated && push!(objects, Object(2; scale=:Leaf, parent=1)) + return CompositeModel(objects...; applications=( + ModelSpec(Writer(2f0); name=:source, on=One(id=1)), + ModelSpec(PairReader{Float32}(); name=:reader, on=Many(scale=:Leaf), + inputs=(left=One(SceneScope(); id=1, var=:x), + right=One(SceneScope(); id=1, var=:y))), + )) + end + reference = run!(make_scene(true); steps=0, outputs=:none) + left = only(b for b in reference.compiled.input_bindings if b.input === :left) + model = make_scene(false) + sim = PSE._prepare_simulation!(model; steps=0, outputs=:none, constants=PSE.Constants(), + input_binding_storage=Vector{typeof(left)}()) + register_object!(model, Object(2; scale=:Leaf, parent=1)) + for attempt in 1:2 + @test_throws MethodError PSE.continue!(sim; steps=0) + @test current_step(sim) == 0 + @test isempty(sim.compiled.input_bindings) + @test isempty(sim.compiled.applications_by_id[:reader].target_ids) + @test !haskey(sim.compiled.applications_by_object, ObjectId(2)) + @test !haskey(sim.compiled.status_views_by_target, (:reader, ObjectId(2))) + @test isnothing(model_status(model, 2)) + end +end + +@testset "Healing a valid selection with a missing writer" begin + model = CompositeModel(Object(1; scale=:Scene), Object(3; scale=:Extra, kind=:wrong, parent=1); + applications=( + ModelSpec(Writer(2f0); name=:source, on=One(id=1)), + ModelSpec(Writer(4f0); name=:later, on=Many(scale=:Extra, kind=:green)), + ModelSpec(PairReader{Float32}(); name=:reader, on=Many(scale=:Leaf), + inputs=(left=One(SceneScope(); id=1, var=:x, application=:source), + right=One(SceneScope(); scale=:Extra, var=:y, application=:later))), + )) + sim = run!(model; steps=0, outputs=:none) + register_object!(model, Object(2; scale=:Leaf, parent=1)) + previous = nothing + for attempt in 1:2 + caught = try + PSE.continue!(sim; steps=1) + nothing + catch err + sprint(showerror, err) + end + @test caught isa String + @test !occursin("Ambiguous canonical writers", something(caught, "")) + isnothing(previous) || @test caught == previous + previous = caught + @test isempty(sim.compiled.input_bindings) + @test isempty(sim.compiled.applications_by_id[:reader].target_ids) + @test !haskey(sim.compiled.applications_by_object, ObjectId(2)) + @test isnothing(model_status(model, 2)) + @test current_step(sim) == 0 + end + remove_object!(model, 3) + register_object!(model, Object(4; scale=:Extra, kind=:green, parent=1)) + step!(sim) + @test current_step(sim) == 1 + @test model_status(model, 2).total === 10f0 + @test length(sim.compiled.input_bindings) == 2 + @test only(sim.compiled.applications_by_object[ObjectId(2)]).id === :reader +end + +@testset "A refused leaf preserves the existing Many carrier and publication history" begin + model = CompositeModel(Object(1; scale=:Scene); applications=( + ModelSpec(Writer(2.0); name=:source, on=One(id=1)), + ModelSpec(Writer(4.0); name=:later, on=Many(scale=:Extra)), + ModelSpec(PairReader{Float64}(); name=:reader, on=Many(scale=:Leaf), + inputs=(left=One(SceneScope(); id=1, var=:x, application=:source), + right=One(SceneScope(); scale=:Extra, var=:y, application=:later))), + ModelSpec(AggregateReader(); name=:sum, on=One(id=1), + inputs=(values=Many(scale=:Leaf, within=SceneScope(), application=:reader, var=:total),)), + )) + sim = run!(model; steps=1, outputs=:all) + original = only(sim.compiled.input_bindings) + carrier = original.carrier + samples = copy(outputs(sim)[(:sum, ObjectId(1), :total)]) + register_object!(model, Object(2; scale=:Leaf, parent=1)) + for attempt in 1:2 + @test_throws "Expected exactly one object" PSE.continue!(sim; steps=1) + @test current_step(sim) == 1 + @test only(sim.compiled.input_bindings) === original + @test isempty(original.source_ids) + @test isempty(carrier) + @test outputs(sim)[(:sum, ObjectId(1), :total)] == samples + @test isempty(sim.compiled.applications_by_id[:reader].target_ids) + @test isnothing(model_status(model, 2)) + end + register_object!(model, Object(3; scale=:Extra, parent=1)) + step!(sim) + @test current_step(sim) == 2 + @test original.carrier === carrier + @test only(parent(carrier)) === PSE.refvalue(model_status(model, 2), :total) + @test original.source_ids == [ObjectId(2)] + @test model_status(model, 2).total === 10.0 + @test model_status(model, 1).total === 10.0 + @test outputs(sim)[(:sum, ObjectId(1), :total)] == [samples; [(2.0,10.0)]] +end + + +@testset "Existing raw-status input rejects a new leaf without publishing its membership" begin + model = CompositeModel(Object(1; scale=:Scene), + Object(2; scale=:Leaf, parent=1, status=Status(x=2.0)); applications=( + ModelSpec(EmptyModel(); name=:tag, on=Many(scale=:Leaf)), + ModelSpec(AggregateReader(); name=:sum, on=One(id=1), + inputs=(values=Many(scale=:Leaf, within=SceneScope(), from_status=true, var=:x),)), + )) + sim = run!(model; steps=1, outputs=:all) + original = only(sim.compiled.input_bindings) + old_cell = only(parent(original.carrier)) + samples = copy(outputs(sim)[(:sum, ObjectId(1), :total)]) + register_object!(model, Object(3; scale=:Leaf, parent=1, status=Status())) + for attempt in 1:2 + @test_throws "no source `Status` reference is available" PSE.continue!(sim; steps=1) + @test current_step(sim) == 1 + @test sim.compiled.applications_by_id[:tag].target_ids == [ObjectId(2)] + @test !haskey(sim.compiled.applications_by_object, ObjectId(3)) + @test only(sim.compiled.input_bindings) === original + @test only(parent(original.carrier)) === old_cell + @test original.source_ids == [ObjectId(2)] + @test outputs(sim)[(:sum, ObjectId(1), :total)] == samples + end + remove_object!(model, 3) + register_object!(model, Object(4; scale=:Leaf, parent=1, status=Status(x=4.0))) + step!(sim) + @test current_step(sim) == 2 + @test model_status(model, 1).total === 6.0 + @test outputs(sim)[(:sum, ObjectId(1), :total)] == [samples; [(2.0, 6.0)]] + new = only(sim.compiled.input_bindings) + @test new.source_ids == ObjectId.([2, 4]) + @test parent(new.carrier)[1] === old_cell + @test parent(new.carrier)[2] === PSE.refvalue(model_status(model, 4), :x) +end + + +@testset "A refused reader keeps conversions pending until its inputs are admitted" begin + model = CompositeModel(Object(1; scale=:Scene); + type_promotion=Dict(Float64 => Float32), applications=( + ModelSpec(Writer(2.0); name=:source, on=One(id=1), output_routing=(x=:stream_only,)), + ModelSpec(Writer(4.0); name=:later, on=Many(scale=:Extra)), + ModelSpec(PairReader{Float64}(); name=:reader, on=Many(scale=:Leaf), + inputs=(left=One(SceneScope(); id=1, var=:x, application=:source), + right=One(SceneScope(); scale=:Extra, var=:y, application=:later))), + )) + sim = run!(model; steps=0, outputs=:all) + register_object!(model, Object(2; scale=:Leaf, parent=1)) + before = copy(model.status_conversion_records) + key = (:stream_only_source_default, :source, ObjectId(1), :x) + @test !haskey(before, key) + for attempt in 1:2 + @test_throws "Expected exactly one object" PSE.continue!(sim; steps=1) + @test model.status_conversion_records == before + @test isempty(sim.compiled.input_bindings) + @test isnothing(model_status(model, 2)) + @test current_step(sim) == 0 + end + register_object!(model, Object(3; scale=:Extra, parent=1)) + step!(sim) + @test current_step(sim) == 1 + @test model.status_conversion_records[key].effective_type === Float32 + @test haskey(model.status_conversion_records, (:model_output_default, :reader, ObjectId(2), :total)) + @test model_status(model, 2).total === 10f0 +end + end From a55afb0ded239b0fbdcb8e992ff517134de87d5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 04:24:25 +0100 Subject: [PATCH 294/324] Exercise rejected leaf registration and repair in the JuliaC binary --- .../src/PSEThirtyProducerControl.jl | 17 ++++ .../src/leaf_recovery.jl | 94 +++++++++++++++++++ test/integration/native_growth.jl | 7 +- 3 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl diff --git a/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl index 919a97704..d25e9dd80 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl @@ -4,13 +4,30 @@ include("native_preparation.jl") using .NativePreparation: close_registry, RuntimeTypes, InputTrace, remember!, batch_schema include("distributed_growth.jl") include("prepare.jl") +include("leaf_recovery.jl") const STATE = prepare_control() function (@main)(args) + length(args) == 1 && only(args) == "recover" && return LeafRecovery.qualify() isempty(args) || return Cint(2) checkpoint(STATE, 0) || return Cint(10) + sim = STATE.simulation + root, producer = sim.execution_plan.groups_by_application_slot + root.application.id === :birth && producer.application.id === :producer || return Cint(30) + root_batch = only(root.batches) + isempty(producer.membership.object_ids) && isempty(producer.batches) || return Cint(31) for day in 1:3 PSE.step!(STATE.simulation) checkpoint(STATE, day) || return Cint(10 + day) + if day == 2 + changed = sim.compiled.changed_execution_application_ids + length(changed) == 1 && :producer in changed || return Cint(32) + current_root, current_producer = sim.execution_plan.groups_by_application_slot + current_root === root && only(current_root.batches) === root_batch || return Cint(33) + current_root.application === sim.compiled.applications_by_id[:birth] || return Cint(34) + current_producer.application === sim.compiled.applications_by_id[:producer] || return Cint(35) + only(current_producer.membership.object_ids) === PSE.ObjectId(:emitter) || return Cint(36) + length(current_producer.batches) == 1 || return Cint(37) + end end return Cint(0) end diff --git a/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl b/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl new file mode 100644 index 000000000..81b74d4e0 --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl @@ -0,0 +1,94 @@ +module LeafRecovery +import PlantSimEngine as PSE +using PlantSimEngine: Default, bound_input +using ..NativePreparation: close_registry, RuntimeTypes, InputTrace, remember!, batch_schema +include("raw_status_readers.jl") +const IDS = (:tag, :sum) + +function scene() + return PSE.CompositeModel(PSE.Object(1; scale=:Scene), + PSE.Object(2; scale=:Leaf, parent=1, status=PSE.Status(x=2.0)); applications=( + PSE.ModelSpec(EmptyModel(); name=:tag, on=PSE.Many(scale=:Leaf)), + PSE.ModelSpec(AggregateReader(); name=:sum, on=PSE.One(id=1), + inputs=(values=PSE.Many(scale=:Leaf, within=PSE.SceneScope(), from_status=true, var=:x),)), + )) +end + +function refused(sim) + try + PSE.step!(sim) + catch err + err isa ErrorException || return false + message = err.msg + return message isa String && message == "Input binding `values` on application `sum` for object `1` reads `x` from objects `[2, 3]`, but no source `Status` reference is available." + end + return false +end + +function exercise!(sim, observe) + PSE.current_step(sim) == 0 || return 10 + observe(sim) + PSE.step!(sim) + observe(sim) + binding = only(sim.compiled.input_bindings) + reference = only(parent(binding.carrier)) + history = get(PSE.outputs(sim), (:sum, PSE.ObjectId(1), :total), nothing) + history isa Vector{Tuple{Float64, Float64}} || return 11 + length(history) == 1 && first(history) === (1.0, 2.0) || return 12 + PSE.register_object!(sim.model, PSE.Object(3; scale=:Leaf, parent=1, status=PSE.Status())) + for _ in 1:2 + refused(sim) || return 13 + PSE.current_step(sim) == 1 && length(history) == 1 || return 14 + only(sim.compiled.input_bindings) === binding || return 15 + only(parent(binding.carrier)) === reference || return 16 + only(binding.source_ids) === PSE.ObjectId(2) || return 17 + haskey(sim.compiled.applications_by_object, PSE.ObjectId(3)) && return 18 + end + PSE.remove_object!(sim.model, 3) + PSE.register_object!(sim.model, PSE.Object(4; scale=:Leaf, parent=1, status=PSE.Status(x=4.0))) + PSE.step!(sim) + observe(sim) + PSE.current_step(sim) == 2 && length(history) == 2 || return 19 + history[1] === (1.0, 2.0) && history[2] === (2.0, 6.0) || return 20 + current = only(sim.compiled.input_bindings) + length(current.source_ids) == 2 && current.source_ids[1] === PSE.ObjectId(2) && + current.source_ids[2] === PSE.ObjectId(4) || return 21 + cells = parent(current.carrier) + length(cells) == 2 && cells[1] === reference && + cells[2] === PSE.refvalue(PSE.model_status(sim, 4), :x) || return 22 + return 0 +end + +ignore(sim) = nothing + +function prepare() + control = PSE.run!(scene(); steps=0, outputs=:all) + result = exercise!(control, ignore) + iszero(result) || error("ordinary retry failed at checkpoint $result") + observed = RuntimeTypes() + trace = InputTrace(observed) + env = PSE._collecting_environment_binding_schema() + recording = PSE._prepare_simulation!(close_registry(scene()); steps=0, outputs=:all, + constants=PSE.Constants(), environment_schema=env, input_binding_storage=trace, status_view_schema=observed) + result = exercise!(recording, ignore) + iszero(result) || error("recorded retry failed at checkpoint $result") + inputs = Vector{Union{observed.inputs...}}() + views = PSE.CompiledMetadataTable(NamedTuple{IDS}(map(id -> Vector{Union{observed.views[id]...}}(), IDS))) + environment = PSE._freeze_environment_binding_schema(env) + fresh() = PSE._prepare_simulation!(close_registry(scene()); steps=0, outputs=:all, + constants=PSE.Constants(), environment_schema=environment, input_binding_storage=inputs, status_view_schema=views) + batches = Dict(id => DataType[] for id in IDS) + function observe(sim) + for group in sim.execution_plan.groups, batch in group.batches + remember!(batches[batch.application.id], typeof(batch)) + end + end + result = exercise!(fresh(), observe) + iszero(result) || error("finite retry failed at checkpoint $result") + schemas = NamedTuple{IDS}(map(id -> batch_schema(batches[id]), IDS)) + return PSE._prepare_execution_batch_schemas(fresh(), schemas) +end + +const SIM = prepare() +qualify() = Cint(exercise!(SIM, ignore)) +end diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl index 529de49a3..e3797382f 100644 --- a/test/integration/native_growth.jl +++ b/test/integration/native_growth.jl @@ -9,7 +9,10 @@ const _palm_growth_app = stage_native_fixture(joinpath(_growth_root, "test", "fixtures", "local_palm_leaf_birth")) const _producer_growth_app = stage_native_fixture(joinpath(_growth_root, "test", "integration", "fixtures", "distributed_producer_birth"); - fixture_sources=(joinpath(_growth_root, "test", "fixtures", "distributed_growth.jl") => "distributed_growth.jl",)) + fixture_sources=( + joinpath(_growth_root, "test", "fixtures", "distributed_growth.jl") => "distributed_growth.jl", + joinpath(_growth_root, "test", "fixtures", "raw_status_readers.jl") => "raw_status_readers.jl", + )) # App modules and all preparation methods exist before entering the testset. Base.include(@__MODULE__, joinpath(_palm_growth_app, "src", "PSELocalPalmLeafBirth.jl")) Base.include(@__MODULE__, joinpath(_producer_growth_app, "src", "PSEThirtyProducerControl.jl")) @@ -84,11 +87,13 @@ end mktempdir() do directory @test PSEThirtyProducerControl.checkpoint(PSEThirtyProducerControl.STATE, 0) @test PSEThirtyProducerControl.main(String[]) == 0 + @test PSEThirtyProducerControl.main(["recover"]) == 0 producer = Compilation.compile(_producer_growth_app; destination=joinpath(directory, "producer")) @test isfile(producer.executable) # main checks every destination, every sample, and the same cells/streams. @test success(`$(producer.executable)`) + @test success(`$(producer.executable) recover`) end end end From 6b2f03e619cbe439a227843884ab8bfb68cdf8d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 04:55:41 +0100 Subject: [PATCH 295/324] Exercise the first distributed leaf from day zero in the shared JuliaC fixture --- .../src/PSEThirtyProducerControl.jl | 40 ++++++++++++++++- .../src/leaf_recovery.jl | 33 +++----------- .../distributed_producer_birth/src/prepare.jl | 39 ++-------------- test/integration/native_growth.jl | 2 + test/integration/native_preparation.jl | 45 +++++++++++++++++++ 5 files changed, 94 insertions(+), 65 deletions(-) diff --git a/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl index d25e9dd80..6311d3014 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl @@ -1,13 +1,51 @@ module PSEThirtyProducerControl import PlantSimEngine as PSE include("native_preparation.jl") -using .NativePreparation: close_registry, RuntimeTypes, InputTrace, remember!, batch_schema +using .NativePreparation: prepare_growth_fixture include("distributed_growth.jl") include("prepare.jl") include("leaf_recovery.jl") +function remove_initial_leaves!(sim) + for id in DistributedGrowthFixture.producer_birth_leaf_ids() + PSE.remove_object!(sim.model, id) + end + return sim +end + +function first_leaf!(sim; observe=(_ -> nothing)) + PSE.current_step(sim) == 0 || return Cint(38) + for _ in 1:2 + PSE.step!(sim) + observe(sim) + end + isempty(only(sim.compiled.distributed_outputs.bindings).destination_ids) || return Cint(39) + id = PSE.ObjectId((:tree, :leaf, 31)) + PSE.register_object!(sim.model, PSE.Object(id; scale=:Leaf, parent=:root)) + PSE.step!(sim) + leaf = PSE.model_status(sim, id) + isnothing(leaf) && return Cint(44) + group = only(sim.compiled.distributed_outputs.bindings) + only(group.destination_ids) === id || return Cint(40) + only(parent(group.columns.signal)) === PSE.refvalue(leaf, :signal) || return Cint(41) + leaf.signal === 60f0 || return Cint(42) + history = get(PSE.outputs(sim), (:producer, id, :signal), nothing) + history isa Vector{Tuple{Float64,Float32}} && length(history) == 1 && + only(history) === (3.0, 60f0) || return Cint(43) + return Cint(0) +end + +function advance_first_destination!(sim, observe) + result = first_leaf!(remove_initial_leaves!(sim); observe) + iszero(result) || error("First leaf failed at checkpoint $result.") + observe(sim) +end + const STATE = prepare_control() +const WITHOUT_LEAVES = remove_initial_leaves!(deepcopy(STATE.simulation)) + function (@main)(args) length(args) == 1 && only(args) == "recover" && return LeafRecovery.qualify() + length(args) == 1 && only(args) == "first-leaf" && return first_leaf!(WITHOUT_LEAVES) isempty(args) || return Cint(2) checkpoint(STATE, 0) || return Cint(10) sim = STATE.simulation diff --git a/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl b/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl index 81b74d4e0..b114d6c6b 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl @@ -1,7 +1,7 @@ module LeafRecovery import PlantSimEngine as PSE using PlantSimEngine: Default, bound_input -using ..NativePreparation: close_registry, RuntimeTypes, InputTrace, remember!, batch_schema +using ..NativePreparation: prepare_growth_fixture include("raw_status_readers.jl") const IDS = (:tag, :sum) @@ -61,34 +61,11 @@ end ignore(sim) = nothing -function prepare() - control = PSE.run!(scene(); steps=0, outputs=:all) - result = exercise!(control, ignore) - iszero(result) || error("ordinary retry failed at checkpoint $result") - observed = RuntimeTypes() - trace = InputTrace(observed) - env = PSE._collecting_environment_binding_schema() - recording = PSE._prepare_simulation!(close_registry(scene()); steps=0, outputs=:all, - constants=PSE.Constants(), environment_schema=env, input_binding_storage=trace, status_view_schema=observed) - result = exercise!(recording, ignore) - iszero(result) || error("recorded retry failed at checkpoint $result") - inputs = Vector{Union{observed.inputs...}}() - views = PSE.CompiledMetadataTable(NamedTuple{IDS}(map(id -> Vector{Union{observed.views[id]...}}(), IDS))) - environment = PSE._freeze_environment_binding_schema(env) - fresh() = PSE._prepare_simulation!(close_registry(scene()); steps=0, outputs=:all, - constants=PSE.Constants(), environment_schema=environment, input_binding_storage=inputs, status_view_schema=views) - batches = Dict(id => DataType[] for id in IDS) - function observe(sim) - for group in sim.execution_plan.groups, batch in group.batches - remember!(batches[batch.application.id], typeof(batch)) - end - end - result = exercise!(fresh(), observe) - iszero(result) || error("finite retry failed at checkpoint $result") - schemas = NamedTuple{IDS}(map(id -> batch_schema(batches[id]), IDS)) - return PSE._prepare_execution_batch_schemas(fresh(), schemas) +function check_recovery!(sim, observe) + result = exercise!(sim, observe) + iszero(result) || error("Leaf recovery failed at checkpoint $result.") end -const SIM = prepare() +const SIM = prepare_growth_fixture(scene, IDS, (check_recovery!,)) qualify() = Cint(exercise!(SIM, ignore)) end diff --git a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl index 6e2bd3a9b..36fa6e769 100644 --- a/test/integration/fixtures/distributed_producer_birth/src/prepare.jl +++ b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl @@ -91,42 +91,9 @@ function advance_host!(state; observe=(_ -> nothing)) end function prepare_control() - # The public ordinary maintained test is independently executed by the host gate. - baseline = state_for(PSE.run!(make_native_producer_model(); - steps=0, outputs=:all)) - advance_host!(baseline) - observed = RuntimeTypes() - input_trace = InputTrace(observed) - environment = PSE._collecting_environment_binding_schema() - recording = PSE._prepare_simulation!(close_registry(make_native_producer_model()); - steps=0, outputs=:all, constants=PSE.Constants(), environment_schema=environment, - input_binding_storage=input_trace, status_view_schema=observed) - advance_host!(state_for(recording)) - isempty(input_trace) || error("Input prototype was mutated.") - all(T -> isconcretetype(T) && T <: PSE.CompiledModelInputBinding, observed.inputs) || error("Invalid actual input evidence.") - prototype = Vector{Union{observed.inputs...}}() - schema = PSE.CompiledMetadataTable(NamedTuple{APPLICATION_IDS}(map(APPLICATION_IDS) do id - types = observed.views[id] - all(T -> isconcretetype(T) && T <: PSE.CompiledModelStatusView, types) || error("Invalid actual view evidence.") - Vector{Union{types...}}() - end)) - environment = PSE._freeze_environment_binding_schema(environment) - prepare() = PSE._prepare_simulation!(close_registry(make_native_producer_model()); - steps=0, outputs=:all, constants=PSE.Constants(), environment_schema=environment, - input_binding_storage=prototype, status_view_schema=schema) - finite = prepare() - batches = Dict(id => DataType[] for id in APPLICATION_IDS) - function observe_batches(sim) - sim.compiled.input_bindings isa Vector{eltype(prototype)} || error("Lost finite input owner.") - sim.compiled.status_view_schema === schema || error("Lost finite view owner.") - for group in sim.execution_plan.groups, batch in group.batches - types = batches[batch.application.id] - remember!(types, typeof(batch)) - end - end - advance_host!(state_for(finite); observe=observe_batches) - schemas = NamedTuple{APPLICATION_IDS}(map(id -> batch_schema(batches[id]), APPLICATION_IDS)) - simulation = PSE._prepare_execution_batch_schemas(prepare(), schemas) + advance_producer!(sim, observe) = advance_host!(state_for(sim); observe) + simulation = prepare_growth_fixture(make_native_producer_model, APPLICATION_IDS, + (advance_producer!, advance_first_destination!)) state = state_for(simulation) checkpoint(state, 0) || error("Final native scene was advanced or changed.") return state diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl index e3797382f..4c4b676a3 100644 --- a/test/integration/native_growth.jl +++ b/test/integration/native_growth.jl @@ -88,12 +88,14 @@ end @test PSEThirtyProducerControl.checkpoint(PSEThirtyProducerControl.STATE, 0) @test PSEThirtyProducerControl.main(String[]) == 0 @test PSEThirtyProducerControl.main(["recover"]) == 0 + @test PSEThirtyProducerControl.main(["first-leaf"]) == 0 producer = Compilation.compile(_producer_growth_app; destination=joinpath(directory, "producer")) @test isfile(producer.executable) # main checks every destination, every sample, and the same cells/streams. @test success(`$(producer.executable)`) @test success(`$(producer.executable) recover`) + @test success(`$(producer.executable) first-leaf`) end end end diff --git a/test/integration/native_preparation.jl b/test/integration/native_preparation.jl index d46d05492..5c15b16b6 100644 --- a/test/integration/native_preparation.jl +++ b/test/integration/native_preparation.jl @@ -72,4 +72,49 @@ function batch_schema(types) return PSE.PreparedExecutionBatchSchema{Vector{Union{types...}}}() end +# Each trajectory starts on a fresh scene. The returned program starts at step +# zero and admits the input, view and batch types seen along those trajectories. +function prepare_growth_fixture(make_model, ids, trajectories) + ignore(sim) = nothing + for advance! in trajectories + advance!(PSE.run!(make_model(); steps=0, outputs=:all), ignore) + end + + observed = RuntimeTypes() + trace = InputTrace(observed) + collecting = PSE._collecting_environment_binding_schema() + function prepare(environment_schema, input_binding_storage, status_view_schema) + return PSE._prepare_simulation!(close_registry(make_model()); steps=0, outputs=:all, + constants=PSE.Constants(), environment_schema, input_binding_storage, status_view_schema) + end + for advance! in trajectories + advance!(prepare(collecting, trace, observed), ignore) + end + isempty(trace) || error("Input prototype was mutated.") + all(T -> isconcretetype(T) && T <: PSE.CompiledModelInputBinding, observed.inputs) || + error("Expected concrete input bindings.") + inputs = Vector{Union{observed.inputs...}}() + views = PSE.CompiledMetadataTable(NamedTuple{ids}(map(ids) do id + types = observed.views[id] + all(T -> isconcretetype(T) && T <: PSE.CompiledModelStatusView, types) || + error("Expected concrete status views for application $id.") + Vector{Union{types...}}() + end)) + environment = PSE._freeze_environment_binding_schema(collecting) + fresh() = prepare(environment, inputs, views) + batches = Dict(id => DataType[] for id in ids) + function observe(sim) + sim.compiled.input_bindings isa Vector{eltype(inputs)} || error("Lost finite input owner.") + sim.compiled.status_view_schema === views || error("Lost finite view owner.") + for group in sim.execution_plan.groups, batch in group.batches + remember!(batches[batch.application.id], typeof(batch)) + end + end + for advance! in trajectories + advance!(fresh(), observe) + end + schemas = NamedTuple{ids}(map(id -> batch_schema(batches[id]), ids)) + return PSE._prepare_execution_batch_schemas(fresh(), schemas) +end + end # module From e2aa012463fb67fda0ed9c8bb8e8631016b54f4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 05:00:38 +0100 Subject: [PATCH 296/324] Admit compiled model input bindings by prepared plan slot --- src/composite_model/compilation.jl | 130 +++++++++++++++++++++---- src/composite_model/runtime_outputs.jl | 21 ++-- test/test-model-input-recipes.jl | 70 +++++++++++++ 3 files changed, 195 insertions(+), 26 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f650695f8..f85907ba6 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -1765,14 +1765,22 @@ function _model_input_binding_storage(prototype::AbstractVector) return similar(prototype, 0) end -@inline function _with_model_input_binding(f::F, - ::AbstractVector{CompiledModelInputBinding}, binding, args::Vararg{Any,N}, -) where {F,N} - return f(binding, args...) -end -@generated function _with_model_input_binding(f::F, ::AbstractVector{B}, binding, +@inline function _with_model_input_binding(f::F, ::AbstractVector{B}, binding, args::Vararg{Any,N}, ) where {F,B,N} + B === CompiledModelInputBinding && return f(binding, args...) + return _apply_input_binding_family(f, Val(B), binding, args) +end + +# Fixed schemas can carry either one concrete type or several possible +# types for the same plan slot. Establish membership before calling a worker. +@inline function _apply_input_binding_family(f::F, family::Val{B}, binding, args::Tuple) where {F,B} + binding isa B || throw(ArgumentError("The input binding is outside its prepared storage family.")) + isconcretetype(B) && return f(binding::B, args...) + return _with_input_binding_union(f, family, binding::B, args) +end + +@generated function _with_input_binding_union(f::F, ::Val{B}, binding, args::Tuple) where {F,B} families = _model_input_binding_family_types(B) branches = [:(binding isa $T && return f(binding::$T, args...)) for T in families] return quote @@ -1781,6 +1789,99 @@ end end end +# A closed program admits each slot's witnessed binding types. Training may +# supply a future consumer's types even if it has no target at the initial step. +struct PreparedInputBindings{B,F<:Tuple} <: AbstractVector{B} + entries::Vector{B} + family_by_slot::Vector{Int} + families::F +end + +const _INPUT_BINDING_FAMILY_WIDTH = 16 + +function _prepared_input_bindings(slot_count::Int, observed) + types = Type[Union{} for _ in 1:slot_count] + for (slot, B) in observed + B isa Type && isconcretetype(B) && B <: CompiledModelInputBinding || + throw(ArgumentError("A plan slot requires concrete input binding types.")) + types[slot] = Union{types[slot], B} + end + family_by_slot = zeros(Int, slot_count) + family_ids = Dict{Type,Int}() + families = Any[] + for (slot, B) in pairs(types) + B === Union{} && continue + family_by_slot[slot] = get!(family_ids, B) do + push!(families, Val(B)) + length(families) + end + end + # Chunk the unique families so a callback need not inline a linear chain + # over hundreds of them. Slots with the same types share one admission. + chunks = Tuple(Tuple(chunk) for chunk in Iterators.partition(families, _INPUT_BINDING_FAMILY_WIDTH)) + B = isempty(family_ids) ? Union{} : + length(family_ids) == 1 ? only(keys(family_ids)) : CompiledModelInputBinding + return PreparedInputBindings(B[], family_by_slot, chunks) +end + +# Carry the open binding value across admission by a single known call shape. +struct _UnadmittedInputBinding + binding::CompiledModelInputBinding +end + +@inline function _visit_input_family(family::Val, f::F, raw::_UnadmittedInputBinding, args::Tuple) where {F} + return _apply_input_binding_family(f, family, getfield(raw, :binding), args) +end + +@noinline function _visit_input_family_chunk(chunk::Tuple, index::Int, + f::F, raw::_UnadmittedInputBinding, args::Tuple, +) where {F} + return _with_metadata_entry(_visit_input_family, chunk, index, f, raw, args) +end + +@inline function _with_model_input_binding(f::F, values::PreparedInputBindings{B}, + binding, args::Vararg{Any,N}, +) where {F,B,N} + b = binding::CompiledModelInputBinding + family = values.family_by_slot[b.slot] + iszero(family) && throw(ArgumentError("No input binding family was prepared for this slot.")) + # Every occupied slot uses B when the storage has a single family. + B !== CompiledModelInputBinding && return _apply_input_binding_family(f, Val(B), b, args) + chunk, index = divrem(family - 1, _INPUT_BINDING_FAMILY_WIDTH) + return _with_metadata_entry(_visit_input_family_chunk, values.families, + chunk + 1, index + 1, f, _UnadmittedInputBinding(b), args) +end + +Base.IndexStyle(::Type{<:PreparedInputBindings}) = IndexLinear() +Base.size(values::PreparedInputBindings) = size(values.entries) +Base.getindex(values::PreparedInputBindings, i::Int) = values.entries[i] +Base.@nospecializeinfer function Base.setindex!(values::PreparedInputBindings{B}, @nospecialize(binding::CompiledModelInputBinding), i::Int) where {B} + _with_model_input_binding(Returns(nothing), values, binding) + values.entries[i] = binding::B + return values +end +Base.@nospecializeinfer function Base.push!(values::PreparedInputBindings{B}, @nospecialize(binding::CompiledModelInputBinding)) where {B} + _with_model_input_binding(Returns(nothing), values, binding) + push!(values.entries, binding::B) + return values +end +function Base.append!(values::PreparedInputBindings, other::PreparedInputBindings) + if !(values.family_by_slot === other.family_by_slot && values.families === other.families) + for binding in other + _with_model_input_binding(identity, values, binding) + end + end + append!(values.entries, other.entries) + return values +end +function Base.similar(values::PreparedInputBindings{B}, ::Type{B}, dims::Dims{1}) where {B} + return PreparedInputBindings(similar(values.entries, dims), values.family_by_slot, values.families) +end +Base.resize!(values::PreparedInputBindings, n::Integer) = (resize!(values.entries, n); values) +Base.empty!(values::PreparedInputBindings) = (empty!(values.entries); values) +Base.sizehint!(values::PreparedInputBindings, n::Integer) = (sizehint!(values.entries, n); values) +Base.deleteat!(values::PreparedInputBindings, indices) = (deleteat!(values.entries, indices); values) + struct CompiledTemporalInput{B,S,I,R} binding::B source_applications::S @@ -2261,9 +2362,9 @@ function _refresh_owned_runtime_bindings!( end function _index_dynamic_input_binding!( + binding::CompiledModelInputBinding, index::SelectorCandidateIndex, model::CompositeModel, - binding::CompiledModelInputBinding, binding_index::Int, many_binding_cache, ) @@ -2296,11 +2397,8 @@ function _index_dynamic_input_bindings( ) index = _selector_candidate_index(model, nothing) for (binding_index, binding) in pairs(bindings) - _index_dynamic_input_binding!( - index, - model, - binding, - binding_index, + _with_model_input_binding( + _index_dynamic_input_binding!, bindings, binding, index, model, binding_index, many_binding_cache, ) end @@ -5098,11 +5196,9 @@ function _extend_compiled_scene( else index = compiled.dynamic_input_binding_indices for binding_index in (previous_binding_count + 1):length(input_bindings) - _index_dynamic_input_binding!( - index, - model, - input_bindings[binding_index], - binding_index, + _with_model_input_binding( + _index_dynamic_input_binding!, input_bindings, input_bindings[binding_index], + index, model, binding_index, many_binding_cache, ) end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index a5687854e..636148509 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4845,18 +4845,21 @@ function _with_model_temporal_retention(f::F, compiled::CompiledCompositeModel, compiled.scenario_plan.input_plans, compiled.scenario_plan.timeline, binding) end -Base.@noinline function _with_model_temporal_retention(f::F, +@inline function _with_model_temporal_retention(f::F, applications_by_id::CompiledMetadataTable, input_plans, timeline, binding::CompiledModelInputBinding, ) where {F} - input_plan = getfield(binding, :plan) - application_id, plan_slot = input_plan.application_id, input_plan.slot - input_name = input_plan.input - source_var = input_plan.source_var - source_application_ids = getfield(binding, :source_application_ids) - policy = getfield(binding, :policy) - integrates = policy isa Union{Integrate,Aggregate} - interpolates = policy isa Union{Interpolate,PreviousTimeStep} + plan = binding.plan + return _with_model_temporal_retention(f, applications_by_id, input_plans, timeline, + plan.slot, plan.application_id, plan.input, plan.source_var, binding.source_application_ids, + binding.policy isa Union{Integrate,Aggregate}, binding.policy isa Union{Interpolate,PreviousTimeStep}) +end + +Base.@noinline function _with_model_temporal_retention(f::F, + applications_by_id::CompiledMetadataTable, input_plans, timeline, + plan_slot::Int, application_id::Symbol, input_name::Symbol, source_var::Symbol, + source_application_ids::Vector{Symbol}, integrates::Bool, interpolates::Bool, +) where {F} consumer_dt = _compiled_application_by_id(applications_by_id, application_id) do consumer consumer.clock.dt end diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index d43e83088..150a43a26 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -495,4 +495,74 @@ end @test model_status(model, 2).total === 10f0 end +@testset "Input binding families follow the prepared plan slot through growth" begin + function make_scene(T, populated) + objects = Object[Object(1; scale=:Scene)] + populated && push!(objects, Object(2; scale=:Leaf, parent=1)) + return CompositeModel(objects...; applications=( + ModelSpec(Writer(T(2)); name=:source, on=One(id=1)), + ModelSpec(PairReader{T}(); name=:reader, on=Many(scale=:Leaf), + inputs=(left=One(SceneScope(); id=1, var=:x), + right=One(SceneScope(); id=1, var=:y))), + )) + end + # These real applications exercise the same two slots under both numeric + # families. The scene being prepared below has no reader at its T0. + examples = map((Float32, Float64)) do T + sim = run!(make_scene(T, true); steps=0, outputs=:none) + return sort(collect(sim.compiled.input_bindings); by=b -> b.slot) + end + single, double = examples + @test getproperty.(single, :slot) == getproperty.(double, :slot) == [1, 2] + @test all(typeof(a) !== typeof(b) for (a,b) in zip(single, double)) + observed = [(b.slot, typeof(b)) for row in examples for b in row] + prototype = PSE._prepared_input_bindings(2, observed) + for row in examples, b in row + @test PSE._with_model_input_binding(identity, prototype, b) === b + @test (@inferred PSE._with_model_input_binding(x -> x.slot, prototype, b)) == b.slot + end + partial = PSE._prepared_input_bindings(2, [(1, typeof(first(single)))]) + @test length(partial.family_by_slot) == 2 + @test iszero(partial.family_by_slot[2]) + @test_throws ArgumentError push!(partial, last(single)) + @test_throws ArgumentError push!(partial, first(double)) + @test_throws BoundsError PSE._prepared_input_bindings(0, [(1, typeof(first(single)))]) + @test_throws ArgumentError PSE._prepared_input_bindings(1, [(1, PSE.CompiledModelInputBinding)]) + @test isempty(PSE._prepared_input_bindings(0, ())) + both = similar(prototype, 0) + push!(both, first(single), first(double)) + @test_throws ArgumentError append!(partial, both) + @test isempty(partial) + repeated = PSE._prepared_input_bindings(3, [(3, typeof(first(single))), + (1, typeof(first(single))), (3, typeof(first(single)))]) + @test repeated.family_by_slot == [1, 0, 1] + incomplete_scene = make_scene(Float32, false) + incomplete = PSE._prepare_simulation!(incomplete_scene; steps=0, outputs=:none, + constants=PSE.Constants(), input_binding_storage=partial) + register_object!(incomplete_scene, Object(2; scale=:Leaf, parent=1)) + @test_throws "No input binding family was prepared" PSE.continue!(incomplete; steps=0) + @test isempty(incomplete.compiled.input_bindings) + @test current_step(incomplete) == 0 + for T in (Float32, Float64) + scene = make_scene(T, false) + sim = PSE._prepare_simulation!(scene; steps=0, outputs=:none, + constants=PSE.Constants(), input_binding_storage=prototype) + @test isempty(sim.compiled.input_bindings) + @test length(sim.compiled.scenario_plan.input_plans) == length(prototype.family_by_slot) + source = PSE.refvalue(model_status(scene, 1), :x) + register_object!(scene, Object(2; scale=:Leaf, parent=1)) + step!(sim) + @test current_step(sim) == 1 + @test model_status(scene, 2).total === T(6) + left = only(b for b in sim.compiled.input_bindings if b.input === :left) + view = sim.compiled.status_views_by_target[(:reader, ObjectId(2))] + @test left.carrier === source + @test PSE.refvalue(view.status, :left) === source + source[] = T(11) + @test view.status.left === T(11) + @test sim.compiled.input_bindings.family_by_slot === prototype.family_by_slot + @test isempty(prototype) + end +end + end From 11412e6e89b0240aa3784cc403dc79ca3927d59c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 05:29:57 +0100 Subject: [PATCH 297/324] Resolve shared newborn inputs through their prepared binding type --- src/composite_model/lifecycle_input_changes.jl | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/composite_model/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl index eaad5176b..d9102ffd3 100644 --- a/src/composite_model/lifecycle_input_changes.jl +++ b/src/composite_model/lifecycle_input_changes.jl @@ -136,16 +136,23 @@ end _publish_added_consumer_bindings!(recorder, input_bindings, ::Nothing, args...) = nothing +function _publish_shared_consumer_input!(binding, destination, cache, model, consumer) + shared = _shared_many_input_binding(cache, model, binding.plan, consumer) + push!(destination, isnothing(shared) ? binding : shared) + return nothing +end + function _publish_added_consumer_bindings!(recorder, input_bindings, staged::_StagedConsumerBindings, model, many_binding_cache, previous_binding_count) for (id, consumer, range) in staged.ranges for index in range binding = staged.entries[index] if index in staged.reused - shared = _shared_many_input_binding(many_binding_cache, model, binding.plan, consumer) - isnothing(shared) || (binding = shared) + _with_model_input_binding(_publish_shared_consumer_input!, staged.entries, + binding, input_bindings, many_binding_cache, model, consumer) + else + push!(input_bindings, binding) end - push!(input_bindings, binding) end _record_consumer_input_bindings!(recorder, input_bindings, id, consumer, previous_binding_count + first(range), previous_binding_count + last(range)) From d055022c5697c4e91a79ce60875bf1c026f3a62f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 05:33:44 +0100 Subject: [PATCH 298/324] Reuse admitted status references while preparing model defaults --- src/composite_model/compilation.jl | 59 +++++++++--------------------- test/test-model-input-recipes.jl | 12 ++++-- 2 files changed, 26 insertions(+), 45 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f85907ba6..f4bb27ad1 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -6816,10 +6816,10 @@ function _status_recipe_reference(original, edit_names, edit_references, variabl return reference end -function _status_recipe_set_reference!( +Base.@nospecializeinfer function _status_recipe_set_reference!( recipe::_CanonicalStatusRecipe, variable::Symbol, - reference::Ref, + @nospecialize(reference::Ref), ) _validate_status_reference(recipe.original, variable, reference) position = findfirst(isequal(variable), recipe.edit_names) @@ -7930,20 +7930,23 @@ _model_input_status_reference(binding) = binding.carrier : Ref(binding.carrier) function _model_input_status_references(objects::AbstractDict{I}, bindings) where {I<:ObjectId} - references = _object_key_index(Tuple{Symbol,I,Symbol}, Any) + references = _object_key_index(Tuple{Symbol,I,Symbol}, Ref) for binding in bindings - binding.carrier_hint == :temporal_stream && continue - isnothing(binding.carrier) && continue - consumer_id = _index_object_id(objects, binding.consumer_id) - references[( - binding.application_id, - consumer_id, - binding.input, - )] = _model_input_status_reference(binding) + _with_model_input_binding(_index_model_input_reference!, bindings, binding, + references, objects) end return references end +function _index_model_input_reference!(binding, references, objects) + binding.carrier_hint === :temporal_stream && return nothing + isnothing(binding.carrier) && return nothing + consumer_id = _index_object_id(objects, binding.consumer_id) + references[(binding.application_id, consumer_id, binding.input)] = + _model_input_status_reference(binding) + return nothing +end + # Projection uses existing raw binding families; no references or values are made. function _model_input_status_reference_types(B) references = Any[] @@ -7961,26 +7964,6 @@ function _model_input_status_reference_types(B) return Tuple(references) end -@inline function _with_model_input_status_reference(f::F, - ::AbstractVector{CompiledModelInputBinding}, reference, args::Vararg{Any,N}, -) where {F,N} - reference isa Ref || throw(ArgumentError("An input status reference must be a Ref.")) - return f(reference, args...) -end - -@generated function _with_model_input_status_reference(f::F, - ::AbstractVector{B}, reference, args::Vararg{Any,N}, -) where {F,B,N} - references = _model_input_status_reference_types(B) - branches = [:(reference isa $R && return f(reference::$R, args...)) for R in references] - return quote - $(branches...) - throw(ArgumentError("The input status reference is outside its prepared binding family.")) - end -end - -# The per-record worker already owns a concrete real B after existing IB admission. -# Use the same projection when no all-bindings union is needed. @generated function _with_model_input_status_reference(f::F, binding::B, reference, args::Vararg{Any,N}, ) where {F,B<:CompiledModelInputBinding,N} @@ -8002,22 +7985,14 @@ Base.@noinline function _stage_model_input_default!(value, recipe, variable, con context.default_status_updates[(context.object_id, variable)] = true return nothing end - Base.@inline _with_model_input_status_reference( - _stage_model_input_default_reference!, context.bindings, reference, - recipe, variable, value, context) - return nothing -end - -function _stage_model_input_default_reference!(reference, preparation, variable, - value, context, -) + reference isa Ref || throw(ArgumentError("An input status reference must be a Ref.")) # Keep the existing conversion/validation even when the carrier owns storage. _no_status_conversion(context.model.status_conversion) || _materialize_status_value(context.model, variable, value; object_id=context.object_id, application_id=context.application_id, origin=:model_input_default, private_copy=true, conversion_records=context.conversion_records) - _status_recipe_set_reference!(preparation, variable, reference) + _status_recipe_set_reference!(recipe, variable, reference) counter = context.input_default_rewrites_avoided isnothing(counter) || (counter[] += 1) return nothing @@ -8085,7 +8060,7 @@ function _prepare_model_input_statuses_batched!( default_status_updates = Dict{Tuple{I,Symbol},Bool}() # Keep optional telemetry local until the staged status transaction succeeds. input_default_rewrites_avoided = isnothing(performance) ? nothing : Ref(0) - context = (; model, recipes, recipe_order, bindings, final_references, + context = (; model, recipes, recipe_order, final_references, conversion_records, default_status_updates, input_default_rewrites_avoided) for partial in applications Base.@inline _with_model_application(applications_by_id, partial) do application diff --git a/test/test-model-input-recipes.jl b/test/test-model-input-recipes.jl index 150a43a26..5104d6899 100644 --- a/test/test-model-input-recipes.jl +++ b/test/test-model-input-recipes.jl @@ -179,7 +179,10 @@ end old_binding = only(simulation.compiled.input_bindings) old_carrier = input_carrier(old_binding) first_ref = PSE.refvalue(first, :x) - @test only(parent(old_carrier)) === first_ref + references = PSE._model_input_status_references(model.registry.objects, simulation.compiled.input_bindings) + aggregate = references[(:aggregate, ObjectId(:plant), :values)] + @test aggregate[] === old_carrier === PSE.refvalue(model_status(model, :plant), :values)[] + @test only(parent(aggregate[])) === first_ref second = Status(x=9.0) register_object!(model, Object(:new_leaf; scale=:Leaf, parent=:plant, status=second)) @@ -189,7 +192,8 @@ end binding = only(simulation.compiled.input_bindings) carrier = input_carrier(binding) @test carrier isa PSE.ObjectRefVector - @test carrier === old_carrier + @test carrier === old_carrier === aggregate[] + @test PSE.refvalue(model_status(model, :plant), :values)[] === carrier @test Set(binding.source_ids) == Set((ObjectId(1), ObjectId(:new_leaf))) @test isempty(binding.source_application_ids) for (id, reference) in zip(binding.source_ids, parent(carrier)) @@ -232,10 +236,12 @@ end I = keytype(model.registry.objects) @test I === Union{ObjectId{Symbol},ObjectId{Tuple{Symbol,Symbol,Int}}} @test keytype(references) === Tuple{Symbol,I,Symbol} + @test valtype(references) === Ref @test length(references) == 4 for binding in bindings key = (binding.application_id, binding.consumer_id, binding.input) - @test references[key] === input_carrier(binding) + @test references[key] === input_carrier(binding) === + PSE.refvalue(model_status(model, :source), binding.source_var) end continue!(simulation) @test model_status(model,:reader).total === 6f0 From 7fc9fc03988e5150c69219c76e103238abb1bf89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 05:47:32 +0100 Subject: [PATCH 299/324] Prepare nested call targets after resolving their existing cohort row --- .../execution_cohort_refresh.jl | 25 +++--- .../src/NestedCallControl.jl | 80 +++++++++++++++++++ .../src/PSESceneDependencyControl.jl | 4 + test/integration/native_growth.jl | 2 +- 4 files changed, 98 insertions(+), 13 deletions(-) create mode 100644 test/integration/fixtures/scene_dependencies/src/NestedCallControl.jl diff --git a/src/composite_model/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl index 1f5470b3d..92d52fc9a 100644 --- a/src/composite_model/execution_cohort_refresh.jl +++ b/src/composite_model/execution_cohort_refresh.jl @@ -270,18 +270,18 @@ function refresh_cohort_membership!(build_target::F, store::ExecutionCohortStore location = cohort_location(store, application_id, object_id; owner) is_current = isnothing(previous) || isnothing(changed_ids) || first(_sorted_object_id_position(current_ids, object_id)) - _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted - if !is_current - push!(removed_ids, object_id) - return nothing - end - previous_target = isnothing(admitted) ? nothing : _execution_cohort_target(admitted) - target = build_target(object_id, previous_target) - _with_execution_cohort_target(schema, target) do accepted - _check_execution_cohort_target(accepted, object_id) - accepted === previous_target || push!(staged_targets, (object_id, accepted)) - return nothing - end + if !is_current + _with_execution_cohort_location(identity, schema, store, location, owner, application_id, object_id) + push!(removed_ids, object_id) + continue + end + previous_target = _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted + return isnothing(admitted) ? nothing : _execution_cohort_target(admitted) + end + target = build_target(object_id, previous_target) + _with_execution_cohort_target(schema, target) do accepted + _check_execution_cohort_target(accepted, object_id) + accepted === previous_target || push!(staged_targets, (object_id, accepted)) return nothing end end @@ -351,6 +351,7 @@ function refresh_cohort_membership!(build_target::F, store::ExecutionCohortStore if isnothing(previous) for object_id in current_ids location = cohort_location(store, application_id, object_id; owner) + isnothing(location) && throw(ArgumentError("An admitted target is missing its execution cohort location.")) _with_execution_cohort_location(schema, store, location, owner, application_id, object_id) do admitted _insert_execution_membership_row!( membership, length(membership.object_ids) + 1, object_id, admitted, diff --git a/test/integration/fixtures/scene_dependencies/src/NestedCallControl.jl b/test/integration/fixtures/scene_dependencies/src/NestedCallControl.jl new file mode 100644 index 000000000..d3481f4aa --- /dev/null +++ b/test/integration/fixtures/scene_dependencies/src/NestedCallControl.jl @@ -0,0 +1,80 @@ +module NestedCallControl + +import PlantSimEngine as PSE +include("native_preparation.jl") + +PSE.@process "nested_prepared" verbose=false +struct Stage{I} <: AbstractNested_PreparedModel end +PSE.inputs_(::Stage) = NamedTuple() +PSE.outputs_(::Stage) = (hits=0,) +function PSE.run!(::Stage, status, environment, constants, context) + status.hits += 1 + return nothing +end + +const STAGES = (:controller, :energy_balance, :photosynthesis, :response) + +function mount(i) + name = STAGES[i] + calls = if i == length(STAGES) + NamedTuple() + else + child = STAGES[i+1] + multiplicity = i == 1 ? PSE.Many : PSE.One + binding = multiplicity(PSE.SceneScope(); id=child, application=child) + NamedTuple{(child,)}((binding,)) + end + return PSE.ModelSpec(Stage{i}(); name, on=PSE.One(id=name), calls) +end + +function prepare(views, environment) + objects = map(name -> PSE.Object(name; scale=name, status=PSE.Status(hits=0)), STAGES) + model = PSE.CompositeModel(objects...; applications=Tuple(mount(i) for i in eachindex(STAGES))) + scene = NativePreparation.close_registry(model, PSE.ObjectId{Symbol}) + return PSE._prepare_simulation!(scene; steps=0, outputs=:none, constants=PSE.Constants(), + status_view_schema=views, environment_schema=environment, + input_binding_storage=PSE.CompiledModelInputBinding[]) +end + +root(simulation) = only(only(simulation.execution_plan.groups).batches) + +function record_batches!(schemas, batch) + calls = first(batch.targets).context.calls + children = map(calls) do call + child = only(PSE._materialize_call_execution_batches!(call)) + return record_batches!(schemas, child) + end + names = Tuple(call.binding.plan.call for call in calls) + B = PSE._execution_batch_type_with_call_schemas(typeof(batch), NamedTuple{names}(children)) + return schemas[batch.application.id] = NativePreparation.batch_schema((B,)) +end + +function prepare_calls() + observed = NativePreparation.RuntimeTypes() + environment = PSE._collecting_environment_binding_schema() + initial = prepare(observed, environment) + record_batches!(Dict{Symbol,Any}(), root(initial)) + tables = map(name -> Vector{Union{observed.views[name]...}}(), STAGES) + metadata = PSE.CompiledMetadataTable(NamedTuple{STAGES}(tables)) + simulation = prepare(metadata, PSE._freeze_environment_binding_schema(environment)) + schemas = Dict{Symbol,Any}() + record_batches!(schemas, root(simulation)) + closed = PSE._prepare_execution_batch_schemas(simulation, + NamedTuple{STAGES}(map(name -> schemas[name], STAGES))) + return only(first(root(closed).targets).context.calls) +end + +const TARGETS = prepare_calls() + +Base.@noinline function check(targets) + schema = targets.batch_schema + batches = PSE._compiled_call_execution_batches(targets.compiled, targets.environment_bindings, + targets.binding, targets.temporal_streams, targets.output_retention, targets.constants; + cohort_schema=PSE._execution_cohort_schema(schema), batch_schema=schema) + length(batches) == 1 || return false + rows = first(batches).targets + length(rows) == 1 || return false + return first(rows).object_id === PSE.ObjectId(:energy_balance) +end + +end diff --git a/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl b/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl index 2d4c7dabf..c4b8cb262 100644 --- a/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl +++ b/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl @@ -1,6 +1,7 @@ module PSESceneDependencyControl import PlantSimEngine as PSE +include("NestedCallControl.jl") const SCENE = PSE._with_object_id_domain(PSE.CompositeModel( PSE.Object(:scene; scale=:Scene, kind=:scene), @@ -19,6 +20,9 @@ Base.@noinline function both_crowns(model, selector, matcher, context) end function (@main)(args) + if length(args) == 1 && only(args) == "nested" + return NestedCallControl.check(NestedCallControl.TARGETS) ? Cint(0) : Cint(3) + end context = isempty(args) ? PSE.ObjectId(:scene) : PSE.ObjectId(:crown_1) both_crowns(SCENE, CROWNS, MATCHER, context) || return Cint(1) ids = PSE._dependency_object_ids(SCENE, RELATIVE, RELATIVE_MATCHER, context) diff --git a/test/integration/native_growth.jl b/test/integration/native_growth.jl index 4c4b676a3..d6732c15d 100644 --- a/test/integration/native_growth.jl +++ b/test/integration/native_growth.jl @@ -103,7 +103,7 @@ end @testset "Native scene and relative model-call selectors" begin mktempdir() do directory scene = Compilation.compile(_scene_dependency_app; destination=joinpath(directory, "scene")) - for args in (String[], ["crown"]) + for args in (String[], ["crown"], ["nested"]) @test PSESceneDependencyControl.main(args) == 0 @test success(`$(scene.executable) $args`) end From bddee98173039aeb07437b47b9f06a8996d37a8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 05:47:52 +0100 Subject: [PATCH 300/324] Store shared and appended Many inputs within their prepared slots --- src/composite_model/compilation.jl | 29 ++++++++++++------- .../lifecycle_input_changes.jl | 4 +-- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index f4bb27ad1..b4e161873 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3136,10 +3136,8 @@ function _record_consumer_input_bindings!( new_bindings = B[] sizehint!(new_bindings, last_new_binding - first_new_binding + 1) for binding_index in first_new_binding:last_new_binding - binding = _share_many_input_binding!( - recorder.many_binding_cache, recorder.model, bindings[binding_index], - ) - bindings[binding_index] = binding + _store_shared_many_input_binding!(recorder.many_binding_cache, recorder.model, + bindings, binding_index) push!(new_bindings, bindings[binding_index]) end append!(recorder.changed_bindings, new_bindings) @@ -3441,11 +3439,18 @@ function _cache_many_binding_plan!(binding, cache::_ManyInputBindingCache, return binding end -@inline function _share_many_input_binding!(cache::_ManyInputBindingCache, - model::CompositeModel, binding, +# Store before leaving the slot admission. Different slots can return different +# concrete bindings while the recording and refresh callers require only the write. +@inline function _store_shared_many_input_binding!(cache::_ManyInputBindingCache, + model::CompositeModel, bindings, index, binding=bindings[index], ) - return Base.@inline _with_model_input_binding(_share_admitted_many_input_binding!, - cache.bindings, binding, cache, model) + return _with_model_input_binding(_store_admitted_many_input_binding!, + cache.bindings, binding, cache, model, bindings, index) +end + +function _store_admitted_many_input_binding!(binding, cache, model, bindings, index) + bindings[index] = _share_admitted_many_input_binding!(binding, cache, model) + return nothing end function _share_admitted_many_input_binding!(binding, cache, model) @@ -3475,7 +3480,7 @@ end function _share_many_input_bindings!(model::CompositeModel, bindings) cache = _empty_many_input_binding_cache(keytype(model.registry.objects), bindings) for index in eachindex(bindings) - bindings[index] = _share_many_input_binding!(cache, model, bindings[index]) + _store_shared_many_input_binding!(cache, model, bindings, index) end return cache end @@ -4803,7 +4808,7 @@ end Base.@noinline function _store_rebuilt_input_binding!( bindings, changed_bindings, index, replacement, cache, model, ) - replacement[1] = _share_many_input_binding!(cache, model, only(replacement)) + _store_shared_many_input_binding!(cache, model, replacement, 1, only(replacement)) copyto!(bindings, index, replacement, 1, 1) append!(changed_bindings, replacement) return nothing @@ -4872,7 +4877,9 @@ function _refresh_existing_scene_input_binding!(binding::B, index::Int, state::S prepared = _pending_input_update(admissions, index) appended_sources = if !isnothing(prepared) && first(prepared) === :append && !force_rebuild delta = admissions.bindings[last(prepared)] - _apply_added_many_sources!(binding, delta, performance) + Base.@inline _with_model_input_binding(admissions.bindings, delta) do admitted + _apply_added_many_sources!(binding, admitted, performance) + end elseif !isnothing(prepared) && first(prepared) === :unchanged && !force_rebuild true elseif !isnothing(prepared) || force_rebuild diff --git a/src/composite_model/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl index d9102ffd3..188e8c3a2 100644 --- a/src/composite_model/lifecycle_input_changes.jl +++ b/src/composite_model/lifecycle_input_changes.jl @@ -67,8 +67,8 @@ function _record_consumer_input_bindings!(staged::_StagedConsumerBindings, bindi range = first_binding:last_binding push!(staged.ranges, (application_id, object_id, range)) for i in range - staged.entries[i] = _share_many_input_binding!(staged.cache.local_cache, - staged.model, staged.entries[i]) + _store_shared_many_input_binding!(staged.cache.local_cache, staged.model, + staged.entries, i) end return nothing end From 7bab6b3ca6b8520ee82ffb1eafff213b8058f2f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 05:48:05 +0100 Subject: [PATCH 301/324] Exercise native growth fixtures with the shared per-slot input storage --- .../local_palm_leaf_birth/src/prepare.jl | 9 +++--- test/integration/native_preparation.jl | 28 +++++++++++-------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/test/fixtures/local_palm_leaf_birth/src/prepare.jl b/test/fixtures/local_palm_leaf_birth/src/prepare.jl index e0d81d684..6f01cda51 100644 --- a/test/fixtures/local_palm_leaf_birth/src/prepare.jl +++ b/test/fixtures/local_palm_leaf_birth/src/prepare.jl @@ -75,9 +75,8 @@ function prepare_native_scene() input_binding_storage=input_trace,status_view_schema=observed) advance_host!(recording,neighbours) == baseline || error("Recording changed state/history.") isempty(input_trace) || error("Input prototype was mutated.") - all(B -> isconcretetype(B) && B <: PSE.CompiledModelInputBinding,observed.inputs) || - error("Invalid input-binding family.") - input_prototype = Vector{Union{observed.inputs...}}() + input_prototype = PSE._prepared_input_bindings( + length(recording.simulation.compiled.scenario_plan.input_plans), observed.inputs) views = PSE.CompiledMetadataTable(NamedTuple{APPLICATION_IDS}(map(APPLICATION_IDS) do id types = observed.views[id] all(V -> isconcretetype(V) && V <: PSE.CompiledModelStatusView,types) || error("Invalid view family.") @@ -89,8 +88,8 @@ function prepare_native_scene() batches = Dict(id=>DataType[] for id in APPLICATION_IDS) function observe_batches(state) simulation = state.simulation - simulation.compiled.input_bindings isa Vector && - eltype(simulation.compiled.input_bindings) === eltype(input_prototype) || error("Lost finite input owner.") + simulation.compiled.input_bindings.family_by_slot === input_prototype.family_by_slot || + error("Lost input slot admissions.") simulation.compiled.status_view_schema === views && all(isempty,values(views)) || error("Lost view admission.") simulation.environment_bindings.environment_schema === environment_schema || error("Lost environment admission.") isempty(input_prototype) || error("Finite input prototype was mutated.") diff --git a/test/integration/native_preparation.jl b/test/integration/native_preparation.jl index 5c15b16b6..391a142c2 100644 --- a/test/integration/native_preparation.jl +++ b/test/integration/native_preparation.jl @@ -17,10 +17,10 @@ function close_registry(model, id_type=nothing) end mutable struct RuntimeTypes - inputs::Vector{DataType} + inputs::Set{Tuple{Int,DataType}} views::Dict{Symbol,Vector{DataType}} end -RuntimeTypes() = RuntimeTypes(DataType[], Dict{Symbol,Vector{DataType}}()) +RuntimeTypes() = RuntimeTypes(Set{Tuple{Int,DataType}}(), Dict{Symbol,Vector{DataType}}()) remember!(pool, T) = (T in pool || push!(pool, T); nothing) struct InputTrace <: AbstractVector{PSE.CompiledModelInputBinding} data::Vector{PSE.CompiledModelInputBinding} @@ -31,13 +31,19 @@ Base.IndexStyle(::Type{InputTrace}) = IndexLinear() Base.size(values::InputTrace) = size(values.data) Base.getindex(values::InputTrace, index::Int) = values.data[index] function Base.setindex!(values::InputTrace, binding, index::Int) - remember!(values.observed.inputs, typeof(binding)); values.data[index] = binding; return values + push!(values.observed.inputs, (binding.slot, typeof(binding))) + values.data[index] = binding + return values end function Base.push!(values::InputTrace, binding) - remember!(values.observed.inputs, typeof(binding)); push!(values.data, binding); return values + push!(values.observed.inputs, (binding.slot, typeof(binding))) + push!(values.data, binding) + return values end function Base.insert!(values::InputTrace, index::Integer, binding) - remember!(values.observed.inputs, typeof(binding)); insert!(values.data, index, binding); return values + push!(values.observed.inputs, (binding.slot, typeof(binding))) + insert!(values.data, index, binding) + return values end Base.append!(values::InputTrace, bindings) = (foreach(binding -> push!(values, binding), bindings); values) Base.similar(values::InputTrace, n::Integer) = @@ -87,13 +93,13 @@ function prepare_growth_fixture(make_model, ids, trajectories) return PSE._prepare_simulation!(close_registry(make_model()); steps=0, outputs=:all, constants=PSE.Constants(), environment_schema, input_binding_storage, status_view_schema) end - for advance! in trajectories - advance!(prepare(collecting, trace, observed), ignore) + slot_counts = map(trajectories) do advance! + simulation = prepare(collecting, trace, observed) + advance!(simulation, ignore) + length(simulation.compiled.scenario_plan.input_plans) end isempty(trace) || error("Input prototype was mutated.") - all(T -> isconcretetype(T) && T <: PSE.CompiledModelInputBinding, observed.inputs) || - error("Expected concrete input bindings.") - inputs = Vector{Union{observed.inputs...}}() + inputs = PSE._prepared_input_bindings(only(unique(slot_counts)), observed.inputs) views = PSE.CompiledMetadataTable(NamedTuple{ids}(map(ids) do id types = observed.views[id] all(T -> isconcretetype(T) && T <: PSE.CompiledModelStatusView, types) || @@ -104,7 +110,7 @@ function prepare_growth_fixture(make_model, ids, trajectories) fresh() = prepare(environment, inputs, views) batches = Dict(id => DataType[] for id in ids) function observe(sim) - sim.compiled.input_bindings isa Vector{eltype(inputs)} || error("Lost finite input owner.") + sim.compiled.input_bindings.family_by_slot === inputs.family_by_slot || error("Lost input slot admissions.") sim.compiled.status_view_schema === views || error("Lost finite view owner.") for group in sim.execution_plan.groups, batch in group.batches remember!(batches[batch.application.id], typeof(batch)) From 54d2302c1e73d2e9a657c0a1a9228c2e70fde0b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 06:08:19 +0100 Subject: [PATCH 302/324] Retain affected input readers through their prepared slots during structural edits --- src/composite_model/compilation.jl | 34 +++++++++++++----------- test/test-model-execution-batch-times.jl | 14 ++++++++++ 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index b4e161873..1ca57ec4e 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -4449,6 +4449,20 @@ end _input_binding_key_set(::AbstractDict{I}) where {I<:ObjectId} = _object_key_set(Tuple{Symbol,I,Symbol}) +function _retain_structural_input_binding!(binding, retained, objects, dirty, + forced_input_keys, previous_temporal_sources) + consumer_id = _index_object_id(objects, binding.consumer_id) + consumer_id in dirty && return nothing + push!(retained, binding) + _sorted_object_ids_intersect_set(binding.source_ids, dirty) || return nothing + key = (binding.application_id, consumer_id, binding.input) + push!(forced_input_keys, key) + if binding.carrier_hint === :temporal_stream + previous_temporal_sources[key] = copy(binding.source_ids) + end + return nothing +end + function _prepare_structural_compiled_delta( model::CompositeModel, compiled::CompiledCompositeModel, @@ -4484,24 +4498,12 @@ function _prepare_structural_compiled_delta( input_bindings = similar(compiled.input_bindings, 0) sizehint!(input_bindings, length(compiled.input_bindings)) - for binding in compiled.input_bindings - consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) - if consumer_id in dirty - continue - end - push!(input_bindings, binding) - end forced_input_binding_keys = _input_binding_key_set(model.registry.objects) previous_temporal_sources = _previous_temporal_source_storage(model) - for binding in input_bindings - _sorted_object_ids_intersect_set(binding.source_ids, dirty) || - continue - consumer_id = _index_object_id(model.registry.objects, binding.consumer_id) - key = (binding.application_id, consumer_id, binding.input) - push!(forced_input_binding_keys, key) - if binding.carrier_hint == :temporal_stream - previous_temporal_sources[key] = copy(binding.source_ids) - end + for binding in compiled.input_bindings + _with_model_input_binding(_retain_structural_input_binding!, compiled.input_bindings, + binding, input_bindings, model.registry.objects, dirty, forced_input_binding_keys, + previous_temporal_sources) end input_bindings_by_target = _index_model_input_bindings( input_bindings, keytype(model.registry.objects), diff --git a/test/test-model-execution-batch-times.jl b/test/test-model-execution-batch-times.jl index 387bc8200..c5189bfa6 100644 --- a/test/test-model-execution-batch-times.jl +++ b/test/test-model-execution-batch-times.jl @@ -88,6 +88,20 @@ function execute_prepared!(data, application, time) simulation.performance) end +@testset "A surviving temporal reader keeps an independent list of its removed sources" begin + simulation = temporal_fixture(false).simulation + binding = only(simulation.compiled.input_bindings) + source = ObjectId(:source) + key = (:consumer, ObjectId(:consumer), :signal) + dirty = Set{ObjectId}([source]) + delta = PSE._prepare_structural_compiled_delta(simulation.model, simulation.compiled, dirty) + @test only(delta.compiled.input_bindings) === binding + @test only(delta.forced_input_binding_keys) == key + previous = delta.previous_temporal_sources[key] + @test previous == binding.source_ids == [source] + @test previous !== binding.source_ids +end + @testset "one batch loop preserves temporal materialization and output publication" begin for performance in (false, true) data = temporal_fixture(performance) From 44742b9f793c8341cf3e57a555405182ad263f17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 07:08:44 +0100 Subject: [PATCH 303/324] Validate selected status cells against required reader types during preparation --- src/composite_model/compilation.jl | 35 ++++++++++++-- .../prepared_status_manifest.jl | 9 +--- test/test-model-input-binding-storage.jl | 48 +++++++++++++++++++ 3 files changed, 82 insertions(+), 10 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 1ca57ec4e..8eef92712 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -8592,15 +8592,44 @@ function _many_current_application_targets(model, application) return _resolve_object_ids(model, many, _resolve_selector_matcher(model, matcher)) end +function _status_reader_value_bound(model, ports, input, selector) + T = _configured_status_value_type(model.status_conversion, input, + getproperty(ports.input_types, input), get(ports.input_element_types, input, nothing)) + isnothing(T) && return nothing + selector isa Many || return T + return T <: AbstractVector ? eltype(T) : nothing +end + +function _check_required_status_sources(_, ports, model, application_id, input, selector, variable, ids) + input in _required_input_names(ports) || return nothing + T = _status_reader_value_bound(model, ports, input, selector) + isnothing(T) && return nothing + T === Union{} && throw(ArgumentError( + "Required input `$input` on application `$application_id` can only read an empty selection.")) + for id in ids + reference = _status_ref_or_nothing(model.registry.objects[id].status, variable) + isnothing(reference) && continue + eltype(reference) <: T || throw(ArgumentError( + "Required input `$input` on application `$application_id` expects `$T` " * + "from `$variable` on object `$(_object_id_text(id))`, got `$(eltype(reference))`.")) + end + return nothing +end + function _many_current_source_ids(model, consumer, producer, variant, selector, - source_selectors, distributed) + source_selectors, distributed, input, source_var) current = Set{ObjectId}() if isnothing(producer) matcher = _authored_selector_matcher(selector) _many_scope_is_current(model, matcher) || return current matcher = _resolve_selector_matcher(model, matcher) for consumer_id in _many_current_application_targets(model, consumer) - union!(current, _dependency_object_ids(model, selector, matcher, consumer_id)) + ids = _dependency_object_ids(model, selector, matcher, consumer_id) + if _selector_from_status(selector) && !isempty(ids) + _with_application_variant(_check_required_status_sources, consumer, consumer_id, + model, consumer.id, input, selector, source_var, ids) + end + union!(current, ids) end else isempty(source_selectors) && return current @@ -8692,7 +8721,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, variants = isnothing(producer) ? ((nothing, nothing, nothing),) : _many_model_variant_types(producer) for (variant, output_types, element_types) in variants current = _many_current_source_ids(model, consumer, producer, variant, - selector, source_selectors, distributed) + selector, source_selectors, distributed, input, source_var) missing_current = copy(current) for source_selector in source_selectors matcher = _authored_selector_matcher(source_selector) diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index 3e8ad65db..d955c932d 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -141,13 +141,8 @@ function _prepared_status_variant_permission(model, application, ports, plans) source_names = Symbol[]; source_refs = Any[] for plan in plans _input_route_from_status(plan.route) || continue - configured = _configured_status_value_type(model.status_conversion, plan.input, - getproperty(ports.input_types, plan.input), - get(ports.input_element_types, plan.input, nothing)) - T = plan.selector isa Many ? - (!isnothing(configured) && configured <: AbstractVector ? eltype(configured) : Union{}) : - (isnothing(configured) ? Union{} : configured) - T === Union{} && continue + T = _status_reader_value_bound(model, ports, plan.input, plan.selector) + (isnothing(T) || T === Union{}) && continue # Real/Any are value bounds, not requests to replace Ref32/Ref64 by # invariant Ref{Real}/Ref{Any}. Keep only already prepared real classes. classes = Tuple(R for slot in fieldtypes(plan.reference_types) diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index e33569acf..0482018dd 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -348,6 +348,54 @@ end end end +struct RequiredValues{T} <: AbstractInput_Binding_Storage_ReaderModel end +PSE.inputs_(::RequiredValues{T}) where {T} = (values=Required(Vector{T}),) +PSE.outputs_(::RequiredValues) = (total=0.0,) +function PSE.run!(::RequiredValues, status, environment, constants, context) + status.total = sum(bound_input(context, :values); init=0.0) + return nothing +end + +@testset "a Required status input checks only selected cells" begin + reader(T) = ModelSpec(RequiredValues{T}(); name=:reader, on=One(id=:scene), + inputs=(values=Many(within=Scope(ObjectId(:inside)), scale=:Leaf, var=:x, from_status=true),)) + make(leaves...; T=Real) = CompositeModel(Object(:scene; scale=:Scene), Object(:inside; parent=:scene), + Object(:annotation; parent=:scene, scale=:Leaf, status=Status(x="label")), leaves...; + applications=(reader(T),)) + leaf(id, ref) = Object(id; parent=:inside, scale=:Leaf, status=Status((x=ref,))) + @test_throws ArgumentError run!(make(leaf(:bad, Ref("text"))); steps=0) + @test isempty(binding(run!(make(); steps=0), :scene, :values).carrier) + @test isempty(binding(run!(make(; T=Union{}); steps=0), :scene, :values).carrier) + @test_throws ArgumentError run!(make(leaf(:one, Ref(1f0)); T=Union{}); steps=0) + + scalar(selector) = CompositeModel(Object(:scene; scale=:Scene, status=Status(single=1f0)), + Object(:annotation; parent=:scene, scale=:Leaf, status=Status(x="label")); applications=( + ModelSpec(Reader(); name=:reader, on=One(id=:scene), inputs=(single=selector, + values=Many(within=SceneScope(), scale=:Absent, var=:x, from_status=true),)),)) + for selector in (One, OptionalOne) + selected = selector(within=SceneScope(), id=:annotation, var=:x, from_status=true) + @test_throws ArgumentError run!(scalar(selected); steps=0) + end + absent = scalar(OptionalOne(within=SceneScope(), id=:missing, var=:x, from_status=true)) + run!(absent; steps=1) + @test model_status(absent, :scene).total == 1.0 + + left, right = Ref(1f0), Ref(2.0) + model = make(leaf(:one, left), leaf(:two, right)) + sim = run!(model; steps=1, outputs=:all) + before = copy(outputs(sim)[(:reader,ObjectId(:scene),:total)]) + @test_throws ArgumentError register_object!(model, leaf(:bad, Ref("text"))) + @test !haskey(model.registry.objects, ObjectId(:bad)) + @test outputs(sim)[(:reader,ObjectId(:scene),:total)] == before + carrier = binding(sim, :scene, :values).carrier + @test length(carrier) == 2 + @test all(cell -> any(ref -> ref === cell, parent(carrier)), (left, right)) + left[] = 4f0 + step!(sim) + @test outputs(sim)[(:reader,ObjectId(:scene),:total)] == [(1.0,3.0), (2.0,6.0)] + @test model_status(model, :annotation).x == "label" +end + @testset "a canonical source right is independent of a consumer's Default seed" begin source = ModelSpec(Reader{Float64}();name=:source,on=Many(scale=:Leaf),inputs=( single=One(id=:anchor,within=SceneScope(),var=:x,from_status=true), From ac7a80df95e70084ff2cd1da1306031b722b3590 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 07:35:27 +0100 Subject: [PATCH 304/324] Infer staged consumer storage from its prepared cache before handling optional routes --- src/composite_model/lifecycle_input_changes.jl | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/composite_model/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl index 188e8c3a2..58480989b 100644 --- a/src/composite_model/lifecycle_input_changes.jl +++ b/src/composite_model/lifecycle_input_changes.jl @@ -50,6 +50,11 @@ struct _StagedConsumerBindings{B,S,R,C,M,A} model::M existing::Union{Nothing,_PendingStatusInputChanges{B,A}} reused::BitSet + + function _StagedConsumerBindings(entries, statuses, ranges, cache, model, existing, has_routes::Bool) + return new{typeof(entries),typeof(statuses),typeof(ranges),typeof(cache),typeof(model),typeof(cache.added)}( + entries, statuses, ranges, has_routes ? cache : nothing, model, existing, BitSet()) + end end Base.length(bindings::_StagedConsumerBindings) = length(bindings.entries) Base.push!(bindings::_StagedConsumerBindings, binding) = push!(bindings.entries, binding) @@ -98,9 +103,7 @@ function _new_consumer_input_storage(compiled, model, applications, added, pure_ cache = _StagedManyInputCache(local_cache, compiled.many_input_binding_cache, added, statuses, pure_addition) ranges = Tuple{Symbol,I,UnitRange{Int}}[] - return _StagedConsumerBindings{typeof(entries),typeof(statuses),typeof(ranges), - typeof(cache),typeof(model),typeof(added)}(entries, statuses, ranges, - any_routes ? cache : nothing, model, existing, BitSet()) + return _StagedConsumerBindings(entries, statuses, ranges, cache, model, existing, any_routes) end function _stage_added_scene_inputs!(compiled, model, applications, output_applications, From 3510dd238e130c6874b5b7dc52634ef453207a48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 08:33:04 +0100 Subject: [PATCH 305/324] Resolve application targets before specializing the shared input recipe --- src/composite_model/compilation.jl | 22 ++++++++++++---------- test/test-model-input-binding-storage.jl | 13 +++++++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 8eef92712..a224d2c5f 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3077,13 +3077,13 @@ end # real consumers. Initial binding, normal growth and targeted newborns share # this loop and the same per-consumer resolver/materializer below. function _compile_application_consumer_bindings!( - bindings, model, application, recipe::CompiledApplicationInputRecipe, + bindings, model, application_id::Symbol, application_process::Symbol, target_ids, + recipe::CompiledApplicationInputRecipe, manual_application_ids, applications_by_object, applications_by_id, distributed_outputs=NoCompiledDistributedOutputs(), many_binding_cache=nothing, performance=nothing, recorder=nothing, ) - application_id, application_process = application.id, application.process - for consumer_id in application.target_ids + for consumer_id in target_ids first_new_binding = length(bindings) + 1 _compile_consumer_input_recipe!( bindings, model, application_id, application_process, consumer_id, recipe, @@ -9219,13 +9219,15 @@ function _compile_model_input_bindings!(bindings, model, applications, manual_ap ) for partial in applications isempty(partial.target_ids) && continue - Base.@inline _with_model_application(by_id, partial) do application - _with_metadata_entry(recipes, application.id) do recipe - _compile_application_consumer_bindings!( - bindings, model, application, recipe, manual_application_ids, - by_object, by_id, distributed_outputs, many_binding_cache, performance, recorder, - ) - end + # Capturing the whole application would specialize the recipe lookup for every model type. + application_id, process, target_ids = Base.@inline _with_model_application(by_id, partial) do application + (application.id, application.process, application.target_ids) + end + _with_metadata_entry(recipes, application_id) do recipe + _compile_application_consumer_bindings!( + bindings, model, application_id, process, target_ids, recipe, manual_application_ids, + by_object, by_id, distributed_outputs, many_binding_cache, performance, recorder, + ) end end return bindings diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 0482018dd..8b004233a 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -638,6 +638,19 @@ end visits[] += 1 end @test visits[] == 0 + + function resolve_inputs(application) + compiled = simulation.compiled + scenario = compiled.scenario_plan + return PSE._compile_model_input_bindings(data.model, (application,), + scenario.manual_application_ids, scenario.input_recipes_by_application, + compiled.distributed_outputs; by_object=compiled.applications_by_object, by_id=owner) + end + resolved = resolve_inputs(partial) + @test length(resolved) == 2 + @test all(binding -> binding.consumer_id == ObjectId(:a), resolved) + @test Set(binding.input for binding in resolved) == Set((:single, :values)) + @test_throws "outside its compiled metadata owner" resolve_inputs(foreign) @test partial.target_ids === targets check_carriers(data, simulation) end From 98f60b1f098c6700723dbabf9f1c52ee04244d12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 08:41:48 +0100 Subject: [PATCH 306/324] Compare shared input storage after admitting each binding once --- src/composite_model/compilation.jl | 36 ++++++++++-------------------- 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index a224d2c5f..349523980 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -2369,11 +2369,7 @@ function _index_dynamic_input_binding!( many_binding_cache, ) binding.origin == :inferred_same_object && return index - if _dynamic_input_binding_shares_canonical_sources( - model, - binding, - many_binding_cache, - ) + if _input_binding_shares_canonical_sources(binding, model, many_binding_cache) return index end _index_selector_candidate!( @@ -3502,6 +3498,12 @@ function _seed_many_input_binding_cache!(binding, cache, model) cache.bindings, cache.by_query[key], cache, model) end +function _shares_input_source_storage(binding, canonical) + return binding.source_ids === canonical.source_ids && + binding.source_application_ids === canonical.source_application_ids && + binding.carrier === canonical.carrier +end + function _shared_same_rate_many_storage( binding::CompiledModelInputBinding, canonical::CompiledModelInputBinding, @@ -3510,33 +3512,19 @@ function _shared_same_rate_many_storage( binding.carrier_hint === :ref_vector || return false canonical.multiplicity == :many || return false canonical.carrier_hint === :ref_vector || return false - return binding.source_ids === canonical.source_ids && - binding.source_application_ids === - canonical.source_application_ids && - binding.carrier === canonical.carrier + return _shares_input_source_storage(binding, canonical) end -@inline function _dynamic_input_binding_shares_canonical_sources( - model::CompositeModel, binding, cache::_ManyInputBindingCache, -) - return Base.@inline _with_model_input_binding(_input_binding_shares_many_cache!, - cache.bindings, binding, model, cache) -end - -function _input_binding_shares_many_cache!(binding, model, cache) +function _input_binding_shares_canonical_sources(binding, model, cache) binding.multiplicity == :many || return false binding.carrier_hint === :ref_vector || return false key = _many_binding_share_key(cache, model, binding) isnothing(key) && return false canonical = get(cache.by_query, key, nothing) isnothing(canonical) && return false - return Base.@inline _with_model_input_binding(_input_binding_shares_many_sources, - cache.bindings, canonical, binding) -end - -function _input_binding_shares_many_sources(canonical, binding) - _shared_same_rate_many_storage(binding, canonical) || return false - return binding.slot != canonical.slot || binding.consumer_id != canonical.consumer_id + _with_model_input_binding(Returns(nothing), cache.bindings, canonical) + return _shares_input_source_storage(binding, canonical) && + (binding.slot != canonical.slot || binding.consumer_id != canonical.consumer_id) end function _shared_same_rate_many_binding_indices(bindings, binding) From 141c054da326bb14d9b9486b6b2e00d64394d37f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 09:11:18 +0100 Subject: [PATCH 307/324] Prepare status fields declared by the MTG organ initializer --- docs/src/API/API_public.md | 7 + docs/src/API/public_symbols.md | 1 + docs/src/guides/multiscale/import_mtg.md | 31 +++ src/composite_model/compilation.jl | 56 +++-- .../prepared_status_manifest.jl | 97 ++++++++- test/test-mtg-birth-status-types.jl | 193 ++++++++++++++++++ test/test_groups.jl | 1 + 7 files changed, 361 insertions(+), 25 deletions(-) create mode 100644 test/test-mtg-birth-status-types.jl diff --git a/docs/src/API/API_public.md b/docs/src/API/API_public.md index 69569b281..1d51bb4c3 100644 --- a/docs/src/API/API_public.md +++ b/docs/src/API/API_public.md @@ -271,6 +271,13 @@ keep those new values consistent with the rest of the simulation: object's output. The initializer itself can still use a `PreviousTimeStep` input. +The MTG initializer can declare fields supplied later through `initial_status`. +See [Importing an MTG](../guides/multiscale/import_mtg.md) for a flower example. + +```@docs +PlantSimEngine.birth_status_types +``` + ### Explanations Use the `Diagnostics` namespace instead of inspecting internals: diff --git a/docs/src/API/public_symbols.md b/docs/src/API/public_symbols.md index a95314799..3592640fc 100644 --- a/docs/src/API/public_symbols.md +++ b/docs/src/API/public_symbols.md @@ -47,6 +47,7 @@ explains the functions and their requirements in detail. `assign_outputs!`. Access each variable's destination values through `targets.columns.` and their object identifiers, in the same order, through `object_ids(targets)`. +- Declare status fields for future MTG organs with `PlantSimEngine.birth_status_types`. - Adding, removing, or moving objects: `register_object!`, `add_organ!`, `remove_object!`, `reparent_object!`, `move_object!`, `update_geometry!`, `mark_environment_binding_dirty!`, `objects_from_mtg`. diff --git a/docs/src/guides/multiscale/import_mtg.md b/docs/src/guides/multiscale/import_mtg.md index 11ca6280c..affcbd6e9 100644 --- a/docs/src/guides/multiscale/import_mtg.md +++ b/docs/src/guides/multiscale/import_mtg.md @@ -103,6 +103,37 @@ when the prepared tree supports that column type. On a tree with only numeric columns, declare the symbol column first. To set only the simulation object's label, pass `kind=:expanding` directly to `add_organ!`. +### Give future organs their own fields + +Suppose the initial plant has no flowers. When a flower appears, the growth +model supplies its sex. Declare this field on the callable that imports the +initial statuses so PSE can prepare its storage before the first flower exists. + +```@example future_flower +using PlantSimEngine, MultiScaleTreeGraph + +struct PalmInitialStatus end +(::PalmInitialStatus)(node) = nothing +PlantSimEngine.birth_status_types(::PalmInitialStatus, objects) = + (Flower=(sex=Symbol,),) + +palm = Node(1, NodeMTG(:/, :Plant, 1, 0), NamedTuple()) +plant = CompositeModel(palm; status=PalmInitialStatus()) +flower = add_organ!(palm, plant, :+, :Flower, 1; initial_status=(sex=:female,)) +flower.sex +``` + +Use a finite union such as `Union{Int,Float64}` when new organs can supply +either representation. If the organ names depend on plant parameters, +read those parameters from the initialized plants in `objects` and return a +dictionary keyed by their organ symbols. Each object exposes its `scale` and +`status`. PSE reuses the declaration as the plant grows. + +A `from_status` input declared with `Required(Real)` can read a numeric cell. +If a new organ falls in its selection, a text cell is rejected before that +organ joins the tree. The same text field can belong to an organ outside that +selection. A `Default` value supplies the input's starting value. + See [Growth within a time step](../../tutorials/growing_plant/part1_growth.md). Use `objects_from_mtg(root; status=initial_status)` when you only want a diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 349523980..47e60cb7a 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -960,9 +960,10 @@ function _finalize_authored_scenario(model, source_specs, authored_records, raw_ failure = isnothing(failure_index) ? nothing : authored_records[failure_index] recipes = _graph_record_vector(AuthoredApplicationRecipe, (record for record in authored_records if record isa AuthoredApplicationRecipe)) - program = _prepare_authored_scenario_program(model, recipes) + birth_types = _prepared_birth_status_types(model) + program = _prepare_authored_scenario_program(model, recipes, birth_types) status_manifest = _capture_authored_metadata(:status_manifest, nothing) do - _prepare_status_manifest(model, authored_records, program, raw_families) + _prepare_status_manifest(model, authored_records, program, raw_families, birth_types) end if isnothing(failure) && status_manifest isa ScenarioPreparationFailure # A missing field family may be downstream of a rejected logical route @@ -1583,11 +1584,11 @@ function _prepare_authored_scenario_graph(application_records, input_records, ca frozen_children, order, failures) end -function _prepare_authored_scenario_program(model, recipes) +function _prepare_authored_scenario_program(model, recipes, birth_types) applications = _graph_record_vector(AuthoredApplicationRecipe, recipes) output_records = _prepare_authored_output_records(applications) destinations = _authored_distributed_output_plans(applications, output_records) - input_records = _prepare_authored_input_records(model, applications, destinations) + input_records = _prepare_authored_input_records(model, applications, destinations, birth_types) inputs = Tuple(record for record in input_records if record isa CompiledModelInputPlan) calls = Tuple(plan for application in applications for plan in application.call_plans) graph = _prepare_authored_scenario_graph(applications, inputs, calls, destinations) @@ -8588,9 +8589,13 @@ function _status_reader_value_bound(model, ports, input, selector) return T <: AbstractVector ? eltype(T) : nothing end -function _check_required_status_sources(_, ports, model, application_id, input, selector, variable, ids) +function _required_status_reader_bound(model, ports, input, selector) input in _required_input_names(ports) || return nothing - T = _status_reader_value_bound(model, ports, input, selector) + return _status_reader_value_bound(model, ports, input, selector) +end + +function _check_required_status_sources(_, ports, model, application_id, input, selector, variable, ids) + T = _required_status_reader_bound(model, ports, input, selector) isnothing(T) && return nothing T === Union{} && throw(ArgumentError( "Required input `$input` on application `$application_id` can only read an empty selection.")) @@ -8605,14 +8610,14 @@ function _check_required_status_sources(_, ports, model, application_id, input, end function _many_current_source_ids(model, consumer, producer, variant, selector, - source_selectors, distributed, input, source_var) + evidence_selector, source_selectors, distributed, input, source_var) current = Set{ObjectId}() if isnothing(producer) matcher = _authored_selector_matcher(selector) _many_scope_is_current(model, matcher) || return current matcher = _resolve_selector_matcher(model, matcher) for consumer_id in _many_current_application_targets(model, consumer) - ids = _dependency_object_ids(model, selector, matcher, consumer_id) + ids = _dependency_object_ids(model, evidence_selector, matcher, consumer_id) if _selector_from_status(selector) && !isempty(ids) _with_application_variant(_check_required_status_sources, consumer, consumer_id, model, consumer.id, input, selector, source_var, ids) @@ -8675,11 +8680,24 @@ function _disjoint_self_status_input(model, consumer, selector::Many) end function _prepare_input_reference_types(model, consumer, input, selector, - source_var, producer_ids, applications_by_id, writer_applications, distributed_output_plans) + source_var, producer_ids, applications_by_id, writer_applications, distributed_output_plans, birth_types) references = Any[] + evidence_selector = selector # A status read can see a canonical output before its first value has been # materialized. Its declared cell type does not create a stream dependency. if _selector_from_status(selector) + if birth_types !== nothing && !(selector isa Many && _disjoint_self_status_input(model, consumer, selector)) + scale = _authored_selector_matcher(selector).scale + for (family, fields) in birth_types + _object_matches_selector_value(family, scale) || continue + for (field, R) in fields + field === source_var && push!(references, R) + end + end + # Membership supplies type evidence. An actual One still enforces + # exactly one source when the prepared route binds in a simulation. + isempty(references) || (evidence_selector = _selector_as_many(selector)) + end _add_status_writer_reference_types!(references, model, selector, source_var, get(writer_applications, source_var, ()), distributed_output_plans) end @@ -8709,7 +8727,7 @@ function _prepare_input_reference_types(model, consumer, input, selector, variants = isnothing(producer) ? ((nothing, nothing, nothing),) : _many_model_variant_types(producer) for (variant, output_types, element_types) in variants current = _many_current_source_ids(model, consumer, producer, variant, - selector, source_selectors, distributed, input, source_var) + selector, evidence_selector, source_selectors, distributed, input, source_var) missing_current = copy(current) for source_selector in source_selectors matcher = _authored_selector_matcher(source_selector) @@ -8761,6 +8779,13 @@ function _prepare_input_reference_types(model, consumer, input, selector, end end end + if _selector_from_status(selector) + bound = _required_status_reader_bound(model, _application_ports(consumer), input, selector) + if !isnothing(bound) + filter!(R -> bound !== Union{} && eltype(R) <: bound, references) + isempty(references) && selector isa Many && return Tuple{} + end + end isempty(references) && !(selector isa OptionalOne) && throw(ArgumentError("An input has no prepared reference family.")) # Julia canonicalizes the union; its members give deterministic witness order. @@ -8779,6 +8804,7 @@ Base.@nospecializeinfer function _compiled_model_input_plan( distributed_output_plans, local_output_names, variable_contracts_by_application, + birth_types, ) # Selector and application values still determine the concrete final plan. @nospecialize application selector @@ -8845,11 +8871,11 @@ Base.@nospecializeinfer function _compiled_model_input_plan( _selector_window(selector), _prepare_input_reference_types(model, application, input, selector, source_var, potential_source_application_ids, - applications_by_id, writer_applications, distributed_output_plans), + applications_by_id, writer_applications, distributed_output_plans, birth_types), ) end -function _prepare_authored_input_records(model, applications, distributed_output_plans) +function _prepare_authored_input_records(model, applications, distributed_output_plans, birth_types) plans = CompiledModelInputPlan[] records = Any[] applications_by_id = Dict(application.id => application for application in applications) @@ -8881,7 +8907,7 @@ function _prepare_authored_input_records(model, applications, distributed_output application, input, selector, get(input_origins(application.spec), input, :model_spec), applications_by_id, distributed_output_plans, local_output_names, - variable_contracts_by_application) + variable_contracts_by_application, birth_types) end push!(records, record) record isa CompiledModelInputPlan && push!(plans, record) @@ -8901,7 +8927,7 @@ function _prepare_authored_input_records(model, applications, distributed_output _compiled_model_input_plan(model, length(plans) + 1, writer_applications, application, input, selector, :inferred_same_object, applications_by_id, distributed_output_plans, local_output_names, - variable_contracts_by_application) + variable_contracts_by_application, birth_types) end push!(records, record) record isa CompiledModelInputPlan && push!(plans, record) @@ -8930,7 +8956,7 @@ function _resolve_model_input_plans(model, preparation::ScenarioPreparation, # A partial report is a different declaration set. Project the real # recipes through the SAME pure factory, without replaying a hook. _prepare_authored_input_records(model, _project_authored_applications(preparation, applications), - distributed_output_plans) + distributed_output_plans, _frozen_birth_status_types(preparation.status_manifest)) end plans = CompiledModelInputPlan[] for record in records diff --git a/src/composite_model/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl index d955c932d..54e8d4d15 100644 --- a/src/composite_model/prepared_status_manifest.jl +++ b/src/composite_model/prepared_status_manifest.jl @@ -2,15 +2,16 @@ # configured selector owners and raw-family correlations, never default values. # These lists refer to the authored owners and their existing permissions. # Cardinalities are data: adding organs never specializes the execution model. -struct PreparedBirthRecipe{S,A,F,D,R} +struct PreparedBirthRecipe{S,A,F,D,R,C} status_type::Type{S} applications::A sources::F destinations::D raw_families::R + declared_fields::C end -mutable struct PreparedStatusManifest{S,A,P,D,R,B} +mutable struct PreparedStatusManifest{S,A,P,D,R,B,C} const status_type::Type{S} const authored::A const permissions::P @@ -18,6 +19,7 @@ mutable struct PreparedStatusManifest{S,A,P,D,R,B} const raw_families::R const birth_recipes::Dict{Union{Nothing,Symbol},B} const all_routes::B + const birth_types::C end # RAW membership, labels and reference classes are constructor evidence DATA. @@ -214,7 +216,70 @@ function _prepared_status_destinations(plans) for plan in plans] end -function _prepared_birth_recipes(S, applications, permissions, destinations, raw, model) +""" + PlantSimEngine.birth_status_types(initializer, objects) + +Declare status fields that an MTG-backed [`CompositeModel`](@ref) can receive when new +organs appear. Extend this method for the callable passed as `status=initializer`. +The default returns `nothing`. + +Return a named tuple or dictionary keyed by organ scale. Each scale maps field names +to concrete value types or finite unions of concrete value types. For example, +`(Leaf=(age=Float64,), Flower=(sex=Symbol,))` allows a new flower to receive +`initial_status=(sex=:female,)` in [`add_organ!`](@ref). The declaration supplies +types. The caller supplies each value at birth. + +During preparation, `objects` iterates the registered [`Object`](@ref)s with +their initialized statuses. Read an object's `scale` and `status` here when the +set of future organs depends on plant parameters. PSE retains the declaration +for later births. A selected `from_status` reader must also accept its source +cell's type when the input is `Required`. A `Default` supplies an initial value. +""" +birth_status_types(initializer, objects) = nothing + +function _prepared_birth_status_types(model) + catalog = model.registry.objects.catalog + catalog isa ClosedObjectFamilyCatalog && return _frozen_birth_status_types(catalog.status_manifest) + adapter = model.source_adapter + adapter isa MTGObjectAdapter || return nothing + declared = birth_status_types(adapter.status, values(model.registry.objects)) + declared === nothing && return nothing + refs = Dict{Symbol,Vector{Pair{Symbol,DataType}}}() + for (scale, fields) in pairs(declared) + scale isa Symbol || throw(ArgumentError("A birth status scale must be a Symbol.")) + classes = Pair{Symbol,DataType}[] + for (field, T) in pairs(fields) + field isa Symbol && T isa Type || throw(ArgumentError( + "Birth status fields must pair a Symbol with a type.")) + R = _prepared_status_declared_reference(model.status_conversion, field, T, nothing) + R === Union{} && throw(ArgumentError( + "Initial field $field on $scale needs a finite concrete storage family.")) + for ref_type in Base.uniontypes(R) + push!(classes, field => ref_type) + end + end + refs[scale] = classes + end + return refs +end + +_declared_birth_reference_admission(::Nothing, name, reference) = (false, true) +function _declared_birth_reference_admission(fields, name, reference) + declared = false + for (field, R) in fields + field === name || continue + declared = true + R === typeof(reference) && return (true, true) + end + return (false, !declared) +end + + +# Reuse the table frozen by the constructor when projecting or refreshing the plan. +_frozen_birth_status_types(manifest) = nothing +_frozen_birth_status_types(manifest::PreparedStatusManifest) = manifest.birth_types + +function _prepared_birth_recipes(S, applications, permissions, destinations, raw, model, declarations) owners = collect(zip(applications, permissions)) by_slot = Dict(first(owner).slot => owner for owner in owners) Source = eltype(fieldtype(eltype(permissions), :sources)) @@ -222,8 +287,10 @@ function _prepared_birth_recipes(S, applications, permissions, destinations, raw (app, permission, source) for (app, permission) in owners for source in permission.sources] routes = Tuple{eltype(applications),eltype(permissions),eltype(destinations)}[ (by_slot[plan.application_slot]..., plan) for plan in destinations] - all_routes = PreparedBirthRecipe(S, owners, sources, routes, raw) + empty_fields = isnothing(declarations) ? nothing : Pair{Symbol,DataType}[] + all_routes = PreparedBirthRecipe(S, owners, sources, routes, raw, empty_fields) scales = Set{Union{Symbol,Nothing}}(keys(model.registry.by_scale)) + isnothing(declarations) || union!(scales, keys(declarations)) push!(scales, nothing) for matcher in Iterators.flatten(((app.target_matcher for app in applications), (source.matcher for (_, _, source) in sources), (plan.matcher for plan in destinations))) @@ -237,7 +304,8 @@ function _prepared_birth_recipes(S, applications, permissions, destinations, raw filter(owner -> matches(first(owner).target_matcher), owners), filter(row -> matches(last(row).matcher), sources), filter(row -> matches(last(row).matcher), routes), - filter(family -> first(family.labels) === scale, raw)) + filter(family -> first(family.labels) === scale, raw), + isnothing(declarations) ? nothing : get(declarations, scale, empty_fields)) end return recipes, all_routes end @@ -314,7 +382,7 @@ function _add_supplied_status_fields!(names, refs, raw) return nothing end -function _prepare_status_manifest(model, authored, program, raw_basis) +function _prepare_status_manifest(model, authored, program, raw_basis, declarations) # Host traversal uses scalar records; freeze exact owner tuples only once # the namespace and all RAW permissions have been prepared. recipes = _graph_record_vector(AuthoredApplicationRecipe, @@ -361,6 +429,11 @@ function _prepare_status_manifest(model, authored, program, raw_basis) raw_basis end _add_supplied_status_fields!(names, refs, raw) + if !isnothing(declarations) + for scale in sort!(collect(keys(declarations))), (name, R) in declarations[scale] + _prepared_status_add_type!(names, refs, name, R) + end + end for permission in permissions for variant in permission.variants, (name, R) in variant.canonical _prepared_status_add_type!(names, refs, name, R) @@ -415,8 +488,8 @@ function _prepare_status_manifest(model, authored, program, raw_basis) # no biological Ref is created for that slot. physical_refs = map(R -> R === Union{} ? Nothing : R, refs) S = _fixed_status_type(Tuple(names), Tuple{physical_refs...}) - recipes_by_scale, all_routes = _prepared_birth_recipes(S, applications, permissions, destinations, raw, model) - return PreparedStatusManifest(S, applications, permissions, destinations, raw, recipes_by_scale, all_routes) + recipes_by_scale, all_routes = _prepared_birth_recipes(S, applications, permissions, destinations, raw, model, declarations) + return PreparedStatusManifest(S, applications, permissions, destinations, raw, recipes_by_scale, all_routes, declarations) end # The catalog references the SAME prepared manifest; runtime never finds a @@ -587,8 +660,11 @@ function _prepared_status_source_route_admission(source, application, permission topology = _prepared_status_topology(model, object, id, parent_id) if _selector_matches_object_id(topology, matcher, id, nothing, false, nothing, false) + # An absent reader gives no permission for an incompatible cell. + # Independent declarations and observed raw families are checked + # separately; a real reader checks its own family on activation. _prepared_status_reference_allowed(source.references, name, reference) || - return (false, false, false) + return (false, false, true) declared, allowed = _prepared_status_source_input_admission( first(permission.variants), source.input, reference) end @@ -757,7 +833,8 @@ Base.@noinline Base.@nospecializeinfer function _prepared_status_source_allowed( present += 1 allowed, compatible = _prepared_status_configured_reference_admission(recipe, model, object, parent_id, name, reference) - compatible && (allowed || + declared, in_family = _declared_birth_reference_admission(recipe.declared_fields, name, reference) + compatible && ((in_family && (allowed || declared)) || _prepared_status_raw_reference_allowed(raw, name, reference)) || return false end end diff --git a/test/test-mtg-birth-status-types.jl b/test/test-mtg-birth-status-types.jl new file mode 100644 index 000000000..bad380a16 --- /dev/null +++ b/test/test-mtg-birth-status-types.jl @@ -0,0 +1,193 @@ +module MTGBirthStatusTypeChecks + +using PlantSimEngine, Test +import MultiScaleTreeGraph as MTG +const PSE = PlantSimEngine + +struct InitialStatus{T} + original::Base.RefValue{T} + declarations::Base.RefValue{Int} +end +InitialStatus(value) = InitialStatus(Ref(value), Ref(0)) + +function (init::InitialStatus)(node) + MTG.symbol(node) === :Scene && return Status(organ_symbol=:Blade) + if MTG.symbol(node) === :Blade + MTG.symbol(MTG.parent(node)) === :Numeric && return Status(mass=1.5) + return Status((mass=init.original,)) + end + return nothing +end + +function PSE.birth_status_types(init::InitialStatus, objects) + init.declarations[] += 1 + plant = only(object for object in objects if object.scale === :Scene) + return Dict(plant.status.organ_symbol => (mass=Union{Float64,String},)) +end + +@process "birth_status_reader" verbose=false +struct NumericReader{T} <: AbstractBirth_Status_ReaderModel end +NumericReader() = NumericReader{Real}() +struct MixedReader <: AbstractBirth_Status_ReaderModel end +PSE.inputs_(::NumericReader{T}) where {T} = (values=Required(Vector{T}),) +PSE.inputs_(::MixedReader) = (values=Default(Float32[]),) +PSE.outputs_(::Union{NumericReader,MixedReader}) = (total=0.0,) +function PSE.run!(::NumericReader, status, environment, constants, context) + status.total = sum(bound_input(context, :values); init=0.0) +end +function PSE.run!(::MixedReader, status, environment, constants, context) + status.total = sum((v for v in bound_input(context, :values) if v isa Real); init=0.0) +end + +root() = MTG.Node(1, MTG.NodeMTG(:/, :Scene, 1, 0), NamedTuple()) +child(id, parent, scale) = MTG.Node(id, parent, MTG.NodeMTG(:+, scale, 1, 1), NamedTuple()) +reader(m, name, target, scope) = ModelSpec(m; name, on=target, + inputs=(values=Many(within=scope, scale=:Blade, var=:mass, from_status=true),)) +plant_leaf(model, parent, cell) = add_organ!(parent, model, :+, :Blade, 1; + initial_status=Status((mass=cell,))) + +@testset "Declared future fields follow the selected reader" begin + tree = root() + numeric = child(2, tree, :Numeric) + mixed = child(3, tree, :Mixed) + child(4, tree, :Blade) + child(5, numeric, :Blade) + init = InitialStatus("outside") + model = CompositeModel(tree; status=init, applications=( + reader(NumericReader(), :numeric, One(id=2), Subtree()), + reader(MixedReader(), :mixed, One(id=3), Subtree()), + )) + sim = run!(model; steps=1, outputs=:all) + @test PSE.refvalue(model_status(model, 4), :mass) === init.original + @test model_status(model, 2).total === 1.5 + previous_outputs = Dict(k => copy(v) for (k, v) in outputs(sim)) + previous_ids = object_ids(model) + @test_throws ArgumentError plant_leaf(model, numeric, Ref("invalid")) + @test object_ids(model) == previous_ids + @test MTG.node_id.(MTG.children(numeric)) == [5] && isnothing(MTG.get_node(tree, 6)) + @test outputs(sim) == previous_outputs && current_step(sim) == 1 + + mass = Ref(2.5) + leaf = plant_leaf(model, numeric, mass) + @test MTG.node_id(source_node(model, leaf)) == 6 + @test PSE.refvalue(leaf, :mass) === mass + label = Ref("allowed") + @test PSE.refvalue(plant_leaf(model, mixed, label), :mass) === label + soft_mass = Ref(4.0) + @test PSE.refvalue(plant_leaf(model, mixed, soft_mass), :mass) === soft_mass + step!(sim) + @test model_status(model, 2).total === 4.0 + @test model_status(model, 3).total === 4.0 + @test PSE.refvalue(model_status(model, 4), :mass) === init.original + @test init.declarations[] == 1 +end + +@testset "A future reader checks independently owned data when it binds" begin + for (value, valid) in (("outside", false), (3.5, true)) + tree = root() + child(2, tree, :Blade) + init = InitialStatus(value) + model = CompositeModel(tree; status=init, applications=( + reader(NumericReader(), :reader, Many(scale=:Numeric), SceneScope()),)) + sim = run!(model; steps=0, outputs=:all) + @test PSE.refvalue(model_status(model, 2), :mass) === init.original + add_organ!(tree, model, :+, :Numeric, 1) + if valid + step!(sim) + @test model_status(model, 3).total === value + else + before = Dict(k => copy(v) for (k, v) in outputs(sim)) + @test_throws ArgumentError continue!(sim; steps=0) + @test current_step(sim) == 0 && outputs(sim) == before + end + @test PSE.refvalue(model_status(model, 2), :mass) === init.original + @test init.declarations[] == 1 + end +end + +struct OtherFields{D} + fields::D + mass::Base.RefValue{String} +end +PSE.birth_status_types(init::OtherFields, objects) = init.fields +(init::OtherFields)(node) = MTG.symbol(node) === :Blade ? Status((mass=init.mass,)) : nothing + +@testset "Future fields follow the configured storage type" begin + tree = root() + declared = OtherFields((Blade=(mass=Float64,),), Ref("unused")) + model = CompositeModel(tree; status=declared, type_promotion=Dict(Float64 => Float32)) + leaf = add_organ!(tree, model, :+, :Blade, 1; initial_status=(mass=2.5,)) + @test leaf.mass === 2.5f0 + @test PSE.refvalue(leaf, :mass) === PSE.refvalue(model_status(model, 2), :mass) + + for fields in (Dict("Blade" => (mass=Float64,)), (Blade=(mass=1.0,),), (Blade=(mass=Real,),)) + @test_throws ArgumentError CompositeModel(root(); status=OtherFields(fields, Ref("unused"))) + end +end + +@testset "Other fields and other scales preserve the original RAW cell" begin + for fields in (nothing, (Blade=(other=Int,),), + (Blade=(other=Int,), Flower=(mass=Float64,))) + init = OtherFields(fields, Ref("outside")) + tree = root() + child(2, tree, :Blade) + spec = ModelSpec(NumericReader(); name=:reader, on=Many(scale=:Numeric), inputs=( + values=Many(within=SceneScope(), scale=(:Blade, :Flower), var=:mass, from_status=true),)) + model = CompositeModel(tree; status=init, applications=(spec,)) + sim = run!(model; steps=0, outputs=:all) + @test PSE.refvalue(model_status(model, 2), :mass) === init.mass + new_cell = Ref("another blade") + @test PSE.refvalue(plant_leaf(model, tree, new_cell), :mass) === new_cell + before = Dict(k => copy(v) for (k, v) in outputs(sim)) + add_organ!(tree, model, :+, :Numeric, 1) + @test_throws ArgumentError continue!(sim; steps=0) + @test current_step(sim) == 0 && outputs(sim) == before + @test PSE.refvalue(model_status(model, 2), :mass) === init.mass + end +end + +struct ScalarReader{T} <: AbstractBirth_Status_ReaderModel end +ScalarReader() = ScalarReader{Real}() +PSE.inputs_(::ScalarReader{T}) where {T} = (value=Required(T),) +PSE.outputs_(::ScalarReader) = (total=0.0,) +PSE.run!(::ScalarReader, status, environment, constants, context) = (status.total = status.value) + +@testset "One and OptionalOne keep the declared scalar input type" begin + for selector in (One, OptionalOne) + function build(value) + tree = root() + child(2, tree, :Blade) + init = InitialStatus(value) + model = CompositeModel(tree; status=init, applications=(ModelSpec(ScalarReader(); + name=:reader, on=One(id=1), inputs=(value=selector( + within=SceneScope(), id=2, var=:mass, from_status=true),)),)) + return model, init + end + model, init = build(3.0) + run!(model; steps=1) + @test model_status(model, 1).total === 3.0 + @test PSE.refvalue(model_status(model, 1), :value) === init.original + @test_throws ArgumentError run!(first(build("invalid")); steps=0) + end + @test PSE.birth_status_types(identity, ()) === nothing +end + +@testset "A future reader can own a compatible cell before its first target exists" begin + for (reader, input, selector) in ((ScalarReader{Float64}(), :value, One), + (NumericReader{Float64}(), :values, Many)) + root = MTG.Node(1, MTG.NodeMTG(:/, :Scene, 1, 0), NamedTuple()) + source = selector(within=SceneScope(), scale=:Blade, var=:x, from_status=true) + spec = ModelSpec(reader; name=:reader, on=Many(scale=:Collector), inputs=(; input => source)) + model = CompositeModel(root; applications=(spec,)) + sim = run!(model; steps=0, outputs=:all) + real = Ref(2.0) + leaf = add_organ!(root, model, :+, :Blade, 1; initial_status=Status((x=real,))) + @test PSE.refvalue(leaf, :x) === real + add_organ!(root, model, :+, :Collector, 1) + step!(sim) + @test model_status(model, 3).total === 2.0 + @test PSE.refvalue(model_status(model, 2), :x) === real + end +end + +end diff --git a/test/test_groups.jl b/test/test_groups.jl index 406670c24..a14db2cb3 100644 --- a/test/test_groups.jl +++ b/test/test_groups.jl @@ -8,6 +8,7 @@ const TEST_GROUPS = ( "test-object-families.jl", "test-prepared-status-registration.jl", "test-fixed-status-scope-growth.jl", + "test-mtg-birth-status-types.jl", "test-model-local-leaf-birth.jl", ), "Concrete runtime object identities" => ( From d2c250d59733f46aa0621c4d28801d35a441f6fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 10:40:00 +0100 Subject: [PATCH 308/324] Compile nested calls for their admitted application types --- src/composite_model/runtime_outputs.jl | 20 ++++++------- test/test-model-prepared-call-schemas.jl | 37 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 10 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 636148509..98b549f6c 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -3784,7 +3784,7 @@ function _compiled_call_execution_batches( admission = _call_cohort_admission(batch_schema,cohort_schema) batches = _execution_batch_buffer(batch_schema) for application_id in binding.callee_application_ids - _compiled_application_by_id(compiled,application_id) do application + _with_call_batch_application(compiled, application_id, batch_schema) do application application_schema = _call_batch_schema_for_application(batch_schema,application) current_ids = [object_id for object_id in binding.callee_object_ids if _call_binding_target_matches(binding,application,object_id)] @@ -4217,18 +4217,18 @@ function _model_execution_batch_accepts_target( return isequal(provider, batch.environment_provider) end -# Only admission needs the closed batch types. The registered application -# supplies its current target IDs for the same ordered-prefix check. -@inline _call_prefix_application(compiled, id, ::OpenExecutionBatchSchema) = - _compiled_application_by_id(compiled, id) +# The ID selects the registered application instance. Its prepared batch schema +# limits which application types the nested call needs to compile. +@inline _with_call_batch_application(f::F, compiled, id, ::OpenExecutionBatchSchema) where {F} = + _compiled_application_by_id(f, compiled, id) -@generated function _call_prefix_application(compiled, id, ::PreparedExecutionBatchSchema{BT}) where {BT} +@generated function _with_call_batch_application(f::F, compiled, id, ::PreparedExecutionBatchSchema{BT}) where {F,BT} owners = unique(fieldtype(batch, :application) for batch in _prepared_execution_batch_types(BT)) - A = Union{owners...} + branches = [:(application isa $A && return f(application::$A)) for A in owners] return quote application = _compiled_application_by_id(compiled, id) - application isa $A || throw(ArgumentError("A callee application is outside its prepared batch schema.")) - return application::$A + $(branches...) + throw(ArgumentError("A callee application is outside its prepared batch schema.")) end end @@ -4288,7 +4288,7 @@ function _extend_execution_target_call_batches_by_prefix!( _execution_call_batches_match_applications(schema, execution_batches, binding.callee_application_ids) || return false for application_id in binding.callee_application_ids - application = _call_prefix_application(compiled, application_id, schema) + application = _with_call_batch_application(identity, compiled, application_id, schema) application_schema = _call_batch_schema_for_application(schema, application) batches = _execution_call_batches_for_application(schema, application_schema, execution_batches, application_id) diff --git a/test/test-model-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl index c5fd23ebf..82a62d8df 100644 --- a/test/test-model-prepared-call-schemas.jl +++ b/test/test-model-prepared-call-schemas.jl @@ -604,4 +604,41 @@ end assert_same_cells(model, cells) end +@testset "Prepared nested calls retain the application of each template instance" begin + counts = Dict(:root => 0, :middle => 0, :leaf => 0) + plant(name, leaf, seed) = ObjectInstance(name, CompositeModelTemplate(( + ModelSpec(Middle(Dict{Symbol,Any}(), counts); name=:branch, on=One(scale=:Plant), + calls=(leaf=One(scale=:Leaf, within=Subtree(), application=:leaf),)), + ModelSpec(Leaf(Xoshiro(seed), counts); name=:leaf, on=One(scale=:Leaf)), + )); root=Object(name; scale=:Plant, parent=:scene), + objects=(Object(leaf; scale=:Leaf, parent=name),)) + scene = CompositeModel(Object(:scene; scale=:Scene), plant(:east, :east_leaf, 3), + plant(:west, :west_leaf, 7); applications=( + ModelSpec(Root(Ref{Any}(nothing), counts); name=:top, on=One(id=:scene), + calls=(middle=Many(scale=:Plant, within=SceneScope(), process=:cold_schema_activation_middle),)),)) + sim = run!(scene; steps=0, outputs=:none) + function prepared(call) + observed = PSE._materialize_call_execution_batches!(call) + types = unique(typeof.(observed)) + schema = PSE.PreparedExecutionBatchSchema{Vector{Union{types...}}}() + return PSE._compiled_call_execution_batches(call.compiled, call.environment_bindings, + call.binding, call.temporal_streams, call.output_retention, call.constants; + cohort_schema=PSE._execution_cohort_schema(schema), batch_schema=schema) + end + applications = sim.compiled.applications_by_id + @test typeof(applications[:east__leaf]) === typeof(applications[:west__leaf]) + @test applications[:east__leaf] !== applications[:west__leaf] + branches = PSE._materialize_call_execution_batches!(call_targets(root_target(sim).context, :middle)) + @test Set(b.application.id for b in branches) == Set((:east__branch, :west__branch)) + for branch in branches + row = only(branch.targets) + east = row.object_id == ObjectId(:east) + leaf = only(prepared(call_targets(row.context, :leaf))) + @test leaf.application === applications[east ? :east__leaf : :west__leaf] + @test only(leaf.targets).object_id == ObjectId(east ? :east_leaf : :west_leaf) + @test only(leaf.targets).status_view.canonical_status === + model_status(scene, east ? :east_leaf : :west_leaf) + end +end + end # module ColdCallSchemaActivationChecks From 844f259b3c7d1fd815173626378f0cc8a2323fde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 10:55:32 +0100 Subject: [PATCH 309/324] Copy occupied status fields by their prepared reference types --- src/component_models/Status.jl | 68 +++++++++++++++++++++++-------- test/test-status-fixed-storage.jl | 4 ++ 2 files changed, 54 insertions(+), 18 deletions(-) diff --git a/src/component_models/Status.jl b/src/component_models/Status.jl index 17ffa31e6..2457259ed 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -248,31 +248,63 @@ function Status(nt::NamedTuple{names}) where {names} end _status_vars(status) = getfield(status, :vars) -# Read or transform each concrete reference before selecting the currently -# present fields. A present reference may itself contain nothing. -# Preserve each slot type for wide prepared layouts without tuple-map widening. +# A standalone status owns a dense, statically named tuple of references. _map_status_slots(::typeof(identity), slots::NamedTuple) = slots @generated function _map_status_slots(f::F, slots::NamedTuple{names}) where {F,names} - fields = [:(let slot = getfield(slots, $i) - isnothing(slot) ? nothing : f(slot) - end) for i in 1:length(names)] - data = Expr(:tuple, fields...) - return :(NamedTuple{$(QuoteNode(names))}($data)) + fields = Expr(:tuple, [:(f(getfield(slots, $i))) for i in eachindex(names)]...) + return :(NamedTuple{$(QuoteNode(names))}($fields)) +end + +# A prepared namespace may be wide and sparsely populated. Compile the operation +# for each distinct reference type and read the occupied positions in field order. +@generated function _status_cell_families(::Type{S}) where {S<:NamedTuple} + types = unique(T for slot in fieldtypes(S) for T in Base.uniontypes(slot) if T !== Nothing) + return :(Tuple{$(types...)}) +end + +# Box the directory once so the compiler can call the same traversal for status +# layouts with hundreds of different names and the same reference types. +struct _StatusReferenceDirectory + slots::NamedTuple +end + +@generated function _append_status_cell!( + items::Vector{Any}, f::F, directory::_StatusReferenceDirectory, index::Int, ::Type{R}, +) where {F,R<:Tuple} + branches = [:(if reference isa $T + push!(items, f(reference::$T)) + return true + end) for T in fieldtypes(R)] + return quote + reference = getfield(directory.slots, index) + isnothing(reference) && return false + $(branches...) + throw(ArgumentError("Invalid prepared status reference.")) + end +end + +function _map_present_status_fields( + f::F, ::Type{T}, directory::_StatusReferenceDirectory, namespace::NTuple{N,Symbol}, ::Type{R}, +) where {F,T,N,R<:Tuple} + names = Symbol[] + items = Any[] + for index in eachindex(namespace) + present = _append_status_cell!(items, f, directory, index, R) + present && T === NamedTuple && push!(names, namespace[index]) + end + data = Tuple(items) + return T === Tuple ? data : NamedTuple{Tuple(names)}(data) end function _map_status_fields(f::F, ::Type{T}, status::Status) where {F,T} - fields = _map_status_slots(f, _status_reference_slots(status)) - names = keys(status) - if names === keys(fields) + storage = _status_vars(status) + if storage isa NamedTuple + fields = _map_status_slots(f, storage) return T === Tuple ? Tuple(fields) : fields end - selected = Vector{Any}(undef, length(names)) - for i in eachindex(names) - selected[i] = getfield(fields, names[i]) - end - data = Tuple(selected) - T === Tuple && return data - return Base.@inline NamedTuple{names}(data) + slots = _status_reference_slots(storage) + return _map_present_status_fields(f, T, _StatusReferenceDirectory(slots), keys(slots), + _status_cell_families(typeof(slots))) end _status_namedtuple(status) = _map_status_fields(getindex, NamedTuple, status) diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl index 5595a379e..d4f45a29f 100644 --- a/test/test-status-fixed-storage.jl +++ b/test/test-status-fixed-storage.jl @@ -132,11 +132,15 @@ end recipe = PSE._CanonicalStatusRecipe(state, true) epoch = PSE._status_reference_epoch(state) shared = Ref(4f0) + @test NamedTuple(state) === NamedTuple() for name in (last(names), first(names), names[80]) PSE._status_recipe_set_reference!(recipe, name, shared) end @test PSE._finish_canonical_status_recipe!(recipe) === state @test keys(state) == (first(names), names[80], last(names)) + @test Tuple(state) === (4f0, 4f0, 4f0) + @test NamedTuple(state) === NamedTuple{(names[1], names[80], names[160])}((4f0, 4f0, 4f0)) + @test PSE.refvalues(state) === (shared, shared, shared) @test all(name -> PSE.refvalue(state, name) === shared, keys(state)) @test PSE._status_reference_epoch(state) == epoch + 1 PSE._finish_canonical_status_recipe!(recipe) From 2c0554aa44fb728bc94f1572dc312544f329cbc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 11:21:18 +0100 Subject: [PATCH 310/324] Exercise the shared application lookup in prefix growth tests --- test/test-model-finite-call-extension-intents.jl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/test-model-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl index 8881da941..00d54c3c4 100644 --- a/test/test-model-finite-call-extension-intents.jl +++ b/test/test-model-finite-call-extension-intents.jl @@ -233,8 +233,9 @@ end if prepared schema = call_targets(target.context, :a).batch_schema compiled = simulation.compiled - @test PSE._call_prefix_application(compiled, :leaf_a, schema) === compiled.applications_by_id[:leaf_a] - @test_throws ArgumentError PSE._call_prefix_application(compiled, :root, schema) + leaf = PSE._with_call_batch_application(identity, compiled, :leaf_a, schema) + @test leaf === compiled.applications_by_id[:leaf_a] + @test_throws ArgumentError PSE._with_call_batch_application(identity, compiled, :root, schema) end add_leaves!(data) @test extend!(:prefix, target, refreshed_owners(data), simulation) === true From fe83c0d576ba0d1dac650199255f77bd33c92a85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 13:08:37 +0100 Subject: [PATCH 311/324] Store shared Many bindings while their concrete slot type is known --- src/composite_model/compilation.jl | 38 +++++++++---------- .../lifecycle_input_changes.jl | 38 +++++++++---------- test/test-model-input-binding-storage.jl | 33 ++++++++++++++++ 3 files changed, 70 insertions(+), 39 deletions(-) diff --git a/src/composite_model/compilation.jl b/src/composite_model/compilation.jl index 47e60cb7a..14d4668f6 100644 --- a/src/composite_model/compilation.jl +++ b/src/composite_model/compilation.jl @@ -3148,15 +3148,10 @@ function _compile_consumer_input_plan!( consumer_id, applications_by_object, applications_by_id, distributed_outputs, many_binding_cache, performance, query_cache, ) - if !isnothing(many_binding_cache) - shared_binding = _shared_many_input_binding( - many_binding_cache, model, plan, consumer_id, - ) - if !isnothing(shared_binding) - _push_shared_many_input!(bindings, shared_binding) - _runtime_performance_count!(performance, :many_input_binding_precompile_reuses) - return nothing - end + if !isnothing(many_binding_cache) && + _try_push_shared_many_input!(bindings, many_binding_cache, model, plan, consumer_id) + _runtime_performance_count!(performance, :many_input_binding_precompile_reuses) + return nothing end _resolve_materialize_input_route!( bindings, model, application_id, application_process, consumer_id, plan, @@ -3408,24 +3403,27 @@ function _binding_with_shared_many_sources( binding.carrier_hint, canonical.carrier) end -function _shared_many_input_binding(cache::_ManyInputBindingCache, - model::CompositeModel, plan::CompiledModelInputPlan, consumer_id::ObjectId, +function _try_push_shared_many_input!(destination, cache::_ManyInputBindingCache, + model::CompositeModel, plan::CompiledModelInputPlan, consumer_id::ObjectId, additions=nothing, ) key = _many_binding_plan_share_key(model, plan, consumer_id) - isnothing(key) && return nothing + isnothing(key) && return false canonical = get(cache.by_plan, key, nothing) - isnothing(canonical) && return nothing - return Base.@inline _with_model_input_binding(_shared_many_binding_for_plan, - cache.bindings, canonical, plan, consumer_id) + isnothing(canonical) && return false + return Base.@inline _with_model_input_binding(_push_admitted_shared_many_input!, + cache.bindings, canonical, destination, model, plan, consumer_id, additions) end -function _shared_many_binding_for_plan(canonical, plan, consumer_id) - canonical.plan.slot == plan.slot || return nothing - canonical.multiplicity == :many || return nothing - isnothing(canonical.carrier) && return nothing - return CompiledModelInputBinding(plan, consumer_id, canonical.source_ids, +function _push_admitted_shared_many_input!(canonical, destination, model, plan, consumer_id, additions) + canonical.plan.slot == plan.slot || return false + canonical.multiplicity == :many || return false + isnothing(canonical.carrier) && return false + _accept_shared_many_sources(additions, canonical, model, plan, consumer_id) || return false + shared = CompiledModelInputBinding(plan, consumer_id, canonical.source_ids, canonical.source_application_ids, canonical.policy, canonical.carrier_hint, canonical.carrier) + _push_shared_many_input!(destination, shared) + return true end function _cache_many_binding_plan!(binding, cache::_ManyInputBindingCache, diff --git a/src/composite_model/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl index 58480989b..4f7077c8e 100644 --- a/src/composite_model/lifecycle_input_changes.jl +++ b/src/composite_model/lifecycle_input_changes.jl @@ -10,29 +10,29 @@ struct _StagedManyInputCache{L,P,I,S} pure_addition::Bool end -function _shared_many_input_binding(staged::_StagedManyInputCache, model, plan, consumer) - shared = _shared_many_input_binding(staged.local_cache, model, plan, consumer) - isnothing(shared) || return shared +function _try_push_shared_many_input!(destination, staged::_StagedManyInputCache, model, plan, consumer) + _try_push_shared_many_input!(destination, staged.local_cache, model, plan, consumer) && return true # A settled source and a single writer keep the prepared Many carrier # family stable on addition. Borrow the cell and recover its final # membership from the live cache after the ordinary refresh has run. staged.pure_addition && (plan.application !== nothing || _input_route_from_status(plan.route) || length(plan.potential_source_application_ids) == 1) || - return nothing - previous = _shared_many_input_binding(staged.published, model, plan, consumer) - isnothing(previous) && return nothing - if isempty(previous.source_ids) - # An empty live group can receive its first column. Check only the - # incoming cells against the existing carrier's admitted element type. - scope = _default_dependency_scope(model, consumer) - R = eltype(parent(previous.carrier)) - for id in staged.added - _selector_matches_object_id(model, plan.matcher, id, consumer, true, scope, false) || continue - ref = _input_source_cell(staged.statuses, model.registry.objects, id, _input_route_source(plan.route)) - ref isa R || return nothing - end + return false + return _try_push_shared_many_input!(destination, staged.published, model, plan, consumer, staged) +end + +_accept_shared_many_sources(::Nothing, canonical, model, plan, consumer) = true +function _accept_shared_many_sources(staged::_StagedManyInputCache, canonical, model, plan, consumer) + isempty(canonical.source_ids) || return true + # The first incoming column must fit the admitted reference element type. + scope = _default_dependency_scope(model, consumer) + R = eltype(parent(canonical.carrier)) + for id in staged.added + _selector_matches_object_id(model, plan.matcher, id, consumer, true, scope, false) || continue + ref = _input_source_cell(staged.statuses, model.registry.objects, id, _input_route_source(plan.route)) + ref isa R || return false end - return previous + return true end struct _PendingStatusInputChanges{B,I} @@ -140,8 +140,8 @@ end _publish_added_consumer_bindings!(recorder, input_bindings, ::Nothing, args...) = nothing function _publish_shared_consumer_input!(binding, destination, cache, model, consumer) - shared = _shared_many_input_binding(cache, model, binding.plan, consumer) - push!(destination, isnothing(shared) ? binding : shared) + _try_push_shared_many_input!(destination, cache, model, binding.plan, consumer) || + push!(destination, binding) return nothing end diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 8b004233a..26860176a 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -152,6 +152,39 @@ end identity, incomplete, control.future) end +@testset "First leaf carries a different reference from the published empty Many" begin + data = fixture() + simulation = prepare(data.model) + id = PSE.ObjectId(:leaf_first) + leaf = birth!(data.model, :leaf_first, 7.0) + reader = PSE.ObjectId(:a) + live = binding(simulation, :a, :values) + @test isempty(live.source_ids) && isempty(parent(live.carrier)) + @test eltype(parent(live.carrier)) === Base.RefValue{Float64} + # The two statuses supply real fixed storage with different numerical families. + # Feed each proposed first column through the same cache query and scope. + statuses = PSE._output_status_preparation(data.model) + existing = simulation.compiled.many_input_binding_cache + destinations = similar(simulation.compiled.input_bindings, 0) + scratch = PSE._empty_many_input_binding_cache(keytype(data.model.registry.objects), destinations) + staged = PSE._StagedManyInputCache(scratch, existing, [id], statuses, true) + statuses.recipes[id] = PSE._CanonicalStatusRecipe(PSE.model_status(data.model, :anchor), false) + @test PSE._input_source_cell(statuses, data.model.registry.objects, id, :x) isa Base.RefValue{Float32} + @test !PSE._try_push_shared_many_input!(destinations, staged, data.model, live.plan, reader) + @test isempty(destinations) && isempty(live.source_ids) && isempty(parent(live.carrier)) + @test isempty(staged.local_cache.by_plan) + statuses.recipes[id] = PSE._CanonicalStatusRecipe(PSE.model_status(data.model, id), false) + @test PSE._input_source_cell(statuses, data.model.registry.objects, id, :x) === leaf + @test PSE._try_push_shared_many_input!(destinations, staged, data.model, live.plan, reader) + reused = only(destinations) + @test reused.carrier === live.carrier + @test reused.source_ids === live.source_ids + @test reused.source_application_ids === live.source_application_ids + step!(simulation) + @test only(parent(binding(simulation, :a, :values).carrier)) === leaf + @test PSE.model_status(data.model, :a).total == 10.0 +end + @testset "direct Many extension stages every admitted reference before committing" begin data = fixture() simulation = prepare(data.model) From 9f1dd76e2c4fa75523f7b99d594674e0d3568245 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 13:42:09 +0100 Subject: [PATCH 312/324] Resolve the live shared binding before publishing a new consumer --- .../lifecycle_input_changes.jl | 26 +++++--- test/test-model-input-binding-storage.jl | 60 +++++++++++++++++++ 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/src/composite_model/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl index 4f7077c8e..e461b592b 100644 --- a/src/composite_model/lifecycle_input_changes.jl +++ b/src/composite_model/lifecycle_input_changes.jl @@ -139,10 +139,15 @@ end _publish_added_consumer_bindings!(recorder, input_bindings, ::Nothing, args...) = nothing -function _publish_shared_consumer_input!(binding, destination, cache, model, consumer) - _try_push_shared_many_input!(destination, cache, model, binding.plan, consumer) || - push!(destination, binding) - return nothing +_shared_consumer_plan_key(binding, model, consumer) = + _many_binding_plan_share_key(model, binding.plan, consumer) + +function _republish_cached_many_input!(canonical, destination, previous::_UnadmittedInputBinding, model, consumer) + plan = getfield(previous.binding, :plan) + # The slot identifies one immutable plan in the prepared scenario. Its + # carrier may change during refresh, while the consumer keeps that plan. + plan isa typeof(canonical.plan) || return false + return _push_admitted_shared_many_input!(canonical, destination, model, plan, consumer, nothing) end function _publish_added_consumer_bindings!(recorder, input_bindings, staged::_StagedConsumerBindings, @@ -151,11 +156,16 @@ function _publish_added_consumer_bindings!(recorder, input_bindings, staged::_St for index in range binding = staged.entries[index] if index in staged.reused - _with_model_input_binding(_publish_shared_consumer_input!, staged.entries, - binding, input_bindings, many_binding_cache, model, consumer) - else - push!(input_bindings, binding) + key = _with_model_input_binding(_shared_consumer_plan_key, staged.entries, + binding, model, consumer) + canonical = isnothing(key) ? nothing : get(many_binding_cache.by_plan, key, nothing) + if !isnothing(canonical) && + _with_model_input_binding(_republish_cached_many_input!, many_binding_cache.bindings, + canonical, input_bindings, _UnadmittedInputBinding(binding), model, consumer) + continue + end end + push!(input_bindings, binding) end _record_consumer_input_bindings!(recorder, input_bindings, id, consumer, previous_binding_count + first(range), previous_binding_count + last(range)) diff --git a/test/test-model-input-binding-storage.jl b/test/test-model-input-binding-storage.jl index 26860176a..6d35b145e 100644 --- a/test/test-model-input-binding-storage.jl +++ b/test/test-model-input-binding-storage.jl @@ -185,6 +185,66 @@ end @test PSE.model_status(data.model, :a).total == 10.0 end +@testset "Publishing a staged Many uses the current shared source or its admitted row" begin + data = fixture() + ordinary = prepare(data.model) + rows = ordinary.compiled.input_bindings + prototype = PSE._prepared_input_bindings(length(ordinary.compiled.scenario_plan.input_plans), + [(row.plan.slot, typeof(row)) for row in rows]) + data = fixture() + simulation = prepare(data.model, prototype) + leaf = birth!(data.model, :leaf_first, 7.0) + step!(simulation) + reader = ObjectId(:b) + previous = binding(simulation, :b, :values) + @test only(parent(previous.carrier)) === leaf + destination = similar(simulation.compiled.input_bindings, 0) + entries = similar(destination, 0) + cache = simulation.compiled.many_input_binding_cache + local_cache = PSE._empty_many_input_binding_cache(keytype(data.model.registry.objects), entries) + statuses = PSE._output_status_preparation(data.model) + staged_cache = PSE._StagedManyInputCache(local_cache, cache, [ObjectId(:leaf_first)], statuses, true) + staged = PSE._StagedConsumerBindings(entries, statuses, [(:reader, reader, 1:2)], staged_cache, + data.model, nothing, true) + @test PSE._try_push_shared_many_input!(staged, staged_cache, data.model, previous.plan, reader) + @test only(staged.reused) == 1 + @test only(entries).carrier === previous.carrier + prefix = binding(simulation, :a, :single) + tail = binding(simulation, :b, :single) + push!(entries, tail) + push!(destination, prefix) + + # A refresh can assign new storage while keeping the same leaf references. + canonical = PSE.CompiledModelInputBinding(previous.plan, ObjectId(:a), copy(previous.source_ids), + copy(previous.source_application_ids), previous.policy, previous.carrier_hint, + PSE.RefVector(copy(parent(previous.carrier)))) + key = PSE._many_binding_plan_share_key(data.model, previous.plan, reader) + cache.by_plan[key] = canonical + PSE._publish_added_consumer_bindings!(nothing, destination, staged, data.model, cache, 0) + @test length(destination) == 3 + @test first(destination) === prefix + @test last(destination) === tail + published = destination[2] + @test published.consumer_id == reader + @test published.plan === previous.plan + @test published.carrier === canonical.carrier + @test published.source_ids === canonical.source_ids + @test published.source_application_ids === canonical.source_application_ids + @test published.carrier !== previous.carrier + @test only(parent(published.carrier)) === leaf + + delete!(cache.by_plan, key) + empty!(destination) + push!(destination, prefix) + PSE._publish_added_consumer_bindings!(nothing, destination, staged, data.model, cache, 0) + @test length(destination) == 3 + @test first(destination) === prefix + @test last(destination) === tail + @test destination[2] === first(entries) + @test destination[2].source_ids === previous.source_ids + @test destination[2].consumer_id == reader +end + @testset "direct Many extension stages every admitted reference before committing" begin data = fixture() simulation = prepare(data.model) From d0d6a94bfce9bf4e4d2481ed067d0223cfa901c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sat, 21 Nov 2026 23:07:10 +0100 Subject: [PATCH 313/324] Resolve changed manual call targets through typed slots [skip ci] --- src/composite_model/runtime_outputs.jl | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 98b549f6c..cd744a18b 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -4148,8 +4148,10 @@ function _model_execution_target_change_reason( target.call_bindings_signature == _call_bindings_signature(target.call_bindings) || return :call_bindings - if any(binding -> _manual_call_binding_has_changed_target(binding,compiled), - target.call_bindings) + for slot in eachindex(target.call_bindings) + Base.@inline _with_metadata_entry( + _manual_call_binding_has_changed_target, target.call_bindings, slot, compiled, + ) || continue context = target.context # Delta markers describe changes entering this compiled owner. A child # already prepared against that exact owner must not replay the delta. @@ -4160,6 +4162,7 @@ function _model_execution_target_change_reason( target.output_targets,target.call_bindings,temporal_streams, output_retention,context.constants) current || return :call_bindings + break end return nothing end From 8fa2404914e669b874f861592b88baff1fc2ba85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 03:32:39 +0100 Subject: [PATCH 314/324] Use typed private copies for retained output samples [skip ci] --- src/composite_model/runtime_outputs.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index cd744a18b..fdf513787 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2191,8 +2191,8 @@ end end # A model may update an array or a nested mutable value in place on its next # execution. Published history must remain independent of that live state. - # `deepcopy` leaves scalar/isbits values unchanged. - push!(samples, (sample_time, copy_value ? deepcopy(value) : value)) + # Use the same private copy as for temporal inputs. + push!(samples, (sample_time, copy_value ? _private_initial_value(value) : value)) return samples end From a6b78557786ce532182e08835a17b074b40bd63e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 07:19:22 +0100 Subject: [PATCH 315/324] Publish typed output tuples without rebuilding their tails [skip ci] --- src/composite_model/runtime_outputs.jl | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index fdf513787..8dd38e026 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2261,15 +2261,15 @@ end return nothing end -@inline _model_publish_runtime_outputs!(::Tuple{}, time::Real) = nothing - -@inline function _model_publish_runtime_outputs!( - outputs::Tuple, - time::Real, -) - _model_publish_runtime_output!(first(outputs), time) - _model_publish_runtime_outputs!(Base.tail(outputs), time) - return nothing +# Select each admitted output by its slot so publication keeps concrete +# types for wide heterogeneous tuples without constructing successive tails. +@generated function _model_publish_runtime_outputs!(outputs::T, time::Real) where {T<:Tuple} + calls = [:(_model_publish_runtime_output!(getfield(outputs, $slot), time)) + for slot in 1:fieldcount(T)] + return quote + $(calls...) + nothing + end end function _model_latest_sample(samples, time::Real) From e49415ce3148e0efc33dfbfc645beba58610b034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 07:19:22 +0100 Subject: [PATCH 316/324] Keep time-step table environment lookups concrete [skip ci] --- src/time/runtime/environment_backends.jl | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index 8a128fd0e..36827a726 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -231,10 +231,21 @@ function sample(backend::AbstractEnvironmentBackend, handle, state, variable::Sy ) end +@inline _environment_row_hasproperty(row, variable::Symbol) = hasproperty(row, variable) + +@inline function _environment_row_hasproperty(row::PlantMeteo.TimeStepRow, variable::Symbol) + # The row's column tuple stores its symbols without fixing the arity. + names = propertynames(row) + for index in 1:nfields(names) + getfield(names, index) === variable && return true + end + return false +end + function sample(backend::GlobalConstant, handle, variable::Symbol, time) source = _environment_row_at_step(environment_source(backend), Int(round(time))) isnothing(source) && return nothing - hasproperty(source, variable) || error( + _environment_row_hasproperty(source, variable) || error( "GlobalConstant source does not provide variable `$(variable)`." ) return getproperty(source, variable) @@ -243,7 +254,7 @@ end function sample(backend::GlobalConstant, handle, state, variable::Symbol, time) source = _environment_row_at_step(state, Int(round(time))) isnothing(source) && return nothing - hasproperty(source, variable) || error( + _environment_row_hasproperty(source, variable) || error( "Transient GlobalConstant state does not provide variable `$(variable)`." ) return getproperty(source, variable) From 3fed540f50c051dd107a9778336f604ffbb62d2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 07:44:27 +0100 Subject: [PATCH 317/324] Copy packed boolean values before retaining samples [skip ci] --- src/input_schema.jl | 1 + 1 file changed, 1 insertion(+) diff --git a/src/input_schema.jl b/src/input_schema.jl index 7ba17aca7..6af847d59 100644 --- a/src/input_schema.jl +++ b/src/input_schema.jl @@ -40,6 +40,7 @@ function _input_default(declaration::Default) end _private_initial_value(value) = deepcopy(value) +_private_initial_value(value::BitArray) = copy(value) function _private_initial_value(value::Array{T}) where {T} # Bits values and interned symbols keep their identities under deepcopy. From 2dbaf6538a652026b05172adba5f6c2cd34de528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 10:40:18 +0100 Subject: [PATCH 318/324] Keep evaluated call snapshots typed during validation [skip ci] Reuse the concrete owner type on prepared call collections and read the lifecycle generation before storing the snapshot in its reusable frame. The exact accepted model owner and all stale-token checks are preserved. --- src/composite_model/call_evaluations.jl | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/composite_model/call_evaluations.jl b/src/composite_model/call_evaluations.jl index ba3feae2a..4b090e481 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -130,8 +130,9 @@ function _begin_call_evaluation!(frame, compiled, time, permission) frame.model_revision = compiled.model.revision frame.runtime_revision = compiled.model.runtime_revision frame.environment_revision = compiled.model.environment_revision - frame.lifecycle_delta = lifecycle_delta(compiled.model) - frame.lifecycle_generation = frame.lifecycle_delta.mutation_generation + delta = lifecycle_delta(compiled.model) + frame.lifecycle_delta = delta + frame.lifecycle_generation = delta.mutation_generation frame.binding_flags = (compiled.model.bindings_dirty, compiled.model.environment_bindings_dirty) frame.execution_generation = compiled.execution_generation frame.time = time @@ -253,13 +254,18 @@ end @noinline _call_execution_matches(stamp::Base.RefValue{UInt64}, executions::IdDict{Base.RefValue{UInt64},UInt64}) = stamp[] == executions[stamp] +@inline _evaluation_compiled(frame::CallEvaluationFrame, targets) = frame.compiled + +@inline _evaluation_compiled(frame::CallEvaluationFrame, ::CallTargets{CS}) where {CS} = + frame.compiled::CS + function _validate_call_evaluation(evaluation::CallEvaluation) frame = evaluation.frame frame.task_identity === _call_evaluation_task_identity!() || throw(ArgumentError("Accept a call evaluation on its originating task.")) frame.pending && frame.generation == evaluation.generation || throw(ArgumentError("Call evaluation is stale or has already been accepted.")) - _validate_call_model_state(frame, frame.compiled) + _validate_call_model_state(frame, _evaluation_compiled(frame, evaluation.targets)) for stamp in keys(frame.executions) _call_execution_matches(stamp, frame.executions) || throw(ArgumentError("Call evaluation is stale after another execution of its targets.")) From 48b771cd0fcab6b46fef735905f8250ff168f655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 11:04:32 +0100 Subject: [PATCH 319/324] Commit environment updates through the typed binding [skip ci] Keep the prepared backend and handle concrete through validation and commit or capture. The same resolved binding, publication permission, and errors apply to immediate and deferred publication. --- src/composite_model/runtime_outputs.jl | 64 ++++++++++++-------------- 1 file changed, 29 insertions(+), 35 deletions(-) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 8dd38e026..dac56bc4a 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -1801,12 +1801,17 @@ end _compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) = _compiled_application_by_id(identity, compiled, id) -function _environment_binding_for(env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId) +@inline function _environment_binding_for( + f::F, env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId, +) where {F} binding = get(env_bindings.by_target, (application_id, object_id), nothing)::Union{Nothing,CompiledEnvironmentBinding} - isnothing(binding) && return nothing - return _with_environment_binding(identity, env_bindings.environment_schema, binding) + isnothing(binding) && return f(nothing) + return _with_environment_binding(f, env_bindings.environment_schema, binding) end +_environment_binding_for(env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId) = + _environment_binding_for(identity, env_bindings, application_id, object_id) + function _model_object_status(model::CompositeModel, object_id::ObjectId) status = model_status(model, object_id) status isa Status || error( @@ -6532,23 +6537,6 @@ function _selected_topology_call_targets(resolved_binding, cached_targets, conte ) end -function _environment_binding_for_current_context(context::RunContext) - binding = _environment_binding_for( - context.environment_bindings, - context.application.id, - context.object_id, - ) - if isnothing(binding) || isnothing(binding.backend) - error( - "Cannot commit environment state for `$(context.application.id)` on object ", - "`$(_object_id_text(context.object_id))`: no environment binding is configured. ", - "Attach an environment with `CompositeModel(...; environment=...)` and ", - "`ModelSpec(model; environment=Environment(...))`." - ) - end - return binding -end - function _validate_environment_commit(context::RunContext, state) declared = _model_environment_output_names(context.application) isempty(declared) && error( @@ -6558,7 +6546,7 @@ function _validate_environment_commit(context::RunContext, state) missing = Symbol[variable for variable in declared if !hasproperty(state, variable)] isempty(missing) || error( "Environment state committed by application `$(context.application.id)` is missing ", - "declared `environment_outputs_` variable(s) `$(Tuple(missing))`.", + "declared `environment_outputs_` variable(s) `$(_diagnostic_symbol_list(missing; as_tuple=true))`.", ) return nothing end @@ -6576,21 +6564,27 @@ hard call. Trial environment states should instead be passed to """ function commit_environment!(context::RunContext, state) context.publication_allowed || return nothing - binding = _environment_binding_for_current_context(context) - _validate_environment_commit(context, state) - frame = _active_call_evaluation() - if frame !== nothing - push!(frame.events, CapturedEnvironmentCommit( - binding.backend, binding.handle, deepcopy(state), context.time, - )) - return nothing + return _environment_binding_for( + context.environment_bindings, context.application.id, context.object_id, + ) do binding + if isnothing(binding) || isnothing(binding.backend) + error( + "Cannot commit environment state for `$(context.application.id)` on object ", + "`$(_object_id_text(context.object_id))`: no environment binding is configured. ", + "Attach an environment with `CompositeModel(...; environment=...)` and ", + "`ModelSpec(model; environment=Environment(...))`.", + ) + end + _validate_environment_commit(context, state) + frame = _active_call_evaluation() + if frame !== nothing + push!(frame.events, CapturedEnvironmentCommit( + binding.backend, binding.handle, deepcopy(state), context.time, + )) + return nothing + end + return commit_environment!(binding.backend, binding.handle, state, context.time) end - return commit_environment!( - binding.backend, - binding.handle, - state, - context.time, - ) end function commit_environment!(context, state) From ff49aad7d1c4ea4220b2bb51c56cdec7eb886b49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 11:23:03 +0100 Subject: [PATCH 320/324] Preserve typed distributed output validation [skip ci] Use the known destination identity type and validate each named source column directly. Render declared symbols through the existing formatter while preserving mixed identifiers, error order, and atomic assignment. --- src/composite_model/output_targets.jl | 73 ++++++++++++++++++-------- src/composite_model/runtime_outputs.jl | 12 +++-- 2 files changed, 59 insertions(+), 26 deletions(-) diff --git a/src/composite_model/output_targets.jl b/src/composite_model/output_targets.jl index dd02aa618..2eba99e0c 100644 --- a/src/composite_model/output_targets.jl +++ b/src/composite_model/output_targets.jl @@ -118,7 +118,13 @@ end function _output_target_context(targets::OutputTargets) binding = getfield(targets, :binding) - return "application `$(binding.application_id)`, output variables `$(propertynames(targets.columns))`" + names = _diagnostic_symbol_list(propertynames(targets.columns); as_tuple=true) + return "application `$(binding.application_id)`, output variables `$(names)`" +end + +_output_coverage_ids_text(ids) = string([id.value for id in ids]) +function _output_coverage_ids_text(ids::Vector{ObjectId{Symbol}}) + return _diagnostic_symbol_list(Symbol[id.value for id in ids]) end function _output_table_columns( @@ -171,21 +177,43 @@ function _validate_output_table_columns( return nothing end -function _validate_output_column_lengths( +@inline function _validate_output_column_length(targets, name::Symbol, column, row_count) + column_count = length(column) + column_count == row_count || throw( + DimensionMismatch( + "Output column `$(name)` for $(_output_target_context(targets)) " * + "has $(column_count) rows, but the ID column has $(row_count).", + ), + ) + return nothing +end + +@generated function _validate_output_column_lengths( targets::OutputTargets, ids, - columns::NamedTuple, -) - row_count = length(ids) - for (name, column) in pairs(columns) - length(column) == row_count || throw( - DimensionMismatch( - "Output column `$(name)` for $(_output_target_context(targets)) " * - "has $(length(column)) rows, but the ID column has $(row_count).", - ), - ) + columns::NamedTuple{Names}, +) where {Names} + checks = [ + :(_validate_output_column_length( + targets, $(QuoteNode(name)), getfield(columns, $index), row_count, + )) + for (index, name) in enumerate(Names) + ] + return quote + row_count = length(ids) + $(checks...) + return row_count end - return row_count +end + +# Exact prepared identities can retain their type throughout the diagnostic. +# An open or differently typed ID column still accepts arbitrary identities. +_output_coverage_id_type(ids, target_ids) = ObjectId +function _output_coverage_id_type( + ::AbstractVector{ObjectId{T}}, + ::AbstractVector{ObjectId{T}}, +) where {T} + return isconcretetype(T) ? ObjectId{T} : ObjectId end function _output_coverage_error( @@ -194,21 +222,22 @@ function _output_coverage_error( ) binding = getfield(targets, :binding) target_ids = binding.destination_ids - row_ids = ObjectId[ObjectId(id) for id in ids] - counts = Dict{ObjectId,Int}() + ID = _output_coverage_id_type(ids, target_ids) + row_ids = ID[ObjectId(id) for id in ids] + counts = Dict{ID,Int}() sizehint!(counts, length(row_ids)) for object_id in row_ids counts[object_id] = get(counts, object_id, 0) + 1 end - duplicate_ids = ObjectId[ + duplicate_ids = ID[ object_id for (object_id, count) in counts if count > 1 ] - unknown_ids = ObjectId[ + unknown_ids = ID[ object_id for object_id in keys(counts) if !haskey(binding.destination_index, object_id) ] - missing_ids = ObjectId[ + missing_ids = ID[ object_id for object_id in target_ids if !haskey(counts, object_id) ] @@ -221,21 +250,21 @@ function _output_coverage_error( extra_ids = isempty(unknown_ids) ? duplicate_ids : unknown_ids push!( details, - "extra result ID(s) `$([id.value for id in extra_ids])`", + "extra result ID(s) `$(_output_coverage_ids_text(extra_ids))`", ) elseif !isempty(unknown_ids) push!( details, - "unknown result ID(s) `$([id.value for id in unknown_ids])`", + "unknown result ID(s) `$(_output_coverage_ids_text(unknown_ids))`", ) end isempty(duplicate_ids) || push!( details, - "duplicate result ID(s) `$([id.value for id in duplicate_ids])`", + "duplicate result ID(s) `$(_output_coverage_ids_text(duplicate_ids))`", ) isempty(missing_ids) || push!( details, - "missing destination ID(s) `$([id.value for id in missing_ids])`", + "missing destination ID(s) `$(_output_coverage_ids_text(missing_ids))`", ) isempty(details) && push!( details, diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index dac56bc4a..3daef8948 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -415,7 +415,7 @@ end "Application `$(context.application.id)` on object " * "`$(_object_id_text(context.object_id))` has no declared Many input " * "`$(input)`. Available identity-aware inputs: " * - "`$(propertynames(context.bound_inputs))`.", + "`$(_diagnostic_symbol_list(propertynames(context.bound_inputs); as_tuple=true))`.", ), ) return getproperty(context.bound_inputs, input) @@ -462,13 +462,14 @@ end throw(ArgumentError( "Application `$(context.application.id)` on object `$(_object_id_text(context.object_id))` " * "has no distributed output `$(name)`. Available variables: " * - "`$(propertynames(context.output_targets))`.", + "`$(_diagnostic_symbol_list(propertynames(context.output_targets); as_tuple=true))`.", )) end @noinline function _unaligned_distributed_output_targets(context, variables) + names = _diagnostic_symbol_list(variables; as_tuple=true) throw(ArgumentError( - "Distributed outputs `$(variables)` on application `$(context.application.id)` " * + "Distributed outputs `$(names)` on application `$(context.application.id)` " * "have different destination ObjectIds. Request separate output target views.", )) end @@ -5780,7 +5781,10 @@ end return _missing_named_call(context, name, available) end -function _diagnostic_symbol_list(names::Vector{Symbol}; as_tuple=false) +function _diagnostic_symbol_list( + names::Union{Vector{Symbol},Tuple{Vararg{Symbol}}}; + as_tuple=false, +) isempty(names) && return as_tuple ? "()" : "Symbol[]" io = IOBuffer() print(io, as_tuple ? '(' : '[') From a3ca0754fcde4fb6fd203cd45f551c8ae261ec85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 11:51:24 +0100 Subject: [PATCH 321/324] Share typed traversal of immediate and evaluated outputs [skip ci] Visit each concrete output slot once, using the same order for publication and for capturing a pending evaluation. Both operations retain their existing history and ownership semantics. --- src/composite_model/call_evaluations.jl | 2 +- src/composite_model/runtime_outputs.jl | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/composite_model/call_evaluations.jl b/src/composite_model/call_evaluations.jl index 4b090e481..e7167de10 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -19,7 +19,7 @@ function _capture_call_output!(frame, output::RuntimeDistributedOutputStream, ti end function _publish_evaluated_call!(frame::CallEvaluationFrame, outputs, context) - for output in outputs + _foreach_runtime_output(outputs) do output _capture_call_output!(frame, output, context.time) end _record_evaluated_call_clock!(frame, context.output_retention, context.application.id, context.time) diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 3daef8948..4a4de30fd 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2269,15 +2269,20 @@ end # Select each admitted output by its slot so publication keeps concrete # types for wide heterogeneous tuples without constructing successive tails. -@generated function _model_publish_runtime_outputs!(outputs::T, time::Real) where {T<:Tuple} - calls = [:(_model_publish_runtime_output!(getfield(outputs, $slot), time)) - for slot in 1:fieldcount(T)] +@generated function _foreach_runtime_output(visit::F, outputs::T) where {F,T<:Tuple} + calls = [:(visit(getfield(outputs, $slot))) for slot in 1:fieldcount(T)] return quote $(calls...) nothing end end +@inline function _model_publish_runtime_outputs!(outputs::Tuple, time::Real) + return _foreach_runtime_output(outputs) do output + _model_publish_runtime_output!(output, time) + end +end + function _model_latest_sample(samples, time::Real) requested_time = float(time) for index in reverse(eachindex(samples)) From aef02a440a6f6aad8f44ec731a131f2f059c3dc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 12:59:57 +0100 Subject: [PATCH 322/324] Keep only publication metadata in captured call outputs [skip ci] --- src/composite_model/call_evaluation_types.jl | 5 +++-- src/composite_model/call_evaluations.jl | 21 ++++++++++++++------ src/composite_model/runtime_outputs.jl | 14 ++++++++----- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/composite_model/call_evaluation_types.jl b/src/composite_model/call_evaluation_types.jl index 3056ffa53..2c1cd6cfa 100644 --- a/src/composite_model/call_evaluation_types.jl +++ b/src/composite_model/call_evaluation_types.jl @@ -1,7 +1,8 @@ abstract type AbstractCallPublicationEvent end -struct CapturedCallOutput{O,S,V} <: AbstractCallPublicationEvent - output::O +struct CapturedCallOutput{S,V} <: AbstractCallPublicationEvent + variable::Symbol + dependency_horizon::Float64 stream::S value::V time::Float64 diff --git a/src/composite_model/call_evaluations.jl b/src/composite_model/call_evaluations.jl index e7167de10..98519fc26 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -6,14 +6,19 @@ end function _capture_call_output!(frame, output::RuntimeOutputStream, time) value = deepcopy(output.reference[]) - push!(frame.events, CapturedCallOutput(output, output.stream, value, time)) + push!(frame.events, CapturedCallOutput( + _runtime_output_variable(output), output.dependency_horizon, output.stream, value, time, + )) return nothing end function _capture_call_output!(frame, output::RuntimeDistributedOutputStream, time) + variable = _runtime_output_variable(output) for index in eachindex(output.references, output.streams) value = deepcopy(output.references[index]) - push!(frame.events, CapturedCallOutput(output, output.streams[index], value, time)) + push!(frame.events, CapturedCallOutput( + variable, output.dependency_horizon, output.streams[index], value, time, + )) end return nothing end @@ -34,8 +39,10 @@ function _evaluated_temporal_source(frame::CallEvaluationFrame, stream::S) where # Build a private read view only when a staged publication affects # this input. Ancestor views are already private and can be reused. source === stream && (source = collect(stream)) - _model_publish_runtime_output_value!(event.output, source, event.value, - event.time; copy_value=false) + _model_publish_runtime_output_value!( + event.variable, event.dependency_horizon, source, event.value, event.time; + copy_value=false, + ) end end return source::Union{S,Vector{eltype(S)}} @@ -280,8 +287,10 @@ function _validate_call_evaluation(evaluation::CallEvaluation) end function _accept_call_event!(event::CapturedCallOutput) - _model_publish_runtime_output_value!(event.output, event.stream, event.value, event.time; - copy_value=false) + _model_publish_runtime_output_value!( + event.variable, event.dependency_horizon, event.stream, event.value, event.time; + copy_value=false, + ) return nothing end diff --git a/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 4a4de30fd..05ed06133 100644 --- a/src/composite_model/runtime_outputs.jl +++ b/src/composite_model/runtime_outputs.jl @@ -2214,7 +2214,8 @@ end end @inline function _model_publish_runtime_output_value!( - output, + variable::Symbol, + dependency_horizon::Float64, stream, value, time::Real, @@ -2222,7 +2223,7 @@ end ) expected_type = fieldtype(eltype(stream), 2) value isa expected_type || error( - "Output `$(_runtime_output_variable(output))` changed value type from ", + "Output `$(variable)` changed value type from ", "`$(expected_type)` to `$(typeof(value))`. CompositeModel temporal ", "streams require a stable output type.", ) @@ -2233,7 +2234,7 @@ end value, ; copy_value=copy_value, ) - _model_prune_dependency_samples!(stream, sample_time, output.dependency_horizon) + _model_prune_dependency_samples!(stream, sample_time, dependency_horizon) return nothing end @@ -2242,7 +2243,8 @@ end time::Real, ) _model_publish_runtime_output_value!( - output, + _runtime_output_variable(output), + output.dependency_horizon, output.stream, output.reference[], time, @@ -2256,9 +2258,11 @@ end ) references = output.references streams = output.streams + variable = _runtime_output_variable(output) @inbounds for index in eachindex(references) _model_publish_runtime_output_value!( - output, + variable, + output.dependency_horizon, streams[index], references[index], time, From 6d94f01295ca1e687c55e9a5ba23f0a91512530b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 13:35:33 +0100 Subject: [PATCH 323/324] Preserve literal weather columns when sampling global forcing [skip ci] --- src/time/runtime/environment_backends.jl | 4 ++-- test/test-environment-backends.jl | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index 36827a726..5ecac8a03 100644 --- a/src/time/runtime/environment_backends.jl +++ b/src/time/runtime/environment_backends.jl @@ -242,7 +242,7 @@ end return false end -function sample(backend::GlobalConstant, handle, variable::Symbol, time) +@inline Base.@constprop :aggressive function sample(backend::GlobalConstant, handle, variable::Symbol, time) source = _environment_row_at_step(environment_source(backend), Int(round(time))) isnothing(source) && return nothing _environment_row_hasproperty(source, variable) || error( @@ -251,7 +251,7 @@ function sample(backend::GlobalConstant, handle, variable::Symbol, time) return getproperty(source, variable) end -function sample(backend::GlobalConstant, handle, state, variable::Symbol, time) +@inline Base.@constprop :aggressive function sample(backend::GlobalConstant, handle, state, variable::Symbol, time) source = _environment_row_at_step(state, Int(round(time))) isnothing(source) && return nothing _environment_row_hasproperty(source, variable) || error( diff --git a/test/test-environment-backends.jl b/test/test-environment-backends.jl index cde75ee09..4b4c3bfe1 100644 --- a/test/test-environment-backends.jl +++ b/test/test-environment-backends.jl @@ -39,3 +39,22 @@ using Dates 1.0, ) end + +@testset "GlobalConstant infers duration from heterogeneous time-step rows" begin + sample_duration(backend, time) = sample(backend, nothing, :duration, time) + sample_duration(backend, state, time) = sample(backend, nothing, state, :duration, time) + + row = ( + date=DateTime(2026, 1, 1), + duration=3600.0, + air_temperature=20.0, + raining=false, + observation_index=1, + source_temperature=22.0, + ) + backend = GlobalConstant(TimeStepTable([row])) + trial = TimeStepTable([merge(row, (duration=1800.0,))]) + + @test (@inferred sample_duration(backend, 1.0)) === 3600.0 + @test (@inferred sample_duration(backend, trial, 1.0)) === 1800.0 +end From f0bde5479bc437d53ea7188df03e9b00013959be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Vezy?= Date: Sun, 22 Nov 2026 14:55:21 +0100 Subject: [PATCH 324/324] Use the prepared weather row lookup for simulation clocks [skip ci] --- src/time/runtime/clocks.jl | 2 +- test/test-environment-backends.jl | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/time/runtime/clocks.jl b/src/time/runtime/clocks.jl index f524b556c..40f913926 100644 --- a/src/time/runtime/clocks.jl +++ b/src/time/runtime/clocks.jl @@ -140,7 +140,7 @@ function _base_step_seconds_from_environment_row( require_duration::Bool=false, context::String="environment", ) - if hasproperty(row, :duration) + if _environment_row_hasproperty(row, :duration) duration = getproperty(row, :duration) seconds = _duration_to_seconds(duration) !isnothing(seconds) && return seconds diff --git a/test/test-environment-backends.jl b/test/test-environment-backends.jl index 4b4c3bfe1..b426ec0df 100644 --- a/test/test-environment-backends.jl +++ b/test/test-environment-backends.jl @@ -58,3 +58,27 @@ end @test (@inferred sample_duration(backend, 1.0)) === 3600.0 @test (@inferred sample_duration(backend, trial, 1.0)) === 1800.0 end + +@testset "GlobalConstant reads the base step from time-step table rows" begin + for (duration, seconds) in ( + (1800.5, 1800.5), + (Minute(30), 1800.0), + (Dates.CompoundPeriod(Minute(30), Second(1)), 1801.0), + ) + forcing = TimeStepTable([(T=20.0, duration=duration, raining=false)]) + @test base_step_seconds(GlobalConstant(forcing)) === seconds + end + + @test_throws "Missing required `duration` in environment." base_step_seconds( + GlobalConstant(TimeStepTable([(T=20.0, raining=false)])), + ) + @test_throws "Invalid duration `nothing` in environment." base_step_seconds( + GlobalConstant(TimeStepTable([(T=20.0, duration=nothing)])), + ) + @test_throws "Invalid duration `missing` in environment." base_step_seconds( + GlobalConstant(TimeStepTable([(T=20.0, duration=missing)])), + ) + @test_throws "Expected a finite duration" base_step_seconds( + GlobalConstant(TimeStepTable([(T=20.0, duration=Inf)])), + ) +end