Skip to content

Fix callback normalization and solver compatibility across Julia versions - #4593

Open
xbtmkmmm5 wants to merge 19 commits into
SciML:masterfrom
xbtmkmmm5:fix/downgrade-callbacks-scalar-mass
Open

xbtmkmmm5 wants to merge 19 commits into
SciML:masterfrom
xbtmkmmm5:fix/downgrade-callbacks-scalar-mass

Conversation

@xbtmkmmm5

@xbtmkmmm5 xbtmkmmm5 commented Sep 22, 2026 •

Copy link
Copy Markdown

This fixes callback and solver compatibility failures exposed by the full OrdinaryDiffEq CI matrix. Callback normalization requires an explicit integrator opt-in, preserving type-erased callbacks for other SciML solvers and older OrdinaryDiffEqCore releases. The trait is documented in the public API.

The solver changes preserve scalar and UniformScaling mass matrices, retain propagated DelayDiffEq discontinuities, and prevent floating-point clock alignment from resetting QNDF's constant-step history. The focused QNDF change is also available in #4651. NonlinearSolve and SDIRK use consistent local sources for normal and downgrade testing, including the upstream PDIRK test dependency. The Dependabot caller grants the read permissions required by the shared workflow.

Numerical corrections:

  • Newton backtracking uses a centered merit-function difference at a scale appropriate for floating-point evaluation.
  • Two DIRK residual expressions preserve fused multiply-add evaluation.
  • SDIRK masks unconstrained algebraic components of an explicit first stage before smoothing the embedded error estimate.
  • NonlinearSolveAlg checks the actual residual before accepting a stationary inner cache; the two-argument _uninformative_step contract is preserved.
  • GeneralizedDFSane receives no Jacobian-recomputation control, avoiding hundreds of thousands of repeated warnings from a derivative-free solver.
  • NLNewton's linear cache uses the existing _inner_lintol absolute tolerance (eps(T)^(4/5)). This resolves small Newton residuals below LinearSolve's default sqrt(eps) floor while retaining the finite round-off allowance needed by fixed-step Krylov solves. Relative-tolerance propagation and explicit warm-start choices remain unchanged.

Current head: be0e88d87a01de16216ae64b2433a35d8470ba82. No test assertions, tolerances, test files, or skip conditions are changed by this PR. The SDIRK time-normalization experiments used during diagnosis are not included.

Validation of the final tolerance correction:

  • Linux Julia 1.10.12 and 1.13.1: both jobs succeed, 36 original assertions each: round-off regression 6, Krylov tolerance 8, warm-start defaults 7, split-ODE linear solvers 10, and preconditioners 5.
  • All four minimum-dependency nonlinear Core shards succeed: 1,019 passing assertions and 40 existing broken cases across all 29 original files. This includes the previously failing SBDF2/SBDF3 MatrixOperator cases. LinearSolve remains 5.15.0; only the companion SimpleNonlinearSolve fix uses candidate source.
  • The 1,471 tracked production/test files used by those Linux validations are byte-identical to this head. The validation branches only add their own runners/workflows.
  • Local original InterfaceIII derivative-utility tests pass 11/11. Original ExponentialRK linear/nonlinear convergence tests pass 46 assertions with 2 existing broken cases; the isolated environment preserves LinearSolve 5.15.0 and the previously resolved versions. Runic and git diff --check pass. The original BDF convergence file is still running in an isolated environment with Enzyme 0.13.180 and compatible FunctionWrappersWrappers 1.10.1.
  • Formal PR CI is running on this head. The candidate dependency validations above do not replace formal CI or establish that every job is green.

Latest upstream master also introduced #4653, which rejects Rosenbrock32 with a singular mass matrix. The existing inference QA still attempts that unsupported combination and fails before its inference assertion; its expected behavior needs to be aligned with the new contract. This PR has not changed that QA file.

Completed results on the preceding 728b0df head:

  • Formal implicit Taylor Core, QA, and downgrade succeeded; Core 4/4 in 20.9s and downgrade 4/4 in 38.8s. Formal Regression II passed on both Julia versions. The two Regression I failures motivated the Newton change above.
  • With the candidate SimpleNonlinearSolve correction, all eight full Core jobs passed all 29 original files: 1,017 passing assertions on LTS and 1,019 on current Julia, with 40 existing broken cases each.
  • All four minimum-version jobs passed: 1,019 assertions and 40 existing broken cases. Preparation preserved all 188 resolved versions from the downgrade action's Manifest, including registered NonlinearSolve 4.25.0, NonlinearSolveBase 2.45.0 and LinearSolve 5.15.0; only SimpleNonlinearSolve used candidate source.

Formal CI still needs companion dependency fixes:

  • NonlinearSolve #1339 corrects the missing Cauchy-point curvature scale in SimpleTrustRegion. Registered SimpleNonlinearSolve 2.14.5 and minimum 2.11.1 fail the original rober-mm iip no-init case with MaxIters. The latest formal LTS job reproduced the same failure at 728b0df. This needs a registered release, then the compatibility floor must be raised to the actual fixed version.
  • SciMLSensitivity #1682 fixes empty CallbackSet backend selection. Downstream CI checks out its default branch, so merging that correction is sufficient for that path.
  • Mooncake #1343 fixes abstract-Any/NamedTuple tangent construction and needs a published release. With both downstream fixes and 728b0df, both Core1 and Core5 pass.

The dependency PRs remain open. This PR does not pin personal forks or declare future release numbers. Passing candidate dependency validations does not make formal CI green; queued self-hosted GPU jobs also require available runners.

@xbtmkmmm5
xbtmkmmm5 marked this pull request as ready for review September 23, 2026 02:47
@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated review from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris. It is posted so that you can act on it. Chris or a maintainer may disagree.

Verdict: changes needed before merge (reviewed at 0b2c851).

Fixes Julia 1.11 callback normalization and scalar/time-varying mass-matrix handling in SDIRK; the existing targeted regressions fail on the base and pass on the head. Request changes because upgrading DiffEqBase while retaining released OrdinaryDiffEqCore 4.18.0 breaks ordinary callback solves in a combination permitted by the package bounds.

Risk assessment

  • Risk: medium
  • Blast radius: Julia 1.11 users with nonempty callbacks and default AutoSpecialize whose environment updates DiffEqBase without the matching OrdinaryDiffEqCore changes.
  • Evidence: Read the full diff, description, comments and reviews; there are no comments/reviews or directly linked closing issues, so no other maintainer is already reviewing. Also read the related scalar-matrix issue. Local Julia 1.11.9 results follow; base is merge-base 61f52b3be9e2451cdd66cbd6aa1e29ce0f42eddd, head is 0b2c851da9f7a8405c349b90273efcfb27a9b1fa.
    • Included unchanged lib/DiffEqBase/test/callbacks.jl and problem_kwargs_merging.jl: base 57 passed, 5 errors; head 62 passed. Base errors include missing callback and continuous_callbacks fields.
    • Included unchanged lib/OrdinaryDiffEqDifferentiation/test/scalar_operator_massmatrix_tests.jl: base 5 passed, 1 error, MethodError: no method matching diag(::ScalarOperator...); head 9 passed, including the time-varying scalar case.
    • The callback reproducer below returns Success and [0.3678794264102952] with all-base and all-head packages. PR DiffEqBase with released Core 4.18.0 throws a CallbackSet conversion error during initialization. PR DiffEqBase with base Core also fails identically.
    • Ran GROUP=Core julia +1.11 --compiled-modules=existing --project=envs/review-pr -e 'using Pkg; Pkg.test("DiffEqBase"; julia_args=["--compiled-modules=existing", "--check-bounds=yes"], allow_reresolve=false)'. It failed in unchanged forwarddiff_dual_detection.jl: that testset reported 338 passed, 2 failed, 15 errors, 9 broken, including ArgumentError: type does not have a definite number of fields. This broader local failure was not independently baselined and is not attributed to this PR; later testsets did not run.
    • Local Runic --check --diff passed for every changed Julia file. No tests, tolerances or workflows are changed. Added SciMLOperators imports are exported and its license is MIT; has_callbacks has its public declaration, docstring and docs entry.
  • Merge: needs changes (preserve or enforce the DiffEqBase/Core compatibility boundary in finding 1).

Head CI versus current default-branch run at 4e8d61f (logs read):

Failing head check Comparison
sublibrary-ci / lib/OrdinaryDiffEqBDF [QA] / Julia 1 / Tests - QA (Julia 1) Both have 17 JET failures, including runtime dispatch through _despecialize_callback.
sublibrary-ci / lib/OrdinaryDiffEqNonlinearSolve / Julia 1 / Tests - Core (Julia 1) Both have three Trapezoid diagonal-mass-matrix restriction errors; 205 pass, 3 errors, 40 broken.
SciMLSensitivity.jl/Core1/1 / Downstream Tests - Core1 Both fail the MooncakeAdjoint test at concrete_solve_derivatives.jl:451, with MethodError: no constructors have been defined for Any.
ProbNumDiffEq.jl/Downstream/1 / Downstream Tests - Downstream Head fails likelihood comparisons at lines 24 and 25; current master passes. An earlier unrelated PR run already failed line 24, but not line 25. The author's claimed base reproduction of both was not independently rerun.

Head DiffEqBase/SDIRK/GlobalDiffEq Core and QA, relevant downgrade jobs, AD lanes, documentation and Runic checks report success. These all-head checks do not cover the incompatible mixed-version pairing.

Findings

  1. [P1] lib/DiffEqBase/src/callbacks.jl:100 — typed callback normalization breaks compatible released Core versions. On Julia 1.11 this branch returns typed vectors. Released OrdinaryDiffEqCore 4.18.0 subsequently assigns a CallbackSet{Vector{Any},Vector{Any}} in _despecialize_callbacks! to an options field parameterized by those typed vectors, throwing MethodError: Cannot convert ... CallbackSet{Array{Any,1},Array{Any,1}} .... Its DiffEqBase = "7.21.2" compatibility allows the PR's version and subsequent 7.x updates. The guard added at lib/OrdinaryDiffEqCore/src/solve.jl:86 fixes only installations using the new Core; there is no package-version boundary excluding older Core. Preserve compatibility through an opt-in/negotiated normalization path, or introduce an effective version/registry compatibility boundary before shipping this behavior. Merely raising the new Core's DiffEqBase lower bound does not exclude old Core with new DiffEqBase. Add a mixed-version regression test.

    Reproducer, run with PR DiffEqBase and released Core 4.18.0 on Julia 1.11.9:

    using OrdinaryDiffEqTsit5, DiffEqBase, SciMLBase
    f!(du, u, p, t) = (du .= -u)
    cb = ContinuousCallback((u, t, i) -> u[1] - 0.5, i -> nothing)
    solve(ODEProblem(f!, [1.0], (0.0, 1.0)), Tsit5(); callback = cb)

Local evidence is under the supplied scratch directory in tmp/review-*.log; reproducible environments are in envs/. GitHub was read-only and both source worktrees remain clean.

AI-generated review. Harness: Codex CLI (Mac) 0.156.1 · Model: gpt-6-astra.
Conversation: local session ID 01a0dd94-d8d0-7812-bf5e-bd7149e70254 (no conversation URL supplied).

Push a fix and the PR is reviewed again automatically at the new head.


🤖 Posted by an AI agent — harness: Claude Code · model: claude-opus-5-5[1m] (fleet master); review by Codex CLI (Mac) 0.156.1 / gpt-6-astra
Conversation: local Claude Code session 3cd6500a-1f81-46b5-ac0b-c466e15b6a53 on Chris's Mac (session ID, no URL)

苗可明 and others added 3 commits September 26, 2026 18:58
Require solver opt-in for typed callback vectors on older Julia and retain tuples for released Core versions. Propagate the selected algorithm through solve, init, and sensitivity callback normalization.
@xbtmkmmm5 xbtmkmmm5 changed the title Fix Julia 1.11 callback normalization and SDIRK scalar mass matrices Fix callback normalization and solver compatibility across Julia versions Sep 27, 2026
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

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

PR: #4593

Reviewed head: be0e88d
Raw SHA-256: 35e4e3e3a4f4a8c81dc36ea67f40ed961f87b6d99dd538e72d466badff3ceb4d
Source SHA-256: d0e3bfc61dcb1d37fc4cce090abc7cf4298f70da4245f684bbec0caf59cda805
Source: standard-review-v1 (harness-log)
Reviewer session: 01a2165b-fa64-7541-8c99-c92ac6bf3a65
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: high (H6)
  • Verdict: CHANGES
  • Reviewed head: be0e88d

Review report

VERDICT: CHANGES
Round: 1
Head: be0e88d
Slot: 1
CI: CI is not green
Session: 01a2165b-fa64-7541-8c99-c92ac6bf3a65
Reviewer: codex-cli 0.170.0; model: gpt-6.2-sol

Risk

high (H6: .github/workflows/DependabotAutoMerge.yml grants checks: read and statuses: read to the token used by the reusable Dependabot auto-merge workflow. An explicit owner decision is required for this privilege change.)

Blocking findings

  • Blocking priorities: P1, P1, P1, P1, P1, P2, P2, P2

  • [P1] lib/OrdinaryDiffEqCore/src/integrators/integrator_utils.jl:1225 lets QNDF integrate a different interval from the one recorded by the clock. I ran eight adaptive step! calls for u′ = 1 with QNDF1 and QNDF2, t₀ = 2^40 + 4, initial dt = 8eps(t₀), IController(qmin=0.2, qmax=1.3, qmax_first_step=1.3), and both tolerances at 1e-8. In both time directions the head's maximum |u − (t − t₀)| was 3.26486e-4, versus at most 6.94e-18 on the merge base. The check uses interior accepted steps, away from endpoint snapping.

    Implementation fix Restore clock alignment in calc_dt_propose!. Handle roundoff-scale proposals in the QNDF step controller and history updates in lib/OrdinaryDiffEqBDF/src/controllers.jl and bdf_perform_step.jl, using the effective step size for the state update and difference history. The shared Core check also reaches composite algorithms. Add the forward and backward constant-RHS case to lib/OrdinaryDiffEqBDF/test/bdf_convergence_tests.jl and assert u ≈ t − t₀ at each accepted step to the requested tolerance.

  • [P1] lib/OrdinaryDiffEqSDIRK/src/generic_imex_perform_step.jl:1319 and :2383 lose dense accuracy on algebraic variables. For M = Diagonal([1, 0]) and f = [1, sin(8t) − y] on [0, 4], KenCarp3 returned Success with three saved states and peak dense error 1.5197 in y at abstol = reltol = 1e-6. The merge base used 231 saved states and had peak dense error 0.007574 in the out-of-place run. The in-place run reproduced the regression. The head met the constraint at saved states to roundoff, so tests confined to those states miss the error.

    Implementation fix In both _perform_step_iip! and _perform_step_oop!, keep the embedded estimate for differential rows and add an algebraic control term based on solved states. One design is to compare the trial dense state with the already solved algebraic state at an interior stage and scale the difference by the state tolerances. Check the ROBER mass-matrix case with TRBDF2 and SimpleNewtonRaphson reaches t = 0.1, since the merge-base estimator exhausted maxiters there. Add the sine DAE in both modes to lib/OrdinaryDiffEqSDIRK/test/dae_esdirk_test.jl and require |y(t) − sin(8t)| < 1/8 between steps, the linear interpolation error bound for a sine advancing by at most one radian per interval.

  • [P1] test/Regression_I/newton_krylov_roundoff.jl:70 fails for Hairer42 in a standalone invocation. With Julia's default bounds setting and the test environment, both solves returned successfully, but the one-ULP perturbation produced drift 1.0358477493560558e-5, above the existing 1e-5 bound. A replay on the head reproduced the failure. The same replay passed all three Hairer42 assertions on the merge base, with LinearSolve 5.19.0 and Krylov 0.10.12 on both trees. Hairer4 passed on both. The official Regression_I group passed all six roundoff assertions, so the failure depends on how the test runs.

    Implementation fix Restore the affected in-place NLNewton residual in _compute_rhs! in lib/OrdinaryDiffEqNonlinearSolve/src/newton.jl and the adaptive Krylov setup in build_nlsolver in lib/OrdinaryDiffEqNonlinearSolve/src/utils.jl to the base behavior. Reapply and test the residual and linear-tolerance changes independently to isolate the culprit before shipping either on this path. Keep the existing drift assertion and add a companion check against the analytic linear DAE trajectory for each of the two runs. For the unperturbed input the differential components are exp(-t) and 3exp(-t/2) - 2exp(-t), and the algebraic components are their sum and signed difference.

  • [P1] lib/DiffEqBase/src/callbacks.jl:126 regresses Enzyme differentiation through heterogeneous callbacks on Julia 1.10.12. In the existing bouncing-ball scenario, I added a second continuous callback with condition u[1] + 100 and an inactive discrete callback. The merge base matched the analytic Jacobian within 1.78e-15 with Enzyme 0.13.180. The head raised Enzyme.Compiler.IllegalTypeAnalysisException while iterating the union-typed vector in DiffEqBase.initialize!. The head matched the analytic Jacobian within 1.78e-15 with the original single callback.

    Implementation fix In _erase_callback_types(callback, alg), keep the tuple-backed set on Julia < 1.12 whenever either callback group has multiple concrete element types. Use the typed-vector representation for homogeneous groups. This covers both stored problem callbacks and solve-time callbacks merged in lib/DiffEqBase/src/solve.jl. Add a mixed callback case to test/AD/autodiff_events.jl and assert that Enzyme returns the analytic bounce Jacobian, exercising callbacks from both call sites.

  • [P1] lib/OrdinaryDiffEqNonlinearSolve/src/newton.jl:1054 evaluates a negative trial before the line search can pick a step. I ran fixed-step ImplicitEuler with a line search for u′ = 1 − u, u(0) = 0, and an RHS that requires u ≥ 0. At dt = 0.1 the merge base returned Success with u = 0.09090909090909091, the exact implicit Euler value. The head threw DomainError at u = −5.504958593084855e-7 in dϕ(0).

    Implementation fix In both relax! and relax, evaluate the slope at zero with a forward stencil and keep all trial points in the nonnegative step interval. Derive the perturbation from the precision of α. Add the in-place boundary problem to lib/OrdinaryDiffEqNonlinearSolve/test/newton_tests.jl and assert a successful step and the analytical implicit Euler endpoint.

  • [P2] lib/OrdinaryDiffEqSDIRK/src/generic_imex_perform_step.jl:67 enables a time-varying scalar mass matrix for Kvaerno3, whose stage clock reduces its order on that input. I ran (1+t)u′ = 1 with ScalarOperator, u(0) = 0 and exact endpoint log(2). Kvaerno3 returned Success with errors 0.010078, 0.005057, and 0.002533 at dt = 1/32, 1/64, and 1/128. Its tableau already stores c[2] = γ on the merge base, while the stage row sums to 2γ. The new mass-matrix support exposes that mismatch on this input.

    Implementation fix Correct Kvaerno3ESDIRKIMEXTableau in lib/OrdinaryDiffEqSDIRK/src/imex_tableaus.jl to store the stage-2 abscissa c2 = 2γ. Both generic step implementations use it for the stage time. Add the analytic scalar-operator problem to lib/OrdinaryDiffEqSDIRK/test/dae_esdirk_test.jl and require the documented third-order convergence under refinement.

  • [P2] lib/OrdinaryDiffEqNonlinearSolve/src/nlsolve.jl:28 uses !stage_unsolved as an affirmative convergence test. A direct probe of stage_unsolved returned false for residuals [Inf] and [NaN], and for [0, 1] at iterate [1e16, 0] with residual scale 1. The new stationary-iterate path accepts those classifications. The direct predicate probe establishes the classification. An end-to-end solve reaching that branch with nonfinite residuals remains unverified.

    Implementation fix In stage_unsolved in lib/OrdinaryDiffEqNonlinearSolve/src/newton.jl, reject nonfinite residuals and scales, and compare the residual with a componentwise roundoff scale from its own stage equation. The same predicate is used in stalled_inner_step and inner-solver failure handling. Add tests in lib/OrdinaryDiffEqNonlinearSolve/test/nsa_residual_convergence_tests.jl that reject these three inputs and accept a finite stage that satisfies every equation to roundoff.

  • [P2] .github/workflows/DependabotAutoMerge.yml:6 changes merge-workflow permissions in a diff that also changes several independent solver behaviors. The changed-path inventory contains 21 files and no test changes.

    Implementation fix Move the two token-permission lines to a separate owner-reviewed workflow change. Validate the reusable merge workflow against passing checks and a failing required check, asserting that the failing check blocks the merge. Keep the solver fixes in focused changes with failing-before and passing-after regression coverage.

Non-blocking findings

None.

What I ran

  • git diff --find-renames --name-status origin/master...HEAD, git diff --check origin/master...HEAD, Runic --check on changed Julia sources, and typos on changed paths. Whitespace, formatting, and spelling checks exited zero. git status --porcelain returned empty.
  • On Julia 1.12.4, I ran GROUP=<group> julia --project -e 'using Pkg; Pkg.test()' from scratch copies with local package sources. The root Regression_I and Integrators_I groups passed. DiffEqBase Core, OrdinaryDiffEqBDF Core, and DelayDiffEq Regression and Interface passed. OrdinaryDiffEqSDIRK passed its default suite, including 103 tableau and 78 DAE assertions.
  • OrdinaryDiffEqNonlinearSolve Core reached test/nsa_noinit_tests.jl:78 and stopped with 101 passes and one failed success assertion in that testset. The focused ROBER replay with --check-bounds=yes isolated TRBDF2 plus SimpleTrustRegion: MaxIters at t=0.004438795354324327 on the head and t=0.004206610115922731 on the merge base. TRBDF2 with SimpleNewtonRaphson, SimpleKlement, and SimpleBroyden each exhausted maxiters on the merge base and reached t=0.1 on the head. The SimpleNewtonRaphson baseline failure reproduced on current master. An adjacent replay with matched Julia and dependencies traced its introduction to the FSAL mass-matrix conversion. Introducing commit
  • The focused nonlinear test files newton_tests.jl and nsa_residual_convergence_tests.jl exited zero. The residual-convergence file passed 5/5 stalled-stage and 8/8 solvable-stage assertions. I also ran the analytic and standalone probes described in the findings against the head and applicable baseline.
  • GlobalDiffEq Core on the merge base raised ArgumentError: GlobalErrorEstimation does not currently support callbacks on a normalized empty callback set. On the head, all 43 companion-estimator assertions passed. The subsequent adjoint tests stopped at UndefVarError: has_easy_rule while precompiling DiffEqBaseEnzymeExt.
  • OrdinaryDiffEqCore Core failed the sparse isdiag wall-time ratio on the head (38.55 < 8 was false). The merge-base and current-master suites passed that assertion and failed the algebraic-detection timing ratio (22.97 < 8 and 15.96 < 8, respectively). Direct baseline reruns passed both files at 10/10 and 22/22 assertions. The inconsistent timing results do not support attributing a performance regression to this diff.
  • I ran the callback probes on Julia 1.10.12. ForwardDiff matched the analytic bounce Jacobian for single and mixed callbacks on the head, with maximum absolute error 2.08e-9. The Enzyme forward-mode results are in the finding above.
  • julia --project=docs docs/make.jl completed doctests, document checks, and HTML rendering in the scratch copy with Git metadata.
  • uv run --locked python --version printed Python 3.13.13 and reported that --locked has no effect outside a project. The checkout contains no uv.lock.

What I did not verify

Hosted CI, live execution of the reusable merge workflow, the full AD and dependency-downgrade matrices, and GPU and downstream suites. The failing testsets prevented the remaining assertions in their respective Core runs from executing.

AUTHOR_GRADE: {"task":"bugfix","score":2,"difficulty":4,"rounds":1,"author_harness":"unknown","author_model":"unknown","note":"Existing GlobalDiffEq and ROBER cases confirm fixes. Independent probes reproduce numerical accuracy losses and failures on supported solver and callback paths."}

Head link: be0e88d


🤖 Posted by an AI agent — harness: codex-cli 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a2165b-fa64-7541-8c99-c92ac6bf3a65 (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