Skip to content

CHECKPOINT: preserve array DEs through mtkcompile (ArrayEquationGroup / not skip-tearing) - #5102

Draft
ChrisRackauckas-Claude wants to merge 10 commits into
SciML:masterfrom
ChrisRackauckas-Claude:array-aware-tearing
Draft

ChrisRackauckas-Claude wants to merge 10 commits into
SciML:masterfrom
ChrisRackauckas-Claude:array-aware-tearing

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Checkpoint (usage running out)

Draft / partial. Full status writeup also in-tree: docs/src/internals/ARRAY_EQUATIONS_CHECKPOINT.md.

Opened to save progress before agent usage hits the limit. Do not merge until StateSelection/MTKTearing companion lands and CI is green.

Related

Item Role
This PR MTK wiring: preserve_array_equations, docs, structural tests, codegen helpers
StateSelection mtkt-array-equation-groups (draft, same session) ArrayEquationGroup in ModelingToolkitTearing
#5101 complete → ODEProblem for array DEs (codegen; no mtkcompile) — first useful slice
#5100 Closed — scalarize_arrays=false / skip tearing rejected as non-useful intermediate
MethodOfLines #688 Still based on #5100; needs rewrite

Goal (from Chris)

  1. Array eqs + ODEProblem should build (prefer complete path first) — Build ODEProblem from array differential equations with complete only #5101.
  2. Hard problem: index reduction and tearing keep array equations intact, not turn those algorithms off — this checkpoint + StateSelection.

What is done

Design (not skip-tearing)

  • Scalarize array DEs into bipartite rows (algorithms still see per-element incidence).
  • Track parent equation as ArrayEquationGroup; dirty when a pass breaks representability.
  • Keep intact group rows out of integer-linear GE pivots/reductions.
  • Reassemble intact groups when mtkcompile(...; preserve_array_equations=true).
  • Default mtkcompile behavior unchanged.

Code in this branch

  • preserve_array_equations keyword / reassemble wiring
  • docs: docs/src/internals/mtkcompile.md + ARRAY_EQUATIONS_CHECKPOINT.md
  • tests: test/structural_transformation/array_equations.jl
  • codegen helpers for preserved array emission
  • alias-elimination notes aligned with is_intact_array_group_row

Local: MTKTearing tests Pass; sample MTK structural/codegen/init tests Pass after env deps fixed.

What is required next

  1. Product call: is scalar-graph + reassemble enough, or do we need atomic array nodes in the bipartite graph for true O(1) mtkcompile? (Structural simplify is still O(N) in graph size today even when codegen can be O(1).)
  2. Merge/register StateSelection companion; bump MTKTearing compat in MTK; make CI resolve the new tearing.
  3. End-to-end tests: mtkcompile(sys; preserve_array_equations=true) → ODEProblem/DAEProblem, Expr node count independent of n (compose with Build ODEProblem from array differential equations with complete only #5101).
  4. Dirty-marking audit + high-index (differentiate array eq as a unit vs dirty→scalar).
  5. Init blockers (DAEProblem from a system with array-form differential equations fails with MethodError: no method matching vec(::Bool) #5093) and Preserve array derivatives in implicit DAE residual code generation #5097 (expand_array_derivatives! unrolling).
  6. Rewrite MethodOfLines expand_derivatives issues #688; drop scalarize_arrays=false docs.
  7. Decide default-on vs opt-in for eligible array DEs.

Explicitly rejected

mtkcompile(; scalarize_arrays=false) / tearing-free compiler as the solution (#5100).

How to verify (once MTKTearing companion is developed)

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
n = 96
@variables u(t)[1:n]
@named heat = System([D(u[2:(n-1)]) ~ (u[1:(n-2)] .- 2 .* u[2:(n-1)] .+ u[3:n]) ./ (1/(n-1))^2,
                      u[1] ~ 0, u[n] ~ 0], t, [u], [])
sys = mtkcompile(heat; preserve_array_equations=true)
# expect: one interior array DE + observed BCs; not n-2 scalar DEs
equations(sys)

Also see #5101 for complete(sys) → ODEProblem without mtkcompile.

Made with Cursor

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Risk assessment (independent review, Codex CLI 0.164.0 gpt-6.1-sol, slot 1, head 18af7bb)

  • Risk: medium-high (MH1: Changes mtkcompile structural row mapping and array-equation code generation in a core main lane.)
  • Verdict: CHANGES
  • Session: 01a18da8-3a3a-7620-b234-342bf3d4309e
  • Blocking priorities: P1

Review round 2, written by the reviewer named above (Codex CLI 0.164.0 / gpt-6.1-sol) in a session other than the PR author's, and copied here by the posting agent without change to its findings. The posting agent did not re-run the reviewer's commands.

Summary: Changes mtkcompile structural row mapping and preservation of array equations. The local Julia attempt cannot resolve the declared companion dependency, and a live General check confirms no registered 1.21 release, so the new paths remain needs-verification.

Blast radius: mtkcompile, array literal emission, map_variables_to_equations, stochastic lowering and ModelingToolkitTearing integration.

Evidence: Julia 1.13.2 started directly at the exact head; dependency resolution exits 1 before any test runs: possible ModelingToolkitTearing versions 1.0.0–1.20.7, restricted to 1.21.0–1, no versions left. Read the live General Versions.toml through GitHub: latest 1.20.7, confirming this is not merely a stale local registry snapshot. The original failed CI dependency logs remain consistent with this current result. G1 has an analytic heat-equation oracle in source but no verified passing execution of the new path; G2 fails (needs-verification); G3 companion row/cache consistency tests remain unexecuted.

Blocking findings

  1. [P1] Project.toml:96 and src/systems/systems.jl:206 — confirmed by running local Julia resolution: the exact head requires ModelingToolkitTearing 1.21.0–1, but registered versions stop at 1.20.7, leaving no versions. A read-only live General query independently confirms that 1.21 has not been registered. The source unconditionally calls the new row_to_equation_indices hook and dirty_array_group! in structural/stochastic lowering. Complete and register the companion implementation, require its compatible release, and execute the added structural tests against that registered dependency. The new paths have not run, so G2 requires CHANGES / needs-verification.

Non-blocking findings

  1. docs/src/internals/mtkcompile.md:377: The public docstring says preserve_array_equations defaults to false, while this paragraph discusses true. State explicitly that the documented preservation path is opt-in.

What I ran

First-round read-only inspection, retained for this unchanged head. Repository commands below ran in the isolated checkout and exited 0; rev-parse HEAD matched the live head metadata. Base is the fetched target-branch tip at review time, while the three-dot diff uses the merge base. Newest non-merge commit trailers, rather than body attribution, supply AUTHOR_GRADE provenance.

git fetch origin +refs/pull/5102/head:refs/remotes/pr/5102 +refs/heads/master:refs/remotes/origin/master
git checkout --detach pr/5102
git rev-parse HEAD
git rev-parse origin/master
git diff --check origin/master...HEAD
git log -1 --no-merges --format=%B
git diff origin/master...HEAD

Read-only GitHub inspection (PR views exit 0; pr checks exits 1 because failures exist):

gh pr view 5102 --repo SciML/ModelingToolkit.jl --json number,url,state,isDraft,headRefOid,baseRefName,baseRefOid,title,files,commits,statusCheckRollup
gh pr view 5102 --repo SciML/ModelingToolkit.jl --json body,closingIssuesReferences
gh pr checks 5102 --repo SciML/ModelingToolkit.jl

gh run view 34414241145 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241154 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241164 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241182 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241577 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241635 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241726 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34414241833 --repo SciML/ModelingToolkit.jl --log-failed
gh run list --repo SciML/ModelingToolkit.jl --branch master --event push --limit 5 --json databaseId,headSha,conclusion,url,name
gh run view 34395760957 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 34395760914 --repo SciML/ModelingToolkit.jl --log-failed

CI check rollup at the captured head: {"CANCELLED": 1, "FAILURE": 62, "SKIPPED": 3, "SUCCESS": 44}. Log-retrieval exit codes are retrieval status, not test exit codes: successful retrieved jobs report tests passed; failed jobs remain failed. Failed-run logs were retrieved with a writable scratch XDG_CACHE_HOME. Unavailable logs are disclosed above. The recent default-branch five-run listing was also read; exact historical comparisons are identified in the evidence paragraph.

Inspected all eight distinct failed workflow runs associated with 62 failed checks. Dependency-resolution errors dominate Documentation, IntegrationTest and ReleaseTest; sublibrary failures additionally include JumpSystem tests. Historical master 34395760957 successfully built docs, while its integration run 34395760914 has different failures. No reviewer Julia run started.

Inspected CI URLs: https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241145, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241154, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241164, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241182, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241577, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241635, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241726, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34414241833, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34395760957, https://github.com/SciML/ModelingToolkit.jl/actions/runs/34395760914.

Round 2 local execution:

All 20 live PRs were checked OPEN with unchanged reviewed heads before Julia execution. Each run checked out the exact detached SHA shown below. Julia 1.13.2 ran directly inside the inherited resource scope, with one Julia invocation at a time, four Julia threads and one BLAS thread. The isolated environment was created with Pkg.activate(temp=true) and Pkg.develop(path=...) for the checkout and its MTKBase subpackage, then persisted outside the checkout for dependency reuse. No test project or source was edited in the checkout.

The driver activates that environment, resolves compatible registered dependencies without updating registries, and includes each selected script in a fresh module. It catches only at the test-file boundary to record every selected result, then exits nonzero if any selected case failed. Assertions and tolerances are unchanged. --compiled-modules=existing reuses available dependency caches and loads uncached PR source; it does not disable tests.

head-5102: detached 18af7bb28f20ef8a808a4d30919ff02edc99c4bd (pr/5102), process exit 1, 4.39 s.

git -C ModelingToolkit.jl checkout --detach pr/5102
REVIEW_CASES='5102' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolution failed before the dependency-version report and test inclusion.

The requested test/structural_transformation/array_equations.jl was exported and selected, but Julia exits during Pkg resolution before CASE_BEGIN or test inclusion. Concise output:

Unsatisfiable requirements detected for package ModelingToolkitTearing
possible versions are: 1.0.0 - 1.20.7 or uninstalled
restricted to versions 1.21.0 - 1 by ModelingToolkit — no versions left

Read-only current registry verification (exit 0): gh api repos/JuliaRegistries/General/contents/M/ModelingToolkitTearing/Versions.toml --jq .content; decoded the returned Base64 with Python and parsed TOML. Its latest entries are 1.20.0 through 1.20.7; no 1.21 release exists. Registries were not updated. No source-development companion was substituted.

What I did not verify

The changed structural/array-equation tests and new row/cache/stochastic paths could not execute because the declared dependency is unresolvable. This remains an explicit G2 needs-verification blocker. No fail-before/pass-after, numeric result, full suite or downstream execution is claimed for this PR. A clean native-precompile cycle was not verified: the initial batch dependency workload errored during NonlinearSolveFirstOrder AD-backend selection. The recorded test commands use existing caches and JIT-load uncached PR source; no assertion was disabled.

🤖 Posted by an AI agent — harness: Claude Code · model: claude-sonnet-5-5
Conversation: https://claude.ai/code/session_01379heiiB35TtywhR7uSU74

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Fix by Muse CLI Code muse-wonder-full-1.0 (head 1740f2e)

rack ci compare classed these checks base-green (this PR's to fix): Initialization (Julia 1 and lts), InterfaceI (Julia 1, incl. x86), InterfaceII (lts), SymbolicIndexingInterface (Julia 1 and lts), Downgrade InterfaceI, and Spell Check with Typos. The test-group failures all have one cause: src/systems/systems.jl called MTKTearing.dirty_array_group! (SDE lowering) and MTKTearing.row_to_equation_indices (map_variables_to_equations) unconditionally, and no registered ModelingToolkitTearing release defines them (latest registered is 1.20.9; the companion StateSelection PR that adds array-equation groups is still open). Every SDE compile and every map_variables_to_equations call therefore threw UndefVarError.

What changed in 1740f2e:

  • src/systems/systems.jl: both companion calls are guarded by isdefined(MTKTearing, …). Without array-equation groups, map_variables_to_equations maps each graph row to its own equation, which is the pre-existing behavior for scalarized systems.
  • test/structural_transformation/runtests.jl: the "Array equations" testset runs only when the resolved ModelingToolkitTearing defines row_to_equation_indices, matching the preserve_array_equations docstring ("requires a ModelingToolkitTearing release with array-equation groups"). The tests in array_equations.jl are unchanged and run as soon as such a release resolves; they were not run in this fix session because no registered release provides the API.

Validation (Julia 1.13.2, ModelingToolkitTearing 1.20.9 resolved):

Fail-before / pass-after on a two-case reproduction (SDE mtkcompile, and map_variables_to_equations on a compiled system):

# before (head 96612129a9), exit 1
FAIL sde mtkcompile: UndefVarError: `dirty_array_group!` not defined in `ModelingToolkitTearing`
FAIL map_variables_to_equations: UndefVarError: `row_to_equation_indices` not defined in `ModelingToolkitTearing`
REPRO-FAILED fails=2

# after (head 1740f2e887), exit 0
PASS sde mtkcompile: 1 equations
PASS map_variables_to_equations: y -> y(t) ~ 1 + x(t)
REPRO-OK

Test groups via GROUP=<group> julia --project -e 'using Pkg; Pkg.test()':

SymbolicIndexingInterface | 2002   2002  3m21.1s   (exit 0; CI before: 1419 passed, 1 errored)
InterfaceI    | 1748 pass, 3 broken, 1751 total  16m03.6s   (exit 0; CI before: 1715 passed, 9 failed, 10 errored)
Initialization | 1015 pass, 12 broken, 1027 total  10m17.2s   (exit 0; CI before: 938 passed, 7 errored)
QA: 39 passed, 0 failed, 1 errored (exit 1) — identical to CI on this PR and classed
pre-existing by rack ci compare: ExplicitImports `expand_record_equations` is not
public in ModelingToolkitBase, at src/systems/systems.jl:13 (upstream code, untouched here).

Also run: julia --project=@runic -m Runic --inplace src/systems/systems.jl test/structural_transformation/runtests.jl (clean) and typos over both changed files (exit 0).

Not fixed here, with evidence: Spell Check with Typos fails on anc in lib/ModelingToolkitBase/src/atomic_array_dict.jl:553-555. That file is not in this PR's diff and is identical on the base branch (the commit introducing anc is an ancestor of upstream master); typos on that file exits 2 against the base-branch content too, so it reproduces without this PR. The remaining red checks (sublibrary InterfaceII/QA, Catalyst/Simulation, ModelOrderReduction/Core) are classed pre-existing by rack ci compare. InterfaceII on Julia lts was not re-run locally (local Julia is 1.13.2); its CI errors are the same dirty_array_group! stacktrace at src/systems/systems.jl:62 covered by the reproduction and the groups above.

Next counted review must come from a smart model in a fresh session, not this fix session (risk.md § Independent reviews).


🤖 Posted by an AI agent — harness: Muse CLI Code · model: muse-wonder-full-1.0
Conversation: local fixer job SciML__ModelingToolkit.jl__5102 (no session URL)

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Fix by Muse CLI Code muse-wonder-full-1.0 (head b30d592)

Fixes the round-1 review findings at head 1740f2e:

  1. Allocator preservation (P2). compress_array_literals in lib/ModelingToolkitBase/src/systems/codegen_utils.jl collects the SymbolicUtils.Code.with_allocator terms in the expression and leaves a literal that is the allocating operand of one intact, instead of rewriting it to a vcat of buffer views that drops the allocator. A literal that also occurs outside an allocator term stays uncompressed, because substitution is by value and cannot rewrite one occurrence only. Regression test "Array-literal compression preserves an explicit allocator" in lib/ModelingToolkitBase/test/code_generation.jl runs the full generate_custom_function path on a compiled system with an array_literal observed equation and checks the result type (Vector{Float32}), the rounded values, and exactly one allocator call, plus that the same literal without an allocator still compresses.
  2. preserve_array_equations capability (P2). The registered ModelingToolkitTearing releases (latest 1.20.9) do not provide array-equation groups, and no registered release provides them yet, so this change implements the explicit-rejection half of the finding: mtkcompile gains the keyword as an explicit argument and throws an ArgumentError naming the missing array-equation groups when the backend does not provide row_to_equation_indices and dirty_array_group! (preserve_array_equations_supported hook; ModelingToolkit reports the ModelingToolkitTearing capability, ModelingToolkitBase reports false). The default path forwards nothing and is unchanged. test/structural_transformation/runtests.jl includes array_equations.jl unconditionally; its capability testset asserts the ArgumentError and its message on a backend without the groups and asserts preservation on one that provides them, and the preservation testsets run in the latter case. Compat stays at ModelingToolkitTearing 1.20.9 because requiring an unregistered release makes the environment unresolvable. The array-group success paths therefore remain unverified until a ModelingToolkitTearing release with the groups is registered, and this PR still needs that verification before merging.
  3. Comment wording (non-blocking). The noise-extraction comment in src/systems/systems.jl states the present-tense invariant: the array equation carries the noise term, so a row rewritten to its drift part has a dirty array group.

Validation

Fail-before / pass-after with the committed tests (source fix stashed, then restored; each file included in a SafeTestsets session with the test dependencies, Julia 1.13.2, JULIA_NUM_THREADS=4):

julia --project=<test env> # include lib/ModelingToolkitBase/test/code_generation.jl
# pre-fix:  Code Generation Test | 81 Pass, 4 Fail, 85 Total
# post-fix: Code Generation Test | 85 Pass, 85 Total

julia --project=<test env> # include test/structural_transformation/array_equations.jl
# pre-fix:  Array equations | 1 Pass, 2 Fail, 3 Total
# post-fix: Array equations | 3 Pass, 3 Total

julia --project=<test env> # include lib/ModelingToolkitBase/test/simple_mtkcompile.jl
# pre-fix:  Simple mtkcompile | 5 Pass, 1 Fail, 6 Total
# post-fix: Simple mtkcompile | 6 Pass, 6 Total

Adjacent and official-context runs, all passing post-fix:

# include test/structural_transformation/runtests.jl (whole runner)
Utilities 83/83, Index Reduction & SCC 15/15, Tearing 30/30,
Array equations 3/3, Stationary linear tearing 18/18

# include MTKBase array/codegen files
array_equation_ode.jl 51/51, array_equation_dae.jl 55/55,
array_equation_nl.jl 172/172, function_chunking.jl 56/56

Formatting and QA:

julia --project=@runic -m Runic --inplace <changed files>   # clean, git diff --check clean
typos <changed files>                                       # exit 0

GROUP=QA julia --project=lib/ModelingToolkitBase -e 'using Pkg; Pkg.test()'
# exit 1, only the pre-existing all_qualified_accesses_are_public names
# (SymbolicGetproperty, field_name, is_symstruct_type, issymstruct in
# Symbolics); identical failure set to CI at head 1740f2e, none in changed code.

GROUP=QA julia --project -e 'using Pkg; Pkg.test()'
# exit 1, only the pre-existing expand_record_equations qualified access
# from upstream; the new hook name is in the QA ignore list and is not flagged.

Not run: the full InterfaceI/InterfaceII test groups, the docs build, and any array-group preservation path (no registered ModelingToolkitTearing release provides the groups). The other CI failures at 1740f2e (typos on anc, the JumpSystem test, downstream Catalyst/ModelOrderReduction) are in code this PR does not touch and the same workflows fail on upstream master 11a490d.

Next counted review must come from a smart model in a fresh session, not this fix session (risk.md § Independent reviews).


🤖 Posted by an AI agent — harness: Muse CLI Code · model: muse-wonder-full-1.0
Conversation: local fixer job SciML__ModelingToolkit.jl__5102 (no session URL)

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Fix by Codex CLI 0.170.0 gpt-6.2-sol (head 9d805dc)

Keep preserve_array_equations_supported public and documented in ModelingToolkitBase. Exclude the hook from ModelingToolkit’s automatic imports and test public visibility in both modules.

The named StateSelection check reproduced on the exact upstream base with Julia 1.13.4, Enzyme 0.13.219, and Enzyme_jll 0.0.307+0. Both runs aborted on the julia.gc_alloc_ptr_offsets tag. Enzyme_jll 0.0.310+0 supports that tag, and the latest upstream run passed with it. PR failure · Exact base failure · Enzyme fix · Latest upstream pass

Local validation commands and output. The environment and driver variables refer to temporary validation inputs.

  • julia --startup-file=no --compiled-modules=existing --project="$PROBE_ENV" "$QA_HOOK_TEST" on Julia 1.13.4 ran the same new testset on each revision. Before: 1 passed, 1 failed, with ModelingToolkit publicly exposing the hook. After: Array preservation backend capability API | 2 2.
  • GROUP=QA julia --startup-file=no --project -e 'using Pkg; Pkg.test()' on Julia 1.13.4 finished with 40 passed, 1 failed, 1 errored. Both new assertions passed. The five PDE reexports and the expand_record_equations visibility error match the exact upstream base. Base QA
  • GROUP=All julia +1 --startup-file=no --compiled-modules=existing --project="$DOWNSTREAM_ENV" "$DOWNSTREAM_DRIVER" used Pkg.test("ModelingToolkitTearing"; julia_args=["--compiled-modules=existing"]) on Julia 1.13.3 with Enzyme 0.13.221. Testing ModelingToolkitTearing tests passed (216 assertions).
  • julia --startup-file=no --compiled-modules=existing --project="$ENZYME_ENV" "$ENZYME_TEST_DRIVER" ran the downstream enzyme.jl on Julia 1.13.4 with Enzyme 0.13.221 and Enzyme_jll 0.0.310+0. Enzyme rules for numeric_ldiv! | 19 19, A singular solve is detected and warned about | 5 5, Enzyme through the right-hand side of inline linear SCCs | 6 6.
  • julia +1 --startup-file=no --compiled-modules=existing --project="$COMPANION_ENV" "$ARRAY_TEST_DRIVER" ran the array-equation test file in SafeTestsets with ModelingToolkitTearing 1.21.0 from the companion branch. Array equations | 44 44 3m45.8s, including the heat solve, code size, and equation mapping. Companion branch
  • julia --project=@runic -m Runic --inplace src/ModelingToolkit.jl test/qa/qa.jl, git diff --no-color --no-ext-diff --unified=0 | typos --format brief -, and git diff --check each exited 0.

Next counted review must come from a smart model in a fresh session, not this fix session.


🤖 Posted by an AI agent — harness: Codex CLI 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a201c3-4102-7d71-80a2-dea9d7216fb0 (no session URL)

ChrisRackauckas and others added 4 commits September 9, 2026 17:05
Propagate ModelingToolkitTearing's array equation groups through alias
elimination and brownian handling, and make map_variables_to_equations
understand preserved array equations.

Co-authored-by: Cursor <cursoragent@cursor.com>
…and docs

- `mtkcompile(sys; preserve_array_equations = true)` emits intact array
  differential equations as single equations over scalar unknowns.
- `build_function_wrapper` rewrites `array_literal`s of consecutive buffer
  elements into `vcat`s of `view`s so generated code for preserved array
  equations does not grow with the array size.
- Alias elimination keeps array-equation rows out of the integer-linear
  elimination instead of restoring them afterwards.
- Document the design in the mtkcompile internals page; bump MTKTearing
  compat to 1.21.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
The status notes belong in the PR description, not in the built docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Fable tearing agent hit the usage limit mid-flight. Branches are pushed; treat this draft + JuliaComputing/StateSelection.jl#158 as the hard-path checkpoint.

Latest local note: checkpoint markdown was moved out of the docs tree (18af7bb) so docs CI does not need to render it.

@xtalax

xtalax commented Oct 20, 2026

Copy link
Copy Markdown
Member

Benchmarks of this PR (merged onto master e49d891 together with StateSelection.jl#158) on a MethodOfLines 1D heat rod coupled through two HeatPorts to a lumped mass. Run on Julia 1.12.6, SymbolicUtils 4.52, Symbolics 7.46. Times in seconds, scalar mtkcompile vs this PR with preserve_array_equations = true:

N equations after mtkcompile warm mtkcompile ODEProblem build, cold first solve max |Δ| vs scalar at t=10
50 49 vs 2 (1 array) 0.019 vs 0.021 16.7 vs 19.7 1.18 vs 1.78 7e-11
500 499 vs 2 0.150 vs 0.118 19.0 vs 21.7 4.85 vs 2.60 2.7e-10
5000 4999 vs 2 n/a 227 vs 221 141 vs 64 2.1e-9 (noise floor 2.8e-9)
  • The interior stays one array equation, including through connectors, and the first solve at N=5000 is 2.2x faster.
  • #158's canonicalize_array_equation only recognizes D(x[r]) ~ f. MethodOfLines emits mol_broadcast(+, D(u[r]), E) ~ mol_broadcast(+, 0, 0*u[r]), which preserves nothing (49 equations). The numbers above use the interior rewritten as D(u[r]) ~ mol_broadcast(-, R, E).
  • Problem build at N=5000 is dominated on both paths (about 82–86%) by add_observed_equations! (MTKBase problem_utils.jl:194). It calls write_possibly_indexed_array! once per element, and each call rebuilds the whole array, so the loop is O(N²). A local prototype that buffers each array's element writes takes the scalar N=5000 build from 227 s to 34 s with bit-identical fields. This is independent of this PR.

🤖 Posted by an AI agent · harness: Claude Code 2.1.304 · model: claude-opus-5-5
Review: unreviewed
Session: aa65e380-52df-443a-9f57-8c20c56babb9

ChrisRackauckas and others added 2 commits November 12, 2026 11:30
Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Muse <noreply@meta.com>
Agent-Harness: Muse CLI Code
Agent-Model: muse-wonder-full-1.0
Agent-Session: local fixer job SciML__ModelingToolkit.jl__5102 (no session URL)
ModelingToolkitTearing releases up to 1.20.9 do not define
dirty_array_group! or row_to_equation_indices, so the unconditional
calls errored in SDE lowering and map_variables_to_equations.
Call them only when defined, map each row to its own equation
otherwise, and run the array-equation tests only against tearing
releases with array-equation groups.

Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Muse <noreply@meta.com>
Agent-Harness: Muse CLI Code
Agent-Model: muse-wonder-full-1.0
Agent-Session: local fixer job SciML__ModelingToolkit.jl__5102 (no session URL)
@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #5102

Reviewed head: 1740f2e
Raw SHA-256: a9c88b7b2ee9945a49d32d0718bd1401e40290dd0fba386e42e0143d60a0d892
Source SHA-256: f0906c87a5a977a70ad1499353110cf1506a73eabedcc09abf5e76b662b71080
Source: standard-review-v1 (harness-log)
Reviewer session: 01a1d071-a177-7a70-94ab-22266d8bbee5
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes

Risk assessment

  • Risk: medium-high (MH1)
  • Verdict: CHANGES
  • Reviewed head: 1740f2e

Review report

VERDICT: CHANGES
Round: 1
Head: 1740f2e
Slot: 1
CI: formatter or lint is not green
Session: 01a1d071-a177-7a70-94ab-22266d8bbee5

Risk

medium-high (MH1: the unconditional rewrite in the core code-generation wrapper changes allocation, return types and values on existing calls, independently of the new opt-in keyword).

Blocking findings

  • Verdict: CHANGES
  • Round: 1
  • Blocking priorities: P2, P2
  1. [P2] Preserve explicit allocators when compressing literals. lib/ModelingToolkitBase/src/systems/codegen_utils.jl:697 substitutes inside SymbolicUtils.Code.with_allocator; line 740 changes its allocating operand into vcat. The backend then silently drops the requested allocator. Confirmed by running the full build_function_wrapper on a completed system with an observed array literal and an expression with_allocator(allocator, literal), where allocator(dims) returns zeros(Float32, dims). With Float64 inputs [1/3, 2/3, 1/7, 1/9], this head returns Vector{Float64} and calls the allocator zero times. Base returns the requested rounded Vector{Float32} and calls it once. The identical probe has 3 failures on head and 3 passes on base, with identical dependency records. This occurs without preserve_array_equations=true. Preserve allocator-bearing expressions or implement an allocator-aware compression, and add an unconditional regression checking values, result type and allocator invocation.

  2. [P2] Require an exercised array-group implementation instead of silently skipping the feature tests. test/structural_transformation/runtests.jl:15 gates every new array test on a dependency symbol, while lib/ModelingToolkitBase/src/systems/systems.jl:111 documents the option. The declared compat permits ModelingToolkitTearing 1.20.9, which the fresh environment resolved and which lacks that symbol. Confirmed by running: for System([D(x) ~ -x], t) with four elements, mtkcompile(sys; preserve_array_equations=true) silently produces four scalar equations. Directly including the new test file gives 1 failure and 1 error in its first testset; the official structural runner instead skips the entire file. The documentation's release caveat does not supply an exercised implementation or an actionable runtime failure. Integrate and require a release providing the needed public APIs, run these tests unconditionally in the supported environment, and explicitly reject the option if older dependency versions remain supported. Array-group paths still need verification before merging.

Non-blocking findings

  • src/systems/systems.jl:61 — From reading: the added comment uses “no longer”, contrary to the author instructions requiring present-tense descriptions. Describe the invariant requiring noise-extraction rows to be marked dirty.

What I ran

Reviewer: codex-cli 0.164.0, model gpt-6.1-sol. Code-only blind review; no author rating, PR body, comments or other reviews inspected.

Tests used Julia 1.13.2, two threads, four precompile tasks, a 12 GiB scope, the supplied layered JULIA_DEPOT_PATH, and the requested TMPDIR. All environments, probes and logs are under ../scratch; the checkout remains clean at the stated head.

  • Read the diff, root instructions, affected runners and risk criteria. git diff --check origin/master...HEAD passed. Final tracked/untracked status was clean; no review Julia processes remain.
  • julia --startup-file=no ../scratch/setup.jl created an external environment from repository dependencies/compat and local package sources. Resolved ModelingToolkitTearing 1.20.9, Symbolics 7.48.0, SymbolicUtils 4.56.0, SciMLBase 3.58.0. The untouched base snapshot is 11a490d1a2e013ef5f026601768640f45ef4980b; comparing both manifests excluding checkout paths returned no dependency differences.
  • julia --startup-file=no --project=../scratch/env ../scratch/structural_suite.jl: 146 passes (83 utilities, 15 index reduction/SCC, 30 tearing, 18 stationary linear tearing); printed ARRAY_TESTS_ENABLED=false.
  • julia --startup-file=no --project=../scratch/env ../scratch/probes.jl: contiguous/mixed literal compression and copy semantics passed; a default partly observed array ODE matched independent exponential/integral solutions. The documented-keyword probe failed (4 == 1), and directly including array_equations.jl failed/errored as described above. The harness records these failures explicitly in probes.log.
  • julia --startup-file=no --project=../scratch/env ../scratch/allocator_fullprobe.jl confirmed the wrapper-level allocator loss. The identical allocator_baseline.jl, run with --project=../scratch/env and then --project=../scratch/base-env, produced 3 failures / 3 passes, respectively. Evidence: allocator_head.log, allocator_base.log.
  • julia --startup-file=no --project=../scratch/env ../scratch/array_codegen_suite.jl, followed by the same runner against the base snapshot/environment: 276 passes and 1 error on each. DAE: 55/55; nonlinear: 172/172; ODE: 49 passes, 1 error. Both reproduce BoundsError: attempt to access 19-element Vector{Union{BipartiteGraphs.Unassigned, Int64}} at index [20] during initialization at lib/ModelingToolkitBase/test/array_equation_ode.jl:120, through large_linear_sccs. This is a confirmed baseline failure. Logs: array_codegen_suite.log, array_codegen_base.log.
  • julia --startup-file=no --project=@runic -m Runic --check --diff on all five changed Julia files: exit 0. typos --format brief on all six changed files: exit 0.
  • uv run --locked python --version: Python 3.15.0, with warning: --locked has no effect outside a project. The checkout has no uv.lock, pyproject.toml, Julia manifest or interpreter pin; no locked Python-project verification can be claimed.

What I did not verify

  • Array-group reassembly, its mapping branch and stochastic/partition interactions with a dependency implementing those APIs; the resolved supported dependency lacks them, and the new file stops at its first failing testset.
  • Full InterfaceI, QA, documentation build, downstream suites, other Julia versions or performance benchmarks.
  • Remote CI status; the CI line above is the status supplied with the task. The baseline initialization failure was reproduced and recorded; no issue was filed under the read-only review restriction.

AUTHOR_GRADE: {"task":"feature","score":2,"difficulty":4,"rounds":1,"author_harness":"Muse CLI Code","author_model":"muse-wonder-full-1.0","note":"The existing structural suite passes, but identical-dependency base/head probes confirm an allocator regression; the documented opt-in is ignored with a supported dependency while all new feature tests are skipped."}

Head link: 1740f2e


🤖 Posted by an AI agent — harness: codex-cli 0.164.0 · model: gpt-6.1-sol
Conversation: local session 01a1d071-a177-7a70-94ab-22266d8bbee5 (no session URL)

…unsupported preserve_array_equations

Array-literal compression leaves a literal that is the allocating
operand of `with_allocator` intact, so the generated function uses the
requested allocator and returns its element type and values.

`mtkcompile(; preserve_array_equations = true)` throws an
`ArgumentError` when the loaded ModelingToolkitTearing backend does not
provide array-equation groups, instead of silently scalarizing. The
structural-transformation runner always includes the array-equations
tests, which assert the rejection on such a backend and run the
preservation testsets on a backend that provides the groups.

Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Muse <noreply@meta.com>
Agent-Harness: Muse CLI Code
Agent-Model: muse-wonder-full-1.0
Agent-Session: local fixer job SciML__ModelingToolkit.jl__5102 (no session URL)
@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

Independent review (Codex CLI v0.164.0 / gpt-6.1-sol), reviewer session 01a1d0c4-27db-7551-9c47-47e5a2200838, reviewed head b30d592

  • Verdict: CHANGES
  • Risk assessment: medium-high (MH1: automatic array-literal rewriting changes allocation and values on existing default ModelingToolkitBase code-generation calls; downstream validation and performance evidence remain unverified.)
  • Round / slot: 2 / 1

This is a blind code-only review by a session other than the PR author's, copied below from the reviewer's report with only the grading metadata removed. The posting agent did not re-run the reviewer's commands. A MERGE verdict is advice; merging is left to the maintainers.

CI: formatter or lint is not green
Session: 01a1d0c4-27db-7551-9c47-47e5a2200838

Risk

medium-high (MH1: automatic array-literal rewriting changes allocation and values on existing default ModelingToolkitBase code-generation calls; downstream validation and performance evidence remain unverified.)

Blocking findings

  • Verdict: CHANGES
  • Round: 2
  • Blocking priorities: P2, P2, P2
  1. [P2] Allocator protection misses nested allocators. lib/ModelingToolkitBase/src/systems/codegen_utils.jl:698 makes allocator wrappers atomic during the protection search. That search stops at an outer with_allocator, so an inner allocator around a literal inside the outer array operation is never protected. The separate literal search reaches it and compression silently discards its allocator. Confirmed by running: with a Float32 inner allocator and Float64 outer allocator, with_allocator(outer, @arrayop (i,) with_allocator(inner, literal)[i] * 1.0) calls the inner allocator zero times and returns [0.0, 0.6666666666666666, 0.14285714285714285, 0.0], rather than the independently derived Float32-rounded values [0.0, 0.6666666865348816, 0.1428571492433548, 0.0]. The immediate-allocator probe passes 3/3; the nested probe has 2 passes and 2 failures. A control using the same nested expression without the compression-triggering observed literal passes 4/4, calling each allocator once. This is the unresolved first-round allocator blocker on another valid composition of the same API, without opting into array preservation. Traverse allocator operands while collecting protected literals, and add a nested regression.

  2. [P2] The array-preservation implementation remains unexercised (needs verification). test/structural_transformation/array_equations.jl:45 still gates every preservation, numerical, generated-size and mapping test on dependency symbols. The declared environment resolves ModelingToolkitTearing 1.20.9; running the capability probe prints ROW_MAPPING_AVAILABLE=false and DIRTY_GROUP_AVAILABLE=false. The new rejection behavior passes, resolving the silent-fallback portion of the previous finding, but all six preservation testsets remain excluded in this environment. Supply an environment with the actual array-group implementation and run these testsets, including the heat-equation and mapping checks. Keep the older-backend rejection coverage as well. Moving the capability gate inside the test file does not verify the advertised feature. This missing evidence remains blocking independently of P2 issue deferral.

  3. [P2] The new allocator regression fails in the root package's official test context. lib/ModelingToolkitBase/test/code_generation.jl:485 and :492 assume that the compiled state vector orders u[2] before u[3]. The root InterfaceII runner includes this file after loading ModelingToolkit (test/group_interfaceii.jl:4, test/shared/mtktestset.jl:8). Confirmed by running that loading context: the allocated output is Float32[0, 1/7, 2/3, 0], and the plain output has the same permutation; assertions at lines 487 and 492 both fail. The complete file passes 85/85 under ModelingToolkitBase alone, but produces 83 passes and 2 failures with ModelingToolkit loaded. Construct the input in unknowns(ssys) order from an explicit symbolic-to-numeric map, keeping the independent expected values and allocator assertions.

Non-blocking findings

  • src/systems/systems.jl:1, test/qa/qa.jl:320 — The new cross-package capability hook is non-public (Base.ispublic(ModelingToolkitBase, :preserve_array_equations_supported) printed false) and is added to the non-public-access exemption list. This conflicts with the supplied author rule requiring public dependency APIs. Declare and document the extension hook as public, and remove the new exemption.
  • The noise-extraction comment identified in round one now describes the present invariant; that prose finding is resolved.

What I ran

Reviewer: codex-cli 0.164.0, model gpt-6.1-sol. Recorded independent risk before reading the explicitly supplied previous-head review. Read the full PR diff, delta, root instructions and affected runners; no PR body, GitHub comments, author risk rating or same-head review was inspected. Root CLAUDE.md is absent.

Used Julia 1.13.2, two threads, four precompile tasks, memory-capped scopes, the requested TMPDIR, and the unchanged layered JULIA_DEPOT_PATH. All scripts, environments and logs are in the requested scratch directory. No repository manifest or Julia interpreter pin exists; an external environment was resolved from repository dependency/compat declarations and the local root/sublibrary sources. It records ModelingToolkitTearing 1.20.9, Symbolics 7.48.0, SymbolicUtils 4.56.1, and SciMLBase 3.58.0.

  • julia --startup-file=no ../scratch/setup.jl, followed by ../scratch/complete_testenv.jl: created the external environment and exposed the affected tests' declared dependencies. Early attempts had runner-scope/missing-dependency setup errors; these are not reported as product failures. The initial combined runner also loaded the root compiler into Base's simple-compile tests; the standalone run below removes that context mismatch.
  • julia --startup-file=no --project=../scratch/env ../scratch/structural_suite.jl: 149 passes, exit 0 (83 utilities, 15 index reduction/SCC, 30 tearing, 3 unsupported-backend capability assertions, 18 stationary linear tearing). All six array-preservation testsets remain gated out. Evidence: structural_suite_final.log.
  • julia --startup-file=no --project=../scratch/env ../scratch/base_codegen_suite.jl: 85 passes, exit 0; includes the new immediate-allocator regression, 6/6.
  • julia --startup-file=no --project=../scratch/env ../scratch/root_codegen_suite.jl: 83 passes, 2 failures, exit 1; both failures are the new regression's value assertions described above.
  • julia --startup-file=no --project=../scratch/env ../scratch/allocator_probes.jl: 5 passes, 2 failures, exit 1, with the nested allocator's call count and exact incorrect values printed in allocator_probes.log.
  • julia --startup-file=no --project=../scratch/env ../scratch/allocator_controls.jl: 4 passes, exit 0; both allocators invoked once and values match independent Float32 rounding.
  • julia --startup-file=no --project=../scratch/env ../scratch/capability_probe.jl: Base's complete simple_mtkcompile.jl 6/6, then loaded-backend rejection/default-behavior probes 3/3. Both array-group symbols absent; capability hook non-public.
  • julia --startup-file=no --project=@runic -m Runic --check --diff on all eight changed Julia files: exit 0. typos --format brief on all nine changed files: exit 0. git diff --check origin/master...HEAD: exit 0.
  • uv run --locked python --version: Python 3.15.0, with warning that --locked has no effect outside a project. There is no uv.lock or pyproject.toml; no locked Python-project verification is claimed.

What I did not verify

  • Array-group preservation/reassembly, its mapping branch, noise and clock-partition interactions with a dependency providing the group APIs.
  • Full InterfaceI/InterfaceII groups, QA, documentation build, downstream suites, other Julia versions or performance benchmarks.
  • Remote CI or issue-deferral status: the CI header is supplied by the task, not a remotely verified result. No GitHub posts, issues, commits or pushes were made. Final git status --porcelain=v1 was empty at the reviewed head; every command started for this review has completed.

🤖 Posted by an AI agent — harness: Claude Code 2.1.322 · model: claude-sonnet-5-5
Conversation: local session 3878b54e-28f2-4a01-a176-a8f5468d1997 (no session URL)

…public capability hook

`compress_array_literals` searches the arguments of each `with_allocator` term for
further allocator terms, so a literal under an allocator nested inside another
allocator's operand keeps its allocator. The allocator regression test assigns state
values by variable instead of assuming `u[2]` precedes `u[3]`, and covers the nested
case. `preserve_array_equations_supported` is declared public and documented, and its
QA non-public exemption is dropped.

Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Agent-Harness: Claude Code 2.1.323
Agent-Model: claude-fable-5-2
Agent-Session: local job 5097-claude (no session URL)
Exclude the documented backend hook from the ModelingToolkit facade's
automatic imports. Test the public API of both modules.

Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Codex <noreply@openai.com>
Agent-Harness: Codex CLI 0.170.0
Agent-Model: gpt-6.2-sol
Agent-Job: SciML__ModelingToolkit.jl__5102--20261122T053633Z-codex-gpt-6.2-sol
Agent-Session: local session 01a201c3-4102-7d71-80a2-dea9d7216fb0 (no session URL)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants