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 new file mode 100644 index 000000000..829742c63 --- /dev/null +++ b/.github/scripts/require_complete_jet.jl @@ -0,0 +1,5 @@ +# 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 diff --git a/.github/scripts/test_require_complete_jet.jl b/.github/scripts/test_require_complete_jet.jl new file mode 100644 index 000000000..35af6bee3 --- /dev/null +++ b/.github/scripts/test_require_complete_jet.jl @@ -0,0 +1,119 @@ +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 "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 "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")) + 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/CI.yml b/.github/workflows/CI.yml index 8dc599e47..1b5b9e9bb 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -20,10 +20,10 @@ 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 }}/${{ matrix.os == 'macOS-latest' && 5 || 4 }} - ${{ github.event_name }} runs-on: ${{ matrix.os }} - # The expanded full suite with coverage can exceed two hours on the latest Julia. - 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 @@ -38,6 +38,10 @@ jobs: - ubuntu-latest - 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 @@ -48,6 +52,8 @@ jobs: - uses: julia-actions/julia-runtest@v1 env: JULIA_NUM_THREADS: 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 with: @@ -88,6 +94,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 @@ -123,13 +133,10 @@ 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; } - - name: Install Playwright browser - working-directory: frontend - run: npx playwright install --with-deps chromium - name: Run graph editor E2E tests working-directory: frontend run: npm run test:e2e 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 diff --git a/.github/workflows/Integration.yml b/.github/workflows/Integration.yml index 0c94d1c87..7b0010d72 100644 --- a/.github/workflows/Integration.yml +++ b/.github/workflows/Integration.yml @@ -13,9 +13,9 @@ 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 + timeout-minutes: ${{ matrix.timeout_minutes || 60 }} permissions: # needed to allow julia-actions/cache to proactively delete old caches that it has created actions: write @@ -23,14 +23,25 @@ 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 + # The complete XPalm suite includes cold compilation and VPalm tests. + timeout_minutes: 120 + 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 + timeout_minutes: 75 + 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 @@ -91,9 +102,14 @@ 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 }} + DOWNSTREAM_TEST_ARGS: ${{ matrix.test_args || '' }} shell: julia --threads 4 --color=yes --project=downstream --depwarn=yes {0} run: | using Pkg @@ -126,7 +142,12 @@ jobs: end Pkg.status() - Pkg.test() + test_args = isempty(ENV["DOWNSTREAM_TEST_ARGS"]) ? String[] : [ENV["DOWNSTREAM_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: | 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/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/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/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-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/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 135b75a67..53dc40eb0 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[] @@ -1133,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)), ) @@ -1164,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 diff --git a/docs/src/API/API_public.md b/docs/src/API/API_public.md index 954b98a59..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: @@ -437,8 +444,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/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/compile_scenario.md b/docs/src/guides/compile_scenario.md index 78d671a85..40a28587d 100644 --- a/docs/src/guides/compile_scenario.md +++ b/docs/src/guides/compile_scenario.md @@ -39,15 +39,20 @@ 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()' ``` 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: @@ -91,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 @@ -112,6 +117,22 @@ 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. + +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 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/docs/src/guides/data/numerical_reliability.md b/docs/src/guides/data/numerical_reliability.md index 37313ab59..0ec088da3 100644 --- a/docs/src/guides/data/numerical_reliability.md +++ b/docs/src/guides/data/numerical_reliability.md @@ -85,11 +85,37 @@ 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. 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/docs/src/guides/extensions/environment_backends.md b/docs/src/guides/extensions/environment_backends.md index 57bb0848c..e86f59dcd 100644 --- a/docs/src/guides/extensions/environment_backends.md +++ b/docs/src/guides/extensions/environment_backends.md @@ -25,6 +25,12 @@ 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. 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 check that the required names exist when it prepares the simulation. diff --git a/docs/src/guides/multiscale/import_mtg.md b/docs/src/guides/multiscale/import_mtg.md index 71fc337db..affcbd6e9 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 ? @@ -67,12 +73,67 @@ 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. 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. +`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. +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,)` +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/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/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/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/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 diff --git a/docs/src/model_execution.md b/docs/src/model_execution.md index 87a364bf0..dc540d7cf 100644 --- a/docs/src/model_execution.md +++ b/docs/src/model_execution.md @@ -68,8 +68,41 @@ 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, 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: 1. finds the objects selected by each application's `on` rule; 2. finds where each input value will come from; @@ -79,17 +112,49 @@ 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. -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. +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: @@ -440,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/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 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" diff --git a/ext/PlantSimEngineGraphEditorExt.jl b/ext/PlantSimEngineGraphEditorExt.jl index 27fa18ce6..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( @@ -184,6 +186,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) 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/frontend/e2e/graph-editor.spec.ts b/frontend/e2e/graph-editor.spec.ts index 44ef57718..9a34a2c71 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"); @@ -194,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) { 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/ModelSpec.jl b/src/ModelSpec.jl index 239297e10..2caca944f 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 @@ -128,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.", @@ -145,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.", @@ -161,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`.", @@ -174,6 +178,7 @@ function _resolved_output_destinations(spec::ModelSpec, effective_model=model_(s return resolved end + """ Updates(vars...; after=nothing) @@ -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, @@ -502,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..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") @@ -47,8 +48,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/authoring.jl b/src/authoring.jl index af5ee1b30..99f5625e9 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 @@ -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/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 0b956e7bd..2457259ed 100644 --- a/src/component_models/Status.jl +++ b/src/component_models/Status.jl @@ -1,12 +1,65 @@ +# 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 + +# 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) -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 +107,137 @@ 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 + +# 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(_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 +@inline _status_reference(storage::NamedTuple, key) = getfield(storage, key) +@inline function _status_reference(storage::_FixedStatusStorage, 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(_status_reference_slots(storage), 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]) + +# Reference/presence edits invalidate projections; ref[] = value does not. +_status_reference_epoch(storage::NamedTuple) = UInt(0) +_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) + 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 Status(vars::NamedTuple{N,T}) where {N,T<:Tuple{Vararg{Ref}}} - return new{N,T}(vars, Ref(nothing)) +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) + 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)) + _advance_status_reference_epoch!(storage) + 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)) + _advance_status_reference_epoch!(storage) + 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 +248,78 @@ function Status(nt::NamedTuple{names}) where {names} end _status_vars(status) = getfield(status, :vars) -_status_values(status) = getindex.(values(_status_vars(status))) -_status_namedtuple(status) = NamedTuple{keys(status)}(values(status)) +# 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 = 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} + storage = _status_vars(status) + if storage isa NamedTuple + fields = _map_status_slots(f, storage) + return T === Tuple ? Tuple(fields) : fields + end + 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) +_status_values(status) = _map_status_fields(getindex, Tuple, 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) = _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) Base.Tuple(mnt::Status) = _status_tuple(mnt) @@ -109,18 +340,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 +360,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 +378,96 @@ 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 _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(_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)) + count = 0 + for index in 1:nfields(references) + getfield(references, index) === nothing || (count += 1) + end + return count +end +@inline _initial_status_reference(source::Status, name::Symbol) = + _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) +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 + +_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 + +@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(_status_reference_slots(storage), $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/authored_ports.jl b/src/composite_model/authored_ports.jl new file mode 100644 index 000000000..5653a9b11 --- /dev/null +++ b/src/composite_model/authored_ports.jl @@ -0,0 +1,200 @@ +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 + +# 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_preparation_error(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 and type carriers preserve declarations without retaining initialization values. +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 + 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_preparation_error(failure.error) + +function _capture_authored_metadata(operation, phase::Symbol, application_id::Union{Nothing,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::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) + 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 + +# 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 + +# 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 +_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_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(typeof, schema), + _authored_output_element_types(schema)) + end + 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 + 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, 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/bound_many.jl b/src/composite_model/bound_many.jl index 2c206d29e..834f4d581 100644 --- a/src/composite_model/bound_many.jl +++ b/src/composite_model/bound_many.jl @@ -119,43 +119,3 @@ end value, _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( - 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/call_evaluation_types.jl b/src/composite_model/call_evaluation_types.jl index 89169c97a..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 @@ -26,7 +27,7 @@ mutable struct CallEvaluationTaskIdentity end mutable struct CallEvaluationFrame events::Vector{AbstractCallPublicationEvent} - executions::Dict{Any,UInt64} + executions::IdDict{Base.RefValue{UInt64},UInt64} generation::UInt64 pending::Bool in_use::Bool @@ -46,9 +47,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 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 08225f1e6..98519fc26 100644 --- a/src/composite_model/call_evaluations.jl +++ b/src/composite_model/call_evaluations.jl @@ -6,20 +6,25 @@ 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 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) @@ -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)}} @@ -105,24 +112,34 @@ 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 +# 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 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 @@ -142,7 +159,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,8 +258,13 @@ call_targets(evaluation::CallEvaluation) = evaluation.targets return nothing end -@noinline _call_execution_matches(cache::CallContextCache, executions::Dict{Any,UInt64}) = - cache.execution_revision == executions[cache] +@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 @@ -250,9 +272,9 @@ function _validate_call_evaluation(evaluation::CallEvaluation) 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) - for cache in keys(frame.executions) - _call_execution_matches(cache, frame.executions) || + _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.")) end frame.parent === _active_call_evaluation() || @@ -265,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 @@ -310,7 +334,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 9664815d1..14d4668f6 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,P,CP} slot::Int id::Symbol spec::S @@ -12,15 +12,30 @@ struct CompiledApplicationPlan{S,AT,TM,TS,CL,MO} target_matcher::TM timestep::TS clock::CL - model_overrides::MO + ports::P + call_plans::CP end """ Object-dependent runtime state for one compiled application. """ -mutable struct CompiledModelApplication{P} +mutable struct CompiledModelApplication{P<:CompiledApplicationPlan,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( @@ -39,15 +54,21 @@ 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 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,RT<:Tuple} + route::TAG slot::Int application_slot::Int application_id::Symbol @@ -59,12 +80,89 @@ struct CompiledModelInputPlan{SEL,M,OA,PSA,W} 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 +end + +@inline Base.getindex(table::CompiledMetadataTable, key::Union{Symbol,Int}) = + _with_metadata_entry(identity, table, key) +@inline Base.get(table::CompiledMetadataTable, key::Symbol, default) = + 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 +@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.""" +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) + 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) = + CompiledMetadataTable(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 @@ -118,15 +216,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 @@ -138,15 +235,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, @@ -155,24 +252,34 @@ 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,I<:ObjectId} plan::P - execution_object_id::ObjectId - destination_ids::Vector{ObjectId} + declarations::D + execution_object_id::I + 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} + const execution_object_id::ID + destination_ids::Vector{ID} columns::C destination_index::I membership_generation::UInt64 @@ -198,7 +305,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) @@ -254,11 +360,84 @@ 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 + +# 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 + +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}} + + # 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) + 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} + 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.""" @@ -274,27 +453,29 @@ 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_target_templates) + 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}}}, + _SelectorScopeAnchorKey{I}, Vector{Int}, }(), - Set{ObjectId}(), - Dict{Symbol,Set{Union{Symbol,ObjectId}}}(), - application_targets ? Dict{Any,Any}() : nothing, + Set{I}(), + Dict{Symbol,Set{Union{Symbol,I}}}(), + application_target_templates, ) 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,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), @@ -305,7 +486,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 @@ -313,9 +494,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 @@ -328,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 @@ -354,16 +519,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; - context=nothing, - default_scope=nothing, + 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 @@ -373,51 +554,56 @@ function _selector_candidate_destination( scope isa Ancestor && !isnothing(matcher.scale) && matcher.scale == scope.scale - return nothing + return index end anchor = _selector_scope_anchor( model, - matcher; - context=context, - default_scope=default_scope, + matcher, + context, + default_scope, ) if !isnothing(anchor) - anchor_id = ObjectId(anchor) + I = keytype(index.by_id) + raw_anchor_id = ObjectId(anchor) + # An out-of-family anchor cannot acquire an object in this registry. + 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!( 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) @@ -425,34 +611,38 @@ 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), - ) - end - end - destination = _selector_candidate_destination( - index, - model, - matcher; - context=context, - default_scope=default_scope, - ) - isnothing(destination) && return index - groups, values = destination - if isnothing(groups) - push!(index.wildcard, candidate_index) - else - for value in values - 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, - ) + 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 - 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 +# 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::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 function _union_selector_candidates!( @@ -463,45 +653,36 @@ 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 = _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) - 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 + 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) + _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 function _application_target_candidate_index(model, application_plans) - index = _selector_candidate_index(; 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, model, plan.target_matcher, plan.slot, + nothing, + nothing, ) end return _freeze_selector_candidate_index(index) @@ -570,16 +751,76 @@ function _compiled_application_schedule( ) end +# Authoring records contain declarations, never current target identities, +# status values, resolved overrides, clocks, or simulation-owned storage. +struct AuthoredApplicationRecipe{S,M,H,P,CP} + slot::Int + id::Symbol + spec::S + process::Symbol + name::Union{Nothing,Symbol} + target_matcher::M + environment_hint::H + 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.ports, call_plans) +end + +# 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,SM} + const owner::M + const source_specs::S + const authored::A + const failure::F + const program::P + const status_manifest::SM + resolved::Any +end + +# 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} + + 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{AP,AI,ATI,IP,IPI,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL} +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 @@ -592,16 +833,247 @@ struct CompiledScenarioPlan{AP,AI,ATI,IP,IPI,CP,CPI,DOP,CO,MA,AC,AO,OAP,AS,TL} timeline::TL end + +# 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. +# 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_families=_prepared_raw_status_families(model)) + # 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}() + 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 + 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) + 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 + ports = _prepare_authored_ports(spec, application_id) + push!(authored, AuthoredApplicationRecipe( + slot, application_id, spec, proc, name, matcher, hint, + ports, (), + )) + 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 = AuthoredApplicationRecipe[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 + return _finalize_authored_scenario(model, source_specs, 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 = _graph_record_vector(AuthoredApplicationRecipe, + (record for record in authored_records if record isa AuthoredApplicationRecipe)) + 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, birth_types) + 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, Tuple(authored_records), failure, + program, status_manifest, nothing) +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, preparation.program, + preparation.status_manifest, nothing) + model.scenario_plan_cache = owned + return owned +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) || + !_authored_specs_match(preparation, model) + 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 + # 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. + return _publish_failed_scenario_preparation!(model, 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. + 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, + # 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 + +@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 + +function _authored_application_recipes(preparation::ScenarioPreparation) + _validate_authored_scenario(preparation) + return preparation.authored +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) +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) ] @@ -618,7 +1090,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) @@ -737,7 +1209,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( @@ -971,8 +1443,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( @@ -1000,9 +1472,9 @@ 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) - variable in keys(plan.declarations) || continue + 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) end return selectors @@ -1073,33 +1545,98 @@ 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, -) +_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])) + 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(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, 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) + 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.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 +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( model::CompositeModel, + preparation::ScenarioPreparation, applications, input_plans, call_plans, @@ -1115,41 +1652,33 @@ 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, - ) - application_plans_by_id = NamedTuple{application_ids}(application_plans) + 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, application_order, manual_application_ids, ) + 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), 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), + CompiledMetadataTable(_plans_by_application(applications, call_plans)), distributed_output_plans, call_owners, manual_application_ids, @@ -1164,10 +1693,10 @@ function _compiled_scenario_plan( ) end -struct CompiledModelInputBinding{PL,P,C} +struct CompiledModelInputBinding{PL<:CompiledModelInputPlan,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 @@ -1199,7 +1728,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 && @@ -1219,6 +1748,141 @@ 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{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 + $(branches...) + throw(ArgumentError("The input binding is outside its prepared storage family.")) + 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 @@ -1226,18 +1890,93 @@ 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} + # 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. +@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 + +# 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 = admission(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 + $(branches...) + throw(KeyError(application_id)) + 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 -struct CompiledModelCallBinding{P} +# 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::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 @@ -1253,11 +1992,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<:CompiledModelCallPlan,I<:ObjectId,J<:ObjectId} + return CompiledModelCallBinding{P,I,J}( plan, consumer_id, callee_object_ids, @@ -1270,6 +2009,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, @@ -1339,7 +2095,15 @@ struct CompiledEnvironmentSamplingRule{T,S} end CompiledEnvironmentSamplingRule(target::Symbol, source::Symbol) = CompiledEnvironmentSamplingRule{target,source}() -struct CompiledEnvironmentApplicationPlan{B,C,RI,SI,PO,R,CR,S,P} +# 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} application_id::Symbol backend::B config::C @@ -1351,6 +2115,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} @@ -1362,6 +2127,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, @@ -1400,25 +2180,30 @@ 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,S} + const model::SC + const application_plans::AP + const application_plans_by_id::API + # 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 + const targets_by_object::OI + const sample_cache::C + const model_revision::Int + const environment_revision::Int + # 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 # 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 @@ -1440,6 +2225,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 @@ -1448,28 +2234,152 @@ 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; + force::Bool=false, + performance=nothing, +) + return _refresh_bindings!(model; force, performance) +end + +function _refresh_bindings!( + model::CompositeModel; + force::Bool=false, + performance=nothing, + 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 + rebuild = force || !isnothing(input_binding_storage) || !isnothing(status_view_schema) + 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, 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, + ) + prepared = PreparedScenario(plan, + _prepared_application_targets(model, applications)) + end + end + end + return _refresh_prepared_bindings!(model, previous, prepared; + force=rebuild, performance, input_binding_storage, status_view_schema) +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, input_binding_storage=nothing, + status_view_schema=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, input_binding_storage, status_view_schema) + 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) + empty!(model.registry.objects.changed_status_ids) + 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; performance=nothing, +) + preparation = getfield(getfield(current.scenario_plan, :authoring), :preparation) + preparation.owner === model || _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. + return _refresh_prepared_bindings!(model, current, nothing; performance) +end + function _index_dynamic_input_binding!( + binding::CompiledModelInputBinding, index::SelectorCandidateIndex, model::CompositeModel, - binding::CompiledModelInputBinding, binding_index::Int, 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!( 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, ), @@ -1482,13 +2392,10 @@ function _index_dynamic_input_bindings( bindings, many_binding_cache, ) - index = _selector_candidate_index() + 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 @@ -1508,9 +2415,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, ), @@ -1519,7 +2426,7 @@ function _index_dynamic_call_binding!( end function _index_dynamic_call_bindings(model::CompositeModel, bindings) - index = _selector_candidate_index() + index = _selector_candidate_index(model, nothing) for (binding_index, binding) in pairs(bindings) _index_dynamic_call_binding!( index, @@ -1532,14 +2439,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 @@ -1571,7 +2479,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 @@ -1586,38 +2494,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 @@ -1631,13 +2515,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 @@ -1646,8 +2526,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 = _object_key_index(Tuple{Symbol,I}, Vector{Int}) for (binding_index, binding) in pairs(bindings) _index_observed_manual_call_binding_by_callee_target!( index, @@ -1679,11 +2560,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 @@ -1700,67 +2582,99 @@ 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 end -function _index_model_bindings(bindings, application_field::Symbol, object_field::Symbol) - grouped = Dict{Tuple{Symbol,ObjectId},Vector{Any}}() - for binding in bindings - key = ( - getproperty(binding, application_field), - getproperty(binding, object_field), - ) - push!(get!(grouped, key, Any[]), binding) - end - return Dict(key => Tuple(values) for (key, values) in grouped) +@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 -""" - compile_composite_model(model[, applications...]) +@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 -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. -""" -function compile_composite_model(model::CompositeModel; performance=nothing) - return compile_composite_model( - model, - model.applications; - performance=performance, - ) +function _group_model_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B,I<:ObjectId} + K = Tuple{Symbol,I} + grouped = _object_key_index(K, Vector{B}) + for binding in bindings + key = _model_binding_target_key(binding, I) + values = get!(grouped, key) do + B[] + end + push!(values, binding) + end + return grouped +end + +function _index_model_input_bindings(bindings::AbstractVector{B}, ::Type{I}) where {B<:CompiledModelInputBinding,I<:ObjectId} + # 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. +# Authored declarations remain unchanged when Scope/potential callees resolve. +@generated function _index_model_call_bindings_for_application!( + plans::Plans, index, application_id::Symbol, object_id::I, bindings, + ::Type{J}, +) 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]) && + 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 + 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 compile_composite_model( - model::CompositeModel, - specs::Tuple; - performance=nothing, -) - return _compile_scene(model, specs; performance=performance) +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!, + plans_by_application, application_id, index, application_id, object_id, values, I) + end + return index end -function compile_composite_model( - model::CompositeModel, - specs::AbstractVector; - performance=nothing, -) - return _compile_scene(model, Tuple(specs); performance=performance) +function _index_model_call_bindings(bindings::AbstractVector{B}, plans_by_application, ::Type{I}) where {B,I<:ObjectId} + index = _object_key_index(Tuple{Symbol,I}, Tuple{Vararg{B}}) + return _index_model_call_bindings!(index, bindings, plans_by_application, I) end -function compile_composite_model( - model::CompositeModel, - specs...; - performance=nothing, -) - return _compile_scene(model, specs; performance=performance) +""" + compile_composite_model(model::CompositeModel) + +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) + 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) @@ -1769,17 +2683,17 @@ 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( - 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, + preparation, applications, input_plans, call_plans, @@ -1788,21 +2702,20 @@ function _compile_resolved_scenario_plan(model::CompositeModel, applications, ti ) end -function _build_scenario_plan( - model::CompositeModel, - raw_specs, - timeline; +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, @@ -1824,40 +2737,39 @@ 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) + _validate_authored_scenario(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 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]) - return model.scenario_plan_cache = prepared + _prepared_application_targets(model, compiled.applications; copy_targets=true)) + preparation.resolved = prepared + return prepared end end - plan, applications = _build_scenario_plan(model, model.applications, timeline; performance) - prepared = PreparedScenario(plan, Vector{ObjectId}[app.target_ids for app in applications]) + plan, applications = _resolve_prepared_scenario(model, preparation, timeline; performance) + 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) return prepared end - return model.scenario_plan_cache = prepared -end - -function _compile_scene( - model::CompositeModel, - raw_specs; - validate_required_inputs::Bool=true, - performance=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) + preparation.resolved = prepared + return prepared 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( @@ -1866,12 +2778,18 @@ function _compile_scene( applications; validate_required_inputs::Bool=true, performance=nothing, + input_binding_storage=nothing, + status_view_schema=nothing, ) 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, ) _runtime_performance_finish!( @@ -1882,6 +2800,7 @@ function _compile_scene( distributed_outputs = _compile_model_distributed_outputs( model, applications, + applications_by_id, scenario_plan.manual_application_ids, scenario_plan.distributed_output_plans, ) @@ -1890,43 +2809,33 @@ function _compile_scene( model, applications, scenario_plan.manual_application_ids, - scenario_plan.input_plans_by_application, - distributed_outputs, + 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) # 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, 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 = Dict{Any,Any}( - _index_model_bindings( - input_bindings, - :application_id, - :consumer_id, - ), + input_bindings_by_target = _index_model_input_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_call_bindings( + call_bindings, scenario_plan.call_plans_by_application, keytype(model.registry.objects), ) 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 @@ -1937,8 +2846,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, @@ -1951,7 +2862,7 @@ function _compile_scene( applications, applications_by_id, ordered_applications, - _applications_by_object(applications), + applications_by_object, input_bindings, call_bindings, input_bindings_by_target, @@ -1965,14 +2876,16 @@ 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, 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)), + _object_key_set(keytype(status_views_by_target), keys(status_views_by_target)), false, application_order, model.revision, @@ -1980,11 +2893,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, @@ -2001,20 +2909,27 @@ function _application_target_template_key( object_id::ObjectId, ) object = _model_object(model, object_id) - scope_roots = if isempty(index.scope_roots) - () - else - ancestors = _object_ancestor_ids(model.registry, object_id) - Tuple( - ancestor_id for ancestor_id in ancestors - if ancestor_id in index.scope_roots - ) + id = _index_object_id(model.registry.objects, object_id) + I = keytype(model.registry.objects) + scope_roots = nothing + if !isempty(index.scope_roots) + ancestors = _object_ancestor_ids(model.registry, id) + 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), - _application_target_template_label(index, :id, object.id), + _application_target_template_label(index, :id, id), scope_roots, ) end @@ -2042,14 +2957,15 @@ 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, + nothing, false, nothing, false) + end + matches && push!(matched_slots, slot) + end template = _ApplicationTargetTemplate( sorted_candidates, matched_slots, @@ -2069,8 +2985,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, @@ -2079,9 +2997,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 @@ -2092,10 +3011,15 @@ 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) + 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 @@ -2137,7 +3061,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) @@ -2145,12 +3070,113 @@ function _insert_sorted_object_ids!(ids, added_ids) return ids end -Base.@nospecializeinfer function _compile_added_consumer_bindings!( +# 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_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, +) + 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, + manual_application_ids, applications_by_object, applications_by_id, + distributed_outputs, many_binding_cache, performance, + ) + _record_consumer_input_bindings!( + recorder, bindings, application_id, consumer_id, + first_new_binding, length(bindings), + ) + end + return bindings +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 + changed_bindings::B + input_bindings_by_target::I +end + +function _record_consumer_input_bindings!( + 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 + new_bindings = B[] + sizehint!(new_bindings, last_new_binding - first_new_binding + 1) + for binding_index in first_new_binding:last_new_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) + recorder.input_bindings_by_target[(application_id, consumer_id)] = new_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) && + _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, + applications_by_object, applications_by_id, nothing, distributed_outputs; + query_cache, query_slot, + ) +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, _route_cells(bindings), + )) + return nothing +end + +function _compile_consumer_input_recipe!( bindings, model, - application, + application_id::Symbol, + application_process::Symbol, consumer_id, - input_plans, + recipe::CompiledApplicationInputRecipe, manual_application_ids, applications_by_object, applications_by_id, @@ -2158,89 +3184,41 @@ 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 && plan.selector isa Many, - 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 - 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, - ) - continue - end - end - _push_model_input_binding!( - bindings, - model, - application, - consumer_id, - plan, - applications_by_object, - applications_by_id, - nothing, - distributed_outputs, - ; object_query_cache, - ) - 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) + query_cache = _input_query_cache(model.registry.objects, recipe.query_count) + # 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 + 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 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( - distributed_outputs, - consumer_id, - plan.source_var, - matches, - ) - isempty(matches) && continue - 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])`. ", - "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, - ) + distributed_outputs, consumer_id, plan.source_var, matches, + ) + isempty(matches) && return nothing + 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]), + Symbol[selected.application], + ) + # 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 @@ -2252,6 +3230,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, @@ -2272,6 +3262,88 @@ 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 +Base.isequal(left::_ManyBindingQueryKey, right::_ManyBindingQueryKey) = + 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 + 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, @@ -2279,154 +3351,158 @@ 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, + _scope_anchor(model, scope, consumer_id)) 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, + _scope_anchor(model, scope, consumer_id)) 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 _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 - canonical = get(cache, key, nothing) - isnothing(canonical) && return nothing - 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, - ) + isnothing(key) && return false + canonical = get(cache.by_plan, key, nothing) + 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 _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!(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) +# 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 _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) + 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]) + _store_shared_many_input_binding!(cache, model, bindings, index) end return cache 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 _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, @@ -2435,26 +3511,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 -function _dynamic_input_binding_shares_canonical_sources( - model::CompositeModel, - binding::CompiledModelInputBinding, - many_binding_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(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 - _shared_same_rate_many_storage(binding, canonical) || return false - return binding.slot != canonical.slot || - binding.consumer_id != canonical.consumer_id + canonical = get(cache.by_query, key, nothing) + isnothing(canonical) && return false + _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) @@ -2469,7 +3538,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) || @@ -2480,42 +3549,52 @@ function _can_append_stable_many_sources(binding::CompiledModelInputBinding) ) end -function _append_stable_many_source_references!( +# 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 + +@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 = _status_ref_or_nothing( - _model_object(model, object_id).status, - binding.source_var, - ) - reference isa eltype(existing_references) || 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, @@ -2523,24 +3602,35 @@ 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) - 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), - ) - ] - isempty(new_source_ids) && return true + matcher = binding.matcher + matching_matcher = matcher + query_prepared = false + 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 + _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, + binding.consumer_id, default_scope, false) || continue + end + first(_sorted_object_id_position(source_ids, object_id)) || + push!(new_source_ids, object_id) + end + isempty(new_source_ids) && return _UnchangedManyInput() _sort_object_ids!(new_source_ids) _filter_many_input_sources_by_writer!( new_source_ids, @@ -2552,28 +3642,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, binding.source_var) - 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[] @@ -2622,15 +3708,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, @@ -2644,18 +3746,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, @@ -2669,11 +3775,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 @@ -2692,7 +3798,7 @@ function _update_structural_many_sources!( _insert_with_spare_capacity!( carrier_references, position, - source_reference, + source_reference::R, ) end end @@ -2704,8 +3810,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, @@ -2746,86 +3851,136 @@ 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( - 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...) + 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)]..., + [:(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 + +@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!, + 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 + +# 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) + haskey(sources, source_key) || (sources[source_key] = copy(binding.source_ids)) + return nothing +end + +function _previous_temporal_source_storage(model::CompositeModel) + I = keytype(model.registry.objects) + return _object_key_index(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!, + 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 + 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) 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, + Base.@inline _preserve_model_status_view_temporal_state!( + current.status_view_schema, first(key), current_view, previous_view, previous_temporal_sources, key, @@ -2841,6 +3996,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 @@ -2865,8 +4022,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 @@ -2875,7 +4044,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, @@ -2884,7 +4053,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 @@ -2900,56 +4070,126 @@ function _stage_temporal_many_extension( ) end -function _extend_temporal_many_inputs_in_place!( - model::CompositeModel, - view::CompiledModelStatusView, - key, - previous_temporal_sources, - applications_by_id, - application_positions, - distributed_outputs, +_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, schema, canonical_status, ) - 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, - ) - isnothing(extension) && return false - push!(staged, 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) - end - return true + 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, schema, canonical_status) + 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 + following_applied = _apply_temporal_many_extensions!(Base.tail(staged)) + return !isnothing(extension) || following_applied +end + +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 + +@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 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) + +@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(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. +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!, + 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, + Base.@inline(_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( +function _extend_model_status_views!( model::CompositeModel, compiled::CompiledCompositeModel, applications, applications_by_id, - applications_by_object, input_bindings_by_target, application_order, new_targets, @@ -2960,15 +4200,41 @@ 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 = _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)) + 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 + + # 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 = 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 + end end end @@ -2976,54 +4242,26 @@ function _extend_model_status_views( application_id => index for (index, application_id) in pairs(application_order) ) - for key in affected_temporal_keys + 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 - if _extend_temporal_many_inputs_in_place!( - model, - view, - key, - previous_temporal_sources, - applications_by_id, - positions, - distributed_outputs, - ) - delete!(affected_keys, key) + extended = Base.@inline _with_model_status_view(_extend_temporal_many_inputs_in_place!, + 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 - 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) - 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 - end - current_view = _compile_model_status_view( - model, - application, - object_id, - get(input_bindings_by_target, key, ()), - applications_by_id, - positions, - distributed_outputs, - ) - views[key] = isnothing(previous_view) ? - current_view : - _preserve_model_status_view_temporal_state!( - current_view, - previous_view, - previous_temporal_sources, - key, - ) + 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 views + return affected_keys end function _append_added_many_call_targets!( @@ -3036,15 +4274,17 @@ 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, 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, @@ -3088,16 +4328,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 = _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 = copy(frontier) while !isempty(frontier) _runtime_performance_count!( performance, @@ -3114,14 +4358,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 = _object_key_set(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) @@ -3136,20 +4381,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 = _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) - 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 @@ -3177,6 +4432,24 @@ 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} = + _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, @@ -3184,20 +4457,25 @@ function _prepare_structural_compiled_delta( performance=nothing, ) started_at = _runtime_performance_start(performance) - dirty = Set{ObjectId}(dirty_object_ids) - removed_target_keys = Set{Tuple{Symbol,ObjectId}}() + 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 = _object_key_set(Tuple{Symbol,I}) 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 @@ -3205,46 +4483,29 @@ 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)) + forced_input_binding_keys = _input_binding_key_set(model.registry.objects) + previous_temporal_sources = _previous_temporal_source_storage(model) for binding in compiled.input_bindings - if binding.consumer_id in dirty - continue - end - push!(input_bindings, binding) - end - forced_input_binding_keys = Set{Tuple{Symbol,ObjectId,Symbol}}() - previous_temporal_sources = Dict{ - Tuple{Symbol,ObjectId,Symbol}, - Vector{ObjectId}, - }() - for binding in input_bindings - _sorted_object_ids_intersect_set(binding.source_ids, dirty) || - continue - key = (binding.application_id, binding.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 + _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 = Dict{Any,Any}( - _index_model_bindings( - input_bindings, - :application_id, - :consumer_id, - ), + input_bindings_by_target = _index_model_input_bindings( + 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 - 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) 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) || @@ -3254,12 +4515,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_call_bindings( + call_bindings, compiled.scenario_plan.call_plans_by_application, keytype(model.registry.objects), ) many_input_binding_cache = _many_input_binding_cache(model, input_bindings) @@ -3284,12 +4541,14 @@ 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, compiled.call_owners, compiled.application_children, compiled.status_views_by_target, + compiled.status_view_schema, changed_application_ids, removed_target_keys, false, @@ -3318,7 +4577,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( @@ -3326,7 +4586,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 @@ -3344,10 +4604,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 = _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) + 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 @@ -3370,12 +4635,13 @@ 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, 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 : @@ -3404,53 +4670,51 @@ function _refresh_scene_call_bindings!( _compile_model_call_bindings( model, added_applications, - applications, ; by_object=applications_by_object, + applications_by_id=applications_by_id, plans_by_application=compiled.scenario_plan.call_plans_by_application, - ) : CompiledModelCallBinding[] - affected_call_applications = CompiledModelApplication[] + ) : similar(compiled.call_bindings, 0) + 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, - CompiledModelApplication( - application.plan, - 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) ? - CompiledModelCallBinding[] : + 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, ) - replacement_call_bindings_by_target = _index_model_bindings( - replacement_call_bindings, - :application_id, - :consumer_id, + replacement_call_bindings_by_target = _index_model_call_bindings( + 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 @@ -3458,42 +4722,32 @@ 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 binding in existing + "for application `$(first(key))` on object `$(_object_id_text(last(key)))`.", + ) + # 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, ) isnothing(binding_index) && error( "Incremental hard-call refresh lost the existing compiled binding ", - "for application `$(first(key))` on object `$(last(key).value)`.", - ) - 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 `$(last(key).value)`.", + "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, @@ -3501,7 +4755,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, ) @@ -3515,6 +4769,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 @@ -3537,81 +4792,279 @@ function _refresh_scene_call_bindings!( observed_manual_call_binding_indices_by_callee_target end -function _extend_compiled_scene( - model::CompositeModel, - compiled::CompiledCompositeModel, - added_objects; - 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}, - }(), - changed_application_ids_seed=Set{Symbol}(), - changed_target_ids_seed=Set{Tuple{Symbol,ObjectId}}(), - pure_addition::Bool=true, - structural_dirty_ids=ObjectId[], - performance=nothing, +# 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, ) - added_ids = ObjectId[id for id in added_objects if haskey(model.registry.objects, id)] - started_at = _runtime_performance_start(performance) - new_targets = _new_application_targets( - model, - compiled, - added_ids, - performance, + _store_shared_many_input_binding!(cache, model, replacement, 1, only(replacement)) + copyto!(bindings, index, replacement, 1, 1) + append!(changed_bindings, replacement) + return nothing +end + +# One existing-binding lifecycle operation; admission precedes this worker. +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, + processed_many_sources, previous_shared_many_sources, forced_input_binding_keys, pure_addition, + 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 + 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) : + empty(source_ids) + 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 && + (!has_writer_rebinds || !(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, + consumer_id, + true, + default_scope, + ) || return false + end + prepared = _pending_input_update(admissions, index) + appended_sources = if !isnothing(prepared) && first(prepared) === :append && !force_rebuild + delta = admissions.bindings[last(prepared)] + 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 + 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) + 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 + delete!(many_binding_cache.by_query, old_cache_key) + end + _store_rebuilt_input_binding!( + input_bindings, changed_bindings, index, replacement, many_binding_cache, model, ) - isnothing(new_targets) && return compile_composite_model( + 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) + # Replace the membership container so shallow diagnostic snapshots retain + # the previous bindings, while all unmodified binding/carrier objects stay shared. + members = get(input_bindings_by_target, target) do + valtype(typeof(input_bindings_by_target))() + end + 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 + +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, + added_objects; + forced_input_binding_keys=_input_binding_key_set(model.registry.objects), + 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=_object_key_set(Tuple{Symbol,keytype(model.registry.objects)}), + pure_addition::Bool=true, + structural_dirty_ids=ObjectId[], + performance=nothing, +) + I = keytype(model.registry.objects) + 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, - model.applications; - performance=performance, + compiled, + added_ids, + performance, ) applications = compiled.applications 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 + _lifecycle_target_count_error(application.id, target_count, "a `One`") + elseif application.applies_to isa OptionalOne && target_count > 1 + _lifecycle_target_count_error(application.id, target_count, "an `OptionalOne`") + 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 + 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, @@ -3621,13 +5074,17 @@ function _extend_compiled_scene( compiled.scenario_plan.distributed_output_plans, added_ids, new_targets, - pure_addition, + pure_addition, before_publish!, ) - 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), - ) + 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)) + push!(changed_application_ids_seed, application_id) + end _runtime_performance_finish!( performance, :application_target_refresh, @@ -3635,13 +5092,6 @@ function _extend_compiled_scene( ) started_at = _runtime_performance_start(performance) - added_applications = CompiledModelApplication[ - CompiledModelApplication( - application.plan, - 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 = _refresh_scene_call_bindings!( model, @@ -3654,21 +5104,6 @@ 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, - ) - if pure_addition - _prepare_model_output_statuses_batched!( - model, - added_applications; - performance=performance, - ) - else - _prepare_model_output_statuses!(model, added_applications) - end _runtime_performance_finish!( performance, :call_binding_refresh, @@ -3676,35 +5111,23 @@ 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, - ) + # 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, - ) - # 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 = CompiledModelInputBinding[] + 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{ObjectId}}() + 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, @@ -3714,23 +5137,17 @@ 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) 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 - _union_selector_candidates!( - candidate_binding_indices, - compiled.dynamic_input_binding_indices, - model, - object_id, - ) - end _runtime_performance_count!( performance, :selector_input_binding_candidates, @@ -3739,174 +5156,31 @@ 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, + processed_many_sources, previous_shared_many_sources, forced_input_binding_keys, pure_addition, + 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, + ) while pending_binding_position <= length(pending_binding_indices) 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) - 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) - 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(binding.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) - 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=binding.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, binding.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[] - _push_model_input_binding!( - replacement, - model, - application, - binding.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, binding.consumer_id) - if binding.carrier_hint == :temporal_stream - key = (binding.application_id, binding.consumer_id) - push!(affected_temporal_keys, key) - previous_temporal_sources[( - key..., - binding.input, - )] = previous_source_ids - end - target = (binding.application_id, binding.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, admissions, ) + rebuild_dynamic_input_index |= rebuilt end previous_binding_count = length(input_bindings) - 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_plans_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 - end + recorder = _AddedConsumerInputBindings( + model, many_binding_cache, changed_bindings, input_bindings_by_target, + ) + _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) @@ -3918,11 +5192,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 @@ -3931,21 +5203,18 @@ function _extend_compiled_scene( affected_input_applications = if pure_addition || isempty(rewired_consumer_ids) - Tuple(added_applications) + added_applications 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, - (), - ) + rewired_applications = copy(added_applications) + 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 push!( get!( targets_by_application, application.id, - ObjectId[], + I[], ), object_id, ) @@ -3953,48 +5222,38 @@ 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, - CompiledModelApplication( - application.plan, - 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 - (added_applications..., rewired_applications...) - end - final_input_references = pure_addition ? - _model_input_status_references(changed_bindings) : - nothing - if pure_addition - _prepare_model_input_statuses_batched!( - model, - affected_input_applications, - changed_bindings; - final_references=final_input_references, - performance=performance, - ) - else - _prepare_model_input_defaults!( - model, - affected_input_applications; - final_references=final_input_references, - performance=performance, - ) - _wire_model_input_carriers!( - model, - changed_bindings; - final_references=final_input_references, - ) + rewired_applications end + final_input_references = _model_input_status_references( + model.registry.objects, 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, + applications_by_id, changed_bindings, ) _runtime_performance_finish!( @@ -4003,24 +5262,19 @@ 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, - :application_id, - :consumer_id, - ), + isempty(new_call_bindings) || _index_model_call_bindings!( + 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 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, applications_by_id, - applications_by_object, input_bindings_by_target, application_order, new_targets, @@ -4030,43 +5284,42 @@ function _extend_compiled_scene( distributed_outputs, previous_views, ) + status_views_by_target = compiled.status_views_by_target _runtime_performance_finish!( performance, :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) - 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, ()) - ), - ) + # 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 = _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) + 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 + 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) + push!(changed_manual_target_ids, (application_id, object_id)) end - changed_manual_target_ids = Set{Tuple{Symbol,ObjectId}}( - key for key in changed_execution_target_ids - if first(key) in manual_application_ids - ) 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!( + model.registry.objects, changed_execution_target_ids, changed_manual_target_ids, call_bindings, @@ -4100,6 +5353,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, @@ -4170,21 +5424,21 @@ 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, ) - 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 - if status isa Status && variable in propertynames(status) + if status isa Status && hasproperty(status, variable) return true, status[variable] end return false, nothing @@ -4224,7 +5478,7 @@ end function _initialization_conversion_fields( model::CompositeModel, - compiled::CompiledCompositeModel, + status_views, application_id::Symbol, object_id::ObjectId, variable::Symbol; @@ -4240,7 +5494,7 @@ function _initialization_conversion_fields( ) has_effective, effective = _initialization_effective_value( model, - compiled, + status_views, application_id, object_id, variable, @@ -4289,53 +5543,68 @@ 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 + +# 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 _required_input_names(ports) + 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; - 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 = environment_outputs_(application.spec) - model_inputs = _input_schema(application.spec) - environment_inputs = environment_inputs_(application.spec) + 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; @@ -4387,7 +5656,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 && @@ -4418,7 +5687,7 @@ function explain_initialization(model::CompositeModel) end conversion = _initialization_conversion_fields( model, - compiled, + status_views, application.id, object_id, variable; @@ -4450,11 +5719,11 @@ function explain_initialization(model::CompositeModel) 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_text(object_id))` Status or add `inputs=(:$(variable) => ..., )` to application `$(application.id)`." : 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), @@ -4469,9 +5738,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, @@ -4483,7 +5752,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..., @@ -4502,101 +5771,86 @@ function explain_initialization(model::CompositeModel) return rows 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}() - 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) - target_ids = _resolve_object_ids(model, selector, target_matcher) +function _compile_model_applications(model::CompositeModel, timeline) + recipes = _authored_application_recipes(_scenario_preparation(model)) + return _resolve_application_recipes(model, recipes, timeline) +end + +function _resolve_application_recipes( + model::CompositeModel, recipes::Tuple, timeline; on_environment_error=nothing, +) + 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) + 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, - spec, - _model_application_hint_scale(model, target_ids), - ) - model_overrides = _compiled_object_model_overrides(spec, target_ids, app_id) - 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, - ), - target_ids, + model, recipe.spec, _model_application_hint_scale(model, target_ids), + recipe.environment_hint, recipe.ports.environment_inputs; + on_error=on_environment_error, + ) + _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), + recipe.ports, recipe.call_plans, ), - ) + 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, 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) + 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 current_window = environment_window(spec) 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, ) end -function _model_environment_bindings_with_environment_sources(spec, bindings) +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)] - 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) @@ -4607,7 +5861,7 @@ function _model_environment_bindings_with_environment_sources(spec, bindings) 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)) @@ -4615,51 +5869,144 @@ function _model_environment_bindings_with_environment_sources(spec, bindings) 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 _model_output_names(application::CompiledModelApplication) - return Symbol[Symbol(var) for var in keys(_local_output_schema(application.spec))] +function _application_model(application, object_id::ObjectId) + return _with_application_variant((model, ports) -> model, application, object_id) 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 - ] +@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 -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)) +@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 + +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 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 + +function _application_default_schemas(application, kind) + model = model_(application.spec) + return model isa ObjectModelOverrides ? IdDict{AbstractModel,NamedTuple}() : + _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...) +@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, ports, cache, kind, + _variant_defaults_type(ports, kind), args...) +end +@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, ports) + 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 +_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. +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, applications_by_id, ::Type{I}, skipped_application_ids=(), +) where {I<:ObjectId} + 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 + 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 @@ -4671,20 +6018,16 @@ 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) - 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[] @@ -4695,16 +6038,10 @@ function _update_after_labels(spec, variable::Symbol) return labels end -function _updates_after_previous_writer(spec, variable::Symbol, previous_applications) - matching = _matching_updates(spec, variable) - isempty(matching) && return false - for update in matching +function _updates_after_previous_writer(spec, variable::Symbol, previous_application_ids) + for update in _matching_updates(spec, variable) 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 @@ -4727,44 +6064,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_text(object_id))`, 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 + 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),)) + previous_writer = last(previous) + error( + "Application `$(application.id)` updates `$(variable)` on object ", + "`$(_object_id_text(object_id))` 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 @@ -4772,146 +6113,191 @@ end _resolve_model_output_destinations( ::CompositeModel, - applications, + applications_by_id, ::NoCompiledDistributedOutputPlans, ) = () -function _resolve_model_output_destinations( - model::CompositeModel, - applications, - compiled_plans::CompiledDistributedOutputPlans, -) - resolved = ResolvedModelOutputDestination[] - for plan in compiled_plans.plans - application = applications[plan.application_slot] - 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, - ) - destination_ids = _dependency_object_ids( - model, - plan.selector, - plan.matcher, - execution_object_id, - ) - sizehint!(destination_ids, length(destination_ids) + 1) - push!( - resolved, - ResolvedModelOutputDestination( - effective_plan, - execution_object_id, - destination_ids, - ), - ) +# Port names are authored metadata; defaults belong to the actual initial or +# newborn destination event, never a previous binding's cached declaration. +function _read_model_output_destination_declarations(producer, ports, + ::CompiledModelOutputDestinationPlan{GROUP,NAMES}, +) where {GROUP,NAMES} + 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(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 end - return Tuple(resolved) + return :(Vector{$rows}()) end -function _push_compiled_writer_owner!( - ownership, - object_id::ObjectId, - variable::Symbol, - owner::CompiledWriterOwner, +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( + model::CompositeModel, applications_by_id, plans::CompiledDistributedOutputPlans, ) - push!( - get!( - ownership, - (object_id, variable), - CompiledWriterOwner[], - ), - owner, - ) - return ownership + 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 -function _validate_compiled_writer_ownership!(ownership, applications) - groups = Dict{Tuple{ObjectId,Symbol},Vector{Tuple{Int,Any}}}() +# 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 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 +# 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 = _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) - 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 " * + "writer for `$(variable)` on object `$(_object_id_text(object_id))`. 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,Any}[], - ), - ( - owner.application_slot, - applications[owner.application_slot], - ), - ) end + groups[(object_id, variable)] = [(owner.application_slot, owner.application_id) for owner in owners] end - _validate_model_writer_groups!(groups) + _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 - application = applications[plan.application_slot] - for destination_id in resolved.destination_ids - for variable_ in keys(plan.declarations) - 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 = _object_key_index(Tuple{I,Symbol}, Vector{CompiledWriterOwner}) + for partial in applications + getfield(getfield(partial, :plan), :id) in manual_application_ids && continue + Base.@inline _with_model_application(_record_application_writers!, applications_by_id, partial, + ownership, nothing, partial.target_ids) end - return _validate_compiled_writer_ownership!(ownership, applications) + _record_destination_writers!(ownership, nothing, resolved_destinations) + return _validate_compiled_writer_ownership!(ownership, applications_by_id) end _validate_manual_model_output_destination_plans!(::NoCompiledDistributedOutputPlans, _) = nothing @@ -4931,51 +6317,36 @@ 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 = _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) + _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::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) @@ -4997,13 +6368,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) @@ -5029,7 +6403,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 @@ -5115,33 +6489,43 @@ 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 -function _cached_dependency_object_ids( - cache, - model::CompositeModel, - selector::AbstractObjectMultiplicity, - matcher::CompiledSelectorMatcher, - context::ObjectId, -) - (isnothing(cache) || !(selector isa Many)) && - return _dependency_object_ids(model, selector, matcher, context) - key = ( - 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) @@ -5151,37 +6535,152 @@ function _carrier_hint(selector::AbstractObjectMultiplicity, policy, window) return :shared_ref end -function _status_ref_or_nothing(status, var::Symbol) - status isa Status || return nothing - var in propertynames(status) || return nothing - return refvalue(status, var) +_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 + name = _input_reference_name(variable) + hasproperty(status, name) || return nothing + return refvalue(status, name) +end + +@inline function _checked_reference(reference) + isnothing(reference) && return nothing + reference isa Ref || throw(ArgumentError( + "Reference carriers require Ref storage; got `$(typeof(reference))`.", + )) + return reference +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) && return RefVector{Union{}} + all(R -> R <: Ref && isconcretetype(R), types) || + throw(ArgumentError("A Many input requires exact prepared reference types.")) + R = Union{types...} + return length(types) == 1 && only(types) <: Base.RefValue && + 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 <: Ref && 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_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 -function _input_carrier(model::CompositeModel, selector::AbstractObjectMultiplicity, source_ids::Vector{ObjectId}, source_var::Symbol) - 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) - isnothing(source_ref) && return nothing - push!(refs, source_ref) +# 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} + R = Union{fieldtypes(RT)...} + return quote + references = $R[] + sizehint!(references, length(source_ids) + 1) + for source_id in source_ids + reference = _checked_reference(reference_for(source_id)) + isnothing(reference) && return nothing + reference isa $R || throw(ArgumentError( + "A reference is outside its prepared collection family.")) + push!(references, reference::$R) + end + return references + end +end + +@generated function _input_reference_carrier( + ::Many, source_ids, reference_for::F, ::Type{RT}, +) where {F,RT<:Tuple} + types = fieldtypes(RT) + 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 - if selector isa Many - isempty(refs) && return RefVector{Any}() - return _ref_vector_carrier(refs) + return quote + references = _collect_reference_family(source_ids, reference_for, $RT) + isnothing(references) && return nothing + return $C(references) end - return isempty(refs) ? nothing : only(refs) 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}, statuses=nothing, +) + objects = model.registry.objects + reference_for = source_id -> + _input_source_cell(statuses, objects, source_id, source_var) + 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, 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 + 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, conversion_records=conversions, + ) + return Ref(initial) end end @@ -5190,34 +6689,20 @@ function _stream_only_initial_reference( source_id::ObjectId, source_application_ids, source_var::Symbol, - applications_by_id, + applications_by_id, statuses=nothing, ) - 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 - 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) - 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(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( @@ -5227,28 +6712,25 @@ function _stream_only_initial_carrier( source_application_ids, source_var::Symbol, applications_by_id, + reference_types::Type{<:Tuple}, statuses=nothing, ) - 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, statuses, + ) + return _input_reference_carrier(selector, source_ids, reference_for, reference_types) +end + +_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(refs) - T = typeof(refs[1][]) +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 @@ -5259,93 +6741,95 @@ 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}} +mutable struct _CanonicalStatusRecipe{S<:Status} + original::S + fresh::Bool + 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::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 -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 +# 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}}() + +@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 - return _CanonicalStatusRecipe( - status, - names, - references, - positions, - 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 _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 _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) = - !iszero(_status_recipe_position(recipe, variable)) +@inline function _status_recipe_has_variable(recipe::_CanonicalStatusRecipe, variable::Symbol) + variable in recipe.edit_names && return true + return _initial_status_reference(recipe.original, variable) !== nothing +end function _status_recipe_reference( recipe::_CanonicalStatusRecipe, variable::Symbol, ) - position = _status_recipe_position(recipe, variable) - iszero(position) && throw(KeyError(variable)) - return recipe.references[position] + 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] + reference = _initial_status_reference(original, variable) + reference === nothing && throw(KeyError(variable)) + return reference end -function _status_recipe_set_reference!( +Base.@nospecializeinfer function _status_recipe_set_reference!( recipe::_CanonicalStatusRecipe, 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) - end - elseif recipe.references[position] === reference - return false + @nospecialize(reference::Ref), +) + _validate_status_reference(recipe.original, variable, reference) + position = findfirst(isequal(variable), recipe.edit_names) + if isnothing(position) + original = recipe.original + if hasproperty(original, variable) && + refvalue(original, variable) === reference + return false + end + 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 @@ -5376,44 +6860,93 @@ function _status_recipe_add_default!( return _status_recipe_set_reference!(recipe, variable, Ref(initial)) end -function _finish_status_recipe(recipe::_CanonicalStatusRecipe) - recipe.changed || return recipe.original - names = Tuple(recipe.names) - references = Tuple(recipe.references) - return Status(NamedTuple{names}(references)) +# 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) + 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)) + _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) + 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 _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_object(model, object_id).status - (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`." - ) + status = model_status(model, object_id) + (isnothing(status) || status isa Status) || _invalid_object_status(object_id, nameof(typeof(status))) return status end function _status_recipe_for_object!( - recipes::Dict{ObjectId,_CanonicalStatusRecipe}, - recipe_order::Vector{ObjectId}, - model::CompositeModel, - object_id::ObjectId, -) - return get!(recipes, object_id) do - status = _model_object_status_for_preparation(model, object_id) - push!(recipe_order, object_id) - _CanonicalStatusRecipe(status) + recipes::AbstractDict{I,R}, recipe_order::AbstractVector{I}, + model::CompositeModel, raw_id::ObjectId, +) where {I<:ObjectId,R<:_CanonicalStatusRecipe} + 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!( - recipes::Dict{ObjectId,_CanonicalStatusRecipe}, - recipe_order::Vector{ObjectId}, + recipes::AbstractDict{I,R}, + recipe_order::AbstractVector{I}, model::CompositeModel, object_id::ObjectId, -) +) where {I<:ObjectId,R<:_CanonicalStatusRecipe} + 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) @@ -5425,18 +6958,22 @@ end function _apply_status_recipes!( model::CompositeModel, - recipes::Dict{ObjectId,_CanonicalStatusRecipe}, - recipe_order::Vector{ObjectId}; + recipes::AbstractDict{I,R}, + 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 - _replace_model_object_status!( - model, - object_id, - _finish_status_recipe(recipe), - ) + 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 + status = _finish_canonical_status_recipe!(recipe) + _replace_model_object_status!(model, object_id, status) _runtime_performance_count!( performance, :lifecycle_binding_refresh_status_recipe_materializations, @@ -5450,7 +6987,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, ), ) @@ -5458,179 +6995,146 @@ 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)) +@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) - isnothing(object.status) && _replace_model_object_status!(model, object, Status()) - object.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`." - ) - return object.status + return Base.@inline _with_prepared_canonical_status_type( + _ensure_prepared_model_object_status!, model, model, object, object_id) 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) +@inline function _ensure_prepared_model_object_status!(::Type{S}, model, object, + object_id, +) where {S<:Status} + status = getfield(object, :status) + if isnothing(status) + replacement = Base.@inline _new_prepared_status(S, nothing) + status = _replace_model_object_status!(model, object, replacement) + end + 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.", + )) + return status::S +end + +# 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} + for variable in variables + if preparation isa Status + 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 + _with_metadata_entry(stage_default!, defaults, variable, + preparation, variable, context) end - return model + return nothing end -function _prepare_model_output_statuses_batched!( - model::CompositeModel, - applications; - performance=nothing, -) - recipes = Dict{ObjectId,_CanonicalStatusRecipe}() - recipe_order = ObjectId[] - 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!( +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 nothing +end + +function _output_status_preparation(model) + I = keytype(model.registry.objects) + recipes = _canonical_status_recipe_storage(model, I) + 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)) + 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!( recipes, recipe_order, model, object_id, ) + 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_status_defaults!, recipes, model.registry.objects.catalog, + preparation, defaults, variables, + _stage_model_output_default!, context, + ) 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 - result = _apply_status_recipes!( - model, - recipes, - recipe_order; - performance=performance, - ) - conversion_records === model.status_conversion_records || - 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!( model::CompositeModel, resolved_destinations, ) - missing = NamedTuple[] + details = nothing 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) - 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 " * "`$(resolved.plan.application_id)` requires `$(expected_type)` " * - "on destination `$(destination_id.value)`; got `$(typeof(value))`.", + "on destination `$(_object_id_text(destination_id))`; got `$(typeof(value))`.", )) 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, - ), - ) + 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( - [ - "`$(row.application_id).$(row.group)` requires `$(row.variable)` on " * - "destination object `$(row.destination_id)`" - for row in 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!( @@ -5641,162 +7145,280 @@ 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 `$(destination_id.value)` 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 end -function _prepare_model_output_destination_statuses!( - model::CompositeModel, - resolved_destinations, -) - recipes = Dict{ObjectId,_CanonicalStatusRecipe}() - recipe_order = ObjectId[] - 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!( +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, + 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, destination_id, ) - for (variable_, declaration) in pairs(resolved.plan.declarations) - declaration isa Default || continue - variable = Symbol(variable_) - if preparation isa Status - variable in propertynames(preparation) && 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 + _status_recipe_add_default!( + model, + preparation, + destination_id, + variable, + _input_default(declaration); + application_id=record.plan.application_id, + origin=:distributed_output_default, conversion_records, + ) + end + end + return nothing +end + +function _prepare_model_output_destination_statuses!( + model::CompositeModel, resolved_destinations, +) + I = keytype(model.registry.objects) + recipes = _canonical_status_recipe_storage(model, I) + recipe_order = I[] + record_conversions = !_no_status_conversion(model.status_conversion) + records_before = record_conversions ? copy(model.status_conversion_records) : nothing + try + 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 - return _apply_status_recipes!(model, recipes, recipe_order) end -function _model_output_destination_columns( - model::CompositeModel, - resolved::ResolvedModelOutputDestination, -) - declarations = resolved.plan.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) +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 - return NamedTuple{names}(Tuple(columns)) + if length(references) != 1 || !(only(references) <: Base.RefValue) || + !isconcretetype(eltype(only(references))) + push!(carriers, ObjectRefVector{Vector{R}}) + end + 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 -function _model_output_destination_index(destination_ids) - index = Dict{ObjectId,Int}() +_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} + 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."))) + columns = Expr(:tuple, [:( + _model_output_destination_column(model, destination_ids, + 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} + index = Dict{I,Int}() sizehint!(index, length(destination_ids)) 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_text(object_id))`.", ) index[object_id] = position end return index end +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, + 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) + 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. +# 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 + +@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}(), _object_key_index(Tuple{Symbol,$I}, $groups)) +end + function _compile_model_output_destination_bindings( model::CompositeModel, resolved_destinations, + plans::CompiledDistributedOutputPlans, ) - bindings = Any[] + 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)) - by_execution_pairs = Dict{ - Tuple{Symbol,ObjectId}, - Vector{Pair{Symbol,Any}}, - }() + resolved_by_plan = Dict{Int,Vector{Tuple{I,Vector{I}}}}() 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 + 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 (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) + 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 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. return bindings, by_execution_target end -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) - 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) +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 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] @@ -5809,29 +7431,35 @@ end function _compile_model_distributed_outputs( model::CompositeModel, applications, + applications_by_id, manual_application_ids, ::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_batched!(model, applications) + _prepare_model_output_statuses!(model, applications, applications_by_id) return NoCompiledDistributedOutputs() end function _compile_model_distributed_outputs( model::CompositeModel, applications, + applications_by_id, manual_application_ids, - plans::CompiledDistributedOutputPlans, + plans::CompiledDistributedOutputPlans, before_publish! = nothing, ) resolved = _resolve_model_output_destinations( model, - applications, + applications_by_id, plans, ) ownership = _compile_model_writer_ownership( + keytype(model.registry.objects), applications, + applications_by_id, manual_application_ids, resolved, ) @@ -5840,38 +7468,47 @@ 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_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) + _compile_model_output_destination_bindings(model, resolved, plans) return CompiledDistributedOutputs( bindings, by_execution_target, ownership, - _index_model_output_destination_ids(bindings), + _index_model_output_destination_ids(model.registry.objects, bindings, plans), ) end -_distributed_output_binding_key(binding) = ( - binding.application_id, - binding.execution_object_id, - binding.group, -) +# 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 +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}}() - 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])) + 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 @@ -5885,24 +7522,81 @@ function _refresh_model_distributed_outputs( plans, added_ids, new_targets, - pure_addition, -) - return previous, Set{Tuple{Symbol,ObjectId}}(), nothing + pure_addition, before_publish!, +) + before_publish!(previous, ()) + 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 +# 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} + 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) && + !_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 _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[])) +# 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, :replace_columns),Tuple{binding,IDs,C,Bool}}} + 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, replace_columns::Bool, +) 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, replace_columns))) + return nothing + end + end) end - push!(owners, owner) - return staged + return quote + $(branches...) + throw(ArgumentError("Distributed addition fields do not match their prepared binding.")) + 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!( @@ -5913,117 +7607,56 @@ 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 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 - resolved_additions = ResolvedModelOutputDestination[] - for binding in previous.bindings - default_scope = _default_dependency_scope( - model, - binding.execution_object_id, - ) - destination_ids = ObjectId[ - object_id for object_id in added_ids - if _selector_matches_object_id( - model, - binding.matcher, - object_id; - context=binding.execution_object_id, - default_to_context=true, - default_scope=default_scope, - ) && !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 - push!( - resolved_additions, - ResolvedModelOutputDestination( - binding.plan, - binding.execution_object_id, - destination_ids, - ), - ) + resolved_additions = _model_output_destination_rows( + keytype(model.registry.objects), applications_by_id, plans) + 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) _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 keys(plan.declarations) - 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 - _validate_compiled_writer_ownership!(staged_ownership, applications) - _prepare_model_output_destination_statuses!(model, resolved_additions) + _record_destination_writers!(staged_ownership, previous, resolved_additions) + _validate_compiled_writer_ownership!(staged_ownership, applications_by_id) + 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 = 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] binding = getproperty(groups, resolved.plan.group) - columns = _model_output_destination_columns(model, resolved) - for variable in keys(binding.declarations) - existing_references = parent(getproperty(binding.columns, variable)) - added_references = parent(getproperty(columns, variable)) - eltype(added_references) <: eltype(existing_references) || - return nothing + columns = _model_output_destination_columns( + model, resolved.plan, resolved.destination_ids, + ) + 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 - push!(column_additions, (binding=binding, resolved=resolved, columns=columns)) + _append_model_output_column_addition!(column_additions, binding, + resolved.destination_ids, columns, replace_columns) end for (key, owners) in staged_ownership @@ -6031,33 +7664,31 @@ function _incremental_distributed_output_addition!( end for addition in column_additions binding = addition.binding - resolved = addition.resolved - for variable_ in keys(binding.declarations) + 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) ] 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) 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 @@ -6070,7 +7701,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!( @@ -6081,368 +7712,374 @@ function _refresh_model_distributed_outputs( manual_application_ids, plans, added_ids, - new_targets, + new_targets, before_publish!, ) isnothing(incremental) || return incremental end current = _compile_model_distributed_outputs( model, 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 # 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 keys(group.declarations) - 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 keys(group.declarations) - 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 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 - default_scope = _default_dependency_scope(model, binding.consumer_id) - for (destination, producer) in candidates - producer in binding.plan.potential_source_application_ids || continue - _selector_matches_object_id( - model, - binding.matcher, - destination; - context=binding.consumer_id, - default_to_context=true, - default_scope, - ) || continue - push!(forced, (binding.application_id, binding.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 _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) - 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}, Ref) for binding in bindings - binding.carrier_hint == :temporal_stream && continue - isnothing(binding.carrier) && continue - references[( - binding.application_id, - binding.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 _prepare_model_input_defaults!( - model::CompositeModel, - applications; - final_references=nothing, - performance=nothing, -) - for application in applications - schema = _input_schema(application.spec) - 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, - 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) - end - end - return model +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 -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, - ) +# 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 <: 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) + end + return Tuple(references) +end + +@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 + +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 nothing end - return model + 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!(recipe, variable, reference) + counter = context.input_default_rewrites_avoided + isnothing(counter) || (counter[] += 1) + return nothing end -function _prepare_model_input_statuses_batched!( - model::CompositeModel, - applications, - bindings; - final_references=nothing, - performance=nothing, -) - 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}() - input_default_rewrites_avoided = 0 - for application in applications - schema = _input_schema(application.spec) - 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, - ) - 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, - ) - input_default_rewrites_avoided += 1 - continue +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_canonical_status_preparation( + _stage_model_bound_input_reference_with_preparation!, context.recipes, + context.model.registry.objects.catalog, preparation, reference, binding, context) +end + +@inline function _stage_model_bound_input_reference_with_preparation!(preparation, + reference, binding, context, +) + return Base.@inline _with_model_input_status_reference( + _stage_admitted_model_input_reference!, binding, + reference, preparation, binding.consumer_id, binding.input, context) +end + +# 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, 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 + elseif !_status_recipe_has_variable(preparation, variable) || + _status_recipe_reference(preparation, variable) !== reference + _status_recipe_set_reference!(preparation, variable, reference) + end + context.default_status_updates[(object_id, variable)] = false + return nothing +end + +function _prepare_model_input_statuses_batched!( + model::CompositeModel, + applications, + applications_by_id, + bindings; + final_references=nothing, + performance=nothing, +) + 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 + 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, 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 + _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 + 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 - _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 nothing end 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!( @@ -6451,8 +8088,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, @@ -6465,79 +8101,23 @@ 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 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) + return _private_initial_value(value) 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 +# Test source ownership inside the existing finite application metadata branch. +_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( binding::CompiledModelInputBinding, @@ -6551,11 +8131,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( + _application_writes_source_variable, applications_by_id, application_id, + distributed_outputs, source_id, binding.source_var, ) ] canonical_application = _distributed_temporal_source_application( @@ -6571,17 +8149,19 @@ 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_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])) 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 `", 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.") + error(String(take!(io))) end _distributed_temporal_source_application( @@ -6621,142 +8201,11 @@ 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(Symbol.(keys(_local_output_schema(application.spec)))) - 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(), -) - # 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( - 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( - 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 - 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( - 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)) - names = collect(Symbol, propertynames(canonical_status)) - for name in private_output_names - name in names || push!(names, name) - 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) - end - status = Status(NamedTuple{Tuple(names)}(Tuple(references))) - return CompiledModelStatusView( - status, - canonical_status, - Tuple(temporal_inputs), - private_outputs, - _compiled_bound_many_inputs(input_bindings, status), - ) +_status_view_execution_stamp(previous::CompiledModelStatusView, model, key) = previous.execution_stamp +@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) end function _compile_model_status_views( @@ -6764,10 +8213,14 @@ function _compile_model_status_views( 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}() + 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( application_id => index for (index, application_id) in pairs(application_order) @@ -6783,6 +8236,9 @@ function _compile_model_status_views( applications_by_id, positions, 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, ) end end @@ -6793,7 +8249,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 @@ -6805,42 +8261,54 @@ 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 - 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 + for source_id in source_ids + _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. + 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, Any[]) - 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) + 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, @@ -6852,7 +8320,6 @@ function _matching_input_source_applications( applications_by_id, ) end - unique!(resolved) resolved end if !allow_empty && @@ -6893,13 +8360,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 @@ -6947,18 +8417,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( @@ -6974,7 +8443,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) || @@ -6996,10 +8465,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( @@ -7007,8 +8476,8 @@ function _input_plan_writer_applications( application.id, (), ) - for variable in keys(plan.declarations) - candidates = get!(Vector{CompiledModelApplication}, writers, variable) + for variable in plan.variable_names + 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) && @@ -7024,32 +8493,14 @@ 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, - application.applies_to, - ) -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( source_selector, - application.applies_to, + applies_to(application.spec), ) && return true - return any( - plan -> variable in keys(plan.declarations) && - _selector_labels_may_overlap(source_selector, plan.selector), - _application_plans(plans.by_application, application.slot), - ) + return _application_declares_distributed_output(application, variable, source_selector, plans) end _application_declares_distributed_output( @@ -7065,13 +8516,22 @@ function _application_declares_distributed_output( source_selector, plans::CompiledDistributedOutputPlans, ) - return any( - plan -> variable in keys(plan.declarations) && - _selector_labels_may_overlap(source_selector, plan.selector), - _application_plans(plans.by_application, application.slot), + return Base.@inline _with_metadata_entry( + _any_matching_output_destination, plans.by_application, application.id, variable, source_selector, ) 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) + 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( applications, selector, @@ -7083,7 +8543,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 @@ -7095,14 +8555,244 @@ 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 +# 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 + 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 _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 _required_status_reader_bound(model, ports, input, selector) + input in _required_input_names(ports) || return nothing + 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.")) + 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, + 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, 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) + end + union!(current, ids) + 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 _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 + +# 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, 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 + 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) + 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 + 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, evidence_selector, source_selectors, distributed, input, source_var) + missing_current = copy(current) + 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 && hasproperty(status, source_var) || continue + reference = refvalue(status, source_var) + reference isa Ref || continue + add(typeof(reference)) + delete!(missing_current, object.id) + end + end + # 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) + # 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, source_var, + getproperty(output_types, source_var), get(element_types, source_var, nothing)) + end + candidates = isnothing(T) ? () : Base.uniontypes(T) + if isempty(candidates) || !all(isconcretetype, candidates) + candidates = fallback === Union{} ? () : (fallback,) + end + # 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) + 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 + 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 + 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. + return Tuple{Base.uniontypes(Union{references...})...} +end + Base.@nospecializeinfer function _compiled_model_input_plan( - plans, - model, + model::CompositeModel, + slot::Int, writer_applications, application, input::Symbol, @@ -7112,6 +8802,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 @@ -7159,222 +8850,287 @@ Base.@nospecializeinfer function _compiled_model_input_plan( "`PreviousTimeStep(:$(input))`." ) end + route = InputRouteTag{input,source_var,_selector_from_status(selector)}() return CompiledModelInputPlan( - length(plans) + 1, - application.plan.slot, + route, + slot, + application.slot, application.id, input, selector, - _compile_selector_matcher(model, selector), + _authored_selector_matcher(selector), origin, Tuple(order_after_application_ids), source_var, process_filter, application_filter, - multiplicity(selector), potential_source_application_ids, breaks_same_step_cycle, _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, birth_types), ) end -function _compile_model_input_plans( - model::CompositeModel, - applications, - distributed_output_plans=_compile_model_output_destination_plans( - model, - applications, - ), -) +function _prepare_authored_input_records(model, applications, distributed_output_plans, birth_types) plans = CompiledModelInputPlan[] - 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. - 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 - ) - # 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. + 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(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, - variable_contracts_by_application, - ), - ) + applications_by_id, distributed_output_plans, local_output_names, + variable_contracts_by_application, birth_types) + 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(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, birth_types) + 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.potential_source_application_ids, + plan.breaks_same_step_cycle, plan.window, plan.reference_types) +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(model, _project_authored_applications(preparation, applications), + distributed_output_plans, _frozen_birth_status_types(preparation.status_manifest)) + 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 +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 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 - destinations = _resolved_output_destinations(application.spec) - 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))) || - error("Object override for application `$(application.id)` has incompatible distributed output names.") + # 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) + 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( + "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, :vars), - 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_slot::Integer) = - getfield(plans_by_application, application_slot) +_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, @@ -7382,24 +9138,20 @@ function _potential_input_source_applications( 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 = _resolved_output_destinations(application.spec) - return any( - destination -> variable in keys(destination.vars), - 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( @@ -7407,16 +9159,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 @@ -7426,7 +9185,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) @@ -7444,7 +9204,8 @@ function _final_canonical_source_application( source_ids, source_application_ids, source_var, - NoCompiledDistributedOutputs(), + NoCompiledDistributedOutputs(); + applications_by_id, ) return Symbol[last(canonical_ids)] end @@ -7452,63 +9213,63 @@ end function _compile_model_input_bindings( model::CompositeModel, applications, - manual_application_ids=Set{Symbol}(), - plans_by_application=nothing, - distributed_outputs=NoCompiledDistributedOutputs(), -) - if isnothing(plans_by_application) - plans_by_application = _plans_by_application( - applications, - _compile_model_input_plans(model, applications), - ) - end - bindings = CompiledModelInputBinding[] - 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(plans_by_application, application.slot), - manual_application_ids, - by_object, - by_id, - distributed_outputs, + manual_application_ids, + 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) + 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 + # 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 end -Base.@nospecializeinfer function _push_model_input_binding!( - 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(), - ; object_query_cache=nothing, + distributed_outputs=NoCompiledDistributedOutputs(); + 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, @@ -7520,7 +9281,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( @@ -7561,7 +9322,8 @@ Base.@nospecializeinfer function _push_model_input_binding!( source_ids, source_application_ids, source_var, - distributed_outputs, + distributed_outputs; + applications_by_id, ) end if selector isa Many && length(source_application_ids) > 1 @@ -7575,27 +9337,45 @@ Base.@nospecializeinfer function _push_model_input_binding!( end if !(selector isa Many) && length(source_application_ids) > 1 error( - "Input `$(input_sym)` on application `$(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 if selector isa OptionalOne && (!isnothing(process_filter) || !isnothing(application_filter)) && isempty(source_application_ids) - source_ids = ObjectId[] + 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, statuses=nothing, +) + 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, ) @@ -7613,9 +9393,10 @@ Base.@nospecializeinfer function _push_model_input_binding!( source_application_ids, source_var, applications_by_id, + plan.reference_types, statuses, ) else - _input_carrier(model, selector, source_ids, source_var) + _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 @@ -7626,26 +9407,42 @@ Base.@nospecializeinfer function _push_model_input_binding!( end _validate_model_input_source!( model, - application, + application_id, consumer_id, input_sym, source_var, source_ids, carrier, - carrier_hint, + carrier_hint, statuses, ) - 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, _route_cells(bindings), + )) return bindings end @@ -7676,14 +9473,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 @@ -7733,12 +9526,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 haskey(_local_output_schema(application.spec), source_var) + 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, @@ -7763,111 +9561,113 @@ 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 -function _model_input_names(application::CompiledModelApplication) - return Symbol[Symbol(var) for var in keys(_input_schema(application.spec))] -end +_model_input_names(application) = _application_ports(application).input_names function _validate_model_input_source!( model::CompositeModel, - application::CompiledModelApplication, + application_id::Symbol, consumer_id::ObjectId, input_sym::Symbol, source_var::Symbol, - source_ids::Vector{ObjectId}, + source_ids::AbstractVector{I}, carrier, - carrier_hint::Symbol, -) + carrier_hint::Symbol, statuses=nothing, +) 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 + if _model_object(model, source_id).status isa Status || + (!isnothing(statuses) && haskey(statuses.recipes, source_id)) ] 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 `", 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[]) + end + print(io, "]`, but no source `Status` reference is available.") + error(String(take!(io))) 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( "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 -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 _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) -end - -function _validate_model_required_inputs!(model::CompositeModel, applications, input_bindings) - bound = _bound_model_inputs(input_bindings) - missing = NamedTuple[] - for application in applications - schema = _input_schema(application.spec) - 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, - ), - ) +function _validate_model_required_inputs!(model::CompositeModel, applications, applications_by_id, 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 + 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 + (application.id, object_id, input) in bound && continue + status = model_status(model, object_id) + status isa Status && hasproperty(status, input) && continue + push!( + missing, + ( + application_id=application.id, + object_id=_index_object_id(model.registry.objects, object_id), + input=input, + ), + ) + end end + return nothing end end isempty(missing) && return nothing - details = join( - [ - "`$(row.application_id)` on object `$(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) - 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) @@ -7876,12 +9676,136 @@ 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 _index_object_id(::AbstractDict{I}, object_id::ObjectId) where {I<:ObjectId} + object_id isa I || throw(ArgumentError( + "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 = _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::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...)) + for (index, entry_key) in enumerate(entry_keys)] + missing = K <: Symbol ? :(throw(KeyError(key))) : :(throw(BoundsError(table, key))) + return quote + $(branches...) + $missing + 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. +@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 + $(branches...) + throw(BoundsError(entries, key)) + end +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 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 + $(Expr(:meta, :inline)) + 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} + 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[]) - 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, ()) + 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 @@ -7897,17 +9821,17 @@ 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 # 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[] @@ -7981,150 +9905,119 @@ function _observe_compiled_call_membership!( return binding end -function _compile_model_call_bindings( - model::CompositeModel, - applications, - lookup_applications=applications, - ; - by_object=nothing, - plans_by_application=nothing, +function _compile_call_plan_binding!( + plan, bindings, model, application_id, consumer_id, application_objects, ) - if isnothing(plans_by_application) - plans_by_application = _plans_by_application( - applications, - _compile_model_call_plans(model, 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...], ) - end - bindings = CompiledModelCallBinding[] - for application in applications - for consumer_id in application.target_ids - for plan in _application_plans( - plans_by_application, - application.slot, + else + 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!( + application_ids, + _matching_callee_applications( + application_objects, + object_id, + proc, + app_name, + ), ) - 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)) - 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, - ), - ) - 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." - ) - end - push!( - bindings, - CompiledModelCallBinding( - plan, - consumer_id, - callee_object_ids, - callee_application_ids, - ), - ) - end end + unique!(application_ids) + (object_ids, application_ids) end - 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 + if mode === :manual && + isempty(callee_application_ids) && selector isa One + 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", + isnothing(proc) ? "." : " with process `$(proc)`.", + ) 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) + 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, + callee_object_ids, + callee_application_ids, + ), + ) 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..., +function _compile_application_call_bindings!( + plans, bindings, model, application_id, targets, application_objects, +) + for consumer_id in targets, slot in eachindex(plans) + Base.@inline _with_metadata_entry( + _compile_call_plan_binding!, plans, slot, bindings, model, application_id, + consumer_id, application_objects, ) - 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 + return nothing 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) +function _compile_model_call_bindings( + model::CompositeModel, + applications; + by_object=_applications_by_object(applications, model.registry.objects), + applications_by_id, + plans_by_application, +) + bindings = _model_call_binding_storage( + plans_by_application, keytype(model.registry.objects), + ) + for partial_application in applications + 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, + ) end end - return children + return bindings +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 _stable_topological_application_order(applications, children) @@ -8158,34 +10051,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 @@ -8207,13 +10072,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= @@ -8223,7 +10088,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), @@ -8234,18 +10099,18 @@ 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)), - 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[] : [ ( @@ -8253,8 +10118,8 @@ function explain_applications(compiled::CompiledCompositeModel) model_type=typeof(model), ) for (object_id, model) in sort!( - collect(application.model_overrides); - by=pair -> string(first(pair).value), + collect(_application_model_overrides(application)); + by=pair -> _object_id_text(first(pair)), ) ], ) @@ -8266,12 +10131,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) @@ -8318,7 +10182,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 @@ -8435,7 +10299,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)), ), @@ -8465,11 +10329,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, ( 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/environment_bindings.jl b/src/composite_model/environment_bindings.jl index 62055da86..2c9891510 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_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 """ @@ -29,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( @@ -46,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 @@ -78,30 +84,49 @@ 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) - 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[] : @@ -109,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!( @@ -134,30 +166,35 @@ function _update_model_environment_indices_for_objects!( dirty_object_ids, ) application_ids = Set{Symbol}() - for object_id in dirty_object_ids - for application in get(compiled.applications_by_object, object_id, ()) + 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 for target in get(cached.targets_by_object, object_id, ()) 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, - ) + Base.@inline _with_environment_plan(cached.environment_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 + Base.@inline _with_environment_plan(cached.environment_schema, plan) do admitted_plan + consume(admitted_plan.backend) + end + end end function _environment_variable_names(vars) @@ -165,112 +202,416 @@ 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 + +# 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, +) + 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 = _environment_sampling_window(application.clock, application.spec) + 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 + 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( model::CompositeModel, - applications; + applications, + applications_by_id; previous_plans_by_id=nothing, prepare_runtime::Bool=true, + environment_schema=EnvironmentBindingSchema(), ) 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 application in applications - config = environment_config(application.spec) - backend = _environment_backend_from_config(model, config) - sampling_rules = Tuple(_environment_sampling_rules(application.spec)) - 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), - ) - 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)) + produced_outputs = _model_environment_output_names(application) + 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 = _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 + 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 + _prepare_environment_application_plan( + backend, nothing, nothing, + uses_raw_global_source, prepare_runtime, application, + environment_schema, config, required_inputs, produced_outputs, sampling_rules) end + 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 - bindings = environment_bindings(application.spec) - has_bindings = bindings isa NamedTuple && !isempty(keys(bindings)) - has_source_overrides = - !isempty(keys(_environment_source_overrides(application.spec))) - plan = CompiledEnvironmentApplicationPlan( - application.id, - backend, - config, - required_inputs, - source_inputs, - produced_outputs, - sampling_rules, - compiled_sampling_rules, - sampler, - prepared_source, - backend isa GlobalConstant && - isnothing(sampler) && - !has_bindings && - !has_source_overrides, - ) - 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 +_environment_schema(::Nothing) = EnvironmentBindingSchema() +_environment_schema(owner::CompiledEnvironmentBindings) = owner.environment_schema +_collecting_environment_binding_schema() = EnvironmentBindingSchema(DataType[], DataType[]) + +_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 + +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, +) + _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(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.") + 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 + +_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 + +@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; environment_schema=schema) +end + function _compile_environment_bindings_for_applications( model::CompositeModel, applications, - plans_by_id, + plans_by_id; + environment_schema=EnvironmentBindingSchema(), ) 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) - 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, + application_id = application.id + application_process = application.process + target_ids = application.target_ids + 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) + 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, + _new_environment_binding( + environment_schema, + plan, + object_id, + handle, + context, + geometry_source_object_id, + geometry_source, + ), + ) + end end end return bindings @@ -279,57 +620,55 @@ end function _compile_environment_bindings( model::CompositeModel, compiled::CompiledCompositeModel, - plans_by_id, + plans_by_id; + environment_schema=EnvironmentBindingSchema(), ) return _compile_environment_bindings_for_applications( model, compiled.applications, - plans_by_id, + plans_by_id; + environment_schema, ) end -function _validate_model_environment_inputs!(bindings, applications_by_id) - missing_rows = NamedTuple[] +function _missing_model_environment_input_detail( + application_id, process, object_id, target, source, available, +) + 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, ")") +end + +function _validate_model_environment_inputs!(bindings, applications_by_id, + ::Type{I}; environment_schema=EnvironmentBindingSchema(), +) where {I<:ObjectId} + missing_details = String[] for binding in bindings - 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)), - ), - ) + plan = getfield(binding, :plan)::CompiledEnvironmentApplicationPlan + object_id = getfield(binding, :object_id)::I + 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)) + 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, _missing_model_environment_input_detail( + application_id, application.process, object_id, target, source, available, + )) + end end end - isempty(missing_rows) && return nothing - details = join( - [ - string( - row.application_id, - "/", - row.object_id, - " (", - row.process, - ") needs `", - row.target, - "` from source `", - row.source, - "`; available=", - row.available, - ) - for row in missing_rows - ], - "; ", - ) - error("Composite model environment is missing required source inputs: ", details) + isempty(missing_details) && return nothing + io = IOBuffer() + print(io, "Composite model environment is missing required source inputs: ") + join(io, missing_details, "; ") + error(String(take!(io))) end struct PreparedGlobalEnvironmentRows{R} @@ -341,6 +680,19 @@ end step::Int, ) = @inbounds prepared.rows[step] +# These are row-type declarations, not calls to sample arbitrary providers. +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) + # 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} @@ -368,16 +720,20 @@ 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), + targets_by_object=_index_environment_targets_by_object( + bindings, keytype(model.registry.objects), + ); + environment_schema=EnvironmentBindingSchema(), ) + _check_environment_schema_owner(environment_schema, application_plans, bindings) return CompiledEnvironmentBindings( model, application_plans, application_plans_by_id, + environment_schema, bindings, by_target, positions_by_target, @@ -385,31 +741,50 @@ function _compiled_environment_bindings( sample_cache, model.revision, model.environment_revision, - objectid(compiled.applications), + compiled.applications, ) 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} + 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} + 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) - # 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 - for binding in bindings - ) +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 = _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 + end length(by_target) == length(bindings) || error( "Environment binding compilation produced duplicate `(application_id, object_id)` targets.", ) @@ -417,23 +792,34 @@ function _index_environment_bindings(bindings) 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_schema(cached)) +end + +function _compile_environment_binding_owner(model::CompositeModel, + compiled::CompiledCompositeModel, environment_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, + compiled.applications_by_id; environment_schema) bindings = _compile_environment_bindings( model, compiled, - application_plans_by_id, + application_plans_by_id; + environment_schema, ) - _validate_model_environment_inputs!(bindings, compiled.applications_by_id) - by_target = _index_environment_bindings(bindings) + _validate_model_environment_inputs!(bindings, compiled.applications_by_id, + keytype(model.registry.objects); environment_schema) + by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, compiled, application_plans, application_plans_by_id, bindings, - by_target, + by_target; + environment_schema, ) end @@ -445,11 +831,20 @@ 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( + 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) @@ -463,7 +858,10 @@ 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) && + isequal(a.sample_schema.window, b.sample_schema.window) && + isequal(a.sample_schema.transforms, b.sample_schema.transforms) end function _reconciled_environment_application_plans( @@ -471,29 +869,95 @@ 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, + compiled.applications_by_id; previous_plans_by_id=cached.application_plans_by_id, + environment_schema=cached.environment_schema, ) plans = CompiledEnvironmentApplicationPlan[] plans_by_id = Dict{Symbol,CompiledEnvironmentApplicationPlan}() + environment_schema = cached.environment_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 + 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 - plan = !isnothing(old) && - _same_environment_application_plan(old, candidate) ? - old : candidates_by_id[candidate.application_id] - 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} + _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, @@ -511,39 +975,24 @@ function _reconcile_environment_binding_metadata( bindings = CompiledEnvironmentBinding[] changed = false + environment_schema = cached.environment_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) - old = get(cached.by_target, key, nothing) + 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, object) + 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.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 - - 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 = 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 + changed |= binding !== old + push!(bindings, binding) end end changed || return _compiled_environment_bindings( @@ -555,10 +1004,13 @@ function _reconcile_environment_binding_metadata( cached.by_target, cached.sample_cache, cached.positions_by_target, - cached.targets_by_object, + cached.targets_by_object; + environment_schema=cached.environment_schema, ) - _validate_model_environment_inputs!(bindings, compiled.applications_by_id) - by_target = _index_environment_bindings(bindings) + _validate_model_environment_inputs!(bindings, compiled.applications_by_id, + keytype(model.registry.objects); + environment_schema=cached.environment_schema) + by_target = _index_environment_bindings(bindings, keytype(model.registry.objects)) return _compiled_environment_bindings( model, compiled, @@ -566,7 +1018,8 @@ function _reconcile_environment_binding_metadata( application_plans_by_id, bindings, by_target, - cached.sample_cache, + cached.sample_cache; + environment_schema=cached.environment_schema, ) end @@ -576,7 +1029,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, @@ -584,44 +1044,45 @@ 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 - current_applications = get( - compiled.applications_by_object, - object_id, - (), - ) - previous_targets = get(cached.targets_by_object, object_id, ()) + K = keytype(cached.by_target) + 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) + current_applications = _application_membership_slots(compiled, object_id) + previous_targets = get(cached.targets_by_object, object_id, empty_targets) 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 = _partial_model_application(application, I[object_id]) + for binding in _compile_environment_bindings_for_applications( + model, + (partial_application,), + cached.application_plans_by_id; + environment_schema=cached.environment_schema, + ) + 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); + environment_schema=cached.environment_schema, ) for target in stale_targets @@ -630,27 +1091,25 @@ 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) 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 - 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, ) @@ -668,7 +1127,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; + environment_schema=cached.environment_schema, ) end @@ -702,3 +1162,76 @@ 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 + +# 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. +# 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, + environment_schema=_environment_schema(cached), +) + 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_binding_owner(compiled, cached, environment_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 && !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_binding_owner(model, compiled, environment_schema) + else + _refresh_environment_bindings_for_objects( + model, + compiled, + partial_owner, + delta.environment_dirty_ids, + ) + end + else + _compile_environment_binding_owner(model, compiled, environment_schema) + 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 + elseif cached.model_revision == compiled.revision && + cached.environment_revision == model.environment_revision && + cached.compiled_applications === compiled.applications + return cached + else + reconciled = _reconcile_environment_binding_metadata(model, compiled, cached) + refreshed = isnothing(reconciled) ? + _compile_environment_binding_owner(model, compiled, environment_schema) : reconciled + model.environment_binding_cache = refreshed + _record_runtime_owner_replacement!(model, cached, refreshed) + return refreshed + end +end diff --git a/src/composite_model/execution_batch_schemas.jl b/src/composite_model/execution_batch_schemas.jl new file mode 100644 index 000000000..3708b20b6 --- /dev/null +++ b/src/composite_model/execution_batch_schemas.jl @@ -0,0 +1,793 @@ +# 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 _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) + 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_batch_storage_type(fieldtype(CT, :binding), 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 = isempty(fieldtypes(C)) || any(fieldtype(CT, :batch_schema) <: PreparedExecutionBatchSchema for CT in fieldtypes(C)) + 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 = _output_target_binding_type(View) + 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 + +# 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. +@inline function _with_execution_target_type(f::F, ::OpenExecutionCohortSchema, + application, status_view::V, object_id, model, output_groups, call_bindings, + 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) + 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, args::Vararg{Any,N}, +) where {T,N} + 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 + V = fieldtype(Target, :status_view) + Views = fieldtype(Target, :output_targets) + Groups = _output_target_binding_groups_type(Views) + checks = Expr[:(application isa $(fieldtype(Context, :application))), + :(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)::$Views) + elseif name === :bound_inputs + # The earlier status_view check short-circuits before this read. + :((status_view::$V).bound_inputs) + else + name + end + 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) + push!(checks, :(getproperty(owners, $(QuoteNode(name))) isa $(fieldtype(Context, name)))) + end + condition = foldl((a,b) -> :($a && $b), checks) + 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(), $(arguments...)) + 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 + +@inline _materialize_call_execution_batches!(::OpenExecutionBatchSchema, targets::CallTargets) = + _materialize_open_call_execution_batches!(targets) + +@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, +) + @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 () + # 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)) + 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) + +@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 + 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)) + 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), batch_schema=schema) + end + 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 + +@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, 0, application.clock.dt) + 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 = _output_target_binding(target) + binding isa B || throw(ArgumentError("A distributed output owner is outside its prepared schema.")) + 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, + 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_view::CompiledModelStatusView, output_targets, + application, object_id, 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 + status = status_view.status + 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,status_view,output_targets,application,object_id, + retention,streams) || throw(ArgumentError("Prepared retained output names or ownership changed.")) + end + return _prepare_runtime_output_capacity!(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, 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) + 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, + _prepare_output_request_schemas(simulation.output_requests, schemas), + 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_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)} + 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) + Store = fieldtype(fieldtype(B, :targets), :store) + Owner = _execution_store_owner_type(Store) + Rows = ExecutionCohortRows{prepared_target,I,Owner,Store} + return CompiledExecutionBatch{fieldtype(B,:application),Rows, + fieldtype(B,:environment_provider),fieldtype(B,:output_publication)} +end + +# 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 (slot, id) in enumerate(fieldnames(Entries)) + Plans = fieldtype(Entries, slot) + index = findfirst(P -> _prepared_call_plan_name(P) === name, fieldtypes(Plans)) + isnothing(index) && continue + 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(id)) + bindings = get(compiled.call_bindings_by_target, (application_id, object_id), ()) + isempty(bindings) && return nothing + bindings isa $Bindings || _unprepared_runtime_configuration() + 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 + $(branches...) + return nothing + end +end + +@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 + +# 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/execution_cohort_refresh.jl b/src/composite_model/execution_cohort_refresh.jl new file mode 100644 index 000000000..92d52fc9a --- /dev/null +++ b/src/composite_model/execution_cohort_refresh.jl @@ -0,0 +1,377 @@ +"""Ordered schedule membership, separate from persistent execution payloads.""" +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} + locations::Vector{L} + runs::Vector{R} + run_starts::Vector{Int} +end + +function _execution_cohort_target(cohort::ExecutionCohort{T}, row::Int) where {T} + target = cohort[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!(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], + 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) && _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) + 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 + _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) + 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) + 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!(starts, run_index + 1, -1) + if run_empty + deleteat!(runs, run_index) + deleteat!(starts, run_index) + if run_index > 1 && run_index <= length(runs) + 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) + deleteat!(starts, run_index) + end + 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, schema=OpenExecutionCohortSchema()) + 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) + sizehint!(ids, capacity) + sizehint!(locations, capacity) + return ExecutionCohortMembership( + 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, 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, previous.store, location, previous.owner, previous.application_id, object_id) + end + for rows in previous.runs + _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 + 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, 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.", + )) + return nothing +end + +@inline function _with_execution_membership_run(f, membership, index) + 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 + + +""" + 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, + 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 && + 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 + 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 + 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 + _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 + 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 + + # 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, store, location, owner, application_id, object_id) + end + membership = isnothing(previous) ? + _new_execution_cohort_membership(store, owner, application_id, length(current_ids), schema) : + 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, schema) + end + for (object_id, target) in staged_targets + 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, 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) + 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) + 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, + ) + end + end + 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 ( + 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 new file mode 100644 index 000000000..4db069dee --- /dev/null +++ b/src/composite_model/execution_cohorts.jl @@ -0,0 +1,436 @@ +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} + + _ExecutionCohortSlot{T}(value::Union{Nothing,T}) where {T} = new{T}(value) +end + +mutable struct ExecutionCohort{T,I<:ObjectId,O} <: AbstractExecutionCohort + owner::O + application_id::Symbol + rows::Vector{_ExecutionCohortSlot{T}} + indices::Dict{I,Int} + + 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 + +struct ExecutionCohortLocation{C<:AbstractExecutionCohort} + cohort::C + 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 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. + +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,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(::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,I<:ObjectId,O,S<:ExecutionCohortStore} <: AbstractVector{T} + store::S + cohort::ExecutionCohort{T,I,O} + indices::Vector{Int} +end + +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 +# 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 + +# 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 + _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.", + )) + return nothing +end + +@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::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) + I = fieldtype(Target, :object_id) + L = ExecutionCohortLocation{ExecutionCohort{Target,I,O}} + push!(branches, quote + if location isa $L + _check_execution_cohort_location(location, owner, application_id, object_id, schema) + return f(location) + end + end) + end + return quote + $(Expr(:meta, :inline)) + $(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, ::ExecutionCohortStore) = + (identity=ObjectId, target=Any, location=ExecutionCohortLocation, rows=ExecutionCohortRows) +@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),O}} 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 + +@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,fieldtype(Target,:object_id),O,S} + 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) +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[slot] + isnothing(target) && throw(ArgumentError( + "This execution target was removed or changed its payload schema.", + )) + return target::T +end + +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.", + )) + I = fieldtype(T, :object_id) + 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, _execution_cohort_key(store, owner, application_id, T)) do + ExecutionCohort{T,I,O}(owner, application_id, _ExecutionCohortSlot{T}[], Dict{I,Int}()) + end + return cohort::ExecutionCohort{T,I,O} +end + +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 + +function _store_execution_cohort_target!(store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T) where {T} + 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 + +function _store_execution_cohort_target!( + store::ExecutionCohortStore, cohort::ExecutionCohort{T}, target::T, previous, +) where {T} + 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, 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) + push!(cohort.rows, _ExecutionCohortSlot{T}(target)) + slot = length(cohort.rows) + cohort.indices[object_id] = slot + else + cohort.rows[slot] = _ExecutionCohortSlot{T}(target) + end + store.locations[_execution_location_key(store, 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) + +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 + +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, _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 = _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 + _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 new file mode 100644 index 000000000..d2ad77a20 --- /dev/null +++ b/src/composite_model/execution_dispatch.jl @@ -0,0 +1,64 @@ +abstract type ExecutionTopology end +struct DynamicExecution <: ExecutionTopology end +struct FixedExecution <: ExecutionTopology end + +# 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 + +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(_close_execution_group_cohorts(group; batches=Tuple(group.batches)) for group in plan.groups) + 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, + 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_model_revision, + simulation.runtime_revision, + simulation.current_step, + simulation.constants, + simulation.performance, + ) +end 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 new file mode 100644 index 000000000..f4ab7c1dc --- /dev/null +++ b/src/composite_model/execution_storage.jl @@ -0,0 +1,141 @@ +"""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},S<:ExecutionCohortStore} <: AbstractDict{K,V} + streams::D + 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}, 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...) +Base.getindex(storage::RuntimeStorage, key) = storage.streams[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!(() -> _runtime_storage_history(storage, default), storage.streams, key) +Base.get!(default::Union{Function,Type}, storage::RuntimeStorage, 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)()) +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) +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) + +# 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 = _call_retirement_current(schema, batches, batch_schema) + obsolete = _call_retirement_obsolete(schema) + 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) + 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 + _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, store, location, owner, application_id, admitted_id) + end + end + for (application_id, object_id) in obsolete + _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(), batch_schema=nothing) = 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/lifecycle_input_changes.jl b/src/composite_model/lifecycle_input_changes.jl new file mode 100644 index 000000000..e461b592b --- /dev/null +++ b/src/composite_model/lifecycle_input_changes.jl @@ -0,0 +1,248 @@ +# 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 _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 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 true +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 + + 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) + +_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 + _store_shared_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(entries, statuses, ranges, cache, model, existing, any_routes) +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 + +_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, + 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 + 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)) + 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/object_families.jl b/src/composite_model/object_families.jl new file mode 100644 index 000000000..5e8ee90a5 --- /dev/null +++ b/src/composite_model/object_families.jl @@ -0,0 +1,281 @@ +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}}} + + ObjectFamily{I,S}(rows::Vector{Union{Nothing,ObjectFamilyRow{I,S}}}) where {I<:ObjectId,S} = + new{I,S}(rows) +end + +struct ObjectFamilyLocation + family::Int + row::Int + object::Object +end + +mutable struct OpenObjectFamilyCatalog + families::Vector{AbstractObjectFamily} + slots::Dict{Tuple{Type,Type},Int} +end + +OpenObjectFamilyCatalog() = OpenObjectFamilyCatalog( + AbstractObjectFamily[], Dict{Tuple{Type,Type},Int}(), +) + +struct ClosedObjectFamilyCatalog{F<:Tuple,M} + families::F + status_manifest::M +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::OP, ::OpenObjectFamilyCatalog, status, + args::Vararg{Any,N}, +) where {OP,N} = f(status, args...) + +@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, args...)) 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.""" +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( + OpenObjectFamilyCatalog(), Dict{I,ObjectFamilyLocation}(), + IdDict{Base.RefValue{Nothing},I}(), +) +ObjectFamilyStore() = ObjectFamilyStore{ObjectId}() + +Base.length(store::ObjectFamilyStore) = length(store.locations) +Base.haskey(store::ObjectFamilyStore, id) = haskey(store.locations, id) +_registry_object_ids(store::ObjectFamilyStore) = keys(store.locations) +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(::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 + +# 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)) + 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 +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) + if !isnothing(existing) && existing != id + throw(ArgumentError( + "The same Status instance cannot be owned by model objects " * + "`$(_object_id_text(existing))` and `$(_object_id_text(id))`. 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, K, S) + if !isnothing(previous) + 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 + 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) + 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 + +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.")) + 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 + +function Base.delete!(store::ObjectFamilyStore, id) + location = get(store.locations, id, nothing) + isnothing(location) && return store + 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 + empty!(family.rows) + end + return store +end + +"""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))...} + 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}}[]), + 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/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/output_targets.jl b/src/composite_model/output_targets.jl index ff576227a..2eba99e0c 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) @@ -95,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( @@ -148,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( @@ -171,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) ] @@ -198,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/prepared_status_manifest.jl b/src/composite_model/prepared_status_manifest.jl new file mode 100644 index 000000000..54e8d4d15 --- /dev/null +++ b/src/composite_model/prepared_status_manifest.jl @@ -0,0 +1,897 @@ +# One constructor-owned manifest. This stores names, exact reference classes, +# 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,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,C} + 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 + const birth_types::C +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 + +# 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) + owner = _application_model_overrides(application) + return isnothing(owner) ? nothing : owner.object_slots +end + +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 + slots = _prepared_status_object_slots(application) + isnothing(slots) ? 1 : get(slots, object_id, 1) +end + +# 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) + 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, 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{} + return Union{map(T -> Base.RefValue{T}, members)...} +end + +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, 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, 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 + 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) + 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 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 +# constructor. A seed Vector value is not a RefVector carrier. +function _prepared_status_input_reference(plan) + refs = fieldtypes(plan.reference_types) + if !(plan.selector isa Many) + return Union{refs...} + end + return Base.RefValue{_many_input_carrier_type(plan.reference_types)} +end + +# 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 + 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 + # 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_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 + +""" + 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)) + 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] + 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))) + 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), + isnothing(declarations) ? nothing : get(declarations, scale, empty_fields)) + end + 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)) + 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 applications if a.slot == plan.application_slot) + _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 + _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), + 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 _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, 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, + (item for item in authored if item isa AuthoredApplicationRecipe)) + applications, permissions = _prepared_status_applications(model, recipes, program) + outputs = _authored_distributed_output_plans( + _graph_record_vector(AuthoredApplicationRecipe, recipes), program.output_records) + 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 + 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) + I = keytype(model.registry.objects) + observed = PreparedRawStatusFamily{I}[] + for object in values(model.registry.objects) + source = object.status + 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, 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) || + 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 + # A force refresh must not promote materialized defaults or aliases to + # new RAW permissions. Preserve the genuine constructor-owned evidence. + 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) + end + 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.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. + # 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, name, + 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 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 + # 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 + # 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...}) + 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 +# 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 + +# 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) + +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 + _prepared_status_reference_allowed(permission.aliases, name, reference) && return true + end + 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. +_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 + # 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 _registry_object_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, +) + # 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, 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 + 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 + +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 + _prepared_status_destination_entry_allowed(application, permission, plan, model, object, + parent_id, name, reference) && return true + end + return false +end + +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 (declared, !declared) +end + +# 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. +function _prepared_status_source_route_admission(source, application, permission, + model, object, parent_id, name, reference) + declared, allowed = false, true + if source.source_var === name + has_consumer = false + 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 + has_consumer = true + _prepared_status_route_matches(model, object, parent_id, + 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.input, reference) + 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, 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.input, reference) + declared |= has_type + allowed &= matches + end + end + 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) + 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, true) + declared, allowed = _prepared_status_source_input_admission( + first(permission.variants), source.input, reference) + end + end + end + return (declared, allowed, true) +end + +function _prepared_status_sources_admission(recipe, model, object, parent_id, name, reference) + declared, allowed = false, true + 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) + declared |= has_type + allowed &= matches + end + return (declared, allowed, true) +end + +# 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( + 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( + recipe, model, object, parent_id, name, reference::$R) + end + end for R in references] + return quote + $(Expr(:meta, :inline)) + $(branches...) + return (false, false) + end +end + +Base.@constprop :none Base.@noinline function _prepared_status_reference_admission( + recipe, model, object, parent_id, name, reference::R, +) where {R<:Ref} + declared, source_allowed, compatible = _prepared_status_sources_admission( + recipe, model, object, parent_id, + name, reference::R) + compatible || return (false, false) + allowed = (declared && source_allowed) || + _prepared_status_application_reference_allowed(recipe, + model, object, parent_id, name, reference::R) || + _prepared_status_destinations_allow(recipe, + 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) + end + return 0 +end +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 + expected == _prepared_status_variant_slot(application, object.id) || return false + elseif !iszero(expected) + return false + end + end + 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 + # 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 +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, 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 + _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.destinations, plan, execution_id, variant) || return -1 + count += 1 + end + return count +end +function _prepared_status_raw_destination_total(recipe, raw, model, object, parent_id) + total = 0 + 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, 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 + _prepared_status_route_matches(model, object, parent_id, + application, source, consumer_id) || continue + variant = _prepared_status_variant_slot(application, consumer_id) + _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, pending_id) + variant = _prepared_status_variant_slot(application, pending_id) + _prepared_status_raw_has_context(raw.sources, source, pending_id, variant) || return -1 + count += 1 + end + return count +end + +function _prepared_status_raw_source_total(recipe, raw, model, object, parent_id) + total = 0 + 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 + end + return total +end + +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(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(recipe, + raw, model, object, parent_id) == length(raw.sources) +end +_prepared_status_raw_reference_allowed(::Nothing, name, reference) = false +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 + +# 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. +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(references, name) + if reference !== nothing + present += 1 + allowed, compatible = _prepared_status_configured_reference_admission(recipe, model, + object, parent_id, name, reference) + 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 + return present == _initial_status_reference_count(references) +end + +_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.")) + recipe = _object_birth_recipe(manifest, object) + 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 + _prepared_status_raw_matches(raw, recipe, model, object, parent_id) || continue + _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 +@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 + +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 + 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(birth_recipe, + 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/registry_topology.jl b/src/composite_model/registry_topology.jl index 6f98adb82..e3dcdf8b6 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, @@ -133,7 +114,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,29 +145,53 @@ function ObjectInstance( return ObjectInstance( Symbol(name), template, - root, + root isa Object ? root : ObjectId(root), normalized_objects, overrides, normalized_object_overrides, ) end -struct ObjectModelOverrides{M,O} <: AbstractModel - base::M - overrides::O +# 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 -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) +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; @@ -200,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), @@ -214,9 +225,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 +236,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 +255,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,E} root::R id::I scale::S @@ -254,8 +265,32 @@ 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 + 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 + +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, 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), + edits, + ) end function _register_mtg_object_identity!(adapter::MTGObjectAdapter, node) @@ -268,7 +303,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_text(id))`.", ) end adapter.object_ids_by_node[node] = id @@ -305,7 +340,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} @@ -314,7 +349,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.""" @@ -411,8 +446,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) @@ -434,7 +470,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_text(object.id))` more than once.") push!(ids, object.id) end return objects, mounted_instances @@ -462,13 +498,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_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_text(id))` belongs to both instances `$(claimed_ids[id])` and `$(instance.name)`." ) end claimed_ids[id] = instance.name @@ -541,6 +577,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, + ) + preparation = _scenario_preparation(model) + return _install_prepared_canonical_registry(model, preparation) +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) @@ -584,11 +644,98 @@ function CompositeModel( 0, 0, ) - return _register_model_objects!( + _register_model_objects!( model, objects; status_values_materialized=_status_values_materialized, ) + 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, 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( + "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 + # 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 + +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 + 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 && return registry + name === :source_adapter && return adapter + return getfield(model, name) + end + prepared = CompositeModel(fields...) + _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 """ @@ -623,9 +770,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, @@ -703,8 +850,41 @@ function CompositeModel( ) end -_mtg_attribute(node, key::Symbol, default=nothing) = - get(MultiScaleTreeGraph.node_attributes(node), key, default) +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 + return map(f -> _prepared_mtg_label(f, adapter.root), labels) +end + +function _prepared_mtg_label(::_MTGAttribute{K}, root) where {K} + T = MultiScaleTreeGraph.attribute_type(root, K) + return _MTGAttribute{K,Union{Nothing,T}}() +end + +_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. +_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 @@ -724,10 +904,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( @@ -795,7 +975,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; @@ -804,10 +986,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, @@ -822,8 +1004,9 @@ 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( @@ -841,6 +1024,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, @@ -851,10 +1041,15 @@ 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 + # Keep explicit collection/frozen evidence while dirty; full_environment + # still forces every handle to be rebuilt before the next execution. + 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) + _union_lifecycle_object_ids!(delta.environment_dirty_ids, model.registry.objects, ids) end if !model.environment_bindings_dirty model.environment_revision += 1 @@ -873,14 +1068,18 @@ 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 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 @@ -891,8 +1090,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 @@ -933,6 +1133,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 @@ -968,70 +1177,39 @@ function _delete_index!(index::Dict{Symbol,Set{ObjectId}}, key, id::ObjectId) return nothing 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) - object.status isa Status && - (registry.object_ids_by_status[_status_identity(object.status)] = object.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) 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) - 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 - -function _validate_status_identity_available!( - registry::ObjectRegistry, - 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 + 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 -function _validate_status_source_identity_available!( +@inline function _validate_status_source_identity_available!( model::CompositeModel, - status, + identity::Union{Nothing,Base.RefValue{Nothing}}, object_id::ObjectId, ) - status isa Status || return nothing - existing = get( + isnothing(identity) && return nothing + raw_existing = get( model.status_source_owners, - _status_identity(status), + identity, nothing, ) + existing = isnothing(raw_existing) ? nothing : + _index_object_id(model.registry.objects, raw_existing) 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 " * + "`$(_object_id_text(existing))` and `$(_object_id_text(object_id))`. Give each Object " * "its own Status instance.", ), ) @@ -1042,15 +1220,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 @@ -1073,37 +1250,66 @@ 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_text(object.id))` status must be a `Status` or `nothing`, " * "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)) + store = model.registry.objects + object_id = object.id::keytype(store) + 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, 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) + _set_status_source_identity!(model, object_id, identity) + return admitted end - 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 function _replace_model_object_status!(model::CompositeModel, object_id, status) return _replace_model_object_status!(model, _model_object(model, object_id), status) 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_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_quoted_symbol(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, '(') + 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 +_model_object(model::CompositeModel, id) = + _require_object_location(model.registry.objects, ObjectId(id)).object + """ model_object(model::CompositeModel, id) -> Object @@ -1143,14 +1349,14 @@ 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_text(object.id))` is not the Object instance registered by this model.", ), ) return object.id 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."), @@ -1158,7 +1364,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_text(matched_id))`. Replace runtime status through the model API.", ) return matched_id end @@ -1189,7 +1395,11 @@ 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)) + +model_status(model::CompositeModel, id::ObjectId) = + _registered_object_status(model.registry.objects, id) """ source_node(model::CompositeModel, source) -> MultiScaleTreeGraph.Node @@ -1208,7 +1418,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_text(id))`.", ) return node end @@ -1219,35 +1429,30 @@ 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_text(object_id))`.", ) return ancestors 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, + ancestor_snapshot = ancestors isa Tuple ? ancestors : Tuple(ancestors) + # Freeze topology, but retain the same passive geometry object without copying. + return LifecycleObjectSnapshot( + id, object.scale, object.kind, object.species, object.name, object.parent, Tuple(object.children), - Tuple(ancestors), - geometry, + ancestor_snapshot, + object.geometry, ) end @@ -1287,7 +1492,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, @@ -1299,58 +1505,102 @@ 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) - isnothing(instance) && return object - isnothing(object.kind) && (object.kind = instance.template.kind) - isnothing(object.species) && (object.species = instance.template.species) +@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) + labels = _instance_object_labels(object, instance) + object.kind = labels.kind + object.species = labels.species 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 `$(_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 `$(parent_id.value)`.") + 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 + +function _register_object_status!(model::CompositeModel, object::Object, + id, parent_id, status_values_materialized::Bool) source_status = object.status - _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) + source_status isa Union{Nothing,Status} || throw(ArgumentError( + "Initial object status must be a Status or nothing.")) + 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_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_identity, converted) + merge!(model.status_conversion_records, conversion_records) + return registered +end + +@inline function _register_converted_status!(model, object, id, parent_id, + identity::Union{Nothing,Base.RefValue{Nothing}}, converted::Union{Nothing,Status}) + catalog = model.registry.objects.catalog + status = if catalog isa ClosedObjectFamilyCatalog + manifest = catalog.status_manifest + Base.@inline _validate_prepared_initial_status(manifest, model, object, converted, parent_id) + isnothing(converted) ? nothing : (Base.@inline _new_prepared_status(manifest.status_type, converted)) + else + converted + end + registry = model.registry + _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 - registry.objects[object.id] = object - _index_object!(registry, object) - _set_status_source_identity!(model, object.id, source_status) + store = registry.objects + _store_object_family_row!(store, object, id, status) + _index_object_labels!(registry, object, id) + _set_status_source_identity!(model, id, identity) 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 @@ -1362,38 +1612,18 @@ 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) - registered = _register_object_without_lifecycle!( +@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 + _register_object_without_lifecycle!( model, object; parent=parent, ) - _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 + _record_added_objects!(model, (object,)) + return object end function _validate_organ_attributes(attributes) @@ -1409,46 +1639,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`. @@ -1463,7 +1679,6 @@ function add_organ!( id=nothing, attributes=NamedTuple(), initial_status=NamedTuple(), - use_status_adapter::Bool=true, kind=nothing, species=nothing, name=nothing, @@ -1478,6 +1693,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) @@ -1486,111 +1702,77 @@ 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." ) 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)) + 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) - status = _organ_status( - adapter, - node, - initial_status; - use_status_adapter=use_status_adapter, - ) - 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, - parent=parent_id, - geometry=adapter.geometry(node), - status=status, - ) + object = _new_object(new_object_id, adapter.scale(node), + 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) - return registered.status + adapter.max_node_id[] = max(adapter.max_node_id[], node_id) + 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 -function _remove_child_link!(model::CompositeModel, parent_id, child_id::ObjectId) - isnothing(parent_id) && return nothing +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 _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 isa eltype(descendant_ids) && id in subtree_ids && push!(instance_roots, id) + end + isempty(instance_roots) && return descendant_ids + _sort_object_ids!(instance_roots) error( - "Cannot $(operation) object `$(object.id.value)` 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.value)` 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) + _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) @@ -1609,48 +1791,43 @@ 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 `$(new_parent_id.value)`.") - new_parent_id == object.id && error( - "Cannot reparent object `$(object.id.value)` 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.value)` below its descendant `$(new_parent_id.value)`.", + 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_ancestors_by_object = Dict{ObjectId,Tuple}() + for descendant_id in descendant_ids + get!(old_ancestors_by_object, descendant_id) do + Tuple(_object_ancestor_ids(model.registry, descendant_id)) + end + end + old_parent_id = _unlink_from_parent!(model, object, 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, @@ -1667,25 +1844,22 @@ end function update_geometry!(model::CompositeModel, id, geometry_or_position; invalidate_environment::Bool=true) object = _model_object(model, id) - old_geometry = object.geometry - affected_object_ids = ObjectId[object.id] - invalidate_environment && append!( - affected_object_ids, - _geometry_inheriting_descendants(model, object.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) + object.geometry === old_geometry || throw(ArgumentError("The object's geometry changed before the update.")) 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 @@ -1717,133 +1891,24 @@ _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 -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 - prepared = model.scenario_plan_cache - 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 - 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 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 + +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 model.environment_binding_cache + return sortperm(labels) end function object_ids(model::CompositeModel; scale=nothing, kind=nothing, species=nothing, id=nothing) @@ -1854,11 +1919,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))) - return sort!(ids; by=id -> string(id.value)) + isnothing(ids) && (ids = collect(_registry_object_ids(model.registry.objects))) + length(ids) < 2 && return 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/src/composite_model/runtime_outputs.jl b/src/composite_model/runtime_outputs.jl index 659757daf..05ed06133 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}} @@ -165,6 +180,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 @@ -259,9 +301,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 @@ -278,14 +320,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, @@ -370,9 +413,9 @@ 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_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) @@ -417,15 +460,16 @@ 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_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 @@ -456,7 +500,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 @@ -507,6 +551,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. @@ -516,8 +565,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) @@ -543,15 +592,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 @@ -582,6 +625,35 @@ 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 + # 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 + +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.compiled_applications, + getfield(binding, :membership_generation), + _compiled_call_membership_generation(binding), + ) +end + """ CallTargets <: AbstractVector{CallTarget} @@ -597,7 +669,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 @@ -611,6 +683,13 @@ 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 + # 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} evaluation::Union{Nothing,CallEvaluationFrame} target_buffer_cache::Union{Nothing,_CallTargetBufferCache} # One singular snapshot or transient slot; numerical state stays in its owner. @@ -630,84 +709,120 @@ 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, -) - # 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 - targets = CallTargets( - compiled, - environment_bindings, - binding, - temporal_streams, - output_retention, - time, - constants, - publication_allowed, - environment, - execution_batches, - nothing, - nothing, - nothing, + batch_schema=OpenExecutionBatchSchema(), +) + 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, + _call_execution_batches_start_materialized(batch_schema, binding)) +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, + 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, + execution_batches_materialized, batch_schema, tracks_full_membership, + _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 -function _current_call_binding_for_retained_view( - compiled::CompiledCompositeModel, - binding::CompiledModelCallBinding, +@inline function _call_targets_preparation_is_current( + targets::CallTargets, compiled, environment_bindings, temporal_streams, + output_retention, constants, ) - bindings = get( - compiled.call_bindings_by_target, - (binding.application_id, binding.consumer_id), - (), + 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.compiled_applications === environment_bindings.compiled_applications && + 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, ) - binding_index = findfirst( - candidate -> - _compiled_call_name(candidate) === _compiled_call_name(binding) && - _compiled_call_mode(candidate) === _compiled_call_mode(binding), - bindings, +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, + # never its owner link; cloning must leave a cold Many membership cold. + return LazyCallExecutionBatches( + nothing, batches.batches, ) - 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)`.", +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), + prototype.batch_schema, prototype.tracks_full_membership, + prototype.execution_batches_materialized, + ) + remaining = _clone_runtime_call_targets( + Base.tail(calls), compiled, environment_bindings, temporal_streams, + output_retention, time, constants, publication_allowed, environment, ) - return bindings[binding_index] + return (targets, remaining...) +end + +function _current_call_binding_for_retained_view(compiled::CompiledCompositeModel, + 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( @@ -716,8 +831,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( @@ -731,41 +845,32 @@ 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 + cached = getfield(model,:binding_cache) + current_compiled = if isnothing(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, - ) - else - refresh_environment_bindings!(model, current_compiled) - 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. + cached isa CS || _unprepared_runtime_configuration() + cached::CS + end + 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); + environment_schema=targets.environment_bindings.environment_schema) + 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 @@ -779,7 +884,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 == @@ -819,10 +924,15 @@ 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, batch_schema=targets.batch_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, @@ -833,6 +943,13 @@ 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. return batches end @@ -843,9 +960,13 @@ 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 + targets.tracks_full_membership || return targets batches = _cached_call_execution_batches(targets) isnothing(batches) && return targets cached.batches = _TrackedCallExecutionBatchCache( @@ -858,10 +979,13 @@ function _record_extended_call_execution_batch_cache!( return targets end -function _materialize_call_execution_batches!(targets::CallTargets) +@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 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) @@ -873,7 +997,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; @@ -916,37 +1040,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!( @@ -1006,11 +1107,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 @@ -1022,10 +1122,15 @@ 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 - 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. @@ -1037,6 +1142,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. @@ -1065,36 +1194,83 @@ CompiledExecutionBatch( ExecutionBatchContextState(nothing, nothing), ) -struct CompiledApplicationExecutionGroup{A,B} +mutable struct CompiledApplicationExecutionGroup{A,B,M<:ExecutionCohortMembership} application::A batches::B + membership::M end -function _compiled_application_execution_group(application, batches) +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 && - 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 + +# 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)) + 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 +# 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 +mutable struct RuntimeApplicationSchedule{P} + const definition::P next_due_steps::Vector{Int} heap::Vector{Int} due_entry_indices::Vector{Int} last_step::Int end -struct CompiledExecutionPlan{G,B,I,S} +struct CompiledExecutionPlan{G,B,I,S,TP,C<:ExecutionCohortStore} + cohorts::C + topology::TP groups::G batches::B groups_by_application_slot::I @@ -1170,6 +1346,7 @@ function _runtime_application_schedule( ) entry_count = length(plan.entries) schedule = RuntimeApplicationSchedule( + plan, fill(typemax(Int), entry_count), Int[], Int[], @@ -1189,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, @@ -1207,7 +1393,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) @@ -1249,8 +1436,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 @@ -1261,7 +1455,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 @@ -1270,8 +1464,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 @@ -1279,6 +1471,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, @@ -1357,8 +1552,79 @@ 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) + +# 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) + 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 = _snapshot_memory(source.mem, memo) + offset = Core.memoryrefoffset(source) + first = Core.memoryref(memory) + point = isone(offset) ? first : Core.memoryrefnew(first, offset, false) + 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) +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 """ @@ -1519,22 +1785,40 @@ 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} + 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, applications_by_id, id) end -function _environment_binding_for(env_bindings::CompiledEnvironmentBindings, application_id::Symbol, object_id::ObjectId) - return get(env_bindings.by_target, (application_id, object_id), nothing) +_compiled_application_by_id(compiled::CompiledCompositeModel, id::Symbol) = + _compiled_application_by_id(identity, compiled, id) + +@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 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) - object = _model_object(model, object_id) - object.status isa Status || error( - "CompositeModel object `$(object_id.value)` has no `Status`; model runtime requires status-backed objects." + status = model_status(model, object_id) + status isa Status || error( + "CompositeModel object `$(_object_id_text(object_id))` has no `Status`; model runtime requires status-backed objects." ) - return object.status + return status end @inline function _model_status_view_for_application( @@ -1542,16 +1826,18 @@ 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)`.", + "`$(_object_id_text(object_id))`.", ) - return compiled.status_views_by_target[key] + 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) - variable in propertynames(status) || error( + hasproperty(status, variable) || error( "Cannot materialize input `$(variable)` because consumer status has no such variable." ) status[variable] = value @@ -1575,26 +1861,34 @@ 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( - 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( @@ -1617,7 +1911,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) @@ -1635,28 +1929,68 @@ _model_output_object_ids(compiled, application, variable::Symbol) = compiled.distributed_outputs, ) -function _model_output_reference( - compiled, - application, - object_id::ObjectId, - variable::Symbol, -) - if variable in keys(_local_output_schema(application.spec)) && - 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) +# 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 - return refvalue( - _model_object(compiled.model, object_id).status, - variable, - ) +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 && hasproperty(status, VARIABLE) || 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, + 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)) && + 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, + Val{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, + 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!( @@ -1669,48 +2003,82 @@ 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), + haskey(streams, key) && 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 + +# 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 - return streams end - 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.", + 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, ) - stream = _model_new_output_stream( - reference[], - retention, - application.id, - variable, + 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, ) - if stream isa Vector && sizehint_steps > 0 - sizehint!( - stream, - max( - 1, - ceil( - Int, - float(sizehint_steps) / - float(application.clock.dt), - ), - ), +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 - streams[key] = stream - return streams + return nothing end function _initialize_changed_model_output_streams!( @@ -1720,52 +2088,37 @@ 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, (), ) 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 = _model_output_names(application) + 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 + 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, + ) end end return streams @@ -1786,22 +2139,24 @@ 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, ) + id = _index_object_id(compiled.model.registry.objects, object_id) + _initialize_model_output_stream!( + streams, + compiled, + retention, + application, + id, + variable, + sizehint_steps, + ) + end end end end @@ -1842,8 +2197,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 @@ -1859,7 +2214,8 @@ end end @inline function _model_publish_runtime_output_value!( - output, + variable::Symbol, + dependency_horizon::Float64, stream, value, time::Real, @@ -1867,18 +2223,18 @@ 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.", ) - sample_time = float(time) + sample_time = Float64(time) _model_publish_sample!( stream, sample_time, 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 @@ -1887,7 +2243,8 @@ end time::Real, ) _model_publish_runtime_output_value!( - output, + _runtime_output_variable(output), + output.dependency_horizon, output.stream, output.reference[], time, @@ -1901,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, @@ -1912,15 +2271,20 @@ end return nothing end -@inline _model_publish_runtime_outputs!(::Tuple{}, time::Real) = nothing +# Select each admitted output by its slot so publication keeps concrete +# types for wide heterogeneous tuples without constructing successive tails. +@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, -) - _model_publish_runtime_output!(first(outputs), time) - _model_publish_runtime_outputs!(Base.tail(outputs), time) - return nothing +@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) @@ -2089,14 +2453,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, consumer_dt::Real, 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(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.clock.dt, timeline) +end + function _model_temporal_source_value( streams, application_id::Symbol, @@ -2108,8 +2476,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, @@ -2117,6 +2485,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, @@ -2155,7 +2543,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_text(source_id)).$(source_var)` has no ", "source application for policy `$(typeof(policy))`." ) end @@ -2182,96 +2570,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 ", - "`$(source_ids[index].value).$(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 ", - "`$(source_id.value).$(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) @@ -2357,18 +2678,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 @@ -2385,18 +2705,13 @@ 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 ", "`$(plan.input)` from ", - "`$(source_ids[index].value).$(plan.source_var)` ", + "`$(_object_id_text(source_ids[index])).$(plan.source_var)` ", "at t=$(time).", ) value = temporal_input.initial[index] @@ -2406,17 +2721,12 @@ 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 ", - "`$(source_id.value).$(plan.source_var)` at t=$(time).", + "`$(_object_id_text(source_id)).$(plan.source_var)` at t=$(time).", ) value = temporal_input.initial end @@ -2548,14 +2858,12 @@ 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] - sampled = _sample_compiled_global_environment( - binding, - application, - step, - ) + return _global_environment_sample_value( + binding.plan.sample_schema, env_bindings.sample_cache[key], + ) + sampled = _sample_compiled_global_environment(binding, 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, @@ -2565,44 +2873,79 @@ 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; +# 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, + call_schema=_context_call_schema(context), ) + 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; + call_schema, + ) + end + return RunContext( + compiled, environment_bindings, application, object_id, calls, + bound_inputs, output_targets, temporal_streams, output_retention, + Float64(time), constants, publication_allowed, environment, + ) + end runtime_changed = context.compiled !== compiled || context.environment_bindings !== environment_bindings @@ -2617,133 +2960,16 @@ 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, - 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, @@ -2767,10 +2993,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 @@ -2781,7 +3010,7 @@ function _synchronize_model_execution_batch_contexts!( return nothing end -@inline function _run_model_execution_target_without_calls!( +@inline function _run_model_execution_target!( compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, application::CompiledModelApplication, @@ -2792,17 +3021,21 @@ end output_retention, sampled_environment, publish_outputs::Bool, + performance::Union{Nothing,RuntimePerformanceCounters}=nothing, ) + 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, application, 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, @@ -2810,18 +3043,20 @@ 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 else - RunContext( + _prepare_model_execution_context!( + target.context, compiled, env_bindings, application, target.object_id, - (), target.bound_inputs, target.output_targets, + target.call_bindings, temporal_streams, output_retention, time, @@ -2830,79 +3065,16 @@ 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 - -@inline function _run_model_execution_target!( - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - application::CompiledModelApplication, - target::CompiledExecutionTarget, - time::Real, - constants, - temporal_streams, - output_retention, - sampled_environment, - publish_outputs::Bool, -) - 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, - ) - status = isempty(target.input_bindings) ? - target.status : - _materialize_model_inputs!( - target.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!( - target.context, - compiled, - env_bindings, - application, - target.object_id, - target.bound_inputs, - target.output_targets, - temporal_streams, - output_retention, - time, - constants, - ) - 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 + return nothing end @inline _model_execution_batch_environment( @@ -2946,11 +3118,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!( @@ -2961,14 +3129,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, @@ -2978,96 +3149,22 @@ end batch_time, 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 : - _materialize_model_inputs!( - target.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, - temporal_streams, - output_retention, - batch_time, - constants, - ) - 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, - env_bindings, - batch.application, - target, - batch_time, - constants, - temporal_streams, - output_retention, - shared_environment, - publish_outputs, - ) - end - return nothing + return _run_model_execution_batch_targets!( + batch, + compiled, + env_bindings, + batch_time, + constants, + temporal_streams, + output_retention, + shared_environment, + performance, + ) end -function _run_model_execution_batch_profiled!( +# 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, @@ -3075,107 +3172,23 @@ function _run_model_execution_batch_profiled!( constants, temporal_streams, output_retention, - performance::RuntimePerformanceCounters, + shared_environment, + performance::Union{Nothing,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 : - _materialize_model_inputs!( - target.status, - target.input_bindings, + _run_model_execution_target!( compiled, + env_bindings, batch.application, - temporal_streams, + target, 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, - temporal_streams, - output_retention, - batch_time, - constants, - ) - 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!( + temporal_streams, + output_retention, + shared_environment, + publish_outputs, performance, - :output_publication, - started_at, ) end return nothing @@ -3235,7 +3248,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_text(binding.source_ids[index]))` ", "and variable `$(binding.source_var)`.", ) return stream @@ -3305,7 +3318,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 @@ -3314,7 +3327,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_text(object_id))` and variable ", "`$(variable)`.", ) stream = _model_new_output_stream( @@ -3322,6 +3335,8 @@ Base.@nospecializeinfer function _runtime_model_output_streams( output_retention, application.id, variable, + 0, + application.clock.dt, ) streams[key] = stream end @@ -3341,7 +3356,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( @@ -3421,7 +3436,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[ @@ -3463,7 +3478,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( @@ -3483,91 +3498,54 @@ function _runtime_model_distributed_output_streams( ) end -_runtime_model_output_targets( - compiled, - application, - object_id, - ::NoCompiledDistributedOutputs, -) = NamedTuple() +_runtime_model_output_groups(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) +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, + ::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)) + 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 - target = OutputTargets(binding, alignment_id) - for name in keys(binding.declarations) - push!(names, name) - push!(targets, target) + push!(statements, :($binding = getfield(groups, $index))) + 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))) + push!(binding_vars, binding) + push!(target_vars, target) + end + return quote + alignment_count = 0 + $(statements...) + return $(Views === Nothing ? :(NamedTuple{$(QuoteNode(Tuple(names)))}) : Views)($(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, - ) - -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 + _runtime_model_output_targets(_runtime_model_output_groups(compiled, application, object_id)) function _compiled_model_execution_target( compiled::CompiledCompositeModel, @@ -3576,89 +3554,88 @@ function _compiled_model_execution_target( object_id::ObjectId, temporal_streams=nothing, output_retention=nothing, - constants=nothing, + constants=nothing; + owner=nothing, + cohort_schema=OpenExecutionCohortSchema(), +) + if temporal_streams isa RuntimeStorage + location = cohort_location(temporal_streams.cohorts, application.id, object_id; owner) + 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; + target_schema=cohort_schema) + end + end + 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; + 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 = _compiled_model_execution_context( - compiled, - env_bindings, - application, - object_id, - bound_inputs, - distributed_targets, - call_bindings, - temporal_streams, - output_retention, - constants, - ) - 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 CompiledExecutionTarget( - object_id, - model, - status_view.status, - status_view.canonical_status, - _runtime_model_temporal_inputs( - status_view.temporal_inputs, - temporal_streams, - ), - bound_inputs, - distributed_targets, - output_bindings, - call_bindings, - _call_bindings_signature(call_bindings), - environment_binding, - context, - CallContextCache(context), - ) -end - -function _typed_model_execution_targets(targets, first_index::Int, last_index::Int) - 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] + 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) + owners = (compiled=compiled, environment_bindings=env_bindings, + temporal_streams=temporal_streams, + output_retention=output_retention, constants=constants, + environment=_NO_ENVIRONMENT_OVERRIDE) + 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, + 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.temporal_streams,owner.output_retention,false) end - return typed + 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( @@ -3692,91 +3669,158 @@ end _compiled_output_publication(::Nothing, application) = CompiledOutputPublication((), false) -function _append_model_execution_batches!( - batches, - env_bindings::CompiledEnvironmentBindings, - application::CompiledModelApplication, - targets, - output_retention, +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 + +# 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,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) + 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, + 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; + batch_schema=OpenExecutionBatchSchema(), ) - 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(targets, first_index, index - 1), - _compiled_model_execution_environment_provider( - env_bindings, - application, - targets[first_index], - ), - output_publication, - ), - ) - first_index = index - target_type = typeof(targets[index]) + # 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) + 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 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 + return nothing + end + end end - push!( - batches, - CompiledExecutionBatch( - application, - _typed_model_execution_targets(targets, first_index, lastindex(targets)), - _compiled_model_execution_environment_provider( - env_bindings, - application, - targets[first_index], - ), - output_publication, - ), - ) - return batches + batches = _execution_batch_buffer(batch_schema) + batches_constructed = 0 + for index in eachindex(membership.runs) + 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, + 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 + 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 + push!(batches,batch) + return nothing + end + return 0 + end + batches_constructed += constructed + end + return (batches=batches,batches_constructed=batches_constructed) end function _compiled_call_execution_batches( - compiled::CompiledCompositeModel, - env_bindings::CompiledEnvironmentBindings, - binding, - temporal_streams, - output_retention, - constants, -) - batches = AbstractExecutionBatch[] + 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) + 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) - 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, - ), - ) + _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)] + 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) + 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 - _append_model_execution_batches!( - batches, - env_bindings, - application, - targets, - output_retention, - ) end - return Tuple(batches) + return _finish_execution_batches(batch_schema,batches) end function compile_model_execution_plan( @@ -3784,62 +3828,53 @@ 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 - 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, - ) - first_batch > length(batches) && continue - push!( - groups, - _compiled_application_execution_group( - application, - batches[first_batch:end], - ), + previous_group = isnothing(batch_schemas) ? nothing : + _prepared_execution_group(application,getproperty(batch_schemas,application.id),cohorts) + _refresh_model_execution_group!( + groups, batches, previous_group, cohorts, compiled, env_bindings, application, + temporal_streams, output_retention, constants, nothing, nothing, ) 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, ) 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] @@ -3873,20 +3908,29 @@ 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, - compiled::CompiledCompositeModel, + status_view::CompiledModelStatusView, + output_targets::NamedTuple, application::CompiledModelApplication, object_id::ObjectId, output_retention, @@ -3902,13 +3946,8 @@ 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 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] @@ -3925,75 +3964,58 @@ 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}}[] - 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 keys(binding.declarations) - 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, (runtime_streams, new_streams)) - end - end + additions = Tuple{Int,Vector{Any}}[] + # 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 + 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(target.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 (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 @@ -4008,41 +4030,39 @@ 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 keys(binding.declarations) - 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, :(_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 - # 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))) - for previous_index in 1:(index - 1) - previous = ordered_bindings[previous_index] - previous_target = getproperty(targets, first(keys(previous.declarations))) - 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( @@ -4101,8 +4121,13 @@ 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 || + # 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 + _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 target.bound_inputs === status_view.bound_inputs || return :bound_inputs @@ -4120,7 +4145,8 @@ function _model_execution_target_change_reason( return :temporal_inputs _model_execution_outputs_match( target.output_bindings, - compiled, + status_view, + target.output_targets, application, object_id, output_retention, @@ -4137,13 +4163,22 @@ 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 + 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. + # 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 + break + end return nothing end @@ -4185,89 +4220,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, @@ -4283,6 +4235,41 @@ function _model_execution_batch_accepts_target( return isequal(provider, batch.environment_provider) end +# 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 _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)) + branches = [:(application isa $A && return f(application::$A)) for A in owners] + return quote + application = _compiled_application_by_id(compiled, id) + $(branches...) + throw(ArgumentError("A callee application is outside its prepared batch schema.")) + 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, @@ -4298,87 +4285,65 @@ 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 + 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) + 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 - 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, - ) - _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 @@ -4388,7 +4353,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 @@ -4398,13 +4363,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) @@ -4430,102 +4392,65 @@ 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, - ) - _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 + # 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) + 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 + 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 + 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 @@ -4559,8 +4484,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!( + groups, batches, previous_group, + cohorts::ExecutionCohortStore, compiled::CompiledCompositeModel, env_bindings::CompiledEnvironmentBindings, application::CompiledModelApplication, @@ -4570,156 +4501,82 @@ 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 + 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; + 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 - previous_target = if isnothing(location) - nothing + target = _new_model_execution_target( + compiled, env_bindings, application, object_id, + 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; + batch_schema=_execution_group_batch_schema(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) + 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 - 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 + nothing 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 + elseif reused_group + previous_group.membership = refreshed.membership + previous_group + else + _retain_execution_group(previous_group, _compiled_application_execution_group( + application, assembled.batches, refreshed.membership; + batch_schema=_execution_group_batch_schema(previous_group), + )) end - - for action in actions - isnothing(action.reason) && continue - _count_model_execution_target_rebuild!( - performance, - action.reason, - ) + if !isnothing(group) && group === previous_group && group_changed + _runtime_performance_count!(performance, :execution_groups_updated_in_place) 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 + if !isnothing(group) + push!(groups, group) + append!(batches, group.batches) end - filter!(batch -> !isempty(batch.targets), batches) - return ( - group=isempty(batches) ? nothing : working_group, - targets_constructed=targets_constructed, - batches_constructed=0, - ) + return (refreshed.targets_constructed, assembled.batches_constructed, + Int(reused_group && !group_changed)) 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) @@ -4727,176 +4584,119 @@ 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, - ) +# 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 " * + "`$(String(application.id))` at slot $(string(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::F, slots, application::CompiledModelApplication, + visited::BitVector, +) where {F} + 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 + _with_matching_previous_execution_group(f, group, application, slots) + end + if !isnothing(counts) + visited[slot] = true + return counts end - push!( - candidates, - ( - application=application, - batch=last_batch, - object_ids=changed_object_ids, - ), - ) end + return _missing_previous_execution_group(f, slots, application) +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, - ), - ) +# 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 - for staged in staged_appends - for target in staged.targets - push!(staged.batch.targets, target) - _count_model_execution_target_rebuild!(performance, :new_target) +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 - isempty(staged.targets) || _runtime_performance_count!( - performance, - :execution_groups_updated_in_place, - ) 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 - return ( - plan=CompiledExecutionPlan( - 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), - ) +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( @@ -4910,48 +4710,14 @@ 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_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, + keytype(compiled.model.registry.objects), ) - 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_slots = previous.groups_by_application_slot + _preflight_execution_group_layout!(previous,compiled,previous_slots) + visited_slots = falses(length(previous_slots)) groups = CompiledApplicationExecutionGroup[] batches = AbstractExecutionBatch[] sizehint!(groups, length(previous.groups)) @@ -4959,165 +4725,66 @@ 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) + # 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 - - 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, + 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 + changed_ids = isnothing(changed_by_application) ? nothing : + get(changed_by_application, application.id, ()) + return _refresh_model_execution_group!( + groups, batches, previous_group, previous.cohorts, compiled, env_bindings, + application, temporal_streams, output_retention, constants, performance, + changed_ids, ) 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 + 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. 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; schema=group.membership.schema) end + return nothing end - - application_batches = AbstractExecutionBatch[] - _append_model_execution_batches!( - application_batches, - env_bindings, - application, - targets, - output_retention, - ) - isempty(application_batches) && continue - push!( - groups, - _compiled_application_execution_group( - application, - application_batches, - ), - ) - append!(batches, application_batches) - batches_constructed += length(application_batches) end - + 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_in_schema, application_count) + slots_in_schema = _execution_groups_in_schema( + previous.groups_by_application_slot, groups_by_slot, + ) return ( plan=CompiledExecutionPlan( - groups, - batches, - _execution_groups_by_application_slot( - groups, - length(compiled.scenario_plan.applications), - ), - previous.schedule, + previous.cohorts, + previous.topology, + same_groups ? previous.groups : groups_in_schema, + same_batches ? previous.batches : batches, + slots_in_schema, + _refreshed_runtime_application_schedule(previous.schedule, + compiled.scenario_plan.application_schedule), compiled.revision, env_bindings.environment_revision, ), @@ -5135,9 +4802,11 @@ 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), + 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) ? @@ -5171,57 +4840,105 @@ function explain_execution_plan(model::CompositeModel) end function _model_temporal_retention_horizon( - binding, - consumer, - source, - timeline, -) - window_steps = _model_input_window_steps(binding, consumer, timeline) - return if binding.policy isa Union{Integrate,Aggregate} - float(window_steps) + max(0.0, float(source.clock.dt) - 1.0) - elseif binding.policy isa Union{Interpolate,PreviousTimeStep} - max(2.0, float(source.clock.dt) + 1.0) + window_steps::Real, + integrates::Bool, + interpolates::Bool, + source_dt::Real, +) + return if integrates + float(window_steps) + max(0.0, float(source_dt) - 1.0) + elseif interpolates + max(2.0, float(source_dt) + 1.0) else 0.0 end end +# 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} + return _with_model_temporal_retention(f, compiled.applications_by_id, + compiled.scenario_plan.input_plans, compiled.scenario_plan.timeline, binding) +end + +@inline function _with_model_temporal_retention(f::F, + applications_by_id::CompiledMetadataTable, input_plans, timeline, + binding::CompiledModelInputBinding, +) where {F} + 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 + # 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) + 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.")) + 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(applications_by_id, 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( plan::OutputRetentionPlan, compiled::CompiledCompositeModel, - binding, + binding::CompiledModelInputBinding, ) 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 _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 - return true +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, ) - 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 - 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 @@ -5258,32 +4975,29 @@ 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, -) - return Tuple(Symbol(variable) for variable in keys(_local_output_schema(application.spec))) +_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 keys(_local_output_schema(application.spec))] - for ((application_id, variable), destination_ids) in - distributed_outputs.destination_ids_by_application_variable + variables = Symbol[Symbol(variable) for variable in _model_output_names(application)] + 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.slot) - for variable_ in keys(plan.declarations) + # 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) end @@ -5292,72 +5006,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}() - timeline = compiled.scenario_plan.timeline - for binding in compiled.input_bindings + for binding in 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, - ) + _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}() - for request in output_requests - request.name in names && error( - "Duplicate output request name `$(request.name)`. Request names must be unique." - ) - push!(names, request.name) - application = _model_request_application( - 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 - Set( - (application.id, variable) - for application in compiled.applications - for variable in _model_application_output_variables( - compiled, - application, - ) - ) + _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 @@ -5382,14 +5115,9 @@ 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, - ) - ) + _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 @@ -5461,58 +5189,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) @@ -5521,34 +5219,39 @@ end "Call `$(name)` on application `$(context.application.id)` is an " * "initializer binding. Use `run_initializer!(context, :$(name), object)` " * "exactly once for the newly registered object.", - ), - ) -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).", - ) + ), + ) +end + +@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 consume(_synchronized_named_call(targets, context, name), args...) end - return found + return _current_topology_call_targets( + _synchronized_named_call(targets, context, name), context, name, requested_ids, consume, args..., + ) 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 @@ -5575,19 +5278,41 @@ 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, + target.call_bindings, + 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; + call_schema=_context_call_schema(context), + ) + 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, @@ -5619,13 +5344,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 @@ -5634,14 +5364,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 @@ -5685,26 +5416,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 @@ -5945,23 +5684,29 @@ 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 # 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 """ @@ -5994,17 +5739,30 @@ 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(_with_selected_call_targets, context.calls, name, context, requested_ids, identity) 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) @@ -6026,35 +5784,46 @@ execution target and remains valid until a lifecycle refresh barrier. ) end -@noinline function _call_model_missing_error(context, name) - available = Symbol[targets.binding.call for targets in context.calls] +@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::Union{Vector{Symbol},Tuple{Vararg{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 ", - "`$(context.object_id.value)` did not declare call `$(name)`. ", - "Declared calls: $(available).", + "`$(_object_id_text(context.object_id))` did not declare call `$(name)`. ", + "Declared calls: ", _diagnostic_symbol_list(available), ".", ) 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(targets, _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) @@ -6066,31 +5835,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 ids -end - -function _partial_model_application( - application::CompiledModelApplication, - target_ids::Vector{ObjectId}, -) - return CompiledModelApplication( - application.plan, - target_ids, - ) -end - -struct _ApplicationsByObjectOverlay{B,O} - base::B - overlay::O + I = keytype(model.registry.objects) + ids = I[object_id(model, object)::I for object in requested] + return unique!(ids) end mutable struct _TargetedApplicationSet{A,B} @@ -6099,56 +5849,44 @@ mutable struct _TargetedApplicationSet{A,B} outputs_prepared::Bool end -mutable struct _TargetedTopologyRuntime{CS,MA} <: +mutable struct _TargetedTopologyRuntime{CS,MA,D<:Dict,O} <: AbstractTargetedTopologyRuntime compiled::CS model_revision::Int - application_sets::Dict{ - Tuple{Vararg{ObjectId}}, - Union{Nothing,_TargetedApplicationSet}, - } - added_applications_by_object::Dict{ - ObjectId, - Vector{CompiledModelApplication}, - } + application_sets::D + added_applications_by_object::O indexed_addition_count::Int manual_application_ids::MA application_positions::Dict{Symbol,Int} 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, ) 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},_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} 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}}(), + D(), + O(), 0, - compiled.scenario_plan.manual_application_ids, + manual, Dict( application_id => index for (index, application_id) in pairs(compiled.application_order) @@ -6164,14 +5902,15 @@ 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, 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) @@ -6182,7 +5921,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, @@ -6202,29 +5941,29 @@ function _targeted_application_set!( model::CompositeModel, requested_ids, ) - key = Tuple(requested_ids) + I = keytype(runtime.added_applications_by_object) + # 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 - 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, ) return _TargetedApplicationSet( output_applications, - _ApplicationsByObjectOverlay( + _LookupOverlay( runtime.compiled.applications_by_object, runtime.added_applications_by_object, ), 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 @@ -6233,31 +5972,44 @@ 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 = ObjectId[]) + isnothing(unindexed_ids) && (unindexed_ids = 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 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, 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 @@ -6276,24 +6028,13 @@ 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 -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( @@ -6303,18 +6044,21 @@ 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, - 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 + cached.application_plans_by_id; + environment_schema=cached.environment_schema, ) + _validate_model_environment_inputs!(partial, applications_by_id, + keytype(model.registry.objects); + environment_schema=cached.environment_schema) + by_target = _index_environment_bindings(partial, keytype(model.registry.objects)) return _compiled_environment_bindings( model, compiled, @@ -6322,7 +6066,8 @@ function _targeted_call_environment_bindings( cached.application_plans_by_id, partial, by_target, - cached.sample_cache, + cached.sample_cache; + environment_schema=cached.environment_schema, ) end @@ -6330,11 +6075,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( @@ -6381,7 +6126,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_text(object_id))` in this lifecycle event.", ) end @@ -6391,21 +6136,20 @@ 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, 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( - "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 @@ -6425,15 +6169,7 @@ 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 - applications_by_object = application_set.applications_by_object callee_applications = _targeted_callee_applications( binding, requested_ids, @@ -6458,39 +6194,50 @@ function _targeted_new_object_call_targets( ) end + return _prepare_targeted_newborn_targets( + context, name, targeted_runtime, application_set, callee_applications, initializer, + cached_targets.batch_schema, + ) +end + +# 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::AbstractVector, + initializer::Bool, + batch_schema::ExecutionBatchSchema, +) + 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) + _prepare_model_output_statuses!(model, output_applications, compiled.applications_by_id) application_set.outputs_prepared = true 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_plans_by_application, - application.slot, - ), - targeted_runtime.manual_application_ids, - applications_by_object, - compiled.applications_by_id, - compiled.distributed_outputs, - ) - end - end - final_input_references = _model_input_status_references(input_bindings) + input_bindings = similar(compiled.input_bindings, 0) + _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!( 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[ @@ -6501,16 +6248,14 @@ function _targeted_new_object_call_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 end - targeted_input_bindings = _index_model_bindings( - input_bindings, - :application_id, - :consumer_id, + targeted_input_bindings = _index_model_input_bindings( + input_bindings, keytype(model.registry.objects), ) environment_bindings = _targeted_call_environment_bindings( @@ -6528,71 +6273,11 @@ function _targeted_new_object_call_targets( return nothing end - targets = CallTarget[] + targets = _targeted_newborn_target_buffer(batch_schema, context) 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 + 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( @@ -6603,39 +6288,168 @@ function _targeted_new_object_call_targets( return targets end +function _append_targeted_newborn_targets!( + partial_application::A, targets, + context::RunContext, + targeted_runtime::_TargetedTopologyRuntime, + targeted_input_bindings, + environment_bindings::CompiledEnvironmentBindings, + batch_schema::ExecutionBatchSchema, +) where {A<:CompiledModelApplication} + compiled = context.compiled + # 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(_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, prepared_cache, targets, context, 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.temporal_streams, + owner.output_retention,true) + 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. +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}; + 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;call_schema, + ) + 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( + context::RunContext, + application::CompiledModelApplication, + object_id::ObjectId, + model, + status_view::CompiledModelStatusView, + outputs::Tuple, + output_targets::NamedTuple, + call_bindings::Tuple, + environment_bindings::CompiledEnvironmentBindings, + environment_binding, + 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, call_bindings, + environment_binding, cache.default, cache, + ) + return CallTarget( + execution_target, context.compiled, environment_bindings, application, + object_id, cache.default.calls, context.temporal_streams, context.output_retention, + context.time, context.constants, context.publication_allowed, context.environment, + ) +end + function _current_topology_call_targets( + cached_targets::CallTargets, context::RunContext, name::Symbol, - objects, -) + requested_ids, + consume::F, + args::Vararg{Any,N}, +) where {F,N} 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) - environment_bindings = refresh_environment_bindings!(model, compiled) - bindings = get( - compiled.call_bindings_by_target, - (context.application.id, context.object_id), - (), - ) - binding = findfirst( - candidate -> _compiled_call_name(candidate) === name, - bindings, + isnothing(targeted) || return consume(targeted, args...) + compiled = _refresh_runtime_bindings!(model, context.compiled) + environment_bindings = _refresh_environment_bindings!( + model, + compiled, + _current_environment_binding_owner(model, context.environment_bindings); + environment_schema=context.environment_bindings.environment_schema, ) + binding = _current_named_call_binding(compiled, context.application.id, context.object_id, + cached_targets.binding, keytype(model.registry.objects)) if isnothing(binding) - available = Symbol[candidate.call for candidate in bindings] - error( - "Application `$(context.application.id)` on object ", - "`$(context.object_id.value)` did not declare call `$(name)`. ", - "Declared calls: $(available).", - ) + bindings = get(compiled.call_bindings_by_target, (context.application.id, context.object_id), ()) + available = Symbol[(item::CompiledModelCallBinding).call for item in bindings] + _missing_named_call(context, name, available) end - resolved_binding = bindings[binding] + 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, + model, compiled, environment_bindings, +) _compiled_call_mode(resolved_binding) === :manual || _initializer_requires_dedicated_api(context, name) resolved_binding.multiplicity != :many && length(requested_ids) > 1 && @@ -6644,16 +6458,18 @@ 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( 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 @@ -6670,15 +6486,12 @@ function _current_topology_call_targets( 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, resolved_binding.consumer_id, - requested_ids, + _application_target_ids(model, requested_ids), callee_application_ids, ) if !isnothing(context.temporal_streams) && @@ -6700,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!( @@ -6736,28 +6546,12 @@ function _current_topology_call_targets( context.environment, ; tracks_full_membership=false, + batch_schema=cached_targets.batch_schema, ) 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 ", - "`$(context.object_id.value)`: 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 = 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.", @@ -6765,7 +6559,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 @@ -6783,21 +6577,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) @@ -6808,17 +6608,28 @@ 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}, ::E, -) 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_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( +@inline function _call_context_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, environment, ) return context.compiled === compiled && @@ -6827,44 +6638,60 @@ end context.bound_inputs === bound_inputs && context.output_targets === output_targets && context.temporal_streams === temporal_streams && context.output_retention === output_retention && context.constants === constants && - typeof(context.environment) === typeof(environment) + _call_context_bindings_match(context.calls, call_bindings) && + typeof(context.environment) === typeof(environment) && + _call_context_preparation_is_current(context.calls, compiled, environment_bindings, + temporal_streams, output_retention, constants) +end + +@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, +) + 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) +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 _call_context_matches(::Nothing, args...) = false @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, - environment, - )) - context = reuse ? cache.transient : nothing - if !(context isa Context && _call_context_matches( - context, compiled, environment_bindings, application, object_id, - bound_inputs, output_targets, temporal_streams, output_retention, constants, - environment, - )) - # 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, - bound_inputs, output_targets, temporal_streams, output_retention, - time, constants, publication_allowed, environment, - )::Context - reuse && (cache.transient = context) - return context + 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 + 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, - bound_inputs, output_targets, temporal_streams, output_retention, - time, constants, publication_allowed, environment, + # 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; fresh=true, ) + reuse && (cache.transient = fresh) + return fresh end @inline function _record_call_execution!(cache) @@ -6872,15 +6699,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 @@ -6919,11 +6747,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 @@ -6937,7 +6765,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, @@ -6960,23 +6788,20 @@ 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, ) - 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. + # 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, frame, - ) - elseif frame === nothing - _run_call_kernel!( - target.model, status, environment_value, context, target.output_bindings, + target.execution_target, environment_value, context::DefaultContext, frame, ) else - _run_evaluated_call_kernel!( - target.model, status, environment_value, context, target.output_bindings, frame, + _run_owned_call_kernel!( + target.execution_target, environment_value, context, frame, ) end finally @@ -7065,7 +6890,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, @@ -7092,6 +6917,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, ) @@ -7099,6 +6925,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, ) @@ -7168,6 +6995,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, @@ -7208,12 +7055,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 @@ -7240,36 +7084,28 @@ 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) - 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) @@ -7322,18 +7158,17 @@ 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(_with_selected_call_targets, context.calls, name, context, + requested_ids, _run_selected_call_targets!, context, publish, sampled_environment, environment) +end + +@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, - ) + context.environment : environment + return _run_call_targets!(targets, publish, sampled_environment, selected_environment) end function run_call!( @@ -7352,12 +7187,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 @@ -7406,7 +7242,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!( @@ -7437,10 +7274,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, @@ -7502,7 +7345,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( @@ -7544,13 +7387,17 @@ 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) - simulation.environment_bindings = refresh_environment_bindings!( + environment_owner = _current_environment_binding_owner(model, simulation.environment_bindings) + environment_delta_covers_runtime = environment_owner === simulation.environment_bindings + simulation.environment_bindings = _refresh_environment_bindings!( model, simulation.compiled, + environment_owner; + environment_schema=simulation.environment_bindings.environment_schema, ) _runtime_performance_finish!( simulation.performance, @@ -7579,7 +7426,8 @@ function _refresh_simulation_runtime!(simulation::Simulation) ), ) end - changed_execution_application_ids = output_retention_reused ? + 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) @@ -7624,37 +7472,42 @@ 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!( 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 = environment_owner === simulation.environment_bindings 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_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 - for application in get( + 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 = _index_object_id( simulation.compiled.applications_by_object, - object_id, - (), + dirty_object_id, ) - push!( - changed_execution_application_ids, - application.id, - ) - push!( - changed_execution_target_ids, - (application.id, 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 : @@ -7662,9 +7515,11 @@ 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; + environment_schema=simulation.environment_bindings.environment_schema, ) _runtime_performance_finish!( simulation.performance, @@ -7702,8 +7557,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!( @@ -7801,7 +7656,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, @@ -7856,16 +7711,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!( @@ -7923,238 +7775,417 @@ 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 $(string(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 -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, 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, args::Vararg{Any,N}) where {F,N} + for slot in 1:length(requests) + Base.@inline _with_metadata_entry(_visit_output_request, requests, slot, operation, args...) + 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 _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 + +@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 + +@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, + 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, action, args...) +end + +function _compile_output_request(model, compiled, request) + matcher = _compile_selector_matcher(model, request.selector) + 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 + +# 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)) + 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) + object_id = _index_object_id(model.registry.objects, raw_id) + object_id in owned_ids || continue + _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 + +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) + prepared = _output_request_record(record.request, record.matcher, record.application_id, + keytype(record.targets), types) + for (id, target) in record.targets + prepared.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) -function _output_request_published_at(simulation, application_id, object_id, variable, 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(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, + request.context, false, nothing, false) && 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 + 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 + 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 + _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 + 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 = _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 @@ -8186,14 +8217,20 @@ function _prepare_simulation!( constants, outputs, performance::Bool=false, -) + 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) 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) + _validate_authored_scenario(preparation) + prepared = preparation.resolved compiled = model.binding_cache if !isnothing(prepared) || !isnothing(compiled) previous = isnothing(prepared) ? compiled.scenario_plan : prepared.plan @@ -8207,9 +8244,11 @@ 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, + status_view_schema, ) compiled.execution_generation += UInt64(1) _runtime_performance_finish!( @@ -8253,7 +8292,8 @@ 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} + env_bindings = _refresh_environment_bindings!(model, compiled, cached_environment; environment_schema) _runtime_performance_finish!( performance_counters, :initial_environment_compile, @@ -8277,7 +8317,8 @@ function _prepare_simulation!( :initial_output_retention_compile, started_at, ) - temporal_streams = Dict{Tuple{Symbol,ObjectId,Symbol},Any}() + # 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, @@ -8313,16 +8354,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, @@ -8341,9 +8373,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, @@ -8412,7 +8442,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 @@ -8440,126 +8470,124 @@ 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) + 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) - candidates = CompiledModelApplication[] - for application in compiled.applications - isnothing(request.application) || - application.id == request.application || - application.name == request.application || - continue - local_output = request.var in keys(_local_output_schema(application.spec)) - 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 - end - push!(candidates, application) + 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(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) - 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 _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 - return any( - plan -> request.var in keys(plan.declarations) && - _selector_labels_may_overlap(request.selector, plan.selector), - _application_plans(plans.by_application, application.slot), + isnothing(plans_by_application) && return false + return Base.@inline _with_metadata_entry( + _any_matching_output_destination, plans_by_application, application.id, request.var, request.selector, ) 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 _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) 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 @@ -8597,9 +8625,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) @@ -8640,7 +8669,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, ), ) @@ -8681,12 +8710,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 @@ -8731,17 +8761,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!( @@ -8781,7 +8807,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/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/src/composite_model/selectors.jl b/src/composite_model/selectors.jl index 6db0ba418..0b16f4a34 100644 --- a/src/composite_model/selectors.jl +++ b/src/composite_model/selectors.jl @@ -220,12 +220,32 @@ 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) + 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[] + 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( @@ -320,7 +340,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,12 +349,47 @@ 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), + 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), + 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) 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_text(override.object))` does not belong to instance `$(instance.name)`." ) matches = findall( index -> @@ -343,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_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_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_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_text(override.object))` in instance `$(instance.name)`", ) push!(object_models, override.object => override.model) end @@ -441,14 +496,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, @@ -477,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 @@ -484,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) @@ -500,41 +560,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 @@ -542,7 +591,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 @@ -550,22 +599,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, @@ -577,18 +610,28 @@ 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] - object = _model_object(model, id)::Object - (isnothing(scale) || object.scale === scale) && - (isnothing(kind) || object.kind === kind) && return id + id = _index_object_id(model.registry.objects, @inbounds ancestors[index]) + _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 @@ -630,18 +673,45 @@ 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 = [selector.relation for selector in selectors if selector isa Relation] - isempty(values) && return nothing - length(unique(values)) == 1 || error("Conflicting `Relation(...)` selector values: $(values).") - return only(unique(values)) + relation = _first_positional_relation(selectors) + isnothing(relation) && return nothing + first_value = relation.relation + for selector in selectors + 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[]) + 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 @@ -658,26 +728,31 @@ 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 `$(_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) symbolic_ids = Symbol[id for id in available_ids if id isa Symbol] 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_text(root_id))` found in the model registry. ", "available_ids=$(available_ids), available_instances=$(available_instances), ", "suggestions=$(suggestions).", ) @@ -690,13 +765,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,41 +790,35 @@ function _compile_selector_matcher( ) 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 _selector_matcher_with_scope(matcher, _compile_selector_scope(model, matcher.scope)) +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)...] + return collect(keys(model.registry.objects)) end 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) 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 @@ -769,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) @@ -803,12 +875,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 candidate_ids isa AbstractSet ? ids : unique!(identity, ids; seen=Set{I}()) end # Resolve topology once, before choosing between a bounded local walk and a @@ -820,12 +897,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 @@ -834,11 +906,33 @@ 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) 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) = @@ -862,9 +956,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_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_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)) @@ -874,7 +968,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 @@ -894,14 +988,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))`.", @@ -985,7 +1075,9 @@ function _available_selector_labels(model::CompositeModel, candidate_ids) scales = Symbol[] kinds = Symbol[] species = Symbol[] - ids = ObjectId[] + 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) @@ -996,10 +1088,196 @@ 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 +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 _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, ('"',)) + 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, _prepared_type_name(T)) + return nothing +end + +function _print_tuple_items(emit::F, io, items::Tuple, args::Vararg{Any,N}) where {F,N} + isempty(items) && return nothing + emit(io, first(items), args...) + if length(items) > 1 + print(io, ", ") + _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, ", ") + _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, _prepared_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, _prepared_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, _prepared_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, _prepared_type_name(T), "(bytes=") + _print_selector_diagnostic(io, reinterpret(NTuple{sizeof(T),UInt8}, value), ancestors) + print(io, ')') + else + _print_selector_diagnostic_record(io, _prepared_type_name(T), value, ancestors) + end + return nothing +end + function _selector_resolution_error( model::CompositeModel, selector, @@ -1019,16 +1297,25 @@ 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)." - ) -end - -function _matches_object_criteria(object::Object; scale=nothing, kind=nothing, species=nothing, id=nothing) + io = IOBuffer() + ancestors = Any[] + print(io, "Expected ", expected, " object for selector `") + _print_selector_diagnostic(io, selector, ancestors) + 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) + 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; 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 @@ -1039,25 +1326,31 @@ end _compiled_relation_symbol(::Val{RELATION}) where {RELATION} = RELATION function _selector_matches_object_id( - model::CompositeModel, + model, 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 - 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, + 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 && @@ -1087,63 +1380,28 @@ function _selector_matches_object_id( _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, - 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( 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 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) @@ -1178,11 +1436,14 @@ 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[] - 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, + model, matcher, id, context, default_to_context, default_scope, relation_resolved, ) && push!(ids, id) end return _sort_object_ids!(unique!(ids)) @@ -1195,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) @@ -1211,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( @@ -1238,46 +1512,44 @@ function _resolve_object_ids( nothing end 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 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] + ancestor_id = _scope_anchor(model, scope::Ancestor, current_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 - ids = _matching_selector_ids( - model, 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. @@ -1334,3 +1606,127 @@ 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,I<:ObjectId} + model::M + object::Object + id::I + parent::Union{Nothing,I} + kind::Union{Nothing,Symbol} + species::Union{Nothing,Symbol} +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, 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) + 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) = + _relation_same_object(topology.model, left, right) +@inline function _relation_parent(topology::_PreparedStatusObjectTopology, id) + return id == topology.id ? topology.parent : _relation_parent(topology.model, id) +end +@inline function _relation_in_subtree(topology::_PreparedStatusObjectTopology, 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.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 +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) = + 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 + 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.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, 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) + 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) + _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, + destination_plan, execution_id) + # 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) + 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 + 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. +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/source_compilation.jl b/src/composite_model/source_compilation.jl index 4aa195172..af62bbbe1 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=_object_id_text) + push!(models, _application_model_overrides(application)[object_id]) end end unique_models = Any[] @@ -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 @@ -618,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) @@ -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, @@ -968,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 @@ -1029,7 +1033,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, @@ -1056,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, @@ -1102,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 @@ -1128,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; @@ -1145,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, @@ -1214,12 +1248,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/composite_model/status_construction.jl b/src/composite_model/status_construction.jl new file mode 100644 index 000000000..8bf9616d1 --- /dev/null +++ b/src/composite_model/status_construction.jl @@ -0,0 +1,100 @@ +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 + +@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) + +"""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,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 + +_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.")) + 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) + 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 + 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 + +@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) + # 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()) : :(_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} + dense = :($Hot($(Expr(:tuple,hot...)))) + projected || return quote + original_refs = $load_refs + return Status($dense)::Result + end + FullNames = _status_schema_names(Result) + Full = fieldtype(fieldtype(Storage, :snapshot), :refs) + 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 + original_refs = $load_refs + hot = $dense + refs = $Full($(Expr(:tuple,full...))) + snapshot = _ProjectedStatusSnapshot(refs, _status_reference_epoch(original)) + return Status($Storage(hot, snapshot))::Result + end +end diff --git a/src/composite_model/status_conversion.jl b/src/composite_model/status_conversion.jl index 2d30bae39..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, " ") @@ -123,6 +123,94 @@ 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) + +# 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_type_rules(policy::StatusConversionPolicy, T, elements) + T === Union{} && return nothing + if T isa Union + results = map(Base.uniontypes(T)) do member + _configured_status_type_rules(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 +238,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) @@ -317,7 +404,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) @@ -331,6 +418,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/src/composite_model/status_view_construction.jl b/src/composite_model/status_view_construction.jl new file mode 100644 index 000000000..67305284b --- /dev/null +++ b/src/composite_model/status_view_construction.jl @@ -0,0 +1,563 @@ +# 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)) + 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) + 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 + +# 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...) + 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) + 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: ", + "`$(Tuple(id.value for id in binding.source_ids))`.", + ) + initial = status[binding.input] + end + 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[(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 ", + "`$(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[(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, + 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[(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 + +@inline function _compile_model_status_view(model::CompositeModel, + application::CompiledModelApplication, object_id::ObjectId, + input_bindings::Union{AbstractVector{<:CompiledModelInputBinding},Tuple{}}, + applications_by_id, application_positions, + distributed_outputs, + execution_stamp::Base.RefValue{UInt64}, status_view_schema, + input_binding_storage, +) + 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 + +# 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, + input_bindings, 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 = Base.@inline _with_application_variant(application, object_id) do effective_model, ports + _read_application_defaults(effective_model, Val(:outputs), ports) + end + 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 + 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 + name in seen_many && error( + "Compiled application input `$(name)` has more than one Many binding.") + push!(seen_many, name) + end + 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) + 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} = + 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 -> 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, 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 + 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.")) + 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) +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)))] + 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) + 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), + initial_matches, + :(_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 = :(_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)...}} + 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, 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]) + 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 9dbd03f81..d4d5a9a0e 100644 --- a/src/composite_model_api.jl +++ b/src/composite_model_api.jl @@ -1,14 +1,24 @@ # 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") 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") 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") 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/input_schema.jl b/src/input_schema.jl index 506b6f302..6af847d59 100644 --- a/src/input_schema.jl +++ b/src/input_schema.jl @@ -40,6 +40,13 @@ 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. + # 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) context = "`inputs_($(typeof(model)))`" @@ -74,11 +81,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/native_compilation.jl b/src/native_compilation.jl index d2a8c9353..8aa15e377 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 @@ -37,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) || @@ -55,23 +54,22 @@ 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) || _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") - # 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) + PSE._sample_compiled_global_environment(binding, 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,22 @@ 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 + # 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 -@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 @@ -161,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 diff --git a/src/output_schema.jl b/src/output_schema.jl index 9804bde51..710adf0b5 100644 --- a/src/output_schema.jl +++ b/src/output_schema.jl @@ -36,13 +36,19 @@ 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)) 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/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)`." 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/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/src/time/runtime/environment_backends.jl b/src/time/runtime/environment_backends.jl index d3213fb64..5ecac8a03 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 @@ -98,7 +102,11 @@ end function _available_environment_variables(source) row = _first_environment_row(source) isnothing(row) && return nothing - return Set(Symbol.(propertynames(row))) + variables = Set{Symbol}() + for name in propertynames(row) + push!(variables, Symbol(name)) + end + return variables end """ @@ -199,6 +207,14 @@ 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. 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( @@ -215,19 +231,30 @@ function sample(backend::AbstractEnvironmentBackend, handle, state, variable::Sy ) end -function sample(backend::GlobalConstant, handle, variable::Symbol, time) +@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 + +@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 - hasproperty(source, variable) || error( + _environment_row_hasproperty(source, variable) || error( "GlobalConstant source does not provide variable `$(variable)`." ) 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 - hasproperty(source, variable) || error( + _environment_row_hasproperty(source, variable) || error( "Transient GlobalConstant state does not provide variable `$(variable)`." ) return getproperty(source, variable) @@ -348,12 +375,14 @@ 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) - rules = Pair{Symbol,Symbol}[] - for target in keys(environment_inputs_(model_spec)) + return bindings, _environment_source_overrides(model_spec) +end + +function _environment_sampling_rules(bindings, environment_sources, input_names) + return map(input_names) do target source = target if haskey(bindings, target) rule = bindings[target] @@ -362,9 +391,8 @@ function _environment_sampling_rules(model_spec::ModelSpec) 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) @@ -382,12 +410,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/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/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/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_editor_api.jl b/src/visualization/model_graph_editor_api.jl index 07b3052cf..ad54a2820 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}() @@ -306,9 +307,19 @@ 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) - return candidate + 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, collect(Any, preparation.source_specs), + collect(Any, preparation.authored), nothing) + else + _prepare_authored_scenario(candidate; raw_families=nothing) + end + candidate.scenario_plan_cache = final_preparation + return _install_prepared_canonical_registry(candidate, final_preparation) end function _model_edit_application_id(spec) @@ -719,7 +730,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 @@ -845,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 && edit.input in Symbol.(propertynames(object.status)) - supplied || _set_model_object_status!(model, object_id, edit.input, edit.initial_value) + supplied = object.status isa Status && hasproperty(object.status, edit.input) + 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) @@ -889,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) @@ -956,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_) @@ -969,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) @@ -1052,7 +1076,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 +1181,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/src/visualization/model_graph_view.jl b/src/visualization/model_graph_view.jl index f3085445b..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 """ @@ -92,34 +93,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) @@ -175,6 +148,7 @@ end function _model_graph_compiled( model, + preparation, applications, input_plans, call_plans, @@ -186,17 +160,19 @@ 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_input_bindings(input_bindings, keytype(model.registry.objects)) timeline = _model_timeline(model) scenario_plan = _compiled_scenario_plan( model, + preparation, applications, input_plans, call_plans, 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 @@ -206,8 +182,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) @@ -217,7 +195,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, @@ -231,12 +209,14 @@ 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, scenario_plan.call_owners, scenario_plan.application_children, status_views, + nothing, Set(application.id for application in applications), Set(keys(status_views)), false, @@ -246,56 +226,37 @@ 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) - 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), - ), - 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) - end - isempty(applications) || return applications - isempty(model.applications) && return applications - +function _model_graph_compile_applications(model, preparation, timeline, diagnostics) 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) + 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)`.", ) 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 @@ -338,6 +299,7 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) Vector{Vector{Symbol}}(), ModelGraphDiagnostic[], compiled, + nothing, ) end @@ -356,9 +318,11 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) Vector{Vector{Symbol}}(), diagnostics, nothing, + CompiledEnvironmentBinding[], ) - 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, @@ -370,12 +334,16 @@ 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; + applications, + _applications_by_id(applications); prepare_runtime=false, ) environment_bindings = _compile_environment_bindings_for_applications( @@ -383,10 +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), - ) + environment_bindings end distributed_output_plans = _model_graph_phase!( @@ -394,18 +359,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, @@ -414,11 +375,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, @@ -427,16 +387,14 @@ 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 _compile_model_call_bindings( model, applications; + applications_by_id=_applications_by_id(applications), plans_by_application=_plans_by_application( applications, call_plans, @@ -446,64 +404,91 @@ 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, - 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, - _plans_by_application(applications, input_plans), - distributed_outputs, - ) - end - _model_graph_phase!(diagnostics, :input_status, nothing) do - _prepare_model_input_defaults!(model, applications) - _wire_model_input_carriers!(model, 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}}() + 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 @@ -524,9 +509,10 @@ function compile_model_report(model::CompositeModel; strict::Bool=false) end end - compiled = try + compiled = !manifest_ready ? nothing : try _model_graph_compiled( model, + preparation, applications, input_plans, call_plans, @@ -552,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) @@ -807,6 +811,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 @@ -830,9 +851,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 - _resolved_output_destinations(spec) + _output_destination_layout(spec, _model_distributed_output_names(application)) catch # Invalid declarations remain editable; compilation reports the error. nothing @@ -841,7 +863,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), ) @@ -890,10 +912,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 @@ -956,7 +978,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))), @@ -964,14 +986,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 @@ -1412,7 +1434,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( @@ -1425,10 +1449,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) @@ -1598,10 +1624,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) @@ -1697,8 +1723,8 @@ 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) + 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 # expose required storage when later compilation phases fail. @@ -1707,7 +1733,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 @@ -1732,7 +1758,7 @@ end function _model_graph_add_status_conversion!(rows, report) explanations = try - explain_initialization(report.model) + _explain_initialization(report) catch NamedTuple[] end @@ -1966,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/fixtures/distributed_growth.jl b/test/fixtures/distributed_growth.jl new file mode 100644 index 000000000..82a3e5002 --- /dev/null +++ b/test/fixtures/distributed_growth.jl @@ -0,0 +1,121 @@ +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 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)) + 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 + +# 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((:tree, :leaf, index)) for index in 1:30] +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 + 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/fixtures/local_palm_leaf_birth/Project.toml b/test/fixtures/local_palm_leaf_birth/Project.toml new file mode 100644 index 000000000..322b82943 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/Project.toml @@ -0,0 +1,16 @@ +name = "PSELocalPalmLeafBirth" +uuid = "b6daedc5-c1c3-4c8e-a43e-b4ee2ff54a35" +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] +PlantSimEngine = {path = "../../.."} + +[compat] +Libiconv_jll = "=1.18.0" +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..aaa262dd9 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/PSELocalPalmLeafBirth.jl @@ -0,0 +1,106 @@ +module PSELocalPalmLeafBirth + +include("native_preparation.jl") +include("fixture.jl") +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() + +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 + 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) + 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..ce55eb9f4 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/fixture.jl @@ -0,0 +1,262 @@ +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[]), + self_leaf_losses=PSE.Required(AbstractVector{<:Real})) +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, self_leaf_losses=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)) - + sum(status.self_leaf_losses; 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), + # 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, + 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..6f01cda51 --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/prepare.jl @@ -0,0 +1,113 @@ +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.") + 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.") + 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.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.") + 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/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..c99f6b86f --- /dev/null +++ b/test/fixtures/local_palm_leaf_birth/src/tree_birth.jl @@ -0,0 +1,33 @@ +# 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]),)) + model = PSE.CompositeModel(root) + 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) + 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 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/integration/fixtures/distributed_producer_birth/Project.toml b/test/integration/fixtures/distributed_producer_birth/Project.toml new file mode 100644 index 000000000..abeff5f4e --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/Project.toml @@ -0,0 +1,14 @@ +name = "PSEThirtyProducerControl" +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" 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..6311d3014 --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/src/PSEThirtyProducerControl.jl @@ -0,0 +1,72 @@ +module PSEThirtyProducerControl +import PlantSimEngine as PSE +include("native_preparation.jl") +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 + 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 +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..b114d6c6b --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/src/leaf_recovery.jl @@ -0,0 +1,71 @@ +module LeafRecovery +import PlantSimEngine as PSE +using PlantSimEngine: Default, bound_input +using ..NativePreparation: prepare_growth_fixture +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 check_recovery!(sim, observe) + result = exercise!(sim, observe) + iszero(result) || error("Leaf recovery failed at checkpoint $result.") +end + +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 new file mode 100644 index 000000000..36fa6e769 --- /dev/null +++ b/test/integration/fixtures/distributed_producer_birth/src/prepare.jl @@ -0,0 +1,100 @@ +# 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))) + 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] + 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 + +# 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 + wide_snapshot_checkpoint(sim) || return false + length(state.ids) == 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) + 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 + 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 + 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() + 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 +end 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/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 new file mode 100644 index 000000000..c4b8cb262 --- /dev/null +++ b/test/integration/fixtures/scene_dependencies/src/PSESceneDependencyControl.jl @@ -0,0 +1,32 @@ +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), + 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) + 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) + return length(ids) == 1 && ids[1] === context ? Cint(0) : Cint(2) +end + +end diff --git a/test/integration/native_fixture_apps.jl b/test/integration/native_fixture_apps.jl new file mode 100644 index 000000000..f21ca0920 --- /dev/null +++ b/test/integration/native_fixture_apps.jl @@ -0,0 +1,60 @@ +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. Direct PSE and MTG dependencies use the packages loaded by the 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 + 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 + manifest = joinpath(template, "Manifest.toml") + if isfile(manifest) + lock = TOML.parsefile(manifest) + for entries in values(lock["deps"]), entry in entries + 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"])) + 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..d6732c15d --- /dev/null +++ b/test/integration/native_growth.jl @@ -0,0 +1,111 @@ +# 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", + 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")) + +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.") + 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 + @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)) + 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 + @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 + + @testset "New producer publishes to thirty existing leaves" begin + mktempdir() do directory + @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 + +@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"], ["nested"]) + @test PSESceneDependencyControl.main(args) == 0 + @test success(`$(scene.executable) $args`) + end + end +end diff --git a/test/integration/native_preparation.jl b/test/integration/native_preparation.jl new file mode 100644 index 000000000..391a142c2 --- /dev/null +++ b/test/integration/native_preparation.jl @@ -0,0 +1,126 @@ +module NativePreparation +import PlantSimEngine as PSE +export close_registry, RuntimeTypes, InputTrace, remember!, batch_schema + +function close_registry(model, id_type=nothing) + 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 + 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 + inputs::Set{Tuple{Int,DataType}} + views::Dict{Symbol,Vector{DataType}} +end +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} + 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) + push!(values.observed.inputs, (binding.slot, typeof(binding))) + values.data[index] = binding + return values +end +function Base.push!(values::InputTrace, binding) + push!(values.observed.inputs, (binding.slot, typeof(binding))) + push!(values.data, binding) + return values +end +function Base.insert!(values::InputTrace, index::Integer, binding) + 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) = + 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 + +# 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 + 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.") + 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) || + 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.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)) + 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 diff --git a/test/runtests.jl b/test/runtests.jl index 61df0c9a5..054a02633 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -26,334 +26,54 @@ 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 - @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") - 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 = test_group_indices(shard_index, shard_count) + @info "Test partition" shard_index shard_count groups=length(group_indices) - @testset "Concrete runtime object identities" begin - include("test-model-concrete-object-identities.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") - 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") - end - - @testset "Isolated model diagnostics" begin - include("test-model-diagnostic-isolation.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") - 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-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") - 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") - 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") - 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") - 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") - end - - @testset "Distributed output runtime" begin - include("test-model-distributed-output-runtime.jl") - end - - @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] + @info "Test group start" group_index name files + group_started_at = time_ns() + try + @testset "$name" begin + for file in files + @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 + @info "Test group end" group_index name elapsed_seconds=(time_ns() - group_started_at) / 1.0e9 + 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-application-membership-slots.jl b/test/test-application-membership-slots.jl new file mode 100644 index 000000000..04237d9bd --- /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._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 +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-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-compilation-metadata.jl b/test/test-compilation-metadata.jl new file mode 100644 index 000000000..15b25e356 --- /dev/null +++ b/test/test-compilation-metadata.jl @@ -0,0 +1,75 @@ +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 +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[] + 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 + @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,) + 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 + +@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 = PSE._input_query_cache(model.registry.objects, 2) + point = One(Ancestor(scale=:Plant); scale=:Plant) + 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._input_route_source_ids(cache, 1, model, plan, ObjectId(:leaf_a)) + @test next_ids == [ObjectId(:plant)] + @test next_ids !== cache[1] + many = Many(SceneScope(); scale=:Leaf) + 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)) + 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 + +end diff --git a/test/test-environment-backends.jl b/test/test-environment-backends.jl index cde75ee09..b426ec0df 100644 --- a/test/test-environment-backends.jl +++ b/test/test-environment-backends.jl @@ -39,3 +39,46 @@ 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 + +@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 diff --git a/test/test-execution-cohort-refresh.jl b/test/test-execution-cohort-refresh.jl new file mode 100644 index 000000000..7db47a710 --- /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[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 new file mode 100644 index 000000000..41b5f097d --- /dev/null +++ b/test/test-execution-cohorts.jl @@ -0,0 +1,139 @@ +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 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 + @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[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[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[1]) +end diff --git a/test/test-fixed-status-manifest.jl b/test/test-fixed-status-manifest.jl new file mode 100644 index 000000000..f7265ff26 --- /dev/null +++ b/test/test-fixed-status-manifest.jl @@ -0,0 +1,307 @@ +module FixedStatusManifestChecks +using Dates, 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 "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 + +@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)) + 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 +@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)) + 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 + + # 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. +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 + + +@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 new file mode 100644 index 000000000..05f9aa3c8 --- /dev/null +++ b/test/test-fixed-status-prospective-distributed.jl @@ -0,0 +1,117 @@ +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 + +@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 + +@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 + +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 diff --git a/test/test-fixed-status-scope-growth.jl b/test/test-fixed-status-scope-growth.jl new file mode 100644 index 000000000..7d7e62384 --- /dev/null +++ b/test/test-fixed-status-scope-growth.jl @@ -0,0 +1,126 @@ +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 + +@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 diff --git a/test/test-initial-status-preparation.jl b/test/test-initial-status-preparation.jl index beaca856f..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,11 +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]) - application = ( - id=:probe, - spec=ModelSpec(InitialStatusPreparationProbe(NamedTuple(), (first=0.0, second=Float32[]))), - ) + 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) + 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-input-default-values.jl b/test/test-input-default-values.jl new file mode 100644 index 000000000..0096d73d2 --- /dev/null +++ b/test/test-input-default-values.jl @@ -0,0 +1,298 @@ +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 + # 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 + +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 diff --git a/test/test-input-source-matching.jl b/test/test-input-source-matching.jl new file mode 100644 index 000000000..1d60869d2 --- /dev/null +++ b/test/test-input-source-matching.jl @@ -0,0 +1,172 @@ +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(; 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; + 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=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) + 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 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. + @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); + 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, distributed = matching_fixture(; growing_a=true) + compiled = simulation.compiled + 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.applies_to) + partial = PSE._partial_model_application(compiled.applications_by_id[:a], + ObjectId[ObjectId(7)]) + 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)], + :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 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 +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._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; + 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-lifecycle-snapshot-allocations.jl b/test/test-lifecycle-snapshot-allocations.jl index 1e988da3d..736383170 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) @@ -90,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!( @@ -99,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-adaptive-selectors.jl b/test/test-model-adaptive-selectors.jl index 952f5243d..dcf2c083f 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.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)) 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-api-stabilization.jl b/test/test-model-api-stabilization.jl index 3fb203875..04fbf6921 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, @@ -211,10 +217,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 +241,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 @@ -800,6 +819,48 @@ 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) + 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)) + @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); @@ -814,7 +875,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 +890,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) @@ -993,7 +1054,7 @@ end end @test contains( ambiguous_scoped_error, - "available=(scales = [:Leaf],", + "available=(scales=[Symbol(\"Leaf\")],", ) missing_scoped_error = try @@ -1008,9 +1069,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}() @@ -1084,8 +1145,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 +1185,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 +1224,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 @@ -1521,12 +1591,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), @@ -1672,11 +1742,13 @@ 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) - @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 == () @@ -2014,8 +2086,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 @@ -2114,7 +2188,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) @@ -2161,6 +2235,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), @@ -2169,6 +2245,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( @@ -2203,7 +2288,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( @@ -2211,7 +2303,7 @@ end scale=:Leaf, kind=:supplied, parent=:plant, - status=Status(signal=10.0), + status=supplied_status, ), ) continue!(simulation) @@ -2225,6 +2317,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) @@ -2236,6 +2330,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 @@ -2505,6 +2603,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, @@ -2542,6 +2644,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!( @@ -2734,7 +2838,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, @@ -2745,11 +2852,14 @@ end simulation.output_retention, nothing, false, - ) === float32_target.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 -@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,13 +2896,11 @@ end @test model_object(model, :leaf_1).status.signal == 1.0 end -@testset "execution plan pure-addition staging is transactional" begin - context_models = PlantSimEngine.ObjectModelOverrides( - StabilizationContextModel(), - Dict( - ObjectId(:leaf_z) => StabilizationAlternativeContextModel(), - ), - ) +@testset "execution plan extends only the affected concrete runs" begin + 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), @@ -2818,10 +2926,21 @@ 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 ) + # 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 @@ -2833,16 +2952,15 @@ 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 + 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( @@ -2853,6 +2971,24 @@ 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 === 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_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 + end @test [ target.object_id for batch in refreshed_source_group.batches for target in batch.targets @@ -2867,13 +3003,101 @@ 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 + ) == 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 +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(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 + 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), + ) + 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=leaf_2_status, + )) + 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 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 + @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) + 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=leaf_0_status, + )) + 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 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 + @test performance.counts[:execution_batches_constructed] == 2 end function stabilization_lifecycle_scene(nleaves_per_plant) diff --git a/test/test-model-authored-call-plans.jl b/test/test-model-authored-call-plans.jl new file mode 100644 index 000000000..ce933e264 --- /dev/null +++ b/test/test-model-authored-call-plans.jl @@ -0,0 +1,232 @@ +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, 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) + 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_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. + 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 + @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 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_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 + @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-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 new file mode 100644 index 000000000..32abf8a17 --- /dev/null +++ b/test/test-model-authored-port-inventory.jl @@ -0,0 +1,790 @@ +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,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 + parentmodule(typeof(value)) === PSE || return false + 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 + +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] + 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 + 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 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}}) + @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),) + @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, 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, + 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) + @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_(model::BrokenInput) + broken_input_calls[] += 1 + model.token === :repaired && return NamedTuple() + 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 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] + @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 "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 + 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, :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 +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 "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=( + 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, 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) + @test counter[] == 1 # even empty contracts validate all declared port names + @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 + 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 + 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)) +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 + +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 + +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 diff --git a/test/test-model-authored-spec-matching.jl b/test/test-model-authored-spec-matching.jl new file mode 100644 index 000000000..a4ca37ea2 --- /dev/null +++ b/test/test-model-authored-spec-matching.jl @@ -0,0 +1,134 @@ +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-binding-index-identities.jl b/test/test-model-binding-index-identities.jl new file mode 100644 index 000000000..f92c43d67 --- /dev/null +++ b/test/test-model-binding-index-identities.jl @@ -0,0 +1,851 @@ +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 + +@testset "registration admits object and parent identities before status conversion" begin + root = Object(:root; status=Status(x=1f0)) + 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) + + # 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) + @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 + 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 +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 = PSE._with_object_id_domain(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)) + 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 = PSE._with_object_id_domain(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( + 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 = 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) +end + +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) === value_type + rebuilt = rebuild_index(bindings, I) + @test keytype(rebuilt) === Tuple{Symbol,I} + @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 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) === 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, 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), + 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{} + end +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 + 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) + repeated = [bindings; first(bindings)] + @test_throws "Hard-call binding count differs from its prepared application declaration" PSE._index_model_call_bindings( + 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) + @test many.execution_batches isa PSE.LazyCallExecutionBatches + if many.execution_batches isa PSE.LazyCallExecutionBatches + @test isnothing(many.execution_batches.batches) + end + @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) + 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 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))) + 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 "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)), + # 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))),)) + 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 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}) + + 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 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) + @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 + @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 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 + 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).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 + @test outputs(simulation)[(:reader, ObjectId(:root), :total)] == + [(1.0, 0.0), (2.0, 7.0)] + 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 + +@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 + 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))) + 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) + @test occursin("available=", expected) && occursin("suggestions=", expected) + @test message(closed, selector) == expected + end + @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 = PSE._with_object_id_domain(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 + +@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, 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...]) + 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] + 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) + @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 = 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) + 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 + +# 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 = PSE._with_object_id_domain(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 + +@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) + 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; 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] + @test (NamedTuple(model_status(model, 1)), NamedTuple(model_status(model, :leaf))) == states + 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 = PSE._with_object_id_domain(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 + +@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 = PSE._with_object_id_domain(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 + +@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 = 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} + @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 = 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, + 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 diff --git a/test/test-model-call-cohort-retirement.jl b/test/test-model-call-cohort-retirement.jl new file mode 100644 index 000000000..b5de4f5a6 --- /dev/null +++ b/test/test-model-call-cohort-retirement.jl @@ -0,0 +1,343 @@ +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, left_selector=Many(scale=:Leaf, application=:leaf)) + 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=left_selector, 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() + 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_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 + @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), + 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) + @test_throws ArgumentError rows[1] + @test value.value[] === 3.0 +end + +# Freeze only the real identity domain. The canonical Status schema is already +# prepared at CompositeModel construction, even when no Leaf remains active. +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 "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=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 + 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_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 + @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, eltype(eltype(snapshot.target_ids))) + 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)] + @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 + 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] + 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 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 retains its prepared Status and real Symbol identity family" begin + function empty_closed(model) + closed = PSE._with_object_id_domain(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 + # 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 + +@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 diff --git a/test/test-model-call-context-cache.jl b/test/test-model-call-context-cache.jl index 920bc7630..7b1cc2c5b 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 @@ -375,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-context-cloning.jl b/test/test-model-call-context-cloning.jl new file mode 100644 index 000000000..a47148eb2 --- /dev/null +++ b/test/test-model-call-context-cloning.jl @@ -0,0 +1,439 @@ +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.execution_target.call_bindings, + 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.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 + 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 + @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.execution_target.call_bindings, + 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 + +@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-call-evaluations.jl b/test/test-model-call-evaluations.jl index b9b1d7606..cac3fe80c 100644 --- a/test/test-model-call-evaluations.jl +++ b/test/test-model-call-evaluations.jl @@ -625,4 +625,85 @@ end end end +@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{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_stamp] == frame.executions[right_stamp] == UInt64(1) + left.transient = (candidate=:changed,) + left.in_use = true + 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) + @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.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) + @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.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 + @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-call-execution-identity.jl b/test/test-model-call-execution-identity.jl new file mode 100644 index 000000000..a90d8c0a7 --- /dev/null +++ b/test/test-model-call-execution-identity.jl @@ -0,0 +1,262 @@ +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)) + 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) + 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_references, 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_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 + @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) + 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) + 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_references, 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_references + @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_references + @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_references + @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_references + @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-canonical-cohorts.jl b/test/test-model-canonical-cohorts.jl new file mode 100644 index 000000000..4a085396e --- /dev/null +++ b/test/test-model-canonical-cohorts.jl @@ -0,0 +1,447 @@ +module CanonicalCohortChecks + +using PlantSimEngine, Dates, 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[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.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 +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 + 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 + @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.status_view.canonical_status === default_official + @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) + # 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) + + # 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[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 + @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 + 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 === 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 + +@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 + + +@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 + # 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 + @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-closed-cohort-schemas.jl b/test/test-model-closed-cohort-schemas.jl new file mode 100644 index 000000000..00ff215ad --- /dev/null +++ b/test/test-model-closed-cohort-schemas.jl @@ -0,0 +1,399 @@ +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[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, store, 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 "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,),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() + 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[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[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 + 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) + @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..55364bffb --- /dev/null +++ b/test/test-model-closed-group-refresh.jl @@ -0,0 +1,251 @@ +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)),), + 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)) + @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) === official + @test official !== status + @test official.count === 2f0 + @test PSE.refvalue(official, :count) === PSE.refvalue(status, :count) + @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 + @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) +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) + 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 + +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..8618df0fb --- /dev/null +++ b/test/test-model-cohort-store-identities.jl @@ -0,0 +1,361 @@ +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 + model = PSE._with_object_id_domain(model) + end + 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 = 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) + @test (@inferred plan_cohorts(simulation.execution_plan)) === store + @test fieldtype(typeof(simulation.temporal_streams), :cohorts) === typeof(store) + @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) + @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[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 + @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[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[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 + +@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 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) + @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 "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) + previous = simulation.execution_plan + store = check_store(simulation, closed) + location = PSE.cohort_location(store,:controller,ObjectId(:root)) + 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 + # 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.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 + @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 + @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[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 +# 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[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[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 + 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 + 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) + 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) + 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 + @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 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 diff --git a/test/test-model-diagnostic-authoring-recovery.jl b/test/test-model-diagnostic-authoring-recovery.jl new file mode 100644 index 000000000..7a4738805 --- /dev/null +++ b/test/test-model-diagnostic-authoring-recovery.jl @@ -0,0 +1,276 @@ +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 + @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) + @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 + @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 + @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)) + @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) + @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),)), + )) + 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 + +@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 + + +@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)), + )) + @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[] == 1 + @test any(diagnostic -> diagnostic.application_ids == [:failed] && + occursin("opaque declaration failed once", diagnostic.message), + report.diagnostics) + 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-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-distributed-output-runtime.jl b/test/test-model-distributed-output-runtime.jl index c6fc57ecc..590427f62 100644 --- a/test/test-model-distributed-output-runtime.jl +++ b/test/test-model-distributed-output-runtime.jl @@ -1226,3 +1226,360 @@ 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. +@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 = 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) + 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._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) + 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 = 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) + @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 = 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) + @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 = 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[ + (: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 + + +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 + + +@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 + + +@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 + +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-distributed-route-ownership.jl b/test/test-model-distributed-route-ownership.jl new file mode 100644 index 000000000..cc5f5c561 --- /dev/null +++ b/test/test-model-distributed-route-ownership.jl @@ -0,0 +1,163 @@ +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, + PSE._model_timeline(model)) + 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) + @test !(:declarations in fieldnames(typeof(plan))) + @test plan.variable_names === (:payload,) + seed[] = 8f0 + before_actual = queries[] + 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)) + @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-empty-output-requests.jl b/test/test-model-empty-output-requests.jl new file mode 100644 index 000000000..b6e57e475 --- /dev/null +++ b/test/test-model-empty-output-requests.jl @@ -0,0 +1,155 @@ +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 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 + @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 === 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 "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), + 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] + # 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) + 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 + +@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 + +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 diff --git a/test/test-model-environment-binding-identity.jl b/test/test-model-environment-binding-identity.jl new file mode 100644 index 000000000..5e262edb3 --- /dev/null +++ b/test/test-model-environment-binding-identity.jl @@ -0,0 +1,1078 @@ +module EnvironmentBindingsIdentityChecks +using PlantSimEngine +using Serialization +using Dates +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,)) +mutable struct Handle + cell::Symbol +end +EA.bind_environment(::Backend, object::Object, context, config) = + Handle(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}; steps=1, environment_schema=PSE.EnvironmentBindingSchema(), + only_application=nothing, backend=nothing, moved_cell=:a) where {T} + capture = Ref{Any}() + 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=moved_cell,)), + Object(:manual; scale=:Leaf, kind=:manual, parent=:scene, geometry=(cell=:a,)); + applications=selected_specs, environment=backend) + 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_schema) + PSE._continue_scene!(prepared, steps) + end + 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 + +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) + buffer = IOBuffer() + serialize(buffer, simulation) + seekstart(buffer) + return deserialize(buffer) +end + +@testset "checkpointed environment owners preserve application identity" begin + 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) + 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) + @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) + + # 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) + + # 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) + 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 + +@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 + +@testset "the typed boundary selects the current model cache after public refresh" begin + 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 + + 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 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) + 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 + + # 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, full) + 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 + 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 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 + 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) + 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) + 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 + +@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 + +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, keytype(model.registry.objects)) === 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, compiled.applications_by_id) + 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)) + 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 " * + "(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, keytype(model.registry.objects)) + 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 + +# 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=PSE.EnvironmentBindingSchema()) + return PSE._prepare_simulation!(data.model; steps=0, outputs=:all, + 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=PSE._collecting_environment_binding_schema()) + first_types = policy_types(first_simulation) + 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) + @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.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) == + 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=PSE._collecting_environment_binding_schema()) + first_types = policy_types(simulation) + first_schema = PSE._freeze_environment_binding_schema(simulation.environment_bindings.environment_schema) + 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) + 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) + 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) + 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 + @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._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) + 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; + environment_schema=PSE._collecting_environment_binding_schema()) + delta = policy_counts(data) .- before + @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) + 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=PSE._collecting_environment_binding_schema()) + @test PSE._is_collecting_environment_schema(collected.environment_bindings.environment_schema) + 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 != + only(previous.environment_bindings.application_plans).compiled_sampling_rules + end +end + +@testset "dirty fixed policies survive checkpoints and rebuild handles" begin + schema = fixture_environment_schema(Float32) + for copy_simulation in (deepcopy, checkpoint_copy) + 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.environment_schema) + current = PSE.Advanced.refresh_environment_bindings!(restored.model, restored.compiled) + @test current !== retained + @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 + step!(restored) + @test model_status(restored.model, :scheduled_move).seen === 20f0 + 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) + 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) + @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 + 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 + @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 + 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 + # 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 + +@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 diff --git a/test/test-model-environment-index-identities.jl b/test/test-model-environment-index-identities.jl new file mode 100644 index 000000000..8360c4cf9 --- /dev/null +++ b/test/test-model-environment-index-identities.jl @@ -0,0 +1,692 @@ +module EnvironmentIndexIdentityChecks + +using PlantSimEngine +using Test +const PSE = PlantSimEngine +const EA = PSE.EnvironmentAPI + +mutable struct Backend <: EA.AbstractEnvironmentBackend + values::Dict{Symbol,Float32} + binds::Int + index_updates::Vector{Any} + on_index::Any +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) +function EA.update_index!(backend::Backend, 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() +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 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(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)); + applications=(ModelSpec(Probe(); name=:probe, on=Many(scale=:Leaf), + environment=Environment(provider=:identity_probe)),), environment=backend) + 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) + return (; model, simulation, backend) +end + +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)) + 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 + 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, 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=applications, + environment=backend_a) + closed && (model = PSE._with_object_id_domain(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(true) + control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, + 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._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 : PSE.EnvironmentBindingSchema() + simulation = PSE._prepare_simulation!(model; steps=0, outputs=:none, + constants=PSE.Constants(), environment_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.environment_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.environment_schema === active_schema + @test index_trace(events) == vcat(discoveries, indexed, discoveries) + + # 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) + 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) == [(: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) + 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(true) + control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, + 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_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] + 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(true) + control = PSE._prepare_simulation!(observed.model; steps=0, outputs=:none, + 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_schema=fixed ? schema : PSE.EnvironmentBindingSchema()) + compiled, owner = simulation.compiled, simulation.environment_bindings + + # 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, 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. + 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, 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)] + end +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} + @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 "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) + 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 + 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,), + 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 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 + 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 + + +@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 +using PlantSimEngine, Dates, Test +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 = PSE._with_object_id_domain(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_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)] + @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._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_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.environment_schema === schema +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..c5189bfa6 --- /dev/null +++ b/test/test-model-execution-batch-times.jl @@ -0,0 +1,195 @@ +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 "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) + @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-finite-call-extension-intents.jl b/test/test-model-finite-call-extension-intents.jl new file mode 100644 index 000000000..00d54c3c4 --- /dev/null +++ b/test/test-model-finite-call-extension-intents.jl @@ -0,0 +1,413 @@ +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 + +# 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), + 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) + materialize_manual_calls!(target) + 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 + 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 + @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 "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) + materialize_manual_calls!(target) + if prepared + schema = call_targets(target.context, :a).batch_schema + compiled = simulation.compiled + 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 + 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() + 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(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) + @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 + + +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-global-environment-sample-schema.jl b/test/test-model-global-environment-sample-schema.jl new file mode 100644 index 000000000..9610586f4 --- /dev/null +++ b/test/test-model-global-environment-sample-schema.jl @@ -0,0 +1,784 @@ +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, + 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 + +@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 "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 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) + 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 + 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)] == + 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 + +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 + +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; 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=specs, 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 = 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_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] + @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, + 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) + 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_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; environment_schema=mapped_schema) + @test model.environment_binding_cache === 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(mapped_model, + alternate.applications, alternate.applications_by_id; + previous_plans_by_id=replacement.application_plans_by_id, + environment_schema=replacement.environment_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))) + 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, 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) + 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 "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( + 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)), + ) + 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) + 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 + @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 + +@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 + + 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 + @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] + 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 + @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 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( 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-hard-calls.jl b/test/test-model-hard-calls.jl index 0ccbb1d2f..b3d300289 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 @@ -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 @@ -1518,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 @@ -1557,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 diff --git a/test/test-model-initializers.jl b/test/test-model-initializers.jl index 260e43637..2c5c8818e 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!( @@ -543,6 +545,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 +571,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 +583,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!( @@ -900,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), @@ -978,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 @@ -1423,6 +1445,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-binding-storage.jl b/test/test-model-input-binding-storage.jl new file mode 100644 index 000000000..6d35b145e --- /dev/null +++ b/test/test-model-input-binding-storage.jl @@ -0,0 +1,772 @@ +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{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) + 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 + 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 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) + 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) + input_cache = simulation.compiled.input_bindings_by_target + @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) + totals = [advance!(data, simulation)] + 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) + 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(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 + +@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 "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) + 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)) + # 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 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) + @test PSE.refvalue(first, :x)[] === 7.0 + @test PSE.refvalue(second, :x)[] === 9f0 + @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 "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), + 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 + +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), + 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)), + 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() + 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 + +@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) + original = data.model + 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)) + 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 "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 + +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) + 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 + + 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 + +@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 diff --git a/test/test-model-input-plan-output-metadata.jl b/test/test-model-input-plan-output-metadata.jl index 6d50f3c39..b6bb1aa30 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]) @@ -99,25 +99,25 @@ 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._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) @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) - @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 == 2 - @test all(==(2), 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 @@ -132,17 +132,17 @@ 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] 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 @@ -392,14 +392,40 @@ 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. + 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 @@ -416,8 +442,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 @@ -436,22 +463,25 @@ 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)) - 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, @@ -471,7 +501,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] @@ -489,7 +519,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 new file mode 100644 index 000000000..5104d6899 --- /dev/null +++ b/test/test-model-input-recipes.jl @@ -0,0 +1,574 @@ +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 +include("fixtures/raw_status_readers.jl") + +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 + +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.id) + 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) + 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) + @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 + # 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) +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=( + 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) + 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)) + 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 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)) + @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 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)] == + [(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_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) + return bindings +end + +@testset "input refresh references use the closed mixed identity domain" begin + organ = (:tree, :leaf, 1) + model = PSE._with_object_id_domain(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 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) === + PSE.refvalue(model_status(model, :source), binding.source_var) + 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) + closed = PSE._with_object_id_domain(model) + 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)) + + 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 + +@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 + +@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 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-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-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-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 diff --git a/test/test-model-newborn-context-initializer.jl b/test/test-model-newborn-context-initializer.jl new file mode 100644 index 000000000..61befb389 --- /dev/null +++ b/test/test-model-newborn-context-initializer.jl @@ -0,0 +1,116 @@ +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 === () + 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) + 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 + +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 diff --git a/test/test-model-newborn-context-nested.jl b/test/test-model-newborn-context-nested.jl new file mode 100644 index 000000000..476752441 --- /dev/null +++ b/test/test-model-newborn-context-nested.jl @@ -0,0 +1,99 @@ +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. + 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 + @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 new file mode 100644 index 000000000..53e9ecc2f --- /dev/null +++ b/test/test-model-newborn-execution-owner.jl @@ -0,0 +1,118 @@ +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 + 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 + @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) + @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_stamp[] == 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-object-id.jl b/test/test-model-object-id.jl index 2d80d3128..a507791a0 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) @@ -353,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) @@ -374,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( @@ -403,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 @@ -570,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 diff --git a/test/test-model-output-boundaries.jl b/test/test-model-output-boundaries.jl index 5a6a863a1..7dc587ea2 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), @@ -423,11 +452,46 @@ 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 ] == [(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 diff --git a/test/test-model-output-destination-declarations.jl b/test/test-model-output-destination-declarations.jl index cfee30128..db6844f26 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 @@ -659,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 diff --git a/test/test-model-output-retention-owners.jl b/test/test-model-output-retention-owners.jl new file mode 100644 index 000000000..a8bf79821 --- /dev/null +++ b/test/test-model-output-retention-owners.jl @@ -0,0 +1,394 @@ +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, status_transform=nothing) + 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, 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, + 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) + @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 + 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] + 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], PSE._private_temporal_value) + second_values = Any[first_copy] + second_copy = @inferred PSE._copy_temporal_status_value(payloads, second_values[1], PSE._private_temporal_value) + @test first_copy === second_copy === 2f0 + # 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)) + 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( + simulation.model, compiled.applications_by_id[:writer], ObjectId(3), (), + 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 + +@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 + +# 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)),) +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 diff --git a/test/test-model-persistent-empty-groups.jl b/test/test-model-persistent-empty-groups.jl new file mode 100644 index 000000000..f65eeefd3 --- /dev/null +++ b/test/test-model-persistent-empty-groups.jl @@ -0,0 +1,108 @@ +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} + # 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)} + 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} + Store = typeof(simulation.temporal_streams.cohorts) + Owner = PSE._execution_store_owner_type(Store) + Rows = PSE.ExecutionCohortRows{Target,I,Owner,Store} + 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 + 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 + @test only(simulation.execution_plan.groups) === future + @test isempty(future.batches) + @test born.status.count == 8 +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..c1263a668 --- /dev/null +++ b/test/test-model-prepared-authoring-owner.jl @@ -0,0 +1,177 @@ +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 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) + + 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 "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)),) + 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 === alternate_model + 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 + @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-prepared-call-schemas.jl b/test/test-model-prepared-call-schemas.jl new file mode 100644 index 000000000..82a62d8df --- /dev/null +++ b/test/test-model-prepared-call-schemas.jl @@ -0,0 +1,644 @@ +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, unselected_numeric=false) + 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 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, + 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 + 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 + leaves = call_targets(middle.context, :leaf) + @test leaves.batch_schema isa PSE.PreparedExecutionBatchSchema + @test leaves.execution_batches isa Vector + @test leaves.tracks_full_membership + 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) === + 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) + # 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 + @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) + 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) + 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 + @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 rejects an unlearned prepared numeric view" begin + witness = fixture(; unselected_numeric=true) + learned = observed_schemas(witness.simulation) + 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=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. + 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 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) + @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 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 + +@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) + 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) + 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) + @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 + +@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 + +@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 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..798ea94f3 --- /dev/null +++ b/test/test-model-prepared-growth-schemas.jl @@ -0,0 +1,320 @@ +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 + fail_after_mutation::Bool +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(Float64),) +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!(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 + +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(; environment=nothing, fail_initializer=false) + 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(fail_initializer); name=:leaf, on=Many(scale=:Leaf)), + ModelSpec(Pulse(); name=:pulse, on=One(id=:owner)), + ), environment, + ) + return (; model, birth_day, seed) +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 + @assert environment_plan.uses_raw_global_source + @assert isempty(application.target_ids) + Empty = NamedTuple{(),Tuple{}} + I = ObjectId{Symbol} + # 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)} + 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} + Store = typeof(simulation.temporal_streams.cohorts) + Owner = PSE._execution_store_owner_type(Store) + Rows = PSE.ExecutionCohortRows{Target,I,Owner,Store} + return PSE.CompiledExecutionBatch{typeof(application),Rows, + PSE.RawGlobalModelEnvironment{typeof(environment_plan.prepared_source)}, + PSE.CompiledOutputPublication{Tuple{}}} +end + +function prepare_schema_growth(; environment=nothing, fail_initializer=false) + setup = make_growth(; environment, fail_initializer) + 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) + 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 + + +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._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) + 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)) + 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, + 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 + @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 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..10a2fb383 --- /dev/null +++ b/test/test-model-prepared-missing-future-schema.jl @@ -0,0 +1,77 @@ +module PreparedExecutionMissingFutureSchemaTests +using PlantSimEngine, Test +const PSE = PlantSimEngine +const Fixtures = getfield(parentmodule(@__MODULE__),:ColdCallSchemaActivationChecks) + +function recorded_views(simulation, selected) + 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 + for batch in PSE._cached_call_execution_batches(selected) + 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) + # 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) + # 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) + # 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 + # 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) + 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) + @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-prepared-scenario.jl b/test/test-model-prepared-scenario.jl index 166c99cdf..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,11 +128,11 @@ 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 - @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-model-previous-timestep-views.jl b/test/test-model-previous-timestep-views.jl index 67ca36b88..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) @@ -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); @@ -770,6 +771,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_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 @@ -787,9 +792,16 @@ 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 - @test length(refreshed_target.status.signals) == 2 + # 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_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)] @@ -843,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, @@ -852,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-public-refresh-owners.jl b/test/test-model-public-refresh-owners.jl new file mode 100644 index 000000000..665c39e7b --- /dev/null +++ b/test/test-model-public-refresh-owners.jl @@ -0,0 +1,437 @@ +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 + + +@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,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) + 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, Ref(false), declarations, kernels); name=:probe, on=One(id=:leaf)) + supplied = Status(visits=5) + model = CompositeModel(Object(:leaf; status=supplied); applications=(original,)) + 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) + 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[] + 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 + @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 + +@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 + +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_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)) + 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 diff --git a/test/test-model-refreshed-schedule.jl b/test/test-model-refreshed-schedule.jl new file mode 100644 index 000000000..747ca391c --- /dev/null +++ b/test/test-model-refreshed-schedule.jl @@ -0,0 +1,137 @@ +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 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 +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 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-runtime-call-names.jl b/test/test-model-runtime-call-names.jl new file mode 100644 index 000000000..5ea103d33 --- /dev/null +++ b/test/test-model-runtime-call-names.jl @@ -0,0 +1,261 @@ +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 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) = + 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 "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"]) + 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 "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) + 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)) + # 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 + @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 diff --git a/test/test-model-runtime-snapshot-isolation.jl b/test/test-model-runtime-snapshot-isolation.jl new file mode 100644 index 000000000..4e30d63a8 --- /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, eltype(eltype(born_snapshot.target_ids)))).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, 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 + @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-runtime-stream-extensions.jl b/test/test-model-runtime-stream-extensions.jl new file mode 100644 index 000000000..32ca4cd9d --- /dev/null +++ b/test/test-model-runtime-stream-extensions.jl @@ -0,0 +1,488 @@ +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, 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, target.output_targets, + 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 + # 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)] + 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 + +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))) + @test !hasproperty(model_status(data.model, 2), :z) + 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) + 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[])), + 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, 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, 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 + # 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 + +@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 diff --git a/test/test-model-scenario-authoring.jl b/test/test-model-scenario-authoring.jl new file mode 100644 index 000000000..69fb6c102 --- /dev/null +++ b/test/test-model-scenario-authoring.jl @@ -0,0 +1,335 @@ +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.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] + @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, 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 + 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)),), + 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, + 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 + # 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) + 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) + @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 diff --git a/test/test-model-slot-group-refresh.jl b/test/test-model-slot-group-refresh.jl new file mode 100644 index 000000000..0b6acfca3 --- /dev/null +++ b/test/test-model-slot-group-refresh.jl @@ -0,0 +1,120 @@ +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, 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, 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) + 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 + @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 + +@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 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( diff --git a/test/test-model-spec-normalization.jl b/test/test-model-spec-normalization.jl new file mode 100644 index 000000000..f755c6bbe --- /dev/null +++ b/test/test-model-spec-normalization.jl @@ -0,0 +1,279 @@ +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) + 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. + 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, PSE.AuthoredPortNames((:T,))) + @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, 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, PSE.AuthoredPortNames(())) + errors = Any[] + 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 + @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 diff --git a/test/test-model-status-type-conversion.jl b/test/test-model-status-type-conversion.jl index 39a745db5..47a4812a9 100644 --- a/test/test-model-status-type-conversion.jl +++ b/test/test-model-status-type-conversion.jl @@ -30,6 +30,77 @@ 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 + +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); + 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 + + 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) + @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 @@ -79,8 +150,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 @@ -122,8 +198,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) diff --git a/test/test-model-status-type-lifecycle.jl b/test/test-model-status-type-lifecycle.jl index eda2cda6a..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( @@ -227,10 +258,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 +288,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 +301,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 +398,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 +414,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 +423,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)) @@ -406,7 +458,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 +468,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 +483,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 @@ -522,3 +576,44 @@ 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 + +@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 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-model-status-view-cache-admission.jl b/test/test-model-status-view-cache-admission.jl new file mode 100644 index 000000000..34f5d36df --- /dev/null +++ b/test/test-model-status-view-cache-admission.jl @@ -0,0 +1,306 @@ +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 "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) + 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 + + +@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 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 diff --git a/test/test-model-temporal-initial-typing.jl b/test/test-model-temporal-initial-typing.jl index 1e3135004..0d3d0332b 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) @@ -79,21 +108,26 @@ 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, Val(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, 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) - 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 ]) @@ -138,4 +172,366 @@ 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 "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 + @test typeof.(temporal.initial) == [Float32, Float64] + step!(simulation) + @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 + +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(: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=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 + 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) + 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 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 + @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 +using Dates, Random, Test, PlantSimEngine +const PSE = PlantSimEngine +import ..TemporalInitialTypingChecks: AbstractTyped_Initial_SourceModel, AbstractTyped_Initial_ConsumerModel, 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 + +# 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))) + model = CompositeModel(objects...; applications=( + ModelSpec(PublicationSource(0.0, rng); name=:source, 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),)) + 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))) + 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[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))) + 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[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 + +@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 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) 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-native-compilation.jl b/test/test-native-compilation.jl index e41806460..7a6041f6e 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,11 +111,46 @@ 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 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) diff --git a/test/test-object-families.jl b/test/test-object-families.jl new file mode 100644 index 000000000..713504ebd --- /dev/null +++ b/test/test-object-families.jl @@ -0,0 +1,504 @@ +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.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 + @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 + expected = string(id) + @test sprint(showerror, failure) == "No model object with id `$(expected)`." + end + @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, 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{keytype(store),typeof(canonical)} + @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_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 + @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) + @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) => "(:missing, :leaf, 2)", + (:missing, (:leaf, 2)) => "(:missing, (: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 +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 + +@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 " * + "`(: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) + 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 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) + 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) + 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[] === 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] + 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) + 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[] === official_replacement === object.status + @test sink[] !== replacement + @test PSE.refvalue(sink[], :items) === PSE.refvalue(replacement, :items) + @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 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; 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) + + official = PSE._replace_model_object_status!(model, first, replacement) + @test official !== replacement + current = store.locations[first.id] + @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) === 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_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) === official + + @test isnothing(PSE._replace_model_object_status!(model, first, nothing)) + @test isnothing(model_status(model, :first)) + @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 +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 !hasproperty(born, :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 !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. + 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) + 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 + @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) + @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 + 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 + 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 + + 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))) + + # 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) + 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) + 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 + +@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 + 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 + 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 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..c389178e3 100644 --- a/test/test-organ-status-assembly.jl +++ b/test/test-organ-status-assembly.jl @@ -1,482 +1,226 @@ -# 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 +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) + import_status(node) = begin + calls[] += 1 + MTG.symbol(node) === :Leaf ? Status(seed=node[:seed], payload=T[0]) : nothing 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) + 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 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 +@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 "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) + 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 -end - -@testset "organ status assembly observes adapter effects before attributes" 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[: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) + 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 "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[])) + 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 - @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, - ) + 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; + 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 "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, :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) + model = CompositeModel(root) + 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") + @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) + 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) + 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 -@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 +@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)) + 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 - 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) - 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) + tip[] = MTG.Node(MTG.node_id(node) + 1, node, MTG.NodeMTG(:<, :Tip, 1, 2), (;)) + throw(ArgumentError("rejected leaf")) 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) + model = CompositeModel(root; kind) + 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[] + @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 - 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 +@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-owned-metadata-tables.jl b/test/test-owned-metadata-tables.jl new file mode 100644 index 000000000..737c11dad --- /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 KeyError 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, :reader) === 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-prepared-status-registration.jl b/test/test-prepared-status-registration.jl new file mode 100644 index 000000000..a5aebf8f9 --- /dev/null +++ b/test/test-prepared-status-registration.jl @@ -0,0 +1,206 @@ +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(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)) + 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,))) + if finite_ids + model = PSE._with_object_id_domain(model) + end + 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 "prospective matching uses the finite registry identity family" begin + 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)) + 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 "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 + 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 + +@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 diff --git a/test/test-registered-status-dispatch.jl b/test/test-registered-status-dispatch.jl new file mode 100644 index 000000000..f01ee522e --- /dev/null +++ b/test/test-registered-status-dispatch.jl @@ -0,0 +1,195 @@ +module RegisteredStatusDispatchChecks + +using PlantSimEngine, Test +const PSE = PlantSimEngine + +@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 === 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 == fill(S, 8) + @test_throws ArgumentError PSE._with_registered_status(identity, catalog, Status(unknown=1)) +end + +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 "ensuring a required status admits root and registered parent identities" begin + 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) + 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. + 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 = 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))...; + 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 + 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) + 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._apply_status_recipes!(model, recipes, order) + full = model_status(model, id) + @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.seed, full.value, full.visits) == (seed.seed, 0.5, 0) + if id === :d + seed_ref[] = :later + @test full.seed === :later + elseif id === :c + seed_ref[] = 9.0 + @test full.seed === 9.0 + end + end + 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 model_object(model, :owner).children == before +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 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 = PSE._with_object_id_domain(source) + canonical = model_status(model, :leaf) + @test propertynames(canonical) == (:seed,) + @test !hasproperty(canonical, :x) + simulation = run!(model; steps=2, outputs=:all) + @test model_status(model, :leaf) === canonical + @test propertynames(canonical) == (: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 = 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)) + baseline_calls = length(seen) + supplied = Status(seed=3.0) + born = register_object!(model, Object(:leaf; parent=:owner, scale=:Leaf, status=supplied)) + effective = model_status(model, :leaf) + @test typeof(effective) === PSE._scenario_preparation(model).status_manifest.status_type + @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; scale=:Leaf, status=supplied)) + @test length(seen) == baseline_calls + 1 + @test !haskey(model.registry.objects, ObjectId(:other)) +end + +@testset "incompatible edited references fail before changing live cells" begin + supplied = Status(seed=2.0) + 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) + 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-resolved-input-materialization.jl b/test/test-resolved-input-materialization.jl new file mode 100644 index 000000000..9cf4e8ab1 --- /dev/null +++ b/test/test-resolved-input-materialization.jl @@ -0,0 +1,999 @@ +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 + +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=( + 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 + +# 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, status_transform=nothing) + 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, status_transform) + 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 "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), + 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 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.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.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 + 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 eltype(parent(binding.carrier)) === + Union{Base.RefValue{Float32},Base.RefValue{Float64}} + 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 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.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 + 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 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 + # 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 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 + +@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=( + 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 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 + +@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} + 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 + 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 + @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, + 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 + @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 +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_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 + @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]) + 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, RT)) + @test isempty(visited) + 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)) + 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, 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)) + @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, 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} + 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) + 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} + 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, 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)) + @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"), 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, Tuple{typeof(cell)}) === cell + @test ids.reads == [7] + end +end + +@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), reference_types) === expected + end + return same +end +@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}}) + +@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) + reference_types = Tuple{typeof(expected)} + for selector in (One(), OptionalOne()) + @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 + 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 diff --git a/test/test-selector-ancestor-index.jl b/test/test-selector-ancestor-index.jl new file mode 100644 index 000000000..6f111915f --- /dev/null +++ b/test/test-selector-ancestor-index.jl @@ -0,0 +1,74 @@ +module IndexedAncestorChecks + +using Test, PlantSimEngine +using PlantSimEngine.GraphEditor +const PSE = PlantSimEngine + +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), + 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-candidate-empty-scope.jl b/test/test-selector-candidate-empty-scope.jl index 1508575ea..b716b5494 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), @@ -17,7 +21,11 @@ using Test Object(:other_leaf; scale=:Leaf, parent=:other_plant), ) leaf_id = ObjectId(:leaf) - index = PlantSimEngine._selector_candidate_index() + 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 +46,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, nothing) candidates = Set([99]) @test PlantSimEngine._union_selector_candidates!( candidates, empty_index, model, leaf_id, @@ -47,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!( @@ -72,7 +80,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, nothing) push!(empty_scope_index.wildcard, 1) for candidate_index in ( empty_scope_index, @@ -91,3 +99,142 @@ using Test end end end + +# Close only the actual existing fixture families. No future family is invented. +@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 + 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), + ) + 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 + @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) === + 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), + Many(scale=(:Leaf, :Fruit)), + Many(kind=:photosynthetic), + Many(species=:rauh), + 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) + @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 + 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)) + candidates = Set([99]) + @test PlantSimEngine._union_selector_candidates!( + candidates, candidate_index, model, ObjectId(leaf_id), + ) === candidates + @test candidates == union(expected, Set([99])) + end + + # Both reverse indexes exist BEFORE the selected future object. + # 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) + 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) + @test PlantSimEngine._index_selector_candidate!(future_index, model, + 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) + @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, + _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) + 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-selector-construction-inference.jl b/test/test-selector-construction-inference.jl index c17ed6144..0e684da07 100644 --- a/test/test-selector-construction-inference.jl +++ b/test/test-selector-construction-inference.jl @@ -15,3 +15,33 @@ 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 + +@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 diff --git a/test/test-selector-query-scope-append.jl b/test/test-selector-query-scope-append.jl new file mode 100644 index 000000000..38298e0b4 --- /dev/null +++ b/test/test-selector-query-scope-append.jl @@ -0,0 +1,138 @@ +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)) + # 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) + 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..e77f6e5d1 --- /dev/null +++ b/test/test-selector-query-scope-root.jl @@ -0,0 +1,196 @@ +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, 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("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)) + @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)) + 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, + 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 + +@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 + + +@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 diff --git a/test/test-status-construction.jl b/test/test-status-construction.jl new file mode 100644 index 000000000..1689a3912 --- /dev/null +++ b/test/test-status-construction.jl @@ -0,0 +1,230 @@ +module StatusConstructionChecks + +using Dates +using PlantSimEngine +using Test + +const PSE = PlantSimEngine + +@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]) + 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 = 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 + + 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) +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] +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) + @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) + @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] +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 diff --git a/test/test-status-fixed-storage.jl b/test/test-status-fixed-storage.jl new file mode 100644 index 000000000..d4f45a29f --- /dev/null +++ b/test/test-status-fixed-storage.jl @@ -0,0 +1,261 @@ +module FixedStatusStorageChecks +using PlantSimEngine, Test +using Serialization +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 = @inferred PSE._projected_status_type(SCHEMA,Val((:x,:q)),Tuple{RF64,RR}) + # 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{}) + @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) + @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 = @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 + @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!(recipe) === original + @test PSE.refvalue(state,:x) === replacement + @test PSE._status_reference_epoch(state) == epoch+1 + @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 +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) + @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) + @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 + +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 + +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) + 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 + +_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 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}() diff --git a/test/test-unified-model-object-api.jl b/test/test-unified-model-object-api.jl index 8689a302b..da118be07 100644 --- a/test/test-unified-model-object-api.jl +++ b/test/test-unified-model-object-api.jl @@ -932,11 +932,28 @@ 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)) 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 +981,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 +999,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 +1014,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 +1039,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 = @@ -1320,7 +1189,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), @@ -1328,8 +1197,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) @@ -1394,16 +1265,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, @@ -1839,7 +1710,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( @@ -1848,22 +1719,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), @@ -1872,8 +1739,7 @@ end Many(scale=:Leaf, var=:carbon_override), ), ), - ), - ) + ))) @test only(explain_bindings(override_input_origin_compiled)).origin == :model_spec @@ -1932,7 +1798,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 == @@ -1965,7 +1832,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) @@ -2107,14 +1974,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] @@ -2197,41 +2064,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 @@ -2321,16 +2185,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); @@ -2459,68 +2321,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 @@ -3008,12 +2858,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 = @@ -3216,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) @@ -4079,19 +3927,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(); @@ -4099,11 +3946,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(); @@ -4111,11 +3955,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, @@ -4123,8 +3964,7 @@ end updates=Updates(:biomass; after=:carbon_allocation), ), biomass_source, - ), - ) + ))) ordered_pruner = ModelSpec( ModelObjectBiomassPrunerModel(); @@ -4132,7 +3972,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 @@ -4303,7 +4143,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 @@ -4641,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 diff --git a/test/test_groups.jl b/test/test_groups.jl new file mode 100644 index 000000000..a14db2cb3 --- /dev/null +++ b/test/test_groups.jl @@ -0,0 +1,330 @@ +# 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", + "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" => ( + "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-fixed-status-manifest.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-input-binding-storage.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-fixed-status-prospective-distributed.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", + "test-status-fixed-storage.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", + ), +) + +# 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. +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 + early = filter(i -> i != prepared && i != reusable, 1:(newborn - 1)) + schemas = prepared:prepared + growth = newborn:(identities - 1) + remaining = identities:lastindex(TEST_GROUPS) + if count == 4 + return (early, schemas, growth, [reusable; remaining])[index] + end + # 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), schemas, growth, remaining, + [reusable; filter(>=(calls), early)])[index] +end