Skip to content

Rationalize JuMP and comparison test suites: separate generic transcription unit tests from per-problem modeling checks #441

Closed

Description

@ocots

Context and Motivation

Since #368, #369, and #370, JuMP models in ext/JuMPModels/ are no longer transcribed problem by problem:

  • Each problem file (ext/JuMPModels/<problem>.jl) only declares a ProblemData struct (components, bounds, times, dynamics, Lagrange/Mayer costs, path and boundary constraints) and delegates model construction to build.
  • The transcription itself (ext/JuMPModels/schemes/: data.jl, tableaux.jl, build.jl) and the solution accessors / builder (ext/JuMPModels.jl: state, control, costate, variable, time_grid, solution) are completely generic.

In #401, test/suite/comparison/test_equivalence.jl was updated to reflect this separation: it checks :trapeze on every problem (to verify that each problem's modeling matches OptimalControl), and checks all schemes on a small subset of problems selected by their features (every_scheme).

However, the rest of test/suite/JuMP/ and test/suite/comparison/ still loops over the Cartesian product all problems × all schemes (× all orderings), running hundreds of redundant JuMP model builds, CTDirect discretizations, and max_iter=0 Ipopt/MadNLP solves that test the generic transcription code over and over instead of testing problem-specific modeling.

Goals

  1. Unit-test the generic JuMP transcription once (test/suite/JuMP/):
    • Test ButcherTableau traits, scheme equations, convergence orders, variable/constraint orderings (:interleaved, :blocks), the model dictionary contract (:scheme, :ordering, :time_grid, :constraints, container lengths), _start! initial guess loading, JuMP.Model argument forwarding, and error paths (IncorrectArgument, NotImplemented) on small toy ProblemData definitions.
  2. Test each problem's modeling once per problem (test/suite/JuMP/ and test/suite/comparison/):
    • Verify that each problem's ProblemData, metadata parameters, and default initial guess are well-formed and consistent on a single default build (without looping over schemes/orderings or launching a solver just to read the initial time grid).
    • Keep test_smoke.jl (SMOKE_GRID, SMOKE_MAX_ITER) on every problem so every problem is shown to build and run a few solver iterations.
    • Verify NLP equivalence with OptimalControl (CTDirect) on every problem using a single configuration (scheme=:trapeze, ordering=:interleaved), plus component name agreement (state_components, control_components, variable_components).
  3. Test transcription & solution integration with OptimalControl.jl on a representative subset of problems (test/suite/comparison/):
    • Use feature-based selection (covering cost types, fixed/free times, scalar vs. vector state/control/variable per DIM1, box/path/boundary constraints) to test all 4 schemes × 2 orderings against CTDirect and to test OCP.solution(model, pb) and its interpolations (:linear vs. :constant).
  4. Preserve cron/ and robustness/ behavior while sharing common test runners (test/common/):
    • Keep test/cron/ and test/robustness/ solving all problems on their default grids and emitting the exact report tables and .tsv/.toml artifacts expected by tools/cron/report.py.
    • Factor out duplicated test code across OptimalControl and OptimalControlScalarized (test_problem.jl, test_smoke.jl, test_convergence.jl) into shared helpers in test/common/, while preserving tools/ci/scope.py dependency detection (Repository.includers).

Current State and Redundancies (for $P = 22$ problems)

1. test/suite/JuMP/

  • test_contract.jl:
    • Current: Builds $P \times 4 \text{ schemes} \times 2 \text{ orderings} = 176$ JuMP models, runs Ipopt with max_iter=0 whenever tf is free to evaluate model[:time_grid](), and runs $2P = 44$ error checks (scheme=:gauss_legendre_2, ordering=:random).
    • Redundancy: Keys like :scheme, :ordering, :constraints, container sizes ($N+1$, $N$, $M$), and unknown scheme/ordering errors are determined solely by schemes/build.jl, not by <problem>.jl.
  • test_kwargs.jl:
    • Current: Builds $3P = 66$ JuMP models to verify that Ipopt.Optimizer and add_bridges=true are forwarded to JuMP.Model and that passing init = 2 * guess doubles JuMP.start_value.
    • Redundancy: Keyword forwarding and _start! are generic functions in schemes/build.jl. Only checking that the problem's default metadata init populates all start values is problem-specific.
  • test_tableaux.jl, test_build.jl, test_signs.jl, test_draft.jl, test_methods.jl, test_smoke.jl:
    • Already targeted and non-redundant.

2. test/suite/comparison/

  • test_equivalence.jl & test/common/equivalence.jl:
    • Current: Tests :trapeze on every problem and all 4 schemes on selected = every_scheme(both, features). However, Equivalence.test_jump still loops over both ORDERINGS = (:interleaved, :blocks) for every problem, even though :blocks only permutes variable/constraint creation order in schemes/build.jl.
  • test_start.jl:
    • Current: Loops over $P \times 4 \text{ schemes} = 88$ pairs, building the JuMP model and calling OptimalControl.discretize + OptimalControl.nlp_model(..., ADNLP()) to compare JuMP.start_value with nlp.meta.x0.
    • Redundancy: Equivalence.compare and consistent_nlps in test_equivalence.jl already compare meta.x0 (:x0) on every problem for :trapeze and on the representative subset for all 4 schemes.
  • test_init.jl (test/common/comparison.jl):
    • Current: Runs Ipopt/MadNLP with max_iter=0 on SMALL_GRID = 50 for every problem across JuMP, OptimalControl, and OptimalControlScalarized ($3P = 66$ solves) to compare nvar, ncon, component names, time grid, initial trajectories, and initial objective.
    • Redundancy: test_equivalence.jl already checks nvar, ncon, bounds, x0, objective, constraints, gradient, Jacobian, and Hessian at x0 to 1e-10 without invoking any solver. Only the component names (state_components, control_components, variable_components) are specific to test_init.jl, and they can be compared directly on the models without solving.
  • test_solution.jl:
    • Current: Loops over $P \times 4 \text{ schemes} = 88$ JuMP models on SMALL_GRID = 50, running Ipopt with max_iter=0 on each to check that OCP.solution(model, pb) and TestStatus.trajectory match the JuMP accessors, plus a full solve on beam for the 4 schemes.
    • Redundancy: OCP.solution(model, pb) and the JuMP accessors in ext/JuMPModels.jl are completely generic. Testing them on a representative subset of problems (covering scalar vs. vector state/control and $0, 1, &gt;1$ variables) across the 4 schemes is sufficient.

3. Duplicated files across OptimalControl and OptimalControlScalarized

  • test/suite/OptimalControl/test_problem.jl and test/suite/OptimalControlScalarized/test_problem.jl are identical except for the backend constant.
  • test/suite/OptimalControl/test_smoke.jl and test/suite/OptimalControlScalarized/test_smoke.jl are identical except for the backend constant.
  • test/cron/OptimalControl/test_convergence.jl and test/cron/OptimalControlScalarized/test_convergence.jl are identical except for the backend constant.

Proposed Solutions

1. Move generic contract and _start! checks to test/suite/JuMP/test_build.jl

  • In test_build.jl:
    • Check the full model dictionary contract (:scheme, :ordering, :time_grid, :constraints, component keys and container lengths $N+1$, $M$, $N$, $1$) across all 4 schemes × 2 orderings on FAKE, plus the IncorrectArgument throws on unknown scheme and ordering.
    • Unit-test _start! (constant, vector, time-dependent function, custom init override, free final time) and JuMP.Model argument/keyword forwarding (Ipopt.Optimizer, add_bridges).
  • Simplify test_contract.jl (or merge test_kwargs.jl into it):
    • Build one model per problem (grid_size=2, default :trapeze and :interleaved).
    • Check problem-specific modeling invariants: non-empty component names, length(costate_components) == length(state_components), all variables have a finite JuMP.start_value, and the initial time grid evaluated at the start values is sorted with T[1] < T[end] (no Ipopt max_iter=0 call needed).

2. Streamline test/suite/comparison/

  • Shared representative problem selector:
    • Extract the feature-based representative problem selection (every_scheme in test_equivalence.jl, extended if needed to ensure scalar/vector state, control, and variable dimensions 0, 1, >1 are covered) into a shared helper in test/common/.
  • test_equivalence.jl & test/common/equivalence.jl:
    • On every problem: test (scheme=:trapeze, ordering=:interleaved) against CTDirect (ADNLP and Exa), which directly checks problem modeling equivalence (including meta.x0).
    • On the representative subset: test all 4 schemes × 2 orderings.
  • test_features.jl:
    • In addition to comparing features(vector) == features(scalarized), check that component names (state_components, control_components, variable_components) and dimensions agree between JuMP, OptimalControl, and OptimalControlScalarized for every problem (no solver call).
  • test_start.jl and test_init.jl:
    • Remove test_start.jl (since meta.x0 equivalence is already checked by test_equivalence.jl on every problem for :trapeze and on the representative subset for all 4 schemes, and _start! is unit-tested in test_build.jl).
    • Remove test_init.jl (since NLP evaluation at x0 is checked to 1e-10 by test_equivalence.jl and component names are checked by test_features.jl). Keep Comparison.within / Comparison.within_L2 (used by test_solution.jl).
  • test_solution.jl:
    • Run check_solution(problem, scheme) across the 4 schemes on the representative subset of problems (plus beam solved against OptimalControl), instead of all $P \times 4$ pairs.

3. Factorize shared OptimalControl / OptimalControlScalarized runners

  • Extract shared helpers in test/common/ for test_problem, test_smoke, and test_convergence so OptimalControl and OptimalControlScalarized call a single implementation parameterized by the backend, without altering report names, TestStatus.result! payloads, or tools/ci/scope.py scoping rules.

Activity

  1. ocots commented on Nov 10, 2026

    @ocots
    MemberAuthor

    Plan: rationalize the JuMP and comparison test suites (#441)

    Conventions: ct-conventions v0.11.0 (commit d164eca) · ct-agents v0.4.0 (commit 61e5e5c)
    Written against main at bc71791. Nothing is implemented yet: this comment is the plan, to be confirmed by the maintainer before any code (see "Decisions to confirm").

    What and why

    The JuMP transcription (ext/JuMPModels/schemes/) and the accessors are generic since #368–#370, but test/suite/JuMP/ and test/suite/comparison/ still run the product problems × schemes (× orderings), which tests the same generic code hundreds of times. This plan tests the generic code once on fake ProblemData, each problem once, and the integration with OptimalControl on a subset chosen by features. It also removes the three files duplicated between OptimalControl and OptimalControlScalarized.

    Test code only, except one optional three-line change in ext/JuMPModels/schemes/build.jl (decision D1).

    Decisions to confirm (⛔ before coding)

    Question Recommendation
    D1 The issue wants the initial time grid checked without a solver. model[:time_grid]() calls JuMP.value, which throws OptimizeNotCalled when the final time is free, and the problem's times function is not reachable from the model. Let the closure take the value function: model[:time_grid] = (value=JuMP.value) -> …, so a test calls model[:time_grid](JuMP.start_value). time_grid(model) is unchanged. Alternative with no source change: keep the max_iter=0 solve, on one model per problem and only when the grid is not available.
    D2 The issue says "build one model per problem". But every ext/JuMPModels/<problem>.jl forwards scheme, ordering, args..., init and kwargs... to build by hand. With one default build, a problem file that drops one of them is no longer caught (today test_contract and test_kwargs catch it on every problem). Two builds per problem at grid_size=2: the default one, and one with every argument non-default. 44 tiny builds instead of 286.
    D3 test_solution must loop over the representative subset only. TestStatus.for_each_problem has no filter; returning early in the closure writes a no test line per skipped problem in the report. Add a keyword only=nothing to for_each_problem (test/common/status.jl). status.jl is named by runtests.jl, so the PR runs every environment once.
    D4 One PR or three? The three phases are independent. One branch, one commit per phase, one PR.

    Scope

    • Public API changes: no.
    • Source changes: none, or ext/JuMPModels/schemes/build.jl (D1).
    • Reports: the lines contract, kwargs, test_start, test_init of test/reports/{JuMP,comparison}.md are replaced (see below). The cron and robustness reports, .tsv and .toml files are unchanged, byte for byte in their test names and columns.

    What changes

    File After
    test/suite/JuMP/test_build.jl + generic contract on fakes (4 schemes × 2 orderings), + _start! unit tests, + JuMP.Model forwarding, + unknown scheme
    test/suite/JuMP/test_contract.jl per-problem checks only, two builds per problem (D2), no solver
    test/suite/JuMP/test_kwargs.jl deleted, merged into test_contract.jl
    test/common/representative.jl new: feature-based selection, moved out of test_equivalence.jl and extended
    test/common/equivalence.jl test_jump and test_problem take the orderings
    test/suite/comparison/test_equivalence.jl every problem: :trapeze, :interleaved; subset: 4 schemes × 2 orderings
    test/suite/comparison/test_features.jl + component names and dimensions, JuMP vs OptimalControl vs Scalarized, no solve
    test/suite/comparison/test_start.jl deleted
    test/suite/comparison/test_init.jl deleted
    test/common/comparison.jl reduced to what test_solution.jl uses
    test/suite/comparison/test_solution.jl check_solution on the subset × 4 schemes
    test/common/status.jl for_each_problem(...; only=nothing) (D3)
    test/common/optimalcontrol_tests.jl new: test_problem, test_smoke, test_convergence parameterized by the backend
    test/suite/{OptimalControl,OptimalControlScalarized}/test_{problem,smoke}.jl, test/cron/{…}/test_convergence.jl thin wrappers (TST1) calling the shared runner
    test/common/configs.jl, test/README.md, CHANGELOG.md comments and documentation updated

    No behaviour change of the package. Test coverage of the generic code is kept (moved to fakes); per-problem coverage is kept for what is written per problem.

    Step 0 — Branch and baseline

    git checkout main && git pull
    git checkout -b test/441-rationalize-jump-comparison-tests

    Before any edit, record the baseline: run ["JuMP"] and ["comparison"] (ct-dev-mcp get_test_command, then generate_report), keep both logs, and note the wall time and the number of tests of each test file. The same numbers are reported at the end, in the PR body.

    Phase A — test/suite/JuMP/: generic tests on fakes, one check per problem

    Rules: TST1, TST3 (fakes at module top-level), TST4 (unit / contract / error sections), TST5, TST7, EXC5.

    1. (D1, if accepted) ext/JuMPModels/schemes/build.jl:

      # before
      _value(a) = a isa Number ? a : JuMP.value(a)
      model[:time_grid] = () -> range(_value(t0), _value(tf), N + 1)
      # after
      _value(a, value) = a isa Number ? a : JuMP.value(value, a)
      model[:time_grid] = (value=JuMP.value) -> range(_value(t0, value), _value(tf, value), N + 1)

      Check the other uses of _value in ext/ first, and that JuMP.value(f, x) accepts both a VariableRef and an expression (a free time may be either).

    2. test_build.jl — add a second fake next to FAKE, EXACT, LINEAR, with a vector state and control, so that the 1-D and n-D cases are both covered (DIM1):

      const VECTOR = EXT.ProblemData(;
          state=[EXT.Component("x₁"), EXT.Component("x₂")],
          control=[EXT.Component("u₁"), EXT.Component("u₂")],
          variable=[EXT.Component("a"), EXT.Component("T")],
          costate=["∂x₁", "∂x₂"],
          times=v -> (0, v[2]),
          dynamics=(x, u, v, t) -> [x[2] + u[1], u[2] + v[1]],
          lagrange=(x, u, v, t) -> u[1]^2 + u[2]^2,
      )
    3. test_build.jl — new function test_contract_generic() (moved from test_contract.jl), for data in (FAKE, EXACT, VECTOR), 4 schemes × 2 orderings, N = 3:

      • model[:scheme] === scheme, model[:ordering] === ordering, model[:time_grid] isa Function;
      • the four *_components keys are Vector{String}, each name resolves in JuMP.object_dictionary(model);
      • lengths: state N + 1, control N + 1 for :trapeze and N otherwise (written by hand, as SCHEMES in the current test_contract.jl), costate N, variable 1;
      • length(model[:constraints]) == JuMP.num_constraints(model; count_variable_in_set_constraints=false);
      • time grid: fixed times (EXACT) collect(model[:time_grid]()) == [0, 1/3, 2/3, 1]; free final time (FAKE with init=(variable=1.5,)) evaluated at the start values (D1).
    4. test_build.jl — new function test_start(), unit tests of _start! through EXT.build(...; init=...) and JuMP.start_value, on FAKE and VECTOR, N = 2, for the 4 schemes:

      • no init: every start value is nothing;
      • constant scalar and constant vector guesses; a missing key leaves its variables unset;
      • function of time: init=(state=t -> …, control=t -> …, variable=…), expected values written by hand on t(i) = i * tf / N with tf the guess of the variable (free final time), and on M controls (N + 1 for :trapeze, N otherwise);
      • :blocks gives the same start value to the same variable name as :interleaved.
    5. test_build.jl — new function test_forwarding(): EXT.build(FAKE, 2, :trapeze, :interleaved, Ipopt.Optimizer; add_bridges=false) gives JuMP.solver_name(model) == "Ipopt" and JuMP.bridge_constraints(model) == false; true with the default. (using Ipopt: Ipopt, already in test/suite/JuMP/Project.toml.)

    6. test_build.jl — error section: Test.@test_throws CTBase.Exceptions.IncorrectArgument EXT.build(LINEAR, 2, :gauss_legendre_2, :interleaved) next to the existing unknown-ordering test. NotImplemented stays in test_tableaux.jl.

    7. test_contract.jl — rewrite as the per-problem check; remove the solve_jump.jl include if D1 is accepted. Shape:

      Main.TestStatus.for_each_problem("contract", OCP.JuMPBackend()) do problem
          build = getfield(OCP, problem)
          # 1. default build: what the problem file writes
          model = build(OCP.JuMPBackend(); grid_size=2)
          # non-empty state and control names, unique names,
          # length(costate_components) == length(state_components)
          # every variable has a finite start value (the metadata guess fills everything, #377)
          # initial time grid at the start values: issorted, T[1] < T[end]   (D1)
          # 2. every argument non-default: what the problem file forwards   (D2)
          other = build(OCP.JuMPBackend(), Ipopt.Optimizer;
              grid_size=3, scheme=:midpoint, ordering=:blocks, init=doubled, add_bridges=false)
          # model[:scheme], model[:ordering], 4 nodes, solver name, bridges off,
          # start values = factor .* default ones (the logic of the current test_kwargs.jl)
      end

      The start-value comparison of test_kwargs.jl matches variables by name, since the two builds differ in scheme and grid: build the doubled comparison at the same grid_size and scheme if matching by name is not straightforward (then use a third build, or compare :trapeze to :trapeze). Keep the report name "contract".

    8. Delete test_kwargs.jl (⛔ ask before deleting).

    9. Mutation checks (README rule "every check you add must be shown to fail"): temporarily break, one at a time, and see the named test fail — drop ordering in one problem file's call to build; drop init=init in one problem file; set M = N for the trapezoidal rule in build; skip the control loop in _start!. Revert each. List them in the PR body.

    Checkpoint:

    get_test_command cwd=<repo> test_args=["JuMP"]     # ct-dev-mcp, then generate_report
    # fallback: julia --project=@. -e 'using Pkg; Pkg.test(; test_args=["JuMP"])' 2>&1 | tee /tmp/ocp_441_phaseA.log
    

    Phase B — test/suite/comparison/

    1. New test/common/representative.jl, module Representative (guarded include, as the other common files). Move PROPERTIES, covered and every_scheme (renamed select) from test_equivalence.jl, and add the dimension cases:

      scalar_state=f -> f.state_dimension == 1,      vector_state=f -> f.state_dimension > 1,
      scalar_control=f -> f.control_dimension == 1,  several_controls=f -> f.control_dimension > 1,
      no_variable=f -> f.variable_dimension == 0,    scalar_variable=f -> f.variable_dimension == 1,
      vector_variable=f -> f.variable_dimension > 1,

      plus selection() returning (problems, features, selected) for OCP.problems(OCP.JuMPBackend(), OCP.OptimalControlBackend()). No problem name is written (README rule 3, core/test_consistency.jl). The selection is made on the whole catalogue, not on problem=, as today.

    2. test/common/equivalence.jl: test_jump(problem, scheme, ref, orderings) and test_problem(problem, schemes, orderings); test_exa unchanged (it does not depend on the ordering). Update the header comment.

    3. test_equivalence.jl: include representative.jl; keep Test.@test covered(selected, features) == covered(both, features) and the @info line; call

      full = problem in selected
      E.test_problem(problem, full ? E.SCHEMES : (:trapeze,), full ? E.ORDERINGS : (:interleaved,))
    4. test_features.jl: keep the vector vs scalarized feature check (report name test_features); add a loop per pair (JuMP, OptimalControl) and (JuMP, OptimalControlScalarized), report name test_components, with no solve: OCP.state_components, control_components, variable_components and the three *_dimension of the JuMP model (grid_size=2) equal those of OCP.model(pb).

    5. test/common/status.jl (D3): for_each_problem(f, test, backends...; only=nothing), which keeps the problems of only when it is given; add its case to test/suite/core/test_status.jl.

    6. test_solution.jl: include representative.jl; loop for_each_problem("test_solution", jump, oc; only=selected) over the 4 schemes; keep the errors testset and the solved beam testset as they are.

    7. Delete test_start.jl and test_init.jl (⛔ ask before deleting). Before deleting test_init.jl, confirm on the baseline log that nothing it checks is lost: nvar, ncon, x0, objective and constraints at x0 are in Equivalence.compare (JuMP vs CTDirect, and scalarized vs vector by test_scalarized); the names are in step 4.

    8. test/common/comparison.jl: remove Data, vec1, from_solution, both solve methods, for_each_comparison, check, compare_*, REFERENCE, OTHERS and the tolerances no longer used (GRID, CONTROL, VARIABLE); keep L2_norm, within, within_L2, OBJECTIVE, STATE, COSTATE and the two includes (test_solution.jl uses Main.SolveJuMP and Main.SolveOptimalControl). Rewrite the header comment.

    9. test/common/configs.jl: the comment of SMALL_GRID (now the grid of test_solution only).

    10. Mutation checks: change one component name in one JuMP problem file (test_components fails); change a sign in the dynamics of a problem outside the subset (NLP equivalence fails on :trapeze); swap two pieces in _in_order for :blocks (fails on the subset and in test_build.jl). Revert each.

    Checkpoint:

    get_test_command cwd=<repo> test_args=["comparison"]
    get_test_command cwd=<repo> test_args=["core"]          # test_status, test_consistency
    python3 -m unittest discover -s tools/ci/test -p 'test_*.py'
    

    The fixtures of tools/ci/test/test_scope.py and tools/cron/test/test_report.py write their own test_init.jl in a temporary repository: they do not depend on the deleted file. Check it rather than assume it.

    Phase C — shared runners for OptimalControl and OptimalControlScalarized

    1. New test/common/optimalcontrol_tests.jl: guarded include of solve_optimalcontrol.jl, then module OptimalControlTests with test_problem(backend), test_smoke(backend), test_convergence(backend) and the helper changed(params). The backend gives everything that differs today:

      name = Main.TestStatus.modeling(backend)                  # :OptimalControl / :OptimalControlScalarized
      configs = getfield(Main.TestConfigs.CONFIGS, name)
      Test.@testset "$name Problem API" verbose = VERBOSE showtiming = SHOWTIMING begin … end
      occursin("$name modeling", shown);  OCP.status(problem)[name]

      Testset titles, report names ("problem", "test_smoke <label>", "test_convergence <label>") and the arguments of TestStatus.result! are copied unchanged.

    2. The six files become wrappers, still one module and one entry function each (TST1):

      isdefined(Main, :OptimalControlTests) ||
          include(joinpath(@__DIR__, "..", "..", "common", "optimalcontrol_tests.jl"))
      
      module TestSmokeOptimalControl
      using OptimalControl: OptimalControl # loads the OptimalControlModels extension
      using OptimalControlProblems: OptimalControlProblems
      test_smoke() = Main.OptimalControlTests.test_smoke(OptimalControlProblems.OptimalControlBackend())
      end # module TestSmokeOptimalControl
      
      test_smoke() = TestSmokeOptimalControl.test_smoke()

      The file name must appear as the literal "optimalcontrol_tests.jl": Repository.includers of tools/ci/scope.py finds includers by that string, transitively through test/common/.

    3. tools/ci/test/test_scope.py: add a case showing that a change of the shared runner is scoped to OptimalControl and OptimalControlScalarized (fixture: two suite files naming it), in the style of the existing solve_jump.jl case.

    4. Check that the reports are unchanged: run the cron mode on one problem before (on main) and after, and compare the test names and the header of the files.

      get_test_command cwd=<repo> test_args=["OptimalControl", "OptimalControlScalarized"]
      get_test_command cwd=<repo> test_args=["OptimalControl", "OptimalControlScalarized", "cron", "problem=beam"]
      diff <(cut -f1-4 before/OptimalControl-cron-results.tsv) <(cut -f1-4 test/reports/OptimalControl-cron-results.tsv)
      python3 -m unittest discover -s tools/ci/test -p 'test_*.py'
      python3 -m unittest discover -s tools/cron/test -p 'test_*.py'
      

    Phase D — documentation and full run

    1. test/README.md: "Three kinds of tests" (item 1: test_kwargs is gone, what test_contract now checks; item 2: every problem with one configuration, every scheme and ordering on the subset), "What is compared, and what is not" (no more zero-iteration comparison: names in test_features, NLP in test_equivalence), and a sentence on the shared runner under "Adding a test". Fix what markdownlint reports in the touched sections (GEN2).

    2. CHANGELOG.md: one entry under [Unreleased] (CHG2), or the label no changelog — the maintainer chooses.

    3. Full suite (last phase only), then the baseline comparison of Step 0:

      get_test_command cwd=<repo>          # no test_args: core and every environment
      # fallback: julia --project=@. -e 'using Pkg; Pkg.test()' 2>&1 | tee /tmp/ocp_441_final.log
      
    4. PR body: the before/after table (wall time and number of tests per file, JuMP and comparison), the mutation checks done, the decisions D1–D4 as applied, and the versions of the conventions. Labels: run ci github-runner; test convergence because test/cron/ changes (README, "When to add test convergence").

    Expected order of magnitude, for 22 problems: JuMP models built by test_contract + test_kwargs 286 → 44; test_start 88 discretizations → 0; test_init about 88 zero-iteration solves → 0; test_solution 88 zero-iteration solves → 4 per selected problem; :blocks equivalence on every problem → on the subset only.

    Human checkpoints

    • ⛔ Confirm D1–D4 before starting.
    • ⛔ Ask before deleting test_kwargs.jl, test_start.jl, test_init.jl.
    • ⛔ Ask before the first commit, and before pushing.
    • ⛔ Ask if the selection of step B1 turns out to be large (more than about 8 problems): the product on the subset would then cost more than what the phase saves.
    • ⛔ Ask if a design decision arises that is not in this plan. The human merges.

    Out of scope

    • test/suite/GPU/test_smoke_{optimalcontrol,scalarized}.jl: duplicated in the same way, but opt-in and with the TST6 skip; a follow-up can give the shared test_smoke a configs argument.
    • test/robustness/ (only OptimalControl and JuMP exist; nothing duplicated) and test/cron/JuMP/.
    • The problem names beam and glider already written in test_solution.jl.
    • ModelingToolkit tests, tools/cron/report.py, the workflows.
    • Any change of a problem, of a scheme or of the solution accessors.

    File summary

    Added: test/common/representative.jl, test/common/optimalcontrol_tests.jl
    Modified: test/suite/JuMP/test_build.jl, test/suite/JuMP/test_contract.jl, test/common/equivalence.jl, test/common/comparison.jl, test/common/status.jl, test/common/configs.jl, test/suite/comparison/test_equivalence.jl, test/suite/comparison/test_features.jl, test/suite/comparison/test_solution.jl, test/suite/core/test_status.jl, test/suite/OptimalControl/test_problem.jl, test/suite/OptimalControl/test_smoke.jl, test/suite/OptimalControlScalarized/test_problem.jl, test/suite/OptimalControlScalarized/test_smoke.jl, test/cron/OptimalControl/test_convergence.jl, test/cron/OptimalControlScalarized/test_convergence.jl, tools/ci/test/test_scope.py, test/README.md, CHANGELOG.md, and ext/JuMPModels/schemes/build.jl if D1 is accepted
    Deleted: test/suite/JuMP/test_kwargs.jl, test/suite/comparison/test_start.jl, test/suite/comparison/test_init.jl

  2. ocots commented on Nov 10, 2026

    @ocots
    MemberAuthor

    Addendum to the plan: a closing summary of what is tested

    D1–D4 of the plan above are confirmed by the maintainer (D1: time_grid takes a value function; D2: two builds per problem; D3: only= in for_each_problem; D4: one PR, one commit per phase). The GPU follow-up is #445.

    One more deliverable, in Phase D, written once the tests are finished so that it describes what is really tested and not what was planned:

    • a short section in test/README.md (replacing the description of the three kinds of tests where needed), and
    • the same text as a synthetic comment on the PR (and a pointer to it from this issue).

    It must state the philosophy in a few lines:

    1. What the suite compares. For each problem, the modelings of the problem: JuMP, OptimalControl and OptimalControlScalarized describe the same problem (same components and dimensions, same NLP as CTDirect's, to 1e-10, on one configuration: :trapeze, :interleaved) and every problem builds and runs a few iterations (test_smoke).
    2. What the suite does not repeat per problem. The discretization (schemes, orderings, start values, argument forwarding, solution accessors) is generic: it is tested once, on fake ProblemData (suite/JuMP/test_build.jl), and against CTDirect on a small representative subset of problems chosen by their features (cost type, free/fixed times, scalar/vector state, control and variable, box/path/boundary constraints), for all 4 schemes × 2 orderings (test_equivalence, test_solution). Running problems × schemes × orderings would test the same generic code again without testing any more modeling.
    3. What stays outside the PR run. Convergence and robustness are reported by the crons, never tested ([Tests] Report convergence instead of testing it; keep hard checks for breakage and model equivalence #360); cron/ and robustness/ are unchanged.
    4. How to read a failure. A failure on a single problem is a modeling error of that problem; a failure on the subset or in test_build.jl is an error of the generic transcription.

    Include in it the before/after table (wall time and number of tests per file, JuMP and comparison) measured against the baseline of Step 0.

  3. ocots commented on Nov 10, 2026

    @ocots
    MemberAuthor

    Revised plan (phase E) and audit of the suite

    Conventions: ct-conventions v0.11.0 (commit d164eca) · ct-agents v0.4.0 (commit 61e5e5c).

    Phases A–D of the first plan are done on test/441-rationalize-jump-comparison-tests (commits 2e15e85, 14e8723, 242687b, 22476df; nothing pushed). Measuring the result showed that the comparison environment is still slow (25 min) and, more importantly, that it does not follow the intent of the maintainer, which I had misread by following the text of the issue literally. This comment states the intent, audits what the suite does, and replaces the second half of the plan.

    The intent (maintainer, confirmed)

    1. Each modeling of a problem is coherent with the others. JuMP, OptimalControl and OptimalControlScalarized describe the same continuous problem: dynamics, cost, constraints, bounds, times. This is checked on every problem, without discretizing.
    2. The JuMP discretization is coherent with CTDirect. Schemes, orderings, NLP structure. The discretization is generic, so this is checked on a few representative problems only.
    3. The modelings share the same initial guess. This holds by construction (every modeling reads initial_guess_data of the metadata), so it needs no test of its own beyond the existing ones (test_contract for JuMP, test_problem for OptimalControl).
    4. The scalarized model is compared to the others at the continuous level only: no discretization of it.

    Why the current comparison is slow (measured, not assumed)

    Measured with scratchpad/profile_equiv*.jl on beam and robot, first call of each step, compilation is 99–100 % of the time (the NLPs are tiny, grid 4):

    Step, per problem beam robot
    reference: CTDirect discretize + ADNLP + Exa 4.5 s 10.8 s
    JuMP side (model, MathOptNLPModel, compare) 2.2 s 21.7 s
    Exa vs ADNLP (test_exa) 2.1 s 4.9 s
    scalarized vs vector (test_scalarized) 29.1 s 56.4 s

    NLPModelsTest.consistent_nlps costs about nothing once compiled (0.0 s on robot after beam). The cost is the compilation of OptimalControl's discretization and NLP builders for each problem, and test_scalarized is the largest part (about three quarters on beam). Each environment runs in its own Julia process, so this compilation is paid again in comparison after OptimalControl's test_smoke (which discretizes and solves every problem with ADNLP and with Exa).

    Audit of the suite (final run of the branch)

    Times are those of the full run on the branch. "Keep" is my judgment; the items marked ? are for the maintainer.

    core (in-process, about 45 s, 24 s of it test_discovery_cache)

    File What it checks Verdict
    test_aqua Aqua quality checks keep
    test_consistency files of each problem exist in every directory, metadata schema, status rule, reference objectives, no hand-written list of problems, sources cited, reference solutions keep
    test_discovery_cache automatic discovery of problems and the precompilation cache (24 s) keep, not related to #441
    test_modelings, test_modules, test_parameters, test_references, test_runner, test_status module layout, parameters and metadata API, reference tool, the test runner and the status loop itself keep

    JuMP (33 s)

    File What it checks Verdict
    test_build the transcription on fake problems: NLP written by hand for each scheme and ordering, order of the schemes, orderings, model dictionary, _start!, argument forwarding, time grid keep (the generic discretization, once)
    test_tableaux Butcher tableaux traits and errors keep
    test_contract per problem: components, finite default start values, initial time grid, every argument forwarded to build keep
    test_methods, test_draft the extension defines a method per problem; the draft warning keep
    test_signs sign of the costate / multipliers (SGN1–SGN6) on hand-written NLPs, then on a problem keep
    test_smoke every problem builds and runs 3 Ipopt iterations (3.8 s) keep

    OptimalControl (9 min) and OptimalControlScalarized (5 min)

    File What it checks Verdict
    test_features features(problem) agrees with the model keep
    test_problem the Problem API, metadata, parameters, initial guess, display (shared since #441) keep
    test_methods the extension defines a method per problem keep
    test_reference_solution the analytic solutions satisfy the discretized model (the references of #379 are right) keep
    test_smoke 8.5 min / 4.9 min: every problem builds, discretizes, evaluates and runs 3 iterations with ADNLP+Ipopt and Exa+MadNLP (Scalarized: Exa+MadNLP) keep, but it is the same compilation that comparison pays again (? a lighter PR run, for instance one modeler, belongs in a separate issue)

    comparison (25 min) — what changes

    File What it checks now Proposal
    test_equivalence, JuMP vs CTDirect, :trapeze/:interleaved, every problem NLP of the JuMP model equals CTDirect's: bounds, x0, objective, constraints, Jacobian, Hessian move to the representative subset; replaced for every problem by the continuous comparison (E2)
    test_equivalence, 4 schemes × 2 orderings, subset the JuMP schemes are CTDirect's keep as is
    test_equivalence, Exa vs ADNLP, every problem OptimalControl's own modelers agree, with a known gap documented in #284 this tests OptimalControl, not our problems: ? subset only, or drop
    test_scalarized (every problem, 29–56 s each) scalarized NLPs equal the vector ones delete; replaced by the continuous comparison (E2)
    test_nonzeros a guard on an NLPModelsJuMP quirk (nnzh counts repeated entries) on every problem ? one problem, or drop
    test_features vector vs scalarized features; components and dimensions of JuMP vs OptimalControl vs Scalarized keep (cheap)
    test_solution OCP.solution(model, pb) and interpolations, subset × 4 schemes, plus a solved beam keep

    Removed since the baseline: test_kwargs (merged), test_start, test_init (their checks are in test_equivalence, test_features and test_build).

    New checks to add (phase E)

    E2 — suite/comparison/test_modelings.jl: the continuous comparison, every problem, no discretization. New helper test/common/continuous.jl (module Continuous), deterministic sample points, for the pair JuMP–OptimalControl and the pair OptimalControl–OptimalControlScalarized:

    • times t0, tf (JuMP: data.times(v); OptimalControl: initial_time, final_time, accounting for a free time that is a component of the variable);
    • dynamics (JuMP data.dynamics(x, u, v, t); OptimalControl CTModels.dynamics(ocp)), at several (t, x, u, v);
    • Lagrange integrand and Mayer cost (data.lagrange, data.cost; lagrange(ocp), mayer(ocp)), noting the sense of the criterion;
    • path and boundary constraints, matched by values at the points, as Equivalence.signatures does (their order is not guaranteed), with their bounds (lb, f, ub);
    • box constraints (state_constraints_box, control_constraints_box, variable_constraints_box against Component.lower / upper).

    Scalar versus vector (DIM1): ProblemData functions take vectors, a one-dimensional state or control of OptimalControl is a scalar; the helper adapts.
    The scalarized model is compared with the vector one in the same way, nothing is discretized.

    E1 — one line in schemes/build.jl: model[:problem_data] = data, so the test reaches the continuous functions of a JuMP problem (they are today local to each problem file). Document the key in test_build (model dictionary).

    Open points the spike must settle: the exact signatures of the in-place constraints of CTModels (f!(val, t, x, u, v)), bounds given as vectors over the nodes in Component (compare at the nodes, or skip with a report), problems whose criterion is :max, and the domain of the functions (log, sqrt: sample around the initial guess, not at arbitrary points).

    Revised steps

    Step What Gate
    E0 Spike on three problems (one with a free time and a variable, one with vector state and control, one with path constraints): the helper, one test, wall time of the new check against test_jump + test_scalarized. ⛔ go / no-go on feasibility and gain before anything is deleted
    E1 model[:problem_data] = data in build; update test_build.
    E2 test/common/continuous.jl and suite/comparison/test_modelings.jl on every problem, vector and scalarized.
    E3 test_equivalence: JuMP vs CTDirect only on the representative subset (4 schemes × 2 orderings); delete test_scalarized; Exa vs ADNLP and test_nonzeros as decided. ⛔ ask before deleting
    E4 Mutation checks, each shown to fail: a sign in the dynamics, a bound, a constraint dropped, in a problem outside the subset and in the scalarized file.
    E5 test/README.md (philosophy), CHANGELOG.md, full run, before/after table, the closing summary comment on the PR.

    The scope rules (tools/ci/scope.py) need nothing new: test/common/continuous.jl is found as an includer through test_modelings.jl. Add a case to tools/ci/test/test_scope.py as in phase C.

    Decisions to confirm

    • D5. The JuMP vs CTDirect NLP comparison moves to the representative subset (confirmed in the maintainer's message).
    • D6 (?). Exa vs ADNLP: subset only, or drop.
    • D7 (?). test_nonzeros: one problem, or drop.
    • D8 (?). The 8.5 + 4.9 min of the smoke solves of the two OptimalControl environments: out of scope here, a separate issue if wanted.
  4. ocots commented on Nov 10, 2026

    @ocots
    MemberAuthor

    Status report (bilan) and handoff — supersedes the plan and the goals above where they differ

    Conventions: ct-conventions v0.11.0 · ct-agents v0.4.0. Branch test/441-rationalize-jump-comparison-tests (4 commits, not pushed, no PR yet), based on main at bc71791.

    In one paragraph. The generic JuMP transcription is now unit-tested once (fake problems), each JuMP problem file is checked on small models, and the two OptimalControl modelings share one test implementation. The comparison environment still takes 25 min because it discretizes every problem with CTDirect, which is mostly compilation. The maintainer's intent is different from the literal text of this issue: modelings are compared at the continuous level, on every problem, without discretizing; the discretization is compared with CTDirect only on a few representative problems. A spike shows this is feasible and cheap (41 comparisons in 31 s, all equal, mutations detected). What remains is to implement it, move the all-problem NLP comparison to a cron, and write the closing summary.

    1. The intent (confirmed by the maintainer; this replaces goals 2 and 3 of the issue)

    1. Each modeling of a problem is coherent with the others: JuMP, OptimalControl and OptimalControlScalarized describe the same continuous problem (times, dynamics, cost, constraints, bounds). Checked on every problem, no discretization. The scalarized model is compared the same way, no NLP.
    2. The JuMP discretization is coherent with CTDirect: schemes, orderings, NLP structure. Generic code, so checked on a few representative problems (4 schemes × 2 orderings, JuMP vs ADNLP only).
    3. The modelings share the same initial guess: true by construction (all read initial_guess_data), no dedicated test beyond test_contract (JuMP) and test_problem (OptimalControl).
    4. Fast tests on pull requests, heavier comparisons in a cron. A pull request already runs only the problems it changes (tools/ci/scope.py, [CI] Test only what a pull request changes: environments and problems; labels only add #405; labels test <env> backend, test comparison, test all problems, test everything, test convergence only add), so per-problem costs do not hit every PR.

    2. What is done on the branch

    Commit Content
    2e15e85 suite/JuMP: test_build (fake problems, scalar and vector: model dictionary for 4 schemes × 2 orderings, _start!, JuMP.Model argument forwarding, time grid, errors); test_contract (per problem, no solver, 3 small builds: components, finite default start values, initial time grid read at the start values, every argument forwarded to build); test_kwargs removed. model[:time_grid] takes an optional function giving the value of a variable (model[:time_grid](JuMP.start_value) works before any solve, also with a free time).
    14e8723 suite/comparison: common/representative.jl (fewest problems that have every property the generic code treats differently, computed from the features: balanced_field, insurance, beam, cart_pendulum, ducted_fan); test_equivalence with trapeze/interleaved for every problem and all schemes and orderings on the subset; test_features (+ components and dimensions JuMP vs OptimalControl vs Scalarized); test_solution on the subset (for_each_problem(...; only=)); test_start, test_init removed; comparison.jl reduced.
    242687b common/optimalcontrol_tests.jl: test_problem, test_smoke, test_convergence written once, parameterized by the backend; the six files are thin wrappers (TST1). Test names, report lines and cron results unchanged (checked on beam: reports identical, results identical but the time). Scope case added to tools/ci/test/test_scope.py.
    22476df test/README.md (philosophy), CHANGELOG.md.

    Uncommitted: one line in ext/JuMPModels/schemes/build.jl, model[:problem_data] = data (see §4).

    Measured (full run of the branch against the baseline on main; single runs, timings vary by machine load: the equivalence took 25 min in the full run and 35.6 min in a filtered run):

    Before After
    JuMP 6280 tests, 36 s 1099 tests, 33 s
    comparison 15704 tests, 83 min 11112 tests, 25.5 min
    test_equivalence 11357 tests, 73.5 min 10450 tests, 25 min
    test_solution 1641 tests, 30 s 409 tests, 21 s
    test_start + test_init 2687 tests, 9 min removed

    All green: full suite, core, Python tools tests. Mutation checks done (each shown to fail, then reverted): beam ignores ordering; beam drops init; trapezoidal rule with N controls; _start! skips the controls; a component renamed; a wrong sign in vanderpol (outside the subset); :blocks order reversed.

    3. Why the comparison is still slow: measured, and what it changes

    Measured on beam and robot (first call of each step, tiny NLPs): 99–100 % compilation. CTDirect discretize + ADNLP + Exa per problem 4.5–10.8 s; the JuMP side 2.2–21.7 s; Exa vs ADNLP 2.1–4.9 s; test_scalarized 29–56 s per problem. consistent_nlps costs nothing once compiled. Each environment runs in its own Julia process, so the compilation of OptimalControl's discretization is paid again in comparison after OptimalControl's test_smoke. Conclusion: comparing NLPs on every problem is what costs; compare the continuous models instead.

    4. Spike E0 (done): the continuous comparison is feasible and cheap

    Prototype below. For every problem and for both OptimalControl modelings it compares, with the JuMP ProblemData (reached through model[:problem_data], a one-line change in build): times, dynamics, Lagrange integrand, Mayer cost, path and boundary constraints, box bounds of the state, control and variable. Points come from the initial guess (domain-safe: the smoke solves start there), with small deterministic perturbations.

    Result: 22 problems vs OptimalControl and 19 vs OptimalControlScalarized (drafts included), all equal, 30.6 s in total (0.2–1.4 s per problem, balanced_field 4.7 s with compilation), against 30–90 s per problem for the NLP route. Mutations are detected: a sign in the dynamics of vanderpol → dynamics; the upper bound of x₁ doubled in beam → state_box.

    What the spike taught (keep in the implementation):

    • CTModels accessors exist (dynamics, lagrange, mayer, criterion, path_constraints_nl, boundary_constraints_nl, state/control/variable_constraints_box, initial_time, final_time). Dynamics and constraints are in place: D(r, t, x, u, v), path f!(r, t, x, u, v), boundary f!(r, x0, xf, v). A fixed time is read with initial_time(ocp), a free one with initial_time(ocp, v) (use has_fixed_initial_time, has_fixed_final_time). Vectors are accepted for 1-D controls.
    • The cost is not decomposed the same way. JuMP always minimizes data.cost(I, x0, xf, v), linear in the integral I of its Lagrange integrand; some problems have cost = -I or a scale (insurance: integrand of opposite sign; ducted_fan: factor 2/3). Compare sign · lagrange_OC with w · data.lagrange, where w = cost(1) − cost(0) and sign follows criterion (:min → 1, :max → −1); the Mayer part is cost(0, x0, xf, v) against sign · mayer.
    • Path and boundary constraints are matched by value (bounds and values at the points), their order is not guaranteed.
    • Compare infinities with a == b ||: Inf - Inf is NaN.
    • No current problem has node-dependent bounds (a Component bound given as a vector): the helper reports it as different if one appears.
    • The boundary check of the prototype uses one (x0, xf) pair; the implementation should use several.
    • OCP.problems(...; status=:all) includes the drafts; Main.TestStatus.for_each_problem handles their status.
    Prototype (to become test/common/continuous.jl, TST1/TST2 style, no problem name written)
    module Continuous
    
    using OptimalControlProblems: OptimalControlProblems
    using JuMP: JuMP # loads the JuMPModels extension
    using OptimalControl: OptimalControl
    
    const OCP = OptimalControlProblems
    const OC = OptimalControl
    
    vec1(a::Number) = [Float64(a)]
    vec1(a) = Float64.(collect(a))
    
    close_to(a, b; tol=1e-10) = length(a) == length(b) && all(@. (a == b) | (abs(a - b) <= tol * max(1, abs(a), abs(b))))
    
    # ---- the OptimalControl side, as plain functions of (t, x, u, v) ----
    function oc_dynamics(ocp)
        D, n = OC.dynamics(ocp), OC.state_dimension(ocp)
        return (t, x, u, v) -> (r = zeros(n); D(r, t, x, u, v); r)
    end
    
    function oc_inplace(c, n)
        lb, f!, ub, _ = c
        return lb, ub, (t, x, u, v) -> (r = zeros(length(lb)); f!(r, t, x, u, v); r)
    end
    
    function oc_boundary(c)
        lb, f!, ub, _ = c
        return lb, ub, (x0, xf, v) -> (r = zeros(length(lb)); f!(r, x0, xf, v); r)
    end
    
    # bounds per component: (lower, upper), -Inf / Inf where unset
    function oc_box(box, dim)
        lb, ind, ub = box[1], box[2], box[3]
        lower, upper = fill(-Inf, dim), fill(Inf, dim)
        for (l, i, u) in zip(lb, ind, ub)
            lower[i] = max(lower[i], l)
            upper[i] = min(upper[i], u)
        end
        return lower, upper
    end
    
    function jump_box(components)
        num(b, default) = isnothing(b) ? default : (b isa Number ? Float64(b) : b)
        return [num(c.lower, -Inf) for c in components], [num(c.upper, Inf) for c in components]
    end
    
    # ---- sample points, from the initial guess ----
    guess(g, t) = g isa Function ? g(t) : g
    
    function sample(init, n, m, nv, t0, tf)
        v = haskey(init, :variable) ? vec1(init.variable) : ones(nv)
        pts = []
        for (k, s) in enumerate((0.0, 0.25, 0.5, 0.75, 1.0))
            t = t0 + s * (tf - t0)
            x = haskey(init, :state) ? vec1(guess(init.state, t)) : fill(0.5, n)
            u = haskey(init, :control) ? vec1(guess(init.control, t)) : fill(0.5, m)
            push!(pts, (t=t, x=x .+ 0.01 * k, u=u .+ 0.01 * k, v=v))
        end
        return pts
    end
    
    "Report of the comparison of the JuMP data of `problem` with the OptimalControl model of `backend`."
    function compare(problem, backend)
        pb = getfield(OCP, problem)(backend)
        ocp = OCP.model(pb)
        d = getfield(OCP, problem)(OCP.JuMPBackend(); grid_size=2)[:problem_data]
        f = OCP.features(pb)
        n, m, nv = f.state_dimension, f.control_dimension, f.variable_dimension
        init = OCP.initial_guess(pb)
        ok = Dict{Symbol,Bool}()
        v0 = haskey(init, :variable) ? vec1(init.variable) : ones(nv)
        t0 = OC.has_fixed_initial_time(ocp) ? OC.initial_time(ocp) : OC.initial_time(ocp, v0)
        tf = OC.has_fixed_final_time(ocp) ? OC.final_time(ocp) : OC.final_time(ocp, v0)
        jt0, jtf = d.times(v0)
        ok[:times] = close_to([t0, tf], [jt0, jtf])
        pts = sample(init, n, m, nv, t0, tf)
        D = oc_dynamics(ocp)
        ok[:dynamics] = all(p -> close_to(D(p.t, p.x, p.u, p.v), vec1(d.dynamics(p.x, p.u, p.v, p.t))), pts)
        x0, xf, v = pts[1].x, pts[end].x, pts[1].v
        sign = OC.criterion(ocp) === :min ? 1.0 : -1.0
        # JuMP always minimizes `cost(I, x0, xf, v)`, linear in the integral `I` of its Lagrange
        # integrand: the weight of the integrand is `cost(1) - cost(0)`; OptimalControl minimizes
        # (`:min`) or maximizes (`:max`) `mayer + ∫ lagrange`. The two integrands may differ by a
        # factor (a sign, a scale) that the weight takes back.
        w = d.cost(1.0, x0, xf, v) - d.cost(0.0, x0, xf, v)
        if OC.has_lagrange_cost(ocp)
            L = OC.lagrange(ocp)
            ok[:lagrange] = all(p -> close_to([sign * L(p.t, p.x, p.u, p.v)], [w * d.lagrange(p.x, p.u, p.v, p.t)]), pts)
        else
            ok[:lagrange] = isnothing(d.lagrange)
        end
        g = OC.has_mayer_cost(ocp) ? OC.mayer(ocp)(x0, xf, v) : 0.0
        ok[:mayer] = close_to([d.cost(0.0, x0, xf, v)], [sign * g])
        # path constraints, matched by (bounds, values at the points)
        plb, pub, P = oc_inplace(OC.path_constraints_nl(ocp), n)
        key(l, u, vals) = Tuple(round.([l; u; vals]; sigdigits=8) .+ 0.0)
        oc_keys = [key(plb[i], pub[i], [P(p.t, p.x, p.u, p.v)[i] for p in pts]) for i in eachindex(plb)]
        jm_keys = [key(l, u, [first(vec1(g(p.x, p.u, p.v, p.t))) for p in pts]) for (l, g, u) in d.path]
        ok[:path] = sort(oc_keys) == sort(jm_keys)
        blb, bub, B = oc_boundary(OC.boundary_constraints_nl(ocp))
        oc_b = [key(blb[i], bub[i], B(x0, xf, v)[i:i]) for i in eachindex(blb)]
        jm_b = [key(l, u, [first(vec1(g(x0, xf, v)))]) for (l, g, u) in d.boundary]
        ok[:boundary] = sort(oc_b) == sort(jm_b)
        for (name, jc, dim, box) in ((:state_box, d.state, n, OC.state_constraints_box(ocp)),
                                     (:control_box, d.control, m, OC.control_constraints_box(ocp)),
                                     (:variable_box, d.variable, nv, OC.variable_constraints_box(ocp)))
            ol, ou = oc_box(box, dim)
            jl, ju = jump_box(jc)
            ok[name] = !(any(x -> x isa AbstractVector, jl) || any(x -> x isa AbstractVector, ju)) && close_to(ol, jl) && close_to(ou, ju)
        end
        return ok
    end
    
    end # module

    5. Decisions

    Decision
    D1 model[:time_grid] takes an optional value function. Done.
    D2 test_contract builds small models per problem to check what the problem file forwards (three builds instead of two). Done.
    D3 TestStatus.for_each_problem(...; only=). Done.
    D4 One branch and one PR, one commit per phase.
    D5 The JuMP vs CTDirect NLP comparison moves to the representative subset; for every problem it is replaced by the continuous comparison.
    D6 In the pull request, JuMP is compared with ADNLP only; Exa vs ADNLP is dropped from the pull request.
    D7 test_nonzeros removed (guard on a quirk of NLPModelsJuMP, no use here).
    D8 The smoke solves of the OptimalControl environments are unchanged: the scope gate already limits them to the changed problems.
    D9 New cron comparison: the NLP comparison JuMP vs OptimalControl (ADNLP), trapeze/interleaved, every problem (discretization without solver: discretize + nlp_model, MathOptNLPModel, then NLPModels obj, grad, cons, jac, hess compared to 1e-10; this is the existing Equivalence).

    To confirm: with D9 limited to JuMP vs OptimalControl, Exa vs ADNLP (a property of OptimalControl, known gap #284) and the scalarized NLP comparison are tested nowhere: the Exa modeler is still exercised by the smoke solves, and the scalarized model by the continuous comparison. Say so if either should go in the cron.

    6. Remaining work (phase E), in order

    1. E1 — commit model[:problem_data] = data in schemes/build.jl; add the key to the model-dictionary test in test_build.jl; CHANGELOG.md line.
    2. E2 — test/common/continuous.jl (from the prototype: several (x0, xf) pairs for the boundary, a docstring per function, errors reported with the failing key, not a bare false) and test/suite/comparison/test_modelings.jl: for_each_problem for the pairs (JuMP, OptimalControl) and (JuMP, OptimalControlScalarized), one Test.@test per key; report name test_modelings. Cheap (about 30 s for all).
    3. E3 — test_equivalence.jl: only the representative subset, JuMP vs ADNLP, 4 schemes × 2 orderings; remove test_exa, test_scalarized, test_nonzeros and the Exa/scalarized helpers from common/equivalence.jl (keep Equivalence.test_jump, PermutedNLP, compare, reference). ⛔ ask before deleting.
    4. E4 — cron comparison: test/cron/comparison/test_equivalence.jl running Equivalence on every problem (it runs in the environment of suite/comparison/); a workflow .github/workflows/CronComparison.yml modeled on CronJuMP.yml (cron-reusable.yml, a free weekday, for instance Friday 4 h); a scope in tools/cron/report.py and its test (test_initial_issue_body_prepopulates_all_known_scopes). Check first how the reusable workflow and the report treat a failing test: the convergence crons report and never fail, whereas this one must fail on a difference.
    5. E5 — mutation checks, each shown to fail, in a problem outside the subset and in a scalarized file: a sign in the dynamics, a bound, a constraint dropped, the Lagrange integrand; revert each.
    6. E6 — test/README.md (rewrite "What is compared, and what is not" with the final scheme: continuous comparison for every problem, discretization on the subset, NLP comparison in the cron), CHANGELOG.md, tools/ci/test/test_scope.py case if needed, full run, before/after table.
    7. E7 — the closing summary, as a comment on the PR and in test/README.md: what is tested, by whom, why (the four-point philosophy of §1), where a failure points (one problem → its modeling; subset or test_build → the transcription; cron → the NLP), and the numbers.

    7. Handoff notes

    • Run tests with ct-dev-mcp (get_test_command, then generate_report), or julia --project -e 'using Pkg; Pkg.test(; test_args=[...])' 2>&1 | tee /tmp/<log>. Useful scopes: ["JuMP"], ["comparison","features"], ["core"], ["OptimalControl","OptimalControlScalarized","problem=beam"], add "cron" for the cron files. Intermediate phases never run the full suite.
    • A test environment is built from test/suite/<env>/Project.toml in a temporary directory; to run a script against the checkout, copy that Project.toml to a scratch directory, Pkg.develop(path=<repo>), Pkg.instantiate(), then julia --project=<scratch> script.jl.
    • No problem name may be written in src/, test/ or the extension files (core/test_consistency): select problems from the catalogue or the features.
    • The GPU smoke files are the same kind of duplicate: Share the GPU smoke test between OptimalControl and OptimalControlScalarized #445.
    • Not changed by this work: the convergence and robustness crons, the solves, the problems.
    • The Manifest of docs/ was modified before this work and is in no commit.
  5. ocots commented on Nov 10, 2026

    @ocots
    MemberAuthor

    Addendum to the status report: three clarifications from the maintainer

    1. The objective is compared, not its decomposition. insurance and ducted_fan are the same problem in both modelings, written with the same formula: OptimalControl writes -∫(U(t) * fx) → min and (1 / tf) * ∫(…) + μ tf → min; the OptimalControl parser puts the sign and the factor 1/tf inside the Lagrange integrand, whereas the JuMP ProblemData keeps cost(I, x0, xf, v) = -I and (1/v[1]) * I + μ v[1] around the integral. No problem file needs to change. The continuous check therefore compares the objective on the same sampled trajectories, with the same quadrature Q (trapezoidal rule on the sample times) on both sides, and no weight w:

    J_jump = data.cost(Q(t -> data.lagrange(x(t), u(t), v, t)), x0, xf, v)
    J_oc   = sign * (mayer(x0, xf, v) + Q(t -> lagrange(t, x(t), u(t), v)))   # sign = +1 for :min, −1 for :max

    for several trajectories (the initial guess plus perturbations of different sizes, since the objective is not affine). This replaces the w · lagrange comparison of the previous comment (§4).

    2. What OptimalControlProblems.jl guarantees, and what it does not. The package guarantees that the user solves the same problem with every modeling it provides (JuMP, OptimalControl, OptimalControlScalarized), and that its own JuMP discretization is CTDirect's. It does not test OptimalControl itself. So, decision D9 is revised:

    • the NLP comparison is JuMP vs OptimalControl (ADNLP) only, in the pull request on the representative subset, in the cron on every problem;
    • Exa vs ADNLP and the scalarized-vs-vector NLP comparison are tested nowhere in this repository (not even in the cron): they are properties of OptimalControl and CTDirect;
    • everything that exists only because the JuMP discretization lives in this package is marked as removable when it moves out (suite/JuMP/test_build.jl, test_tableaux.jl, common/equivalence.jl, common/representative.jl for the schemes, the cron comparison): say so in a header comment and in test/README.md, so that the day it is released as a package these tests are deleted, not maintained.

    3. The cron fails on a difference. Convergence is reported and not tested because it depends on the platform (several local solutions). The NLP comparison is deterministic (no solver, no platform dependence), so a difference is a real defect, and a cron that never fails would tell nobody that the JuMP model drifted from OptimalControl's. What I verified in tools/cron/report.py and cron-reusable.yml: a row with outcome fail or error is a failure finding (cron-failure label) and the workflow runs report.py --tests-failed and ends with a failing job when a test failed; the summary issue of a scope is created, updated and reopened by the report. To confirm in E4 by a dry run of report.py on a results directory with one failing row, before creating CronComparison.yml.

  6. ocots commented on Nov 11, 2026

    @ocots
    MemberAuthor

    Draft PR: #446. It implements the revised plan (phase E included); the closing summary of what is tested, and why, is in its description and in test/README.md.

    Measured, no sleep, against main: comparison environment 15704 tests / 83 min → 4615 tests / 3 min 25 s; JuMP 6280 → 1123 tests; new test_modelings (every problem, JuMP vs OptimalControl and Scalarized, no discretization) 312 tests / 15 s; new weekly cron comparison (NLP of every problem vs CTDirect's ADNLP) 1911 tests / 3 min 31 s.

    One open question for the maintainer, in the PR: since the all-problem NLP comparison now costs 3.5 min and a pull request only runs the problems it changes, it could run in the pull request instead of the cron.

  7. added a commit that references this issue on Nov 11, 2026
  8. ocots commented on Nov 11, 2026

    @ocots
    MemberAuthor

    Merged in #446 (b1e7a1d). Summary of what the test suites now do:

    • Every problem, no discretization (suite/comparison/test_modelings): the JuMP modeling against OptimalControl and OptimalControlScalarized at the continuous level (times, dynamics, objective, path and boundary constraints, bounds). 312 tests, about 15 s.
    • The JuMP discretization, once: on fake problems (suite/JuMP/test_build), and against CTDirect's ADNLP on a few representative problems computed from the features, with every scheme and ordering. All of it is marked as leaving with the JuMP discretization.
    • Weekly cron comparison: the NLP of every problem against CTDirect's. It stays in the cron so that the CI time does not grow when problems are added. A difference fails the run and appears in the cron-failure issue of the scope comparison.
    • Shared tests for the two OptimalControl modelings (common/optimalcontrol_tests.jl); the initial guess is shared by construction and has no test of its own.
    • Removed: the Exa and scalarized NLP comparisons (OptimalControl's job), test_nonzeros, test_start, test_init, test_kwargs.

    The comparison environment went from 15704 tests (83 min) to 4615 tests (about 4 min on the CI runner). CI on the PR was green, including the cron part (1911 tests).

    Left to do: run CronComparison.yml once by workflow_dispatch to check the workflow itself and its cron-failure section. Sharing the GPU smoke tests is in #445.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions