Python engineer reviewing SciPy least_squares results and checking residuals against acceptance limits.

Why SciPy least_squares Reports Success with Large Residuals

Wed, Nov 25, 2026

Two targets ask a one-parameter model to equal 1 and 3 at the same time. The least-squares compromise is p = 2: its residuals are +1 and −1, its gradient cancels to zero, and SciPy can legitimately report successful gradient termination. If the application's declared requirement is instead that every residual have magnitude at most 0.25, that candidate is unusable.

There is no contradiction. scipy.optimize.least_squares solves a stated least-squares optimization problem and reports why its algorithm stopped. Its success flag does not import an application's independent residual-acceptance rule. In SciPy 1.17.0, least_squares documents success=True when a convergence criterion produced a positive status; for method='trf', gtol concerns a gradient measure scaled to account for bounds.

This article builds a deliberately small laboratory around that distinction: ordinary CPU float64, one parameter, finite bounds, affine residuals, and one bounded quadratic counterexample. The proposed baseline is Python 3.12.14, NumPy 2.3.5, and SciPy 1.17.0. The ten behavioral cases below are EXPECTED / NOT EXECUTED. No optimizer transcript, warning count, timing, or PASS result is claimed.

The objective is operational: preserve the candidate and its evidence, independently recompute what matters, and return exactly one of ACCEPT, HOLD_RESIDUAL, HOLD_TERMINATION, or HOLD_EVIDENCE. Changing a starting point, evaluation budget, or bound is a separate reviewed revision, not a way to redefine the original requirement after seeing an inconvenient answer.

Define what a candidate must satisfy

Before looking at a solver result, fix the problem that the result is supposed to answer.

For the affine cases, the authored residuals are

r_i(p) = p − t_i,

with a single parameter p, an m × 1 Jacobian consisting entirely of ones, explicit finite lower and upper bounds, immutable target identities and ordering, and a strictly interior starting value. With loss='linear', SciPy's documented least-squares cost is one half the sum of squared residuals.

The application's synthetic acceptance rule is separate:

|r_i| ≤ 0.25 for every residual i.

That number is an authored laboratory budget. It has no claimed measurement calibration, statistical interpretation, or scientific authority. Real fitting tasks do not generally require zero residuals, and this article does not propose that they should. The acceptable residual scale has to come from the problem owner. For broader prerequisite context around statistical modelling and residual interpretation, the surrounding statistical question is how residuals relate to the model and application; here the narrower concern is whether a returned numerical candidate satisfies a rule already declared before fitting.

The gate uses four decisions. ACCEPT means the retained evidence is coherent, termination is successful, and every independently recomputed residual satisfies 0.25. HOLD_RESIDUAL means evidence is coherent and termination is successful, but at least one residual exceeds that budget. HOLD_TERMINATION means the evidence is coherent but the solver did not terminate successfully. HOLD_EVIDENCE means the record cannot safely support the other classifications because required evidence is missing, non-finite, malformed, unexpectedly warned, or internally inconsistent.

Laboratory assertions have another role. They ask whether a future execution matches this article's expected ten-case behavior. A case can therefore be a successful laboratory case while deliberately producing HOLD_RESIDUAL or HOLD_TERMINATION. A hypothetical PASS_10_CASES would mean the expected behavior inventory reconciled; it would not mean ten application candidates were accepted.

Read SciPy's stopping criteria

SciPy 1.17.0 documents least_squares as minimizing a sum-of-squares objective subject to bounds. Its returned OptimizeResult includes x, cost, the least-squares residual vector fun, optimality, active_mask, evaluation counts, status, message, and success. Use the least_squares documentation for the meaning of its residual-valued fun: the generic OptimizeResult page describes result fields across multiple solvers and notes that fields are solver dependent.

For this fixture, ftol=None disables termination based on cost change and xtol=None disables termination based on parameter-step size for trf. The only enabled convergence tolerance is gtol=1e-10, except L08 overrides it to 1e-12. SciPy 1.17.0 documents the trf gradient condition as

‖g_scaled‖∞ < gtol,

where the scaling accounts for bounds. It also documents status 1 as satisfaction of gtol, status 0 as exhaustion of the maximum number of function evaluations, and success=True when the termination status is positive.

Do not generalize those integers to every SciPy optimizer. OptimizeResult.status is explicitly solver dependent. The message and solver-specific documentation belong with the number.

The official SciPy v1.17.0 tagged least_squares.py page contains the termination-message mapping, including status 0 for an exceeded evaluation maximum and status 1 for gtol; the public API documentation independently states the positive-status success rule. A separately reported inspection of an installed 1.17.0 source tree observed assignment of success from positive status. That source inspection did not execute the behavioral fixture.

This distinction is also different from the separate curve_fit covariance contract. That article concerns how weighting conventions affect reported covariance. The present laboratory excludes covariance, weighting, and uncertainty reporting and instead audits direct least_squares termination against an independently declared residual rule.

Separate cost, gradient, and residual requirements

Three quantities answer three different questions.

The cost

C(p) = (1/2) ∑_i [r_i(p)]²

measures the least-squares objective. A gradient condition asks whether a first-order change in the parameter can reduce that objective according to the solver's stopping test. The residual budget asks whether each individual mismatch is small enough for the application.

For targets 1 and 3,

r(p) = (p − 1, p − 3),

and the scalar gradient for the linear-loss affine model is

g(p) = Jᵀr = (p − 1) + (p − 3) = 2p − 4.

At p = 2, g = 0 although r = (1, −1). The residuals cancel in the derivative but not in the application gate. Tightening a gradient tolerance cannot turn mutually incompatible equations into compatible ones.

That is the central reason successful least_squares termination and application residual acceptance must not be treated as synonyms.

Pin the environment and preserve the inputs

Use an isolated environment so that any future execution can state exactly which Python and package versions it actually loaded. The proposed interpreter baseline is Python 3.12.14; naming an executable python3.12 does not prove its patch release, so verify it before installing the numerical packages.

python3.12 -c 'import sys; print(sys.version); assert sys.version_info[:3] == (3, 12, 14)'
python3.12 -m venv .venv-lsq-acceptance
. .venv-lsq-acceptance/bin/activate

python -m pip install --upgrade pip
python -m pip install 'numpy==2.3.5' 'scipy==1.17.0'

python - <<'PY'
import platform
import sys
import numpy
import scipy

print("python:", sys.version)
print("numpy:", numpy.__version__)
print("scipy:", scipy.__version__)
print("platform:", platform.platform())

assert sys.version_info[:3] == (3, 12, 14)
assert numpy.__version__ == "2.3.5"
assert scipy.__version__ == "1.17.0"
PY

The versioned SciPy 1.17.0 documentation identifies that API version explicitly. Python's currently served 3.12 documentation branch identified itself as 3.12.16 when checked on the research date, so documentation-branch maintenance and the proposed 3.12.14 runtime should not be conflated. The fractions API behavior used below is documented on that Python 3.12 branch.

Package pins are still not a complete binary lock: they do not by themselves identify every wheel build, platform library, installer state, or native numerical dependency. The laboratory therefore records runtime metadata and should retain its exact source alongside the evidence. Readers wanting broader ecosystem context can treat Python libraries for scientific computing as background, not as a substitute for recording the specific versions actually used here.

The common solver configuration is deliberately narrow:

method="trf"
loss="linear"
x_scale=1.0
tr_solver="exact"
ftol=None
xtol=None
gtol=1e-10
max_nfev=100

Every bound is finite, every ordinary start is strictly inside it, every parameter has shape (1,), and every solver array is float64. L07 overrides max_nfev; L08 overrides gtol. Those are the only manifest overrides.

Record metadata without inventing execution

The reported metadata inspection on November 25, 2026 identified Python 3.12.14, NumPy 2.3.5, and SciPy 1.17.0; source files were also inspected. No optimizer call was executed.

A future behavioral run should generate new evidence containing its own interpreter and package versions, platform, source digest, exact manifest, candidate diagnostics, warnings, stdout, stderr, and process exit status. Do not borrow timestamps, digests, warning counts, or a PASS marker from another experiment.

A convenient shell wrapper is:

python least_squares_acceptance_lab.py \
  > least_squares_acceptance.json \
  2> least_squares_acceptance.stderr
printf '%s\n' "$?" > least_squares_acceptance.exit
sha256sum least_squares_acceptance_lab.py \
  > least_squares_acceptance.source.sha256

Until such an execution exists, every behavioral row in this article remains EXPECTED / NOT EXECUTED.

Derive expectations before calling the solver

The affine optimum is simple enough that SciPy should not be its own oracle.

For targets t_1, …, t_m,

C(p) = (1/2) ∑_i (p − t_i)².

Differentiating gives

C′(p) = ∑_i (p − t_i) = mp − ∑_i t_i.

The unconstrained optimum is therefore the target mean,

t̄ = (1/m) ∑_i t_i.

With scalar finite bounds [l, u], the exact constrained optimum is

p* = min(max(t̄, l), u).

The corresponding residuals are p* − t_i, and the exact cost is one half their squared sum.

The laboratory constructs these expectations with Fraction from authored integer literals rather than converting the eventual float64 arrays back into rationals. Python 3.12 documents exact rational construction from integer and string inputs; it also warns that constructing Fraction from a binary float preserves the exact supplied binary value rather than recovering a decimal value someone may have intended.

For example, L02 has targets 1 and 3:

t̄ = (1 + 3)/2 = 2, p* = 2,

so

r* = (1, −1), C* = (1/2)[1² + (−1)²] = 1.

L04 has targets 3 and 3 but bounds [0, 1]. The unconstrained mean is 3, so clipping gives p* = 1; its residuals are (−2, −2) and C* = 4. L05 similarly clips the mean −2 upward to 0, yielding (2, 2) and cost 4.

The second oracle is computed after a candidate returns. Given only the preserved model identity, original target literals, and returned scalar p, the laboratory reconstructs residuals with fresh scalar arithmetic. It does not call the solver's residual callback again and does not use result.fun to decide application acceptance. It independently computes

C_independent = (1/2) ∑_i [r_(i, independent)]²

and reconciles that evidence against result.fun and result.cost.

For the nonlinear control,

r(p) = p² − 4, J(p) = 2p,

with bounds [−3, 3]. The zero-residual roots are exactly −2 and 2. The least-squares objective is

F(p) = (1/2)(p² − 4)².

Those roots are analytical optima with zero cost, but they do not describe every possible stopped candidate.

Keep optimum and stopped-candidate oracles separate

L07 and L09 are designed specifically to prevent oracle collapse.

L07's authored affine optimum is p* = 2, but max_nfev=1 is expected to stop at its initial p = 0.5. The optimum oracle remains 2; the expected stopped-candidate oracle remains 0.5.

L09's mathematical zero-cost optima are ±2, while its expected stopped candidate is p = 0 because the Jacobian and gradient vanish at the starting point. Treating “expected returned parameter” as “mathematical optimum” would erase the phenomenon the test is meant to expose.

For converged affine cases and L10, the future fixture reconciles the returned float64 shape (1,) with the indicated optimum using rtol=0, atol=1e-8, equal_nan=False, and strict=True. NumPy 2.3 documents that assert_allclose(..., strict=True) additionally enforces matching shape and dtype, while equal_nan=False prevents paired NaNs from being accepted as equal. This 1e-8 is only a fixture reconciliation allowance. It is never added to the application's 0.25 residual budget.

Establish feasible and incompatible affine controls

L01 is the clean feasible control. With targets (2,2), bounds [-10,10], and start 0.5, the exact mean is 2 and lies inside the bounds. The exact optimum is therefore p* = 2, giving residuals (0,0) and cost 0. The expected SciPy outcome is status 1 and successful gtol termination. Because every independently recomputed residual also satisfies the application rule, the expected candidate decision is ACCEPT.

L02 changes only the targets to (1,3). The optimum remains 2, but now that compromise leaves residuals (1,-1) and cost 1. Its gradient is zero, so successful status-1 termination is entirely consistent with the least-squares problem. The application nevertheless rejects both residuals against 0.25, producing HOLD_RESIDUAL.

That pair is the simplest demonstration that successful termination and acceptable residuals are separate predicates.

The complete laboratory below is intentionally self-contained. The manifest is authored first, with literal IDs, model identity, target identity and order, bounds, starts, expected stopped candidates, and overrides preserved before any NumPy solver arrays are constructed.

from future import annotations

import hashlib
import json
import platform
import sys
import warnings
from fractions import Fraction

import numpy as np
import scipy
from numpy.testing import assert_allclose
from scipy.optimize import least_squares


APPLICATION_RESIDUAL_BUDGET = 0.25
DIAGNOSTIC_ATOL = 1e-8

COMMON = {
    "method": "trf",
    "loss": "linear",
    "x_scale": 1.0,
    "tr_solver": "exact",
    "ftol": None,
    "xtol": None,
    "gtol": 1e-10,
    "max_nfev": 100,
}

TARGETS = {
    "T22": (2, 2),
    "T13": (1, 3),
    "T33": (3, 3),
    "TN2N2": (-2, -2),
}

CASES = (
    dict(id="L01", model="affine", target_id="T22",
         bounds=(-10, 10), start=Fraction(1, 2),
         expected_stop=Fraction(2), expected_status=1,
         expected_success=True, expected_decision="ACCEPT"),
    dict(id="L02", model="affine", target_id="T13",
         bounds=(-10, 10), start=Fraction(1, 2),
         expected_stop=Fraction(2), expected_status=1,
         expected_success=True, expected_decision="HOLD_RESIDUAL"),
    dict(id="L03", model="affine", target_id="T13",
         bounds=(-10, 10), start=Fraction(2),
         expected_stop=Fraction(2), expected_status=1,
         expected_success=True, expected_nfev=1,
         expected_decision="HOLD_RESIDUAL"),
    dict(id="L04", model="affine", target_id="T33",
         bounds=(0, 1), start=Fraction(1, 2),
         expected_stop=Fraction(1), expected_status=1,
         expected_success=True, expected_decision="HOLD_RESIDUAL"),
    dict(id="L05", model="affine", target_id="TN2N2",
         bounds=(0, 1), start=Fraction(1, 2),
         expected_stop=Fraction(0), expected_status=1,
         expected_success=True, expected_decision="HOLD_RESIDUAL"),
    dict(id="L06", model="affine", target_id="T33",
         bounds=(0, 4), start=Fraction(1, 2),
         expected_stop=Fraction(3), expected_status=1,
         expected_success=True, expected_decision="ACCEPT"),
    dict(id="L07", model="affine", target_id="T22",
         bounds=(-10, 10), start=Fraction(1, 2),
         overrides={"max_nfev": 1},
         expected_stop=Fraction(1, 2), expected_status=0,
         expected_success=False,
         expected_decision="HOLD_TERMINATION"),
    dict(id="L08", model="affine", target_id="T13",
         bounds=(-10, 10), start=Fraction(2),
         overrides={"gtol": 1e-12},
         expected_stop=Fraction(2), expected_status=1,
         expected_success=True, expected_nfev=1,
         expected_decision="HOLD_RESIDUAL"),
    dict(id="L09", model="quadratic", target_id=None,
         bounds=(-3, 3), start=Fraction(0),
         expected_stop=Fraction(0), expected_status=1,
         expected_success=True, expected_nfev=1,
         expected_decision="HOLD_RESIDUAL"),
    dict(id="L10", model="quadratic", target_id=None,
         bounds=(-3, 3), start=Fraction(1),
         expected_stop=Fraction(2), expected_status=1,
         expected_success=True, expected_decision="ACCEPT"),
)

EXPECTED_IDS = {
    "L01", "L02", "L03", "L04", "L05",
    "L06", "L07", "L08", "L09", "L10",
}

The remainder of that script appears below with the acceptance gate; keeping it in one file matters because the manifest, solver call, independent recomputation, and evidence ledger must share one traceable identity.

Start at an incompatible stationary point

L03 uses the same incompatible targets and bounds as L02 but starts exactly at p = 2.

At that point,

r = (1, −1)

and, because the affine Jacobian is (1,1),

Jᵀr = 1 + (−1) = 0.

No iteration is needed to discover that the first-order gradient condition is already satisfied. The expected result is therefore p = 2, status 1, success=True, and nfev=1. The residual gate still yields HOLD_RESIDUAL.

L08 repeats L03 while changing gtol from 10⁻¹⁰ to 10⁻¹². The exact authored gradient at the start remains zero, which is below either positive tolerance. Its expected behavior is again immediate status-1 termination with one function evaluation and the same residual hold.

This control is important because “tighten the optimizer tolerance” is often proposed reflexively when residuals look too large. Here no amount of merely reducing gtol can make one scalar p equal both 1 and 3. Extra numerical precision is not a model repair, and an optimization tolerance is not an application residual tolerance.

Examine successful solutions at the bounds

L04 and L05 exercise a different reason for nonzero residuals after successful least_squares termination: the residuals are reducible in the unconstrained problem, but the permitted parameter interval excludes the zero-residual solution.

L04 has targets (3,3) and bounds [0,1]. The exact unconstrained mean is 3, but the constrained optimum is

p* = 1.

That produces residuals

(−2, −2)

and cost

(1/2)(4 + 4) = 4.

The optimizer can therefore converge successfully at the best value allowed by the declared bounds while the application residual budget is badly violated. The expected decision is HOLD_RESIDUAL.

L05 is the reflected case. Targets (-2,-2) have mean -2, but bounds [0,1] force the constrained optimum to p* = 0. Its residuals are (2,2), again with cost 4 and an expected residual hold.

For unconstrained affine least squares, the raw gradient at L04's upper-bound optimum would point toward increasing p, and at L05's lower-bound optimum it would point toward decreasing p. Those directions are infeasible. SciPy's documented trf first-order condition uses a gradient measure scaled to account for bounds, and its returned optimality is the quantity compared with gtol in constrained iterations. A nonzero ordinary raw derivative at a binding constraint is therefore not, by itself, evidence of a solver defect.

The maintenance check should instead ask two independent questions: is this actually the constrained optimum of the authored mathematical problem, and does that optimum meet the application's acceptance rule? For L04 and L05 the expected answers are yes and no.

Treat active_mask as a diagnostic

Record active_mask, but do not turn it into a brittle oracle.

SciPy 1.17.0 documents -1, 0, and 1 as lower-active, inactive, and upper-active indications. It also cautions that active_mask can be somewhat arbitrary under trf, because the method maintains strictly feasible iterates and determines activity within a tolerance threshold.

Accordingly, the fixture records the field but does not require L04 to return exactly 1 or L05 exactly -1. It also does not demand exact floating-point equality between the candidate and a bound. The analytical optimum and the candidate are reconciled with the declared 1e-8 diagnostic allowance, while actual bounds compliance is checked directly.

That prevents a secondary diagnostic from replacing the real evidence: preserved bounds, independently derived optimum, independently recomputed residuals, and the solver's own termination fields.

Review a changed-bound comparison

L06 uses L04's targets (3,3) and the same start 0.5, but it changes the declared bounds from [0,1] to [0,4].

Under that new synthetic contract, the mean 3 is now feasible:

p* = 3, r = (0, 0), C = 0.

The expected solver outcome is successful status-1 termination and the expected application decision is ACCEPT.

The comparison is numerically useful precisely because the original L04 result is preserved. L04 demonstrates the old contract: constrained optimum 1, residual failure. L06 demonstrates a separately declared contract: optimum 3, residual acceptance.

Nothing about the improvement authorizes widening a real parameter range. A bound may encode physics, safety, design authority, policy, or some other domain requirement that a numerical maintainer is not entitled to rewrite. The domain owner responsible for that operating range must decide whether a changed bound is legitimate. The numerical maintainer's responsibility is to show what consequence the proposed revision has and to keep the old evidence available.

If a proposed revision is rejected or produces unacceptable evidence, restore the prior reviewed configuration rather than silently leaving the exploratory bound in place.

Stop after the evaluation budget

L07 returns to L01's feasible problem (targets (2,2), bounds [-10,10], start 0.5) but changes max_nfev from 100 to 1.

The analytical optimum is still 2. The expected stopped candidate is instead the untouched start, 0.5, with residuals

(−1.5, −1.5)

and cost

(1/2)(2.25 + 2.25) = 2.25.

SciPy 1.17.0 documents status 0 as termination because the maximum number of function evaluations was exceeded; positive status, not status 0, is what constitutes successful convergence for least_squares. The expected application classification is therefore HOLD_TERMINATION, not HOLD_RESIDUAL, because valid evidence showing an unsuccessful termination is classified before the residual budget.

That ordering preserves cause. The residuals are indeed too large, but the candidate is already held because the configured optimization process did not successfully terminate.

Increasing max_nfev is a reasonable reviewed diagnostic revision when evaluation exhaustion prevents convergence, but it does not alter the mathematical compatibility of the requirements. A larger budget would help L07 reach its feasible optimum; it would not make L02's targets 1 and 3 simultaneously satisfiable.

Expose the nonlinear stationary-start trap

The quadratic case prevents another overreach: replacing “success means acceptable residuals” with “success proves a local minimum.”

Define

r(p) = p² − 4, J(p) = 2p

inside bounds [-3,3]. Its zero-residual roots are p = ±2, each with cost zero.

At L09's start p = 0,

r(0) = −4, J(0) = 0.

For a scalar least-squares residual the gradient is

F′(p) = J(p)r(p) = 2p(p² − 4).

Thus

F′(0) = 0.

A gradient-based termination condition can therefore be satisfied immediately even though the residual magnitude is 4, sixteen times the laboratory's 0.25 budget.

More importantly, zero gradient does not make p = 0 a local minimum. Write the objective explicitly:

F(p) = (1/2)(p² − 4)².

Then

F′(p) = 2p(p² − 4)

and

F″(p) = 6p² − 8.

At zero,

F″(0) = −8 < 0.

So p = 0 is a strict local maximum of this one-dimensional objective, not a minimum. L09's expected status-1, success=True, nfev=1 outcome would establish only that the configured first-order stopping test is satisfied at the starting point. It would not establish that the candidate minimizes the objective locally, and certainly not that its residual meets the application rule.

The expected candidate is p = 0, residual (-4,), cost 8, and HOLD_RESIDUAL.

This counterexample is deliberately bounded and elementary. It does not claim that least_squares commonly terminates at maxima, nor does it generalize every nonlinear problem. Its role is narrower: a successful gradient stop is not a logical certificate of the stronger property “this point is an acceptable local minimum.”

Compare the zero start with a nonzero start

L10 keeps the same quadratic model and [-3,3] bounds but changes the start from 0 to 1.

Its expected stopped candidate is the positive root p ≈ 2, with residual approximately zero, cost approximately zero, and successful status-1 termination. The future fixture reconciles that candidate against float64([2.0]) using the same rtol=0, atol=1e-8, equal_nan=False, strict=True diagnostic rule used for converged affine cases.

This is a controlled starting-point comparison, not a qualification of every possible start. The negative root is also an exact mathematical solution. Nor does L10 authorize changing a real starting state merely because one starting point produces a more convenient result. A revised start must remain traceable as a revised numerical assumption whose appropriateness is reviewed.

Implement the separate residual acceptance gate

The acceptance gate must operate on evidence that is independent enough to catch self-consistent mistakes. It therefore validates shapes and finiteness, checks bounds, recomputes residuals and cost from preserved authored inputs, reconciles SciPy's fields, interprets termination, and only then applies the 0.25 residual budget.

NumPy 2.3 documents isfinite as false for NaN and both positive and negative infinity, which makes it appropriate for admission checks before a record is allowed into numerical acceptance logic or JSON output. The diagnostic reconciliation below deliberately uses explicit tolerances rather than inheriting defaults; for a broader discussion of why a numerical allowance needs a stated contract, see explicit numerical tolerance policies.

Append the following to the earlier manifest in the same file:

def exact_affine_oracle(case):
    targets = tuple(Fraction(v) for v in TARGETS[case["target_id"]])
    lower, upper = map(Fraction, case["bounds"])
    mean = sum(targets, Fraction(0)) / len(targets)
    p_star = min(max(mean, lower), upper)
    residuals = tuple(p_star - t for t in targets)
    cost = sum((r r for r in residuals), Fraction(0)) / 2
    return p_star, residuals, cost


def quadratic_exact_oracle():
    return (Fraction(-2), Fraction(2)), Fraction(0)


def solver_functions(case, target_array):
    if case["model"] == "affine":
        def residual(x):
            return np.asarray(
                [float(x[0]) - float(t) for t in target_array],
                dtype=np.float64,
            )

        def jacobian(x):
            return np.ones((len(target_array), 1), dtype=np.float64)

        return residual, jacobian

    if case["model"] == "quadratic":
        def residual(x):
            p = float(x[0])
            return np.asarray([p p - 4.0], dtype=np.float64)

        def jacobian(x):
            p = float(x[0])
            return np.asarray([[2.0 p]], dtype=np.float64)

        return residual, jacobian

    raise ValueError(f"unknown model: {case['model']}")


def independent_residuals(case, candidate):
    p = float(candidate[0])

    if case["model"] == "affine":
        return np.asarray(
            [p - float(t) for t in TARGETS[case["target_id"]]],
            dtype=np.float64,
        )

    if case["model"] == "quadratic":
        return np.asarray([p p - 4.0], dtype=np.float64)

    raise ValueError(case["model"])


def independent_cost(residuals):
    total = 0.0
    for value in residuals:
        scalar = float(value)
        total += scalar scalar
    return 0.5 total


def all_finite_array(value):
    arr = np.asarray(value)
    return bool(np.all(np.isfinite(arr)))


def reconcile_array(actual, desired, label, problems):
    try:
        assert_allclose(
            np.asarray(actual),
            np.asarray(desired),
            rtol=0.0,
            atol=DIAGNOSTIC_ATOL,
            equal_nan=False,
            strict=True,
            err_msg=label,
        )
    except AssertionError as exc:
        problems.append(f"{label}: {exc}")


def expected_optimum_array(case):
    if case["model"] == "affine":
        p_star, , = exact_affine_oracle(case)
        return np.asarray([float(p_star)], dtype=np.float64)

    if case["id"] == "L10":
        return np.asarray([2.0], dtype=np.float64)

    return None


def expected_stop_array(case):
    return np.asarray(
        [float(case["expected_stop"])],
        dtype=np.float64,
    )


def application_decision(result, residuals, evidence_problems):
    if evidence_problems:
        return "HOLD_EVIDENCE"

    if not bool(result.success):
        return "HOLD_TERMINATION"

    if any(abs(float(r)) > APPLICATION_RESIDUAL_BUDGET
           for r in residuals):
        return "HOLD_RESIDUAL"

    return "ACCEPT"


def manifest_assertions():
    ids = [case["id"] for case in CASES]
    assert len(ids) == len(set(ids)), "duplicate case ID"
    assert set(ids) == EXPECTED_IDS, "manifest membership mismatch"
    assert len(ids) == 10

    by_id = {case["id"]: case for case in CASES}

    # Required cross-case identities/revisions.
    for key in ("model", "target_id", "bounds", "start"):
        assert by_id["L01"][key] == by_id["L07"][key]

    for key in ("model", "target_id", "bounds", "start"):
        assert by_id["L03"][key] == by_id["L08"][key]

    assert by_id["L04"]["model"] == by_id["L06"]["model"]
    assert by_id["L04"]["target_id"] == by_id["L06"]["target_id"]
    assert by_id["L04"]["start"] == by_id["L06"]["start"]
    assert by_id["L04"]["bounds"] != by_id["L06"]["bounds"]

    for key in ("model", "target_id", "bounds"):
        assert by_id["L09"][key] == by_id["L10"][key]
    assert by_id["L09"]["start"] != by_id["L10"]["start"]


def run_case(case):
    settings = dict(COMMON)
    settings.update(case.get("overrides", {}))

    lower_literal, upper_literal = case["bounds"]
    lower = np.asarray([float(lower_literal)], dtype=np.float64)
    upper = np.asarray([float(upper_literal)], dtype=np.float64)
    x0 = np.asarray([float(case["start"])], dtype=np.float64)

    if not (lower[0] < x0[0] < upper[0]):
        raise ValueError(f"{case['id']}: start must be strictly interior")

    if case["model"] == "affine":
        target_array = np.asarray(
            TARGETS[case["target_id"]],
            dtype=np.float64,
        )
    else:
        target_array = np.empty((0,), dtype=np.float64)

    # Preserve independent snapshots of source-derived arrays.
    x0_before = x0.copy()
    lower_before = lower.copy()
    upper_before = upper.copy()
    targets_before = target_array.copy()

    residual, jacobian = solver_functions(case, target_array)

    warning_records = []
    try:
        with warnings.catch_warnings(record=True) as caught:
            warnings.simplefilter("always")
            result = least_squares(
                residual,
                x0,
                jac=jacobian,
                bounds=(lower, upper),
                **settings,
            )
            warning_records = [
                {
                    "category": type(item.message).__name__,
                    "message": str(item.message),
                }
                for item in caught
            ]
    except Exception as exc:
        return {
            "id": case["id"],
            "evidence_state": "EXPECTED / NOT EXECUTED in article; "
                              "this field belongs to a later run",
            "unexpected_exception": {
                "type": type(exc).__name__,
                "message": str(exc),
            },
            "warnings": warning_records,
            "decision": "HOLD_EVIDENCE",
            "fixture_assertions": ["unexpected exception"],
        }

    problems = []

    if not np.array_equal(x0, x0_before):
        problems.append("source x0 array changed")
    if not np.array_equal(lower, lower_before):
        problems.append("source lower-bound array changed")
    if not np.array_equal(upper, upper_before):
        problems.append("source upper-bound array changed")
    if not np.array_equal(target_array, targets_before):
        problems.append("source target array changed")
    if warning_records:
        problems.append("unexpected warning captured")

    candidate = np.asarray(result.x)
    result_fun = np.asarray(result.fun)
    active_mask = np.asarray(result.active_mask)

    expected_m = len(TARGETS[case["target_id"]]) \
        if case["model"] == "affine" else 1

    if candidate.shape != (1,) or candidate.dtype != np.float64:
        problems.append("candidate shape/dtype mismatch")
    if result_fun.shape != (expected_m,) or result_fun.dtype != np.float64:
        problems.append("result.fun shape/dtype mismatch")
    if active_mask.shape != (1,):
        problems.append("active_mask shape mismatch")

    for label, value in (
        ("candidate", candidate),
        ("result.fun", result_fun),
        ("active_mask", active_mask),
    ):
        if not all_finite_array(value):
            problems.append(f"{label} contains non-finite values")

    for label, value in (
        ("cost", result.cost),
        ("optimality", result.optimality),
    ):
        if not np.isfinite(float(value)):
            problems.append(f"{label} is non-finite")

    if not (float(lower[0]) <= float(candidate[0]) <= float(upper[0])):
        problems.append("candidate violates declared bounds")

    independent_r = independent_residuals(case, candidate)
    independent_c = independent_cost(independent_r)

    reconcile_array(
        result_fun,
        independent_r,
        "result.fun versus independent residuals",
        problems,
    )
    reconcile_array(
        np.asarray([float(result.cost)], dtype=np.float64),
        np.asarray([independent_c], dtype=np.float64),
        "result.cost versus independent cost",
        problems,
    )

    if bool(result.success) != (int(result.status) > 0):
        problems.append("success/status reconciliation failed")

    if not isinstance(result.message, str):
        problems.append("message is not a string")

    if int(result.nfev) < 1:
        problems.append("invalid nfev")
    if result.njev is not None and int(result.njev) < 0:
        problems.append("invalid njev")

    decision = application_decision(result, independent_r, problems)

    residual_budget_verdicts = [
        {
            "index": i,
            "residual": float(value),
            "abs_residual": abs(float(value)),
            "budget": APPLICATION_RESIDUAL_BUDGET,
            "within_budget":
                abs(float(value)) <= APPLICATION_RESIDUAL_BUDGET,
        }
        for i, value in enumerate(independent_r)
    ]

    fixture_assertions = []

    if int(result.status) != case["expected_status"]:
        fixture_assertions.append(
            f"status expected {case['expected_status']} "
            f"got {int(result.status)}"
        )

    if bool(result.success) != case["expected_success"]:
        fixture_assertions.append(
            f"success expected {case['expected_success']} "
            f"got {bool(result.success)}"
        )

    if "expected_nfev" in case and int(result.nfev) != case["expected_nfev"]:
        fixture_assertions.append(
            f"nfev expected {case['expected_nfev']} "
            f"got {int(result.nfev)}"
        )

    try:
        assert_allclose(
            candidate,
            expected_stop_array(case),
            rtol=0.0,
            atol=DIAGNOSTIC_ATOL,
            equal_nan=False,
            strict=True,
        )
    except AssertionError as exc:
        fixture_assertions.append(
            f"stopped-candidate oracle mismatch: {exc}"
        )

    optimum = expected_optimum_array(case)
    if optimum is not None:
        try:
            assert_allclose(
                candidate,
                optimum,
                rtol=0.0,
                atol=DIAGNOSTIC_ATOL,
                equal_nan=False,
                strict=True,
            )
        except AssertionError as exc:
            fixture_assertions.append(
                f"optimum reconciliation mismatch: {exc}"
            )

    if decision != case["expected_decision"]:
        fixture_assertions.append(
            f"decision expected {case['expected_decision']} got {decision}"
        )

    record = {
        "id": case["id"],
        "model": case["model"],
        "target_id": case["target_id"],
        "authored_targets":
            list(TARGETS[case["target_id"]])
            if case["target_id"] is not None else None,
        "bounds": list(case["bounds"]),
        "start": float(case["start"]),
        "settings": settings,
        "candidate": candidate.tolist(),
        "independent_residuals": independent_r.tolist(),
        "result_fun": result_fun.tolist(),
        "independent_cost": independent_c,
        "result_cost": float(result.cost),
        "success": bool(result.success),
        "status": int(result.status),
        "message": result.message,
        "optimality": float(result.optimality),
        "active_mask": active_mask.tolist(),
        "nfev": int(result.nfev),
        "njev": None if result.njev is None else int(result.njev),
        "warnings": warning_records,
        "evidence_problems": problems,
        "residual_budget_verdicts": residual_budget_verdicts,
        "decision": decision,
        "fixture_assertions": fixture_assertions,
    }

    # Reject NaN/Infinity before final serialization.
    json.dumps(record, allow_nan=False)
    return record


def main():
    manifest_assertions()

    source_path = file
    with open(source_path, "rb") as handle:
        source_sha256 = hashlib.sha256(handle.read()).hexdigest()

    records = [run_case(case) for case in CASES]
    seen_ids = {record["id"] for record in records}

    report_problems = []
    if seen_ids != EXPECTED_IDS or len(records) != 10:
        report_problems.append("incomplete case report")

    fixture_pass = (
        not report_problems
        and all(
            not record.get("fixture_assertions")
            and record.get("decision") != "HOLD_EVIDENCE"
            for record in records
        )
    )

    report = {
        "evidence_status":
            "NEW EXECUTION RECORD: do not substitute article expectations",
        "python": sys.version,
        "numpy": np.__version__,
        "scipy": scipy.__version__,
        "platform": platform.platform(),
        "source_sha256": source_sha256,
        "application_residual_budget":
            APPLICATION_RESIDUAL_BUDGET,
        "diagnostic_atol": DIAGNOSTIC_ATOL,
        "expected_ids": sorted(EXPECTED_IDS),
        "report_problems": report_problems,
        "fixture_pass": fixture_pass,
        "cases": records,
    }

    print(json.dumps(report, indent=2, sort_keys=True, allow_nan=False))
    return 0 if fixture_pass else 1


if name == "__main__":
    raise SystemExit(main())

The code contains admission guards for shapes, finiteness, source-array preservation, manifest identity, bounds, warnings, and serialization. Because the article has not executed the fixture, those guards are code-level precautions, not tested coverage.

Preserve failures before reducing to one decision

The ledger should not reduce (-2,-2) to one Boolean before reviewers can see which residuals failed. Each residual therefore keeps its value, absolute value, budget, and individual budget verdict.

Likewise, the case identity, source target ID and ordering, bounds, start, solver settings, result.fun, independent residuals, two costs, status, message, optimality, active_mask, nfev, njev, and warning record all survive the aggregate decision.

result.success participates in the termination classification; it is not the aggregate application verdict.

This is also why numerical discrepancy checks are evidence checks rather than residual-budget checks. A candidate whose independently recomputed residual is 0.20 is not acceptable when result.fun claims something materially inconsistent. That is HOLD_EVIDENCE, because the record cannot establish what computation should be trusted.

Reconcile the ten-case evidence ledger

All rows below are EXPECTED / NOT EXECUTED. C means one half the sum of squared residuals, not MSE.

ID

Authored inputs

Expected stopped candidate and diagnostics

Expected decision

L01

Affine t=(2,2), bounds [-10,10], start 0.5

EXPECTED / NOT EXECUTED: p≈2, r≈(0,0), C≈0; success, status 1

ACCEPT

L02

Affine t=(1,3), bounds [-10,10], start 0.5

EXPECTED / NOT EXECUTED: p≈2, r≈(1,-1), C≈1; success, status 1

HOLD_RESIDUAL

L03

L02 targets/bounds, start exactly 2

EXPECTED / NOT EXECUTED: p=2, r=(1,-1), C=1; initial gradient stop, status 1, nfev=1

HOLD_RESIDUAL

L04

Affine t=(3,3), bounds [0,1], start 0.5

EXPECTED / NOT EXECUTED: p approaches 1, r≈(-2,-2), C≈4; success, status 1

HOLD_RESIDUAL

L05

Affine t=(-2,-2), bounds [0,1], start 0.5

EXPECTED / NOT EXECUTED: p approaches 0, r≈(2,2), C≈4; success, status 1

HOLD_RESIDUAL

L06

L04 targets/start; separately declared bounds [0,4]

EXPECTED / NOT EXECUTED: p≈3, r≈(0,0), C≈0; success, status 1

ACCEPT under changed synthetic contract

L07

L01 inputs, max_nfev=1

EXPECTED / NOT EXECUTED: p=0.5, r=(-1.5,-1.5), C=2.25; status 0, success false

HOLD_TERMINATION

L08

L03 inputs, gtol=1e-12

EXPECTED / NOT EXECUTED: p=2, r=(1,-1), C=1; status 1, nfev=1

HOLD_RESIDUAL

L09

Quadratic r=p²-4, bounds [-3,3], start 0

EXPECTED / NOT EXECUTED: p=0, r=(-4,), C=8; status 1, nfev=1, zero gradient

HOLD_RESIDUAL

L10

L09 model/bounds, start 1

EXPECTED / NOT EXECUTED: p≈2, r≈(0,), C≈0; success, status 1

ACCEPT

The required membership is exactly {L01,…,L10}; uniqueness and set equality matter because “ten records” could otherwise hide one duplicate and one missing case. Cross-case assertions also preserve the intended comparisons: L01/L07 differ only through the evaluation-budget override; L03/L08 through gtol; L04/L06 through bounds; L09/L10 through the start.

Any future warning must remain in the evidence. Because no warning is expected here, a warning creates an evidence problem rather than being discarded. An unexpected exception similarly yields HOLD_EVIDENCE. A truncated report, missing case ID, non-finite serializable diagnostic, or process failure prevents a laboratory PASS.

A discrepancy with an expected stopped candidate should be reported rather than “fixed” by moving the oracle. The expectation describes the behavior under investigation; an actual run is evidence that may confirm or contradict it.

Recover held candidates and assign ownership

A hold is a routing decision, not permission to mutate requirements until the solver turns green.

Evidence pattern

Meaning

Reviewed next action

Primary owner

Successful stop; incompatible affine residuals, as L02/L03/L08

Objective compromise is stationary but violates per-residual budget

Revisit whether one-parameter model and targets are jointly satisfiable; preserve original case

Domain/model owner with numerical maintainer

Successful bound solution; residual failure, as L04/L05

Best feasible constrained point still misses application rule

Review whether bounds and residual requirement are simultaneously legitimate

Domain owner for bounds; maintainer demonstrates consequences

Changed bound succeeds, as L06

New contract admits a zero-residual solution

Approve or reject bound revision separately; do not rewrite L04

Domain owner

Status 0 from evaluation exhaustion, as L07

Configured process did not reach successful termination

Review a larger max_nfev as a new diagnostic run

Numerical maintainer

Gradient stop at nonlinear stationary start, as L09

First-order stop does not establish a local minimum

Review start/model structure; retain L09 evidence and compare a separately identified start such as L10

Numerical maintainer plus model owner

Missing, non-finite, warned, or inconsistent diagnostics

Candidate cannot be responsibly interpreted

Repair evidence production or data admission before judging residuals

Numerical maintainer

The maintainer owns faithful implementation of the declared objective, evidence capture, independent recomputation, termination interpretation, and transparent comparison of reviewed numerical revisions. The domain owner owns the scientific or operational meaning of targets, parameter bounds, and the application residual budget.

That division matters when recovery appears numerically easy. A new start may escape L09. More evaluations may complete L07. A wider bound may transform L04 into L06. None of those numerical observations grants authority to change the original model contract.

The same engineering habit appears in a different numerical setting when evaluating residual checks against the intended mathematical problem: a diagnostic is meaningful only after the mathematical object being validated is fixed. In this least-squares case the objective itself is explicit, so the key additional question is whether its returned candidate meets a separately declared application requirement.

If a proposed revision fails review, restore the prior reviewed settings and retain both evidence records. Do not overwrite the held candidate simply because a subsequent exploratory run looks better.

Deepen numerical Python practice with Refonte Learning

The review discipline illustrated here (preserving inputs, deriving expectations independently, separating optimization diagnostics from application acceptance, and making numerical revisions explicit) sits naturally beside broader Python and statistical-modelling foundations.

Refonte Learning's Data Science & AI Program currently lists Python Data Science, Statistical Modelling, Model Optimization & Problem-Solving Techniques, EDA and visualization, machine learning, and industry-project work. Its Program Specifics section states three months and 12–14 hours per week; its tools FAQ names Python, Jupyter Notebook, Pandas, NumPy, Matplotlib, scikit-learn, and TensorFlow. The page also contains differing prerequisite and duration wording elsewhere, so prospective learners should confirm current terms directly.

SciPy coverage, least_squares, constrained optimization, this exact laboratory, and specialized mentorship availability remain unconfirmed; they should not be inferred from adjacent competencies. The page describes a virtual-internship opportunity and “Potential Internship,” not guaranteed placement, and states that successful completion can lead to a Training Certificate and Certificate of Internship.

For readers who want structured practice beyond this fixture, the appropriate next step is to review the current program details and verify that its present syllabus matches the numerical Python topics they want to develop.