Skip to content

Add multiconnect: graph-based connections over node arrays - #5117

Draft
ChrisRackauckas-Claude wants to merge 6 commits into
SciML:masterfrom
ChrisRackauckas-Claude:multiconnect-graph-connections
Draft

ChrisRackauckas-Claude wants to merge 6 commits into
SciML:masterfrom
ChrisRackauckas-Claude:multiconnect-graph-connections

Conversation

@ChrisRackauckas-Claude

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

Copy link
Copy Markdown
Member

Draft. Ignore until reviewed by @ChrisRackauckas.

Summary

Adds a graph primitive for connections between repeated instantiations of component subsystems — connect, but applied to an array of nodes with a connection graph and labeled edges. Motivated by #341 (NetworkSystem) and #2674 (array of components): clone component prototypes per graph node, declare connectivity once, and let the existing connection machinery do the lowering.

Two forms:

Subsystem form — multiconnect(nodes, edges) / multiconnect(nodes, g, portmap):

nodes = [Resistor(; name = :r1), Resistor(; name = :r2), ...]
multiconnect(nodes, [ConnectionEdge(1, 2, :p, :n), ...])   # explicit edges
multiconnect(nodes, g, :p => :n)                           # Graphs.jl graph + port map
  • Builds a single Connection equation whose payload is a ConnectionNetwork (nodes + ConnectionEdges). The symbolic representation is O(1) in graph size until expand_connections.
  • portmap accepts a Pair/2-tuple applied to every edge, a Dict keyed by Graphs.Edge or (i,j), a callable portmap(i,j), or nothing (infer the sole connector; a node itself can be the port when it is a connector).
  • Lowering dispatches each edge through the existing connection-set machinery: acausal connector ports and causal input/output variable ports behave exactly like the corresponding connects, and multi-edge ports merge into one connection set (star of equalities + flow conservation).
  • Construction validates: nonempty/unique nodes, edge bounds, no self-edges, port existence, connector-vs-variable port-kind match, causal input→output orientation, unambiguous inference.
  • network_edge_ports(net) (public, documented) returns the resolved (src_port, dst_port) pair of every edge, typed Union{System, SymbolicT} per port. It is the one place a ConnectionNetwork is resolved to ports; the connection-set lowering, unit validation and isolate_subsystem all go through it.

Array-variable form — multiconnect(portspec::Pair, g):

@variables (v(t))[1:n] (f(t))[1:n]
multiconnect(:v => :f, g)   # per-node array vars; edge equalities + flow conservation

encodes the edge list in sparse selection matrices and emits compact equations — Ps * a ~ Pd * b for equality variables and one conservation equation per flow net — so the representation does not grow with the number of edges. Union-find merges nets that share flow variables.

Consumers of Connection payloads

Connection equations store wrapped symbolic values, so eq.lhs isa Connection never fired in several places, and every consumer that iterated get_systems(rhs) assumed a vector. Fixed to unwrap with value(...) and to handle ConnectionNetwork:

  • round_trip_eq (serialization/toexpr) — also emits domain_connect and reconstructs ConnectionNetwork node/edge expressions
  • change_independent_variable — rebuilds ConnectionNetwork with transformed nodes resolved hierarchically
  • substitute_component's recreate_connections — resolves each network node through recursive_getproperty and rebuilds
  • Base.show equation counter / n_expanded_connection_equations
  • Unit checking (MTKDynamicQuantitiesExt): _validate(::Connection) iterated the payload and threw MethodError: no method matching iterate(::ConnectionNetwork) for any unit-carrying model containing a multiconnect. Each connector-port edge is now validated exactly like the pairwise connect it stands for. Variable-port edges are skipped, because pairwise connect of causal variables already crashes the unit checker on master — filed as Unit validation crashes on causal variable connect: unknowns(::BasicSymbolic) MethodError in MTKDynamicQuantitiesExt #5118.
  • isolate_subsystem: the component-graph walk and the reconstruction pass iterated the payload the same way and crashed. Network edges now contribute one graph edge per (src, dst), and on reconstruction a network is restricted to the edges whose endpoints are inside the isolated region, dropping nodes no kept edge references. A network with several disconnected components is therefore kept partially, which is what the equivalent list of pairwise connects would do.

Also fixes docs/Project.toml [sources]: a stale absolute path from a prior sandbox session → ModelingToolkit = {path = ".."}.

A note on network_edge_ports' return type

The first version of the unit-validation branch let the port element type be inferred from getproperty(::System, ::Symbol). Any code consuming those elements inside the extension then sent type inference into a multi-minute (never observed to finish, >3.8e9 inference allocations) cascade at the first System(...) construction after using DynamicQuantities — bisected over eight variants of the extension code; the only fast variants were the ones that never touched the elements. Declaring the port type as Union{System, SymbolicT} at the source fixes it and is the more honest API. Reviewers: this is the one non-obvious design choice in the diff.

Verification

Local Julia 1.12.4, MTKBase and MTK dev'd from this branch, DynamicQuantities 1.13.0.

Formatting / spelling (Runic via Runic.main, typos) on every changed file: clean. The first push failed Runic on the new files; that is commit "Runic-format the multiconnect additions".

MTKBase test/multiconnect.jl (in InterfaceII; 56 tests = the original 51 + the new "Unit validation of networks" set):

Test Summary: | Pass  Total     Time
mc            |   56     56  4m26.7s

New outer test/isolate_subsystem.jl (registered in InterfaceII; isolate_subsystem had no test before — the docs example is the first testset):

Test Summary: | Pass  Total     Time
iso           |   10     10  4m06.3s

test/substitute_component.jl (outer): 22/22 on the first push, unchanged since apart from Runic.

Bug-fix discrimination. The new tests run against the pre-fix source (fix stashed, only the test files restored):

Unit validation of networks: Error During Test at .../lib/ModelingToolkitBase/test/multiconnect.jl:468
  MethodError: no method matching iterate(::ModelingToolkitBase.ConnectionNetwork)
Test Summary: | Pass  Fail  Error  Total     Time
mc            |   51     2      3     56  5m25.2s

multiconnect networks are restricted to the isolated region: Error During Test at .../test/isolate_subsystem.jl:22
  MethodError: no method matching iterate(::ModelingToolkitBase.ConnectionNetwork)
Test Summary: | Pass  Error  Total     Time
iso           |    3      1      4  6m56.5s

and the earlier discriminations from the first push (stale network nodes after change_independent_variable/substitute_component; toexpr emitting a bare ConnectionNetwork repr) still hold.

CI on the first push, and what changed:

  • Runic: failed on the new files → formatted.
  • downgrade-mtkbase (InterfaceII): UndefVarError: unwrap in the new test file → explicit using Symbolics: unwrap. (That job also fails on master for other reasons.)
  • tests / QA: "No unapproved public reexports" listed multiconnect, ConnectionEdge, ConnectionNetwork (plus names since approved on master in Fix QA: approve the limited/constraints_to_penalties API additions #5116) → added to REEXPORTED_API, along with network_edge_ports.
  • sublibrary-ci / MTKBase [QA]: JET mode = typo reports 234 ##gensym may be undefined frames in untouched files; the same job fails identically on the master run of the base commit. Not addressed here.
  • NeuralPDE.jl/NNPDE1 downstream: allowed-to-fail, not investigated.

Outer QA group (julia --project=test/qa ... include("test/qa/qa.jl"), Julia 1.12.4): 19/20. The single failure is No unapproved public reexports: Evaluated: isempty([:tovar]), which is #5120 on master and is fixed separately in #5123; the four names this PR adds are approved. The CI tests / QA job on this branch fails with exactly the same single entry.

MTKBase QA on CI: fails on the same 234 JET mode = typo reports as master; zero reports in multiconnect.jl or the extension.

Docs build (docs/make.jl, doctests on, checkdocs = :exports, linkcheck on): the @docs block for network_edge_ports resolves (it has to be referenced as ModelingToolkitBase.network_edge_ports, the convention for public non-exported names), doctests pass, and the build reaches linkcheck, which then fails on a GitHub 429 rate limit for an untouched link (NEWS.md); the first push saw the same 429 on the ColPrac link.

CI on this push: every test job that runs the new code is green — outer and MTKBase InterfaceII on Julia 1, lts and pre, downgrade-mtkbase (InterfaceII), Runic, spell check, Documentation. The two red jobs are the QA ones above.

downgrade-mtkbase (Initialization) failed once on this commit (https://github.com/SciML/ModelingToolkit.jl/actions/runs/34704969119/job/103584112015: initializationsystem.jl:2313, ForwardDiff.gradient(loss, [1.5])[1] ≈ fd evaluated as 1.3e153 ≈ -1.15, preceded by the Dual-valued solve aborting with all states non-finite at t = 0) and passed on the retriggered run of the same commit (https://github.com/SciML/ModelingToolkit.jl/actions/runs/34712340782/job/103603372204). The same group with the identical floor versions also passes locally on this commit (691 pass / 12 broken) and the failing testset passes in six standalone processes on Julia 1.10.11 and 1.10.12. The four commits touch nothing on the initialization or AD path, so this is treated as a nondeterministic failure; tracked in #5125.

Not verified locally: GPU/downstream jobs, julia pre.

Related: #341, #2674, #814. Filed while working on this: #5118.


First version: 🤖 Generated with Devin CLI 3000.10.21 (model: SWE-2 Max), local CLI session (transcript summary at <local transcript>, no shareable URL).

Review, rebase, CI fixes, network_edge_ports, unit-checking and isolate_subsystem support: 🤖 Generated with Claude Code (Claude Code 2.1.269, model: claude-fable-5-1)

https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ

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

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

VERDICT: CHANGES
The additive connection API has three reproduced correctness gaps. All 56 assertions in lib/ModelingToolkitBase/test/multiconnect.jl pass, including its analytic RC reference and comparison with ordinary connections. A focused connection-transformation assertion fails on base bf209c9 (connection independent variables remain [t,t]) and passes on this head (both become sys₊s), confirming that fix. The supplied CI failures cannot be classified as pre-existing from the available evidence.

  1. [P2] lib/ModelingToolkitBase/src/systems/multiconnect.jl:501 — Reduce acausal equality constraints to an independent set. Confirmed by running: define three-element arrays v(t) and f(t), mark f as Flow, and combine D(v[i]) ~ f[i] for i=1:3 with multiconnect((v,f)=>(v,f), complete_graph(3)). mtkcompile throws ExtraEquationsSystemException: "There are 7 equations and 6 unknowns." Substituting path_graph(3) compiles successfully and describes the same connected potential/flow net. The selection matrices retain all three cycle equalities, whereas ordinary connection-set expansion needs only two. Build a spanning forest of the resolved port graph for acausal equalities and add a cyclic-network compile regression test.

  2. [P2] lib/ModelingToolkitBase/ext/MTKDynamicQuantitiesExt.jl:264 — Validate units for causal variable edges. Confirmed by running: for a.y marked output with unit m and b.u marked input with unit s, validate(connect(a.y,b.u)) returns false with a mismatched-units warning, but validate(multiconnect([a,b],[ConnectionEdge(1,2,:y,:u)])) returns true. System construction with checks=true also accepts that network. The continue bypasses the causal-unit validation immediately below this branch, so equivalent declarations enforce different physical constraints. Apply that validation to variable edges and test both matching and mismatched units.

  3. [P2] lib/ModelingToolkitBase/src/systems/abstractsystem.jl:2546 — Preserve the edge element type when serializing an empty network. Confirmed by running: multiconnect([a,b], ConnectionEdge[]) constructs successfully, but round_trip_eq emits multiconnect([a,b], []). Evaluating this expression throws MethodError: no method matching multiconnect(::Vector{System}, ::Vector{Any}). An edgeless Graphs graph reaches the same valid construction case. Emit a typed ConnectionEdge[] expression and test evaluation of the serialized result; the current serialization test checks substrings only.

Gate assessment: G1 has independent numerical evidence from the passing analytic RC and ordinary-connection tests. G2 introduces no GPU, AD-rule, Reactant or MPI implementation; the new lowering paths are exercised by the passing local test file and supplied InterfaceII checks. G3 has no cache, threading or global-default change to assess. The separate no-test-regressions prerequisite remains unverified.

Not verified: local outer isolate_subsystem/substitute_component suites, full test groups, QA and documentation build; linked issue contents (no issue-*.json inputs were supplied). No failure logs or master comparison were available for any of the eight red checks in checks.txt: Documentation/build; SciMLBase/SymbolicIndexingInterface; SciMLSensitivity/Core8; MTKBase InterfaceI on Julia 1 and lts; MTKBase RegressionI on Julia 1 and lts; downgrade-mtkbase Optimization. The GitHub read attempt was blocked by the restricted environment; these failures are not established as pre-existing. Tracked repository files were left unchanged.

🤖 Posted by an AI agent — harness: Codex CLI 0.162.1 · model: gpt-6.1-sol
Conversation: Codex exec session 01a14b4f-a2c8-74e2-b3d8-aefb4de8ae5f (no public URL)

Codex CLI gpt-6.1-sol rated it medium-low (ML7: additive public API, with existing signatures/defaults preserved) at head e03411c

🤖 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 e03411c)

  • Risk: medium-high (MH1: Adds public connection API and changes System connection lowering, serialization and transformations across subsystems.)
  • Verdict: CHANGES
  • Session: 01a18da8-3a3a-7620-b234-342bf3d4309e
  • Blocking priorities: P2

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: Adds graph-based multiconnect networks across subsystem and array-variable connections. The submitted test files pass locally, but independent probes confirm causal unit validation and empty-network round-trip defects; the earlier cyclic-graph suspicion is withdrawn.

Blast radius: System connection expansion, DynamicQuantities validation, toexpr/write, component substitution and subsystem isolation.

Evidence: Julia 1.13.2: all 56 multiconnect assertions pass, isolate_subsystem passes 10 and substitute_component passes 22. The cyclic K3 D(v)=f probe passes through mtkcompile, so that earlier source-only blocker is removed. The independent causal-unit probe has 1 pass / 1 failure: ordinary metres-to-seconds connect is rejected, but the network validator returns true. Re-evaluating an empty-edge network expression throws MethodError because [] has Vector{Any} type. G2 is exercised locally for network construction, compilation, extraction and substitution; G1 uses explicit connection/flow expectations and the physical unit mismatch; G3 transformation/reuse tests run. Two confirmed blockers remain.

Blocking findings

  1. [P2] lib/ModelingToolkitBase/ext/MTKDynamicQuantitiesExt.jl:264 — confirmed by running: a metres-valued output connected to a seconds-valued input returns false under ordinary connect validation, while the equivalent multiconnect network validates true. The causal-edge continue bypasses the ordinary unit checks. Reuse causal-variable validation for every such edge and add matching/mismatched-unit regressions. This issue was independently identified before the embedded prior review.

  2. [P2] lib/ModelingToolkitBase/src/systems/abstractsystem.jl:2546 — confirmed by running: a valid ConnectionEdge[] network serializes as (ModelingToolkitBase.multiconnect)([a,b], []); evaluating it throws MethodError: no method matching multiconnect(::Vector{System}, ::Vector{Any}). Emit a typed empty ConnectionEdge vector and test actual evaluation of the round trip. This probe was prompted by the embedded prior same-head review and is now locally reproduced.

Non-blocking findings

None.

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/5117/head:refs/remotes/pr/5117 +refs/heads/master:refs/remotes/origin/master
git checkout --detach pr/5117
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 5117 --repo SciML/ModelingToolkit.jl --json number,url,state,isDraft,headRefOid,baseRefName,baseRefOid,title,files,commits,statusCheckRollup
gh pr view 5117 --repo SciML/ModelingToolkit.jl --json body,closingIssuesReferences
gh pr checks 5117 --repo SciML/ModelingToolkit.jl
gh issue view 341 --repo SciML/ModelingToolkit.jl --json number,title,body,state,url
gh issue view 2674 --repo SciML/ModelingToolkit.jl --json number,title,body,state,url
gh issue view 814 --repo SciML/ModelingToolkit.jl --json number,title,body,state,url
gh issue view 5118 --repo SciML/ModelingToolkit.jl --json number,title,body,state,url
gh issue view 5125 --repo SciML/ModelingToolkit.jl --json number,title,body,state,url
gh run view 38853544238 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 38853544285 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 38853544912 --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 38846662245 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 38846662285 --repo SciML/ModelingToolkit.jl --log-failed
gh run view 38894707737 --repo SciML/ModelingToolkit.jl --log-failed
gh run view --repo SciML/ModelingToolkit.jl --job 116852179033 --log

CI check rollup at the captured head: {"CANCELLED": 1, "FAILURE": 7, "SKIPPED": 3, "SUCCESS": 100}. 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.

CI MTKBase InterfaceII reports Multiconnect Test 56/56 and package tests passed. Python Fraction elimination independently finds rank 2 for the three K3 potential-equality rows (exit 0); this is a mathematical check, not a Julia integration test. Failed docs/SII/Core8 and Parsing/Latexify signatures were compared with historical master 38846662245/38846662285 and 38894707737 where logs exist; the latter supplied no usable matching failure output, so all sublibrary failures are not established as pre-existing.

Inspected CI URLs: https://github.com/SciML/ModelingToolkit.jl/actions/runs/38853544238, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38853544285, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38853544912, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38853544912/job/116852179033, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38846662245, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38846662285, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38894707737.

A separate Python 3 Fraction Gaussian-elimination calculation on rows [1,-1,0], [1,0,-1], [0,1,-1] exited 0 and reported rank 2 for 3 rows; structural counts are 7 equations/6 unknowns with all K3 equalities, versus 6/6 with a spanning tree. This does not execute ModelingToolkit.

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-5117: detached e03411c266a2b9a025c497d886c8303c646e53af (pr/5117), process exit 1, 296.68 s.

git -C ModelingToolkit.jl checkout --detach pr/5117
REVIEW_ENV_DIR=tmp/rerun/env-extra \
REVIEW_CASES='5117,5117-contract-0,5117-contract-1,5117-serialization,5117-isolate_subsystem,5117-substitute_component' \
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

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 9.33.1, NonlinearSolve 4.32.0, ModelingToolkit 11.45.4, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.77.4, OptimizationBase 5.10.0.

Included unchanged head files lib/ModelingToolkitBase/test/multiconnect.jl, test/isolate_subsystem.jl and test/substitute_component.jl: 56, 10 and 22 assertions pass, respectively. The real cyclic acausal graph probe passes 1/1 and mtkcompile completes; the earlier rational-rank/source-only concern is therefore withdrawn rather than presented as a confirmed package failure.

Independent probe output:

Causal connection unit contract | 1 pass 1 fail
ordinary connect validator=false; network validator=true
SERIALIZED_EMPTY_NETWORK=(ModelingToolkitBase.multiconnect)([a,b], [])
MethodError: no method matching multiconnect(::Vector{System}, ::Vector{Any})
FAILED_CASES=5117-contract-1,5117-serialization

The process exits 1 for these two confirmed contract failures. The added cyclic, extraction and substitution paths were actually executed and passed.

Exact reviewer script 5117-contract-0.jl:

using ModelingToolkit, ModelingToolkitBase, Symbolics, DynamicQuantities, Graphs, Test
using ModelingToolkit: t_nounits as t, D_nounits as D
@testset "Cyclic acausal connection contract" begin
 @variables v(t)[1:3] f(t)[1:3] [connect=Flow]
 eqs=[D(v[i]) ~ f[i] for i in 1:3]
 append!(eqs,multiconnect((v,f)=>(v,f),complete_graph(3)))
 raw=System(eqs,t,collect([v...;f...]),[];name=:cyclic_net)
 @test_nowarn mtkcompile(raw)
end

Exact reviewer script 5117-contract-1.jl:

using ModelingToolkit, ModelingToolkitBase, Symbolics, DynamicQuantities, Graphs, Test
using ModelingToolkit: t_nounits as t, D_nounits as D
@testset "Causal connection unit contract" begin
 @variables y(t) [output=true,unit=u"m"] x(t) [input=true,unit=u"s"]
 @named a=System(Equation[],t,[y],[])
 @named b=System(Equation[],t,[x],[])
 @test !ModelingToolkitBase.validate(connect(a.y,b.x))
 @test !ModelingToolkitBase.validate(multiconnect([a,b],[ConnectionEdge(1,2,:y,:x)]))
end

Exact reviewer script 5117-serialization.jl:

using ModelingToolkit, ModelingToolkitBase, Symbolics, Test
using ModelingToolkit: t_nounits as t
@variables y(t) [output=true] x(t) [input=true]
@named a=System(Equation[],t,[y],[])
@named b=System(Equation[],t,[x],[])
@testset "Empty edge network serialization contract" begin
 eq=multiconnect([a,b],ConnectionEdge[])
 expr=ModelingToolkitBase.round_trip_eq(eq,Dict())
 println("SERIALIZED_EMPTY_NETWORK=",expr)
 @test Core.eval(@__MODULE__,expr) isa Equation
end

What I did not verify

No whole suite, GPU, Reactant, MPI or exhaustive graph/topology matrix was run. The specific K3 cyclic probe passes and does not support the first-round blocker; it does not prove every cyclic topology valid. The two retained blockers are direct runtime observations. Numerical equivalence beyond the submitted connected-model tests was not exhaustively benchmarked. 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. The first-round embedded prior review was encountered after preliminary source/risk assessment but before the full findings freeze; that historical comparison was not fully blind. This execution rerun does not claim a new blind assessment.

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

ChrisRackauckas and others added 3 commits September 12, 2026 10:27
Adds a graph primitive for connections between repeated instantiations of
component subsystems, analogous to `connect` but operating on an array of
nodes with labeled edges (motivated by SciML#341).

Two forms:

- `multiconnect(nodes, edges)` / `multiconnect(nodes, g, portmap)` builds a
  single `Connection` equation whose payload is a `ConnectionNetwork` (node
  systems + `ConnectionEdge`s). Lowering expands each edge through the
  existing connection-set machinery, so acausal connector ports and causal
  input/output variable ports behave exactly like the corresponding
  `connect`s, and multi-edge ports merge into single connection sets. The
  stored representation is O(1) in graph size until `expand_connections`.
- `multiconnect(portspec::Pair, g)` targets per-node array variables: it
  encodes the edge list in sparse selection matrices and emits compact
  equations (`Ps * a ~ Pd * b` for equality variables, one conservation
  equation per flow net), so the symbolic representation does not grow with
  the number of edges.

Also fixes several connection-equation consumers that tested
`eq.lhs isa Connection` even though equation sides are wrapped symbolic
values, so those branches were dead. They now unwrap with `value(...)`,
which makes `toexpr` serialization, `change_independent_variable`,
`substitute_component`'s `recreate_connections`, and the equation
display/`n_expanded_connection_equations` counters handle connections - and
the new network payload - correctly.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.10.21
Agent-Model: SWE-2 Max
Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_dc407dd7a55247ee.md (local transcript summary; no shareable URL)
Pure formatting of the files added or touched by the multiconnect change; no
semantic change. Fixes the Runic check that failed on the first push.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Agent-Harness: Claude Code 2.1.269
Agent-Model: claude-fable-5-1
Agent-Session: https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ
Claude-Session: https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ
…ports

The downgrade job resolves a Symbolics version that does not export `unwrap`,
so the test file imports it explicitly. `multiconnect`, `ConnectionEdge` and
`ConnectionNetwork` are documented exports of ModelingToolkitBase, so they are
added to the QA reexport audit list.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Agent-Harness: Claude Code 2.1.269
Agent-Model: claude-fable-5-1
Agent-Session: https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ
Claude-Session: https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ
…isolate_subsystem

Every consumer of a `Connection` payload iterated `get_systems(rhs)` as a
vector, so a `ConnectionNetwork` crashed with
`MethodError: no method matching iterate(::ConnectionNetwork)` in the
DynamicQuantities unit checker (any unit-carrying model containing a
`multiconnect`) and in `isolate_subsystem`.

`network_edge_ports(net)` is the single place a network is resolved to its
`(src_port, dst_port)` pairs, typed `Union{System, SymbolicT}` per port. The
connection-set lowering, the unit checker and `isolate_subsystem` all use it.
Unit checking validates each connector-port edge like the pairwise `connect` it
stands for; variable-port edges are skipped because pairwise variable
`connect` already crashes the checker (SciML#5118). `isolate_subsystem` adds one
graph edge per network edge and, on reconstruction, restricts a network to the
edges whose endpoints are inside the isolated region.

The port type is declared explicitly because letting it be inferred from
`getproperty(::System, ::Symbol)` sent inference into a cascade that never
finished at the first `System` construction after loading DynamicQuantities.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Agent-Harness: Claude Code 2.1.269
Agent-Model: claude-fable-5-1
Agent-Session: https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ
Claude-Session: https://claude.ai/code/session_01ReTWnXHfsN2gZziNYQaCAQ
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.3 (conflict resolution), Claude Code 2.1.285 (orchestration)
Agent-Model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Agent-Session: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master); Devin log /Users/chrisrackauckas/sandbox/master/fusion-fixes/SciML_ModelingToolkit.jl-5117/log.txt

# Conflicts:
#	lib/ModelingToolkitBase/ext/MTKDynamicQuantitiesExt.jl
#	test/qa/qa.jl
@ChrisRackauckas

Copy link
Copy Markdown
Member

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

Merged the default branch into this PR to resolve conflicts (head 25235f8). Re-review the resolution before merging.

Conflict resolution report

STATUS: RESOLVED

Merge of origin/master (37d63bc) into multiconnect-graph-connections (PR #5117), committed as 25235f8 with the prepared merge message and trailers. No follow-up commit was needed. Nothing was pushed.

Conflicting files

lib/ModelingToolkitBase/ext/MTKDynamicQuantitiesExt.jl

  • PR: MTK._validate(::Connection) gained a ConnectionNetwork branch that unit-checks each connector-port edge through a new helper, _validate_connected(syss), and skips variable-port edges.
  • master (d2c0ca3, the fix for Unit validation crashes on causal variable connect: unknowns(::BasicSymbolic) MethodError in MTKDynamicQuantitiesExt #5118): added an is_causal_variable_connection(conn) branch that compares units on the variables of a causal connect(a.y, b.u).
  • Resolution: MTK._validate(conn) checks the network branch first (PR), then master's causal-variable branch (now with its own local valid = true), and otherwise calls _validate_connected(syss; info) (PR). Behaviour is unchanged on both sides: variable-port edges of a network are still skipped, as the PR does. The PR's inline comment said pairwise variable connect is not unit-checked either. Master made that false, so the comment now reads "variable-port edges of a network are not unit-checked". Follow-up for the PR author: now that master validates pairwise variable connects, the network branch could validate variable-port edges too. I left that out because it would change behaviour.

test/qa/qa.jl

  • REEXPORTED_API line: kept both the PR's :ConnectionEdge, :ConnectionNetwork and master's :constraint_residual. Everything else master added there merged cleanly.

Formatting

julia +1.12 --project=@runic -m Runic -i lib/ModelingToolkitBase/ext/MTKDynamicQuantitiesExt.jl test/qa/qa.jl: exit 0, no further changes.

Tests (Julia 1.12, run one at a time; logs in ../scratch/)

  • julia --project -e 'using Pkg; Pkg.instantiate()' (repo root): OK.
  • lib/ModelingToolkitBase/test/multiconnect.jl: run in the scratch env scratch/env_mtkbase, which devs lib/ModelingToolkitBase and adds the test deps (OrdinaryDiffEqRosenbrock, OrdinaryDiffEqNonlinearSolve, Symbolics, SymbolicUtils, Graphs, DynamicQuantities, SciMLBase, SafeTestsets, Test). Result: 56 pass / 0 fail / 0 error across 11 testsets, the same 56 the PR reports. This includes "Unit validation of networks" 5/5, which runs the merged ext code. Log: scratch/multiconnect.log
  • test/isolate_subsystem.jl: run in scratch/env_mtk (devs repo root, lib/ModelingToolkitBase, lib/SciCompDSL; adds ModelingToolkitStandardLibrary, OrdinaryDiffEq, SafeTestsets, Test). Result: 10 pass / 0 fail / 0 error. Log: scratch/isolate_subsystem.log
  • test/substitute_component.jl (scratch/env_mtk): 22 pass / 0 fail / 0 error. Log: scratch/substitute_component.log
  • test/qa/qa.jl (julia --project=test/qa): 40 pass / 0 fail / 0 error. Log: scratch/qa.log
  • Smoke check of master's causal-variable unit fix after the merge, scratch/smoke_validate_units.jl (scratch/env_mtkbase): validate(connect(a.y, b.u)) returns true when the units match (m/m), and returns false with a "mismatched units" warning when they differ (m/s).

All Julia processes started by this run have exited.

Links


🤖 Posted by an AI agent — harness: Devin CLI 3000.11.3 (merge), 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)

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.

2 participants