Skip to content

fix isinplace inference and add inference tests - #1019

Open
oscardssmith wants to merge 4 commits into
SciML:masterfrom
oscardssmith:os/fix-isinplace-stability
Open

oscardssmith wants to merge 4 commits into
SciML:masterfrom
oscardssmith:os/fix-isinplace-stability

Conversation

@oscardssmith

@oscardssmith oscardssmith commented May 12, 2025 •

Copy link
Copy Markdown
Member

fixes #1017
This also removes NoMethodsError, TooManyArgumentsError, and TooFewArgumentsError and fixes inference for some *Function constructors`

Comment thread src/scimlfunctions.jl Resolved
Comment thread src/utils.jl
hasmethod(f, ntuple(_->Any, outofplace_param_number)) && return false
hasmethod(f, ntuple(_->Any, inplace_param_number)) && return true
end
throw(FunctionArgumentsError(fname, f))

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.

This error message loses a lot of information. Can we in the error path do a method check and throw the more informative error message?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

IMO the better method is to just put the expected nargs in the exception and then we can make the exception printing in charge of that logic. That way none of the complicated bits are in the main function.

@oscardssmith

Copy link
Copy Markdown
Member Author

I just remembered the tricky part here. This query isn't quite right (see JuliaLang/julia#56279 for details):

julia> f(a::Int, b) = true
f (generic function with 1 method)

julia> hasmethod(f, (Any, Any))
false # because !(Any<:Int)

@ChrisRackauckas

Copy link
Copy Markdown
Member

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

PR: #1019

Reviewed head: 6f7e8c6
Raw SHA-256: 95fdebebb3052bb876bfd56ca889e2759f00bfdc8b6f9bb563228b293a51a51b
Source SHA-256: 5c4e4f14d1b651af6e4e5a2176f89d391cd93b15ad42bd8b64346848d37b2fbf
Source: operator-attested-codex-v1 (runner attested by pankgeorg)
Reviewer session: 01a224e5-6c65-7620-b646-c77b9e81737c
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: high (H1)
  • Verdict: CHANGES
  • Reviewed head: 6f7e8c6

Review report

VERDICT: CHANGES
PR: #1019
Head: 6f7e8c6
Base: 80e6ea5
Reviewer: codex-cli 0.172.0 / gpt-6.2-sol
Session: 01a224e5-6c65-7620-b646-c77b9e81737c

Risk

high (H1: the exported isinplace API and common problem constructors reject previously valid callbacks or select the wrong calling convention.)

This affects users constructing ODEs, other SciML problems, and optimization objectives from typed, generated, composed, partial, or foreign-language callbacks. The classification feeds common solve and init paths through the problem type. I reproduced the failure with a runtime-generated callback of the kind used by modeling tools. The diff changes callback selection, with no edit to default solver selection. The BVP Jacobian changes affect users who supply operator prototypes.

Blocking findings

  • P1 · src/utils.jl:101 — Typed callbacks are rejected or classified incorrectly. With f(u::Float64, p::Nothing, t::Float64) = -u, the concrete call f(2.0, nothing, 0.0) returns -2.0. methods(f, Tuple{Any,Any,Any}) finds one method, while hasmethod(f, Tuple{Any,Any,Any}) is false. A genuinely invalid g(u,t) = -u has no matching three-argument method and applicable(g, 2.0, nothing, 0.0) is false. The head throws FunctionArgumentsError for both. The base constructs the typed ODE, and it also selects the preferred four-argument method when that method is typed and the three-argument method is generic. The head selects the generic three-argument method in that mixed case. Change isinplace to check for matching methods at the preferred arity before falling back to the other arity. Keep the constant-foldable probe where it preserves that order. Assert that typed out-of-place and in-place constructors work, the mixed table honors preference, and the wrong-arity control still throws. The same fix must preserve typed objectives, which returned 4.0 through OptimizationProblem on the base and were rejected on the head.
  • P1 · src/utils.jl:105 — Forwarding methods hide the underlying arity. A three-argument composed callback, RuntimeGeneratedFunction, PythonCall callback, and PartialFunction all changed from out-of-place to in-place. The composed callback threw MethodError under the selected convention and PythonCall raised PyException. The generated RHS was silent: for u = [2.0], the base returned [-2.0], while invoking the head’s selected in-place path left du = [1.0] untouched. Restore wrapper-specific arity handling in isinplace before the generic method-table probe. Assert the mode and actual derivative for each wrapper. The existing PartialFunctions test checks numargs alone and passed on both snapshots.
  • P2 · src/utils.jl:102, src/scimlfunctions.jl:4230, src/scimlfunctions.jl:4286 — Single-signature validation is bypassed. has_two_dispatches=false now accepts a callback at the alternate arity. OptimizationFunction{true} and MultiObjectiveOptimizationFunction{true} accepted unary objectives that the base rejected, even though their convenience constructors rejected the same inputs. Honor has_two_dispatches=false inside isinplace and validate the two-argument objective once in each parameterized constructor. Assert that both constructor forms reject unary and ternary objectives and accept a valid two-argument objective.
  • P2 · src/utils.jl:59 — Exception aliases break qualified callers. The old one-argument NoMethodsError and three-argument TooFewArgumentsError constructors now throw MethodError, and the three old exception types can no longer be distinguished in a catch. Keep the distinct types and their constructors in the isinplace error paths, or make consolidation a separately documented compatibility change. I recommend preserving them here. Assert the old constructor signatures and their distinct error cases.
  • P2 · src/scimlfunctions.jl:4343, src/scimlfunctions.jl:4521, src/scimlfunctions.jl:4530 — Retire the BVP prototype hoists. Both snapshots throw UndefVarError for iip_f or iip_bc before reaching the changed closures. Executing the extracted closures with MatrixOperator returned nothing on both snapshots. With a test operator that returns itself, the head reused the same object and overwrote the first result. The dynamical boundary closure also copied the interior prototype and produced 7 where the boundary coefficient should be 35. Revert the hoists in BVPFunction and DynamicalBVPFunction. A separate repair should use the resolved callback modes, the proper Jacobian arities, and independently owned out-of-place results. Assert that each constructor works with only a boundary prototype, returns the analytical Jacobian at two inputs, and leaves the first result and original prototype unchanged after the second call.

Nonblocking findings

  • src/utils.jl:101 — Compiler inference still depends on which values are known. @inferred staticval(oop) with staticval(f) = Val(isinplace(f,4)) failed on the base and passed on the head. With a runtime n::Int, Val(isinplace(f,n)) still inferred only Val, even though valid calls returned Val{false}() at n=4 and Val{true}() at n=3. Runtime preference and a callback stored in a Function field showed the same loss of precision. The valid concrete calls and the method-table control above distinguish compiler inference from invalid dispatch. Keep the static inference tests and use an explicit mode or a type-level arity where a caller already knows it.
  • test/function_building_error_messages.jl:241, test/function_building_error_messages.jl:376 — Two strengthened tests miss their stated cases. Give friip the five-argument RODE signature and assert the in-place flag and mutation. Pass ddeWfact_t to the DDE constructor and assert that the supplied callback is stored. The new @inferred checks compare compiler inference with the actual runtime type, so they cannot independently establish that the selected mode is correct. The exception assertions lost specificity, but I found no new skips or weakened numerical tolerances. The Aqua ambiguity limit was preserved.

What I ran

  • git apply --stat changes.diff, git apply --check --directory=before changes.diff, and diff -qr before head identified five changed files and confirmed that the patch applies. The workspace has no separate target/ snapshot. Both check lists in ci.json:1 are empty.
  • On ARM64, I resolved cached dependencies offline with Pkg.instantiate(; update_registry=false) in temporary projects and ran Julia 1.10.14 against each snapshot’s test/function_building_error_messages.jl and test/aqua.jl. Both passed. The first Aqua run failed dependency checks because I had added test dependencies directly to the temporary package project. Both passed with Aqua on an overlay and the original package dependencies active.
  • I ran .julia-scratch/review-probes.jl and .julia-scratch/review-extension-probes.jl against both temporary projects, plus test/downstream/partial_functions.jl on both snapshots. The targeted probes reproduced the constructor, wrapper, exception, and Jacobian outcomes above. A standalone Julia 1.13.4 probe of the extracted isinplace source passed 19 assertions after I corrected the expected baseline classification for typed varargs.
  • G1 and G3. An independent RK4 loop using the constructed ODE callback for (u'=-u,\ u(0)=2) gave errors of 6.66e-7, 4.00e-8, and 2.45e-9 at (t=1) against (2e^{-1}) with 10, 20, and 40 steps on both snapshots for the generic callback. The typed callback gave the same errors on the base and was rejected on the head. In the two-call BVP closure probe, the base kept the distinct boundary coefficients 15 and 35. On the head the first result was overwritten, and the dynamical boundary closure ended at 7.

What I did not verify

  • End-to-end BVP accuracy and convergence through the changed operator constructor are unverified. Both snapshots fail before reaching the callback. To establish G1 and G3, run the analytical Jacobian and two-call ownership assertions through both public constructors, then solve a BVP with a known solution using both explicit and generated Jacobians.
  • I did not run the full downstream suite, ModelingToolkit compilation, the full Python integration suite, or the RCall and PyCall extensions. Exact-head runs of those integrations would establish coverage beyond the local callback probes. I found no before/after timings or allocation measurements for the constructor or BVP changes.
  • I ran no GPU-only paths on ARM64. The diff changes no GPU kernel, AD rule, Reactant path, or MPI path, so G2 does not apply to the edited code. The supplied CI record provides no device-specific coverage evidence.

Head link: 6f7e8c6


🤖 Posted by an AI agent — harness: codex-cli 0.172.0 · model: gpt-6.2-sol
Conversation: local session 01a224e5-6c65-7620-b646-c77b9e81737c (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.

isinplace fails to infer on v1.10+

2 participants