Skip to content

Preserve contiguous array derivative views in implicit residual codegen - #5242

Closed
ChrisRackauckas-Claude wants to merge 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:agent/5097-adopt-5121
Closed

ChrisRackauckas-Claude wants to merge 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:agent/5097-adopt-5121

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Please ignore until reviewed by @ChrisRackauckas.

Summary

Adopts stalled #5121 onto current master. Implicit DAE residuals previously expanded each array derivative into one scalar du read per element via SymbolicUtils.array_literal, so residual expression size grew with state dimension (D(x) ~ -x AST nodes 623→1631 for n=24→96). Contiguous derivative blocks are now bound as reshape(view(du, a:b), size) of the du argument, keeping generated residual code size independent of n when the state layout is contiguous.

Cherry-picked from #5121 with authorship preserved (7bb83a3, e19beae). The DiffEqBase 7.18.1 bump commit was skipped: master already requires it. Conflict resolution kept master's existing array_equation_dae.jl coverage and master's element-wise dervars handling in build_explicit_observed_function (from the #5148 array-equation work); #5121's regression tests for code size / observations / interleaved layouts / sentinel collision were retained.

Review follow-ups

AayushSabharwal: IRStructureSearchBuffer term collection, STerm/SArgsT, IRSubstituter, intent comments (96afb6e).

Devin / Fusion Opus 5.5 (non-blocking):

  • Emit a real view in the contiguous binding (0d8c71e): generated code is now (reshape)((view)(du, 1:n), size). In-place residual @allocated at n=200: 7008 → 5344 bytes (getindex-copy path → view path) on this host.
  • Removed the unreachable any(is_array_shape, dvs) guard: dvs = flat_unknowns(sys) is always scalarized.
  • Added a docstring for array_derivative_arguments!.

Relation to #5101 / #5121

Fixes #5097.

Verification

Negative control (src fix reverted to master codegen.jl, new tests kept)

array derivative code size: Test Failed
  Expression: sizes[1] == sizes[2]
   Evaluated: 623 == 1631

With fix (include("lib/ModelingToolkitBase/test/array_equation_dae.jl")) after view change

All 14 testsets passed, including:

array derivative code size |    7      7   6.3s
Multidimensional derivative code size |   10     10  12.0s
array derivative sentinel collision |    1      1   0.5s
TEST_EXIT=0

Generated snippet at n=200: (reshape)((view)(___mtkunknowns___, 1:200), (200,)).

Owning group (earlier on this branch, Symbolics v7.42.0)

InterfaceI    | 1794       5   1799  34m11.9s
     Testing ModelingToolkitBase tests passed

Current CI reds in InterfaceI / RegressionI / Optimization also fail on master; not from this diff. Do not rebase solely for those. Local InterfaceI used Symbolics v7.42.0.

Runic --check --diff and typos clean on codegen.jl.

Not verified

  • Full Core / InterfaceII / QA / Extended suites after the view change
  • Large-array solver/factorization wall-clock scaling
  • Re-running InterfaceI under Symbolics ≥ 7.44.1
  • Offset-axis array unknowns (already BoundsError on master)

What a reviewer should push back on

Risk assessment

  • Risk: medium — changes implicit-DAE residual codegen for systems with array-shaped derivatives.
  • Blast radius: generate_rhs(...; implicit_dae=true) / DAEFunction / DAEProblem; observed equations and assertions on that path.
  • Evidence: fail-before / pass-after code-size regression; full array_equation_dae.jl after view change; alloc drop 7008→5344 at n=200; earlier InterfaceI green on Symbolics 7.42.0.
  • Independent review: Devin/Fusion Opus MERGE (medium); Aayush suggestions applied
  • Merge: needs review

Please ignore this draft until reviewed by @ChrisRackauckas.

Harness: Cursor Agent CLI 2026.10.01-14929f9 · Model: auto · Transcript: /log.txt

Risk assessment (independent review, Claude Code 2.1.301 claude-opus-5-5, reviewed head a85ab15)

  • Risk: medium
  • Blast radius: generate_rhs(...; implicit_dae = true) for continuous time-dependent systems, i.e. DAEFunction/DAEProblem residual codegen, plus observed equations and assertions on that path. The new branch only runs when array-valued derivatives appear in residuals, observed RHS or assertions. Otherwise it returns the old map(D, dvs) binding, so scalarized mtkcompile output is unaffected. With array derivatives, contiguous blocks of du become reshape(view(du, a:b), size) and noncontiguous/partial layouts fall back to the existing scalar expansion. New internal helper array_derivative_arguments! (not exported). Reserves the symbol name __mtk_dae_du on this path. No public API change, no new deps.
  • Evidence: Reviewed head a85ab158af1fef3390f42c3333b298dc1e98058e. Ran lib/ModelingToolkitBase/test/array_equation_dae.jl (Julia 1.13, MTK root loaded as in @mtktestset): PR source 57/57 pass. Same tests with lib/ModelingToolkitBase/src from master (5abac29): 53 pass, 4 fail (array derivative code size Evaluated 623 == 1631; multidimensional 637 == 1645, 639 == 1647; sentinel-collision). Fail-before / pass-after confirmed. Wrote an independent probe (work/probe5242.jl): contiguous block at an offset ([z; x[1:5]]) has the correct IIP and OOP residual (checked by hand: [-3,-5,-7,-9,-11,-2]); OOP with SVector inputs works; ForwardDiff.jacobian w.r.t. du is the correct permutation; jac = true gives dF/du + γ dF/d(du) correctly; DFBDF solve matches analytic z(1)=e^-2, x1(1)=2e^-1-e^-2; a partial array (only some elements differentiated) gives zero residual at consistent du0; an mtkcompiled D(w) ~ -w DAEProblem solves to e^-1. The probe output is identical between PR and master source. CI: 99 pass. The 6 reds are pre-existing: sublibrary InterfaceI "Parsing Test" and RegressionI "Latexify recipes Test" under Symbolics 7.45 (e.g. https://github.com/SciML/ModelingToolkit.jl/actions/runs/38853530735/job/116844159307), fixed on master by Update MTKBase tests and compat floors for Symbolics 7.43-7.45 #5281; the Documentation build fails identically to master on :linkcheck (https://github.com/SciML/ModelingToolkit.jl/actions/runs/38856355754); and the SciMLBase.jl/SymbolicIndexingInterface integration job also fails on master (https://github.com/SciML/ModelingToolkit.jl/actions/runs/38856355740). Root tests / InterfaceI/II green; sublibrary Extensions/InterfaceII (Julia 1) still running.
  • Independent review: Claude Code 2.1.301 claude-opus-5-5 rated it medium, medium-high confidence: the logic is correct in every layout I probed and numerics match master exactly, but it is a ~90-line codegen change on a shared path with three open sibling PRs touching the same block.
  • Merge: needs human review. A codegen change of this size on the implicit-DAE path, overlapping open PRs Promote Dual inputs in out-of-place array DAE residuals #5244, WIP: build implicit DAE Jacobians and sparsity from scalarized array residuals #5136 and Support array unknowns in initialized DAE constructors #5144, is not a small-blast-radius change, even though nothing I ran found a defect. Merge master first so the Symbolics 7.45 reds clear.

🤖 Posted by an AI agent — harness: Claude Code 2.1.301 · model: claude-opus-5-5 (independent reviewer; appended by Claude Code 2.1.301 · claude-opus-5-5)
Conversation: https://claude.ai/code/session_01VZjwf7Ux9YtTzwHGHMqnsq

Independent review (Codex CLI 0.162.1 gpt-6.1-sol, head a85ab15)

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

VERDICT: CHANGES
The array-derivative optimization works in the tested layouts, but its sentinel guard introduces a compatibility regression. Reviewed the complete two-file diff and linked issue. With Julia 1.12.7, Symbolics 7.46.0 and SymbolicUtils 4.51.0, the head passes all 57 array DAE assertions. Running the identical test file against the merge-base packages gives 53 passes and four failures: code-size comparisons 623 == 1631, 637 == 1645 and 639 == 1647, plus the newly expected sentinel exception. Independent offset-block and reversed/interleaved-layout probes pass 4/4 on both versions with identical in-place and out-of-place residuals.

All six failing CI checks have baseline evidence. Both InterfaceI jobs fail on the scalar variable's array default, and both RegressionI jobs fail the Latexify reference comparison; the same failures occur on master run 38488998911. Master's test/compat update subsequently makes all four jobs pass in run 38856356536. Documentation fails with Documenter's [:linkcheck] error on both the PR and master run 38856355754. The SciMLBase SymbolicIndexingInterface integration job has the same State indexing/Observed BoundsError on the PR and master run 38856355740. These failures do not establish a PR regression. Read-only GitHub queries also confirm the current head still has CHANGES_REQUESTED from the maintainer; that request needs resolution before merging.

G1: independent analytic heat/decay references pass on the head. G2: no GPU kernel, AD rule, Reactant or MPI implementation is changed; the affected residual paths run in CI and locally. G3: no new shared cache lifecycle, threading or global-default mechanism is introduced. No G1–G3 failure was identified.

Links

  1. lib/ModelingToolkitBase/src/systems/codegen.jl:73 — confirmed by running: the new guard rejects previously working user inputs. A system with @variables x(t)[1:2], @parameters __mtk_dae_du[1:2] and equation D(x) ~ -x .+ __mtk_dae_du constructs and evaluates correctly on the base: with x=[1,2], du=[7,11], and parameters=[3,5], the residual is [-5,-8]. At this head, DAEFunction(sys) throws ArgumentError solely because of the parameter name. The new test at lib/ModelingToolkitBase/test/array_equation_dae.jl:307 codifies that rejection instead of preserving the working case. Select a deterministic collision-free sentinel and test the residual for this input. Otherwise this is an intentional breaking restriction requiring an explicit SemVer/release decision, rather than a compatible codegen optimization. H1 sets the risk level even though the affected spelling is unusual.

Not verified: full local InterfaceI/RegressionI/QA/downstream suites, a local docs build, large-array wall-clock performance, cross-process expression hashes, offset-axis arrays, or interactions with sibling PRs. CI logs were read; jobs were not rerun or modified. No GitHub posts were made and tracked repository files were not modified.

🤖 Posted by an AI agent — harness: Codex CLI 0.162.1 · model: gpt-6.1-sol
Conversation: Codex exec session 01a14b5b-feaa-76b1-991a-0326be29780d (no public URL)

Codex CLI gpt-6.1-sol rated it high (H1) at head a85ab15

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

Fix by Claude Code 2.1.327 claude-sonnet-5-5 (head a3f8996)

Rebase outcome. Rebased onto current master (a0ecca4). Master already contains the array-derivative reshape(view(du, …)) codegen from the merged #5353, which supersedes this PR, so git dropped the PR's original five commits and the merge commit as already applied. The branch is now one commit on master. The body above describes the original, larger change and is stale. What remains is the repair of the reserved-name regression raised in the independent review (a system that uses the name __mtk_dae_du constructed on the old base but threw ArgumentError with the guard; master has the same guard).

Changes

  • lib/ModelingToolkitBase/src/systems/codegen.jl: array_derivative_arguments! picks the first unused name of the fixed sequence __mtk_dae_du, __mtk_dae_du_1, … instead of throwing. The choice depends only on set membership, so the generated Expr stays deterministic across processes.
  • lib/ModelingToolkitBase/test/array_equation_dae.jl: replaces the @test_throws ArgumentError with numerical residual tests (in-place and out-of-place) for array state, scalar state, parameter and observed collisions with 1 and 3 occupied names, and adds a test for an observed derivative of an array slice.

Validation (Julia 1.12.7, JULIA_NUM_THREADS=4)

  • Negative control (master codegen.jl, new tests): include("lib/ModelingToolkitBase/test/array_equation_dae.jl") gives 8 errors, all ArgumentError: the array derivative sentinel __mtk_dae_du collides with a symbol of the system, exit 1.
  • With the fix, same file: Test Summary: | Pass Total Time / x | 101 101 2m16.3s, exit 0.
  • GROUP=InterfaceI julia --project=lib/ModelingToolkitBase -e 'using Pkg; Pkg.test()': InterfaceI | 2224 5 2229 18m36.4s (5 pre-existing broken), Testing ModelingToolkitBase tests passed.
  • GROUP=QA: JET 54/54; Aqua 20 pass / 1 fail, "No unapproved public reexports" ([:Curl, :Divergence, :Grad, :Laplacian, :NormalDerivative]). The same single failure occurs on a clean upstream master checkout (20/1), so it is pre-existing and not caused by this change.
  • julia --project=@runic -m Runic --check --diff on both files and typos: exit 0.

Not verified: Core, InterfaceII and Extended groups; docs build; other Julia versions. The partial-state failure tracked in #5297 is untouched.

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


🤖 Posted by an AI agent — harness: Claude Code 2.1.327 · model: claude-sonnet-5-5
Conversation: local fixer job SciML__ModelingToolkit.jl__5242 (no session URL)

@AayushSabharwal AayushSabharwal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some more comments inside array_derivative_arguments! would be nice too.

Comment on lines +44 to +47
terms = Set{SymbolicT}()
for expressions in (rhss, extra_expressions), rhs in expressions
Symbolics.get_variables!(terms, rhs; is_atomic = array_derivative_is_atomic)
end

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
terms = Set{SymbolicT}()
for expressions in (rhss, extra_expressions), rhs in expressions
Symbolics.get_variables!(terms, rhs; is_atomic = array_derivative_is_atomic)
end
terms = Set{SymbolicT}()
buffer = SU.IRStructureSearchBuffer(ir, terms)
for expressions in (rhss, extra_expressions), rhs in expressions
Symbolics.get_variables!(buffer, rhs; is_atomic = array_derivative_is_atomic)
end

if length(positions) == length(indices) &&
positions == collect(first(positions):last(positions)) &&
all(isequal(dvs[i], parent[j]) for (i, j) in zip(positions, indices))
arrays[parent] = Symbolics.term(reshape, du[first(positions):last(positions)], size(parent); type = symtype(parent), shape = SU.shape(parent))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
arrays[parent] = Symbolics.term(reshape, du[first(positions):last(positions)], size(parent); type = symtype(parent), shape = SU.shape(parent))
arrays[parent] = Symbolics.STerm(reshape, Symbolics.SArgsT((du[first(positions):last(positions)], size(parent))); type = symtype(parent), shape = SU.shape(parent))

Less compilation

subs[term] = unwrap(Symbolics.substitute(wrap(only(expanded)), subs))
end
end
subber = ex -> unwrap(Symbolics.substitute(wrap(ex), subs))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
subber = ex -> unwrap(Symbolics.substitute(wrap(ex), subs))
subber = SU.IRSubstituter{false}(ir, subs)

@ChrisRackauckas

Copy link
Copy Markdown
Member

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

Independent review (Devin CLI 3000.11.3, model fusion-claude-opus-5-5-high-sidekick-swe-2-medium): MERGE, risk medium.

Full review

VERDICT: MERGE
RISK: medium

Implicit-DAE residual codegen changes for every system with an array-shaped derivative. No public API change. Scalar-only DAEs still take the old path: I checked that the generated code has no sentinel.

Blocking findings

None.

Non-blocking findings

  1. "Views" is not what the code generates. Confirmed by running. The title, the PR body ("bound to reshaped views of the du argument") and the comments at lib/ModelingToolkitBase/src/systems/codegen.jl:42 and :75 all say "view". The generated code for D(x) ~ -x (n=24) actually does
    local var"##cse#7" = __argₛᵧₘ…[1:24]; local var"##cse#9" = reshape(var"##cse#7", (24,)).
    That is a getindex copy, not a view. Allocations still go down: for n=200 an in-place residual call measured 6656 bytes on the PR and 11520 bytes at the merge base. Either emit view in the STerm at codegen.jl:80-84, or change the wording to "slice".
  2. Commit 03179221c ("Handle observations of differentiated array slices") has no source change. Confirmed by running. It only adds 4 assertions to an existing testset (test/array_equation_dae.jl:143-146), and they pass on the merge base too. They don't hurt, but they are not coverage for this PR and the commit title promises more than it does.
  3. The view path uses size(parent) and drops the axes. Suspected from reading. reshape(du[a:b], size(parent)) gives a 1-based array. For a parent declared as x(t)[0:5], a substituted D(x[0]) would index [0] into it. I could not tell this apart from existing behaviour: offset-axis arrays (@variables x(t)[0:5], D(x) ~ -x) already throw BoundsError: attempt to access 6-element Vector{Float64} at index [0] at the merge base and on the PR. Worth a guard, or a @test_broken, when offset axes get supported.
  4. The fallback condition any(v -> SU.is_array_shape(SU.shape(v)), dvs) (codegen.jl:51) looks unreachable today. Suspected from reading: dvs = flat_unknowns(sys) is always scalar. It may be meant for the array-unknown work in Support array unknowns in initialized DAE constructors #5144. If so, fine. If not, remove it.
  5. array_derivative_arguments! has no docstring. Its sibling expand_array_derivatives! has one. It is internal, so this is minor.
  6. Interface fit with other open PRs.
  7. CI is red, but not from this diff. Read from CI logs, not rerun.
    • InterfaceI fails with variable_parsing.jl:66 "Variable x must have default of matching size", an error raised inside Symbolics setdefaultval.
    • RegressionI fails on a reference-image mismatch.
    • The Optimization reds are a BoundsError in optimization codegen tests.
    • In the same CI InterfaceI run, Array equations reach DAEProblem passed 57/57.
    • Current master (1699fa0ab) has Sublibrary CI green, so a rebase should be enough to clear these.
  8. Process items:
    • AayushSabharwal's review is still "changes requested". His suggestions were applied in 96afb6e, but he has not re-reviewed.
    • The PR body does not open with the banner format CLAUDE.md requires; it starts with "Please ignore until reviewed…". The attribution footer is present.

What I ran

All runs used Julia 1.12.7 on aarch64 macOS, Symbolics 7.45.0, SymbolicUtils 4.50.0, SciMLBase 3.57.0, OrdinaryDiffEqBDF 2.4.12. There were two scratch environments: PR head (../repo/lib/ModelingToolkitBase dev'd), and the merge base 34711f668 exported with git archive into scratch/master.

  • PR test file on the PR head: include("lib/ModelingToolkitBase/test/array_equation_dae.jl"). All 14 testsets pass. Confirmed.

  • Same test file at the merge base (negative control), wrapped in an outer testset: 53 pass, 4 fail.

    • array derivative code size: 623 == 1631
    • Multidimensional derivative code size: 637 == 1645 and 639 == 1647
    • array derivative sentinel collision: no exception thrown, as expected since master has no sentinel.

    The observed-expression and interleaved tests pass on both sides, so they act as regression guards rather than as proof of the fix. The fail-before/pass-after claim reproduces.

  • Residual probes (scratch/probes.jl, scratch/probes2.jl), run on both trees. For every case below, the PR and the merge base gave identical outputs:

    • D(u[2:4]) slice inside a contiguous layout.
    • 2-D slice D(w[2:3,2:3]).
    • Two arrays stored in reverse block order with a scalar between them, so the view offset is nonzero.
    • Reversed element order, which takes the fallback path.
    • 2-D unknowns in row-major order with a distinct coefficient per element, which rules out permutation errors. The outputs match the hand-derived values.
    • 2-D column-major contiguous block placed after a scalar, also with distinct coefficients; the PR emits no array_literal.
    • An observed chain v ~ D(z), w ~ 2 .* v with array z gives [-9,-9,-9,0,0,0], matching the hand-derived values.
    • An assertion: zero residual when it holds, NaN when it is violated.
    • The default build_initializeprob = true path solves to exp(-1).
    • A scalar-only DAE: the sentinel is absent from its generated code.
  • Hash stability (AGENTS.md): the generated Expr string for the n=24 system hashes to the same value (5957598767528083742) in two separate processes. No gensym leakage.

  • Expected values in the new tests: I checked the hard-coded expected values in "derivatives in observed expressions" ([-ones(6); 0]) and "array derivatives in observed expressions" (zeros(12)) by hand from rhs − lhs. They are derived, not copied from output. No tolerances were loosened and no skipped or broken tests were added.

  • Formatting and spelling: julia +1.12 --project=@runic -m Runic --check --diff on both changed files exits 0. typos on the diff flags only a git hash in the diff header.

  • CI logs: read with gh pr checks 5242 and gh run view --log-failed for jobs 112860423445, 112860424659 and 112860424051.

What I did not verify


🤖 Posted by an AI agent — harness: Devin CLI 3000.11.3 (review), Claude Code 2.1.285 (posting) · model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Conversation: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master)

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

🤖 Automated comment from an AI agent — not written or reviewed by Chris Rackauckas.

Independent execution at current head a85ab158af1fef3390f42c3333b298dc1e98058e confirms that the sentinel guard rejects working public constructor inputs. This parameter example constructs/evaluates on current master and returns [-5.0, -8.0], but the PR throws the new collision ArgumentError during construction:

using ModelingToolkit, Test
@independent_variables t
@variables x(t)[1:2]
@parameters __mtk_dae_du[1:2]
D = Differential(t)
sys = complete(System([D(x) ~ -x .+ __mtk_dae_du], t,
    collect(x), [__mtk_dae_du]; name = :collision))
prob = DAEProblem(sys,
    [x => [1., 2.], D(x) => [7., 11.], __mtk_dae_du => [3., 5.]],
    (0., 1.); build_initializeprob = false)
out = zeros(2)
prob.f(out, prob.du0, prob.u0, prob.p, 0.)
@test out == [-5.0, -8.0]

The expected result follows directly from -x + p - du. The reviewer also executed the same-name cases as an array state, scalar state, and observed array: all four work on master and all four are rejected on this head. Reproduced on Julia 1.12.7 with Symbolics 7.47.0 / SymbolicUtils 4.53.0 and the compatible older pair 7.41.1 / 4.46.4. The checked master was 207f39e2.

Please preserve these inputs with a deterministic collision-free binding or a correct scalar fallback, and replace the new collision @test_throws with numerical regression coverage. Removing the guard alone does not establish that the generated binding is safe. An intentional name restriction instead requires an explicit breaking-release decision.

There is also useful positive coverage to retain: the independent nonuniform observed-derivative slice probe fails on master with MethodError: no method matching (::Differential)(::Vector{Float64}) and passes here. Please promote that case to the official suite when revising the tests. The separately observed partial-state UndefVarError: x not defined occurs on both trees and is being tracked as a baseline investigation, not attributed to this PR.

The committed test file passes 57/57 on this head, but its new exception assertion currently codifies the constructor regression. This was a read-only review; no repair has been applied or tested, and no author branch was pushed. The reviewer disclosed that the supplied body still contained historical review/risk prose; the constructor differences above were independently executed rather than inferred from that prose.

Links:

🤖 Posted by an AI agent — harness: Codex CLI 0.163.0 · model: gpt-6.1-sol. Independent reviewer: Codex CLI 0.163.0 / gpt-6.1-sol, local session 01a15cf7-7aff-7db3-80ad-3982b6db8ad9 (no session URL).
Conversation: local session 01a15ca3-5696-7ea3-bbac-ba551b6975af (no session URL exposed).

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

🤖 Automated comment from an AI agent — not written or reviewed by Chris Rackauckas.

A two-file proposal for the reserved derivative-name regression on exact head a85ab158af1fef3390f42c3333b298dc1e98058e. It collects names already present in the system and selects the first unused __mtk_dae_du, __mtk_dae_du_1, … binding. Selection depends only on membership and increasing suffixes, so fresh-process expression generation stays deterministic. Valid user names work without changing derivative views, substitution or residual generation.

The same final official array_equation_dae.jl test file discriminates on Julia 1.12.7, Symbolics 7.47.0 and SymbolicUtils 4.53.0. The before/after parsed dependency graphs are identical after local path normalization:

Unpatched exact PR: 58 passed, 8 errors; exit 1
Patched exact PR:   74 passed; exit 0

All eight errors before the fix are the reserved-name ArgumentError, across four symbol roles and one/three occupied names. The patched tests also retain the existing analytic solves, symbolic Jacobians, array layouts, expression-size checks and observed derivatives.

Two fresh-process extra-control runs each pass 53/53: suffix holes; independent-variable collisions with nonzero time; composed state/parameter names; contiguous, offset, interleaved and reversed derivative layouts with ForwardDiff; matrix slices; and both residual variants with satisfied and violated derivative assertions. Both n=24/n=96 generated expressions have 493 nodes and their hashes match across processes. This does not fix the separately tracked partial-state failure.

A fresh independent Codex CLI 0.163.0 / gpt-6-astra session reproduced the exact same-file result: 58 passes / 8 errors → 74 passes, reran 53/53 author controls and passed 21/21 additional controls. Those combine state/parameter/observed name collisions with a colliding independent variable, contiguous/interleaved/reversed layouts, hand-checked residuals and Jacobians, generated jac=true, assertion enforcement, an analytic DFBDF solve and observed lookup. Its final rating is low risk, high confidence for this narrow two-file repair, with no blocking findings. All source/script/graph/log hashes were rechecked and all processes ended.

Full official InterfaceI completed with 1,814 passes, no failed assertions, one parsing error and 5 existing broken tests (exit 1), including all 74 array-DAE assertions. The sole error is the scalar variable with array default at variable_parsing.jl:66, the exact signature documented in merged parsing fix. This full-suite error is retained. A separate run of the exact official parsing file on unpatched a85ab158 reproduces the same error (17 passes / 1 error, exit 1) using the actual InterfaceI sandbox dependency graph with only local source paths changed. The original PR still needs its separate master updates.

Compatible symbolic-dependency floors were independently resolved and verified on Julia 1.12.7: Symbolics 7.41.1 / SymbolicUtils 4.46.4. The identical official file reports 58 passes / 8 reserved-name errors without the patch and 74/74 with it; patched controls pass 53/53 + 21/21. Expression sizes/hashes match the newer graph. This is a compatible symbolic pair, not an all-packages-minimum graph: EnzymeCore, IrrationalConstants and StaticArrays also move one patch version, and Moshi resolves 0.3.9 instead of 0.3.13.

Official QA passed with unchanged assertions and bounds: dedicated JET 54/54 and Aqua 21/21, true exit 0. The initial default-watcher run passed JET 54 but errored in one Aqua check due to FolderMonitor EMFILE; its raw failure is retained. The successful retry changes only the job-scoped JULIA_REVISE_POLL=1 setting, following the documented watcher fallback.

The separately extracted corrected official parsing file from current master passes 48/48 against the identical unpatched source and dependency graph (exit 0). Neither the candidate nor its original parsing test was overwritten. This verifies the existing merged correction separately; the full InterfaceI error above is not hidden or replaced by this control.

Final source/setup audit is complete: the candidate binary diff exactly matches the patch below, with only the two intended tracked files changed. The QA runner's generated environment and metadata diff were archived, its tracked Project restored byte-for-byte, and its archived ignored Manifest removed only after all jobs ended. All frozen source/test/environment hashes were checked; every controller/child has ended and both author/reviewer grants are released.

Scope: the exact two-file repair is independently low risk/high confidence. The original whole PR remains unapproved: it still needs current-master integration, including the existing parsing/Latexify fixes, and fresh CI/review on its final author-adopted head. No source was pushed to the author's branch. Other Julia versions, GPU, downstream routes and an all-packages-minimum graph were not rerun for this repair.

Runic, added-line spelling and diff whitespace checks exited 0. No dependency, public name, docstring or compatibility change. Exact patch SHA256 5a4512ebd2fec6a346dbc8cfa33d3fd10327d1b01d4f15d00f3593c1e40b73eb; 73 insertions / 12 deletions across two files. Final source SHA256 2b6d30f639cd3812fda868eac350b1a81695a45555f535031e5487d7afef52c6, test SHA256 68fc1cc68a3758e97de67c0a687df1668c73792bb846c0aa76f83643adeaf7de.

Exact proposed patch
diff --git a/lib/ModelingToolkitBase/src/systems/codegen.jl b/lib/ModelingToolkitBase/src/systems/codegen.jl
index fc5f02b297..3f4b7ab51f 100644
--- a/lib/ModelingToolkitBase/src/systems/codegen.jl
+++ b/lib/ModelingToolkitBase/src/systems/codegen.jl
@@ -64,14 +64,16 @@ function array_derivative_arguments!(rhss::Vector{SymbolicT}, dvs, D, ir::IRStru
         return map(D, dvs), identity
     end
 
-    # A fixed sentinel keeps the generated Expr hash-stable across processes; reject a
-    # collision so a user symbol cannot silently shadow the `du` argument binding.
-    du_name = :__mtk_dae_du
+    reserved_names = Set{Symbol}()
     for v in reserved_symbols
         parent, _ = split_indexed_var(v)
-        if hasname(parent) && getname(parent) === du_name
-            throw(ArgumentError("the array derivative sentinel `$du_name` collides with a symbol of the system; this name is reserved for internal use."))
-        end
+        hasname(parent) && push!(reserved_names, getname(parent))
+    end
+    du_name = :__mtk_dae_du
+    suffix = 0
+    while du_name in reserved_names
+        suffix += 1
+        du_name = Symbol(:__mtk_dae_du_, suffix)
     end
     du = unwrap(only(@variables $du_name[1:length(dvs)]))
     subs = Dict{SymbolicT, SymbolicT}(D(v) => du[i] for (i, v) in enumerate(dvs))
diff --git a/lib/ModelingToolkitBase/test/array_equation_dae.jl b/lib/ModelingToolkitBase/test/array_equation_dae.jl
index 7afe3bdc96..52374bbe92 100644
--- a/lib/ModelingToolkitBase/test/array_equation_dae.jl
+++ b/lib/ModelingToolkitBase/test/array_equation_dae.jl
@@ -293,18 +293,77 @@ end
     @test out ≈ zeros(12)
 end
 
-@testset "array derivative sentinel collision" begin
+@testset "array derivative argument name collisions" begin
+    for count in (1, 3), role in (:array_state, :scalar_state, :parameter, :observed)
+        @testset "$role with $count occupied names" begin
+            @independent_variables t
+            @variables x(t)[1:2]
+            D = Differential(t)
+            names = [:__mtk_dae_du; [Symbol(:__mtk_dae_du_, i) for i in 1:(count - 1)]]
+            collisions = map(names) do name
+                if role === :scalar_state
+                    only(@variables $name(t))
+                elseif role === :parameter
+                    only(@parameters $name[1:2])
+                else
+                    only(@variables $name(t)[1:2])
+                end
+            end
+            eqs = [D(x) ~ -x]
+            vars = collect(x)
+            ps = []
+            obs = Equation[]
+            op = Pair[x => [1.0, 2.0], D(x) => [7.0, 11.0]]
+            expected = [-8.0, -13.0]
+            for (i, v) in enumerate(collisions)
+                if role === :parameter
+                    push!(ps, v)
+                    push!(op, v => [3.0i, 5.0i])
+                    eqs[1] = D(x) ~ eqs[1].rhs .+ v
+                    expected .+= [3.0i, 5.0i]
+                elseif role === :observed
+                    push!(obs, v ~ (i + 1) .* x)
+                    eqs[1] = D(x) ~ eqs[1].rhs .+ v
+                    expected .+= (i + 1) .* [1.0, 2.0]
+                elseif role === :scalar_state
+                    push!(vars, v)
+                    push!(eqs, D(v) ~ -v)
+                    append!(op, [v => 3.0i, D(v) => 13.0i])
+                    push!(expected, -16.0i)
+                else
+                    append!(vars, collect(v))
+                    push!(eqs, D(v) ~ -v)
+                    append!(op, [v => [3.0i, 5.0i], D(v) => [13.0i, 17.0i]])
+                    append!(expected, [-16.0i, -22.0i])
+                end
+            end
+            sys = complete(System(eqs, t, vars, ps; observed = obs, name = :collision))
+            prob = DAEProblem(sys, op, (0.0, 1.0); build_initializeprob = false)
+            out = zeros(length(expected))
+            prob.f(out, prob.du0, prob.u0, prob.p, 0.0)
+            @test out == expected
+            @test prob.f(prob.du0, prob.u0, prob.p, 0.0) == expected
+        end
+    end
+end
+
+@testset "observed derivative of an array slice" begin
     @independent_variables t
-    @variables x(t)[1:6]
-    @parameters __mtk_dae_du[1:6]
+    @variables x(t)[1:4] v(t)[1:2]
     D = Differential(t)
     sys = complete(
         System(
-            [D(x) ~ -x .+ __mtk_dae_du], t, collect(x),
-            [__mtk_dae_du]; name = :collision
+            [D(x[1:2]) ~ -x[1:2] .+ v, D(x[3:4]) ~ -x[3:4]], t, collect(x), [];
+            observed = [v ~ D(x[3:4])], name = :observed_slice
         )
     )
-    @test_throws ArgumentError DAEFunction(sys)
+    f = DAEFunction(sys)
+    du = [11.0, 12.0, 13.0, 14.0]
+    u = [1.0, 2.0, 3.0, 4.0]
+    out = zeros(4)
+    f(out, du, u, SciMLBase.NullParameters(), 0.0)
+    @test out == [1.0, 0.0, -16.0, -18.0]
+    @test f(du, u, SciMLBase.NullParameters(), 0.0) == out
 end
 
 @testset "Multidimensional derivative code size" begin

Links

🤖 Written by an AI agent: Codex CLI 0.163.0, model gpt-6-astra, local session 01a15f92-d0ac-7da2-a4e3-048ba72a9dfc (no session URL).
Fresh independent review: Codex CLI 0.163.0, model gpt-6-astra, local session 01a15fb1-5d06-78c1-bba8-c588ce48c3fd (no session URL).
🤖 Posted by an AI agent — harness: Codex CLI 0.163.0 · model: gpt-6.1-sol.
Conversation: local session 01a15ca3-5696-7ea3-bbac-ba551b6975af (no session URL).

@xtalax-droid

Copy link
Copy Markdown
Contributor

Draft #5353 carries these commits on current master (with master merged in); reason: the xtalax-droid fork cannot push to this branch.


🤖 Posted by an AI agent · harness: Claude Code 2.1.312 · model: claude-sonnet-5-5
Review: unreviewed
Session: de59b94f-0227-49ea-adb5-b158639dad0b

AayushSabharwal pushed a commit that referenced this pull request Nov 17, 2026
Conflict in lib/ModelingToolkitBase/test/array_equation_dae.jl: both sides
appended new testsets at the end of the file; kept both.

Agent-Harness: Claude Code 2.1.312
Agent-Model: claude-sonnet-5-5
Agent-Session: de59b94f-0227-49ea-adb5-b158639dad0b
Agent-Review: unreviewed
Co-authored-by: Claude Code <agent@noreply.juliahub.com>
AayushSabharwal added a commit that referenced this pull request Nov 17, 2026
Preserve contiguous array derivative views in implicit residual codegen (supersedes #5242)
The implicit-DAE residual binds array derivatives to a synthetic `du`
symbol. Reject-on-collision made systems that use the name `__mtk_dae_du`
(as a state, parameter or observed variable) fail at construction even
though they work without the array-derivative path. Pick the first unused
name of the fixed sequence `__mtk_dae_du`, `__mtk_dae_du_1`, ... instead,
which stays deterministic across processes, and replace the
`@test_throws` with numerical residual tests for each symbol role. Also
cover an observed derivative of an array slice.

Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Agent-Harness: Claude Code 2.1.327
Agent-Model: claude-sonnet-5-5
Agent-Session: local fixer job SciML__ModelingToolkit.jl__5242 (no session URL)
@AayushSabharwal

Copy link
Copy Markdown
Member

Superseded by #5353

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.

Preserve array derivatives in implicit DAE residual code generation

4 participants