← Back to Pull requests

Preserve estimator errors when `error_score="raise"` #331

Merged
ska2704 merged 2 files (32 lines) on Oct 20, 2026 03:32 UTC
View on GitHub
ska2704 ska2704 commented on Oct 12, 2026 02:11 UTC
Author

Motivation

Closes #330.

When an estimator raises ValueError, OptunaSearchCV(error_score="raise") currently builds a score array containing "raise" and fails in np.nanmean. This hides the estimator's validation message and prevents catch=(ValueError,) from continuing the search.

Description of the changes

Re-raise the original exception before constructing fallback scores, matching the existing pruning path and the documented error_score behavior. Numeric fallback scores are unchanged.

The regression test uses an invalid SGDClassifier parameter and covers pruning on and off, with and without catch. Both non-pruning cases fail on unchanged upstream and pass with this fix.

Validation:

  • pytest tests/sklearn/test_sklearn.py -q: 38 passed on Python 3.13 / scikit-learn 1.9.1 and Python 3.11 / scikit-learn 1.3.2.

  • Black, isort, Flake8, mypy, Blackdoc, and pre-commit checks pass for the affected files.
  • No documentation change is needed because the existing error_score docstring already describes this behavior.

    Diff: 32 lines (+32 / -0) across 2 files Reviewer: not522 Review duration: 11600m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.25) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.25 · 32 lines diff across 2 files
    0.25
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.95 · 5 substantive comment(s)
    0.95
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.209
    Real PR Conversation Timeline
    7 items
    ska2704 ska2704 commented on Oct 12, 2026 02:16 UTC
    Author

    The test matrix is blocked during dependency installation. The Python 3.9 job installs Optuna's current development branch, which now requires Python 3.10 or later. Tests never start, and fail-fast cancels the other Python versions.

    The same error occurs in the scheduled Python 3.9 job on unchanged main:

    the current Python version (3.9.25) does not satisfy Python>=3.10
    

    Additional local verification of this branch:

  • Python 3.9.25, scikit-learn 1.6.1, and released Optuna 5.0.0: all 38 sklearn tests pass.

  • Python 3.13.13, scikit-learn 1.9.1, and the exact Optuna development commit used by CI (13a3ff1c78314b6a1117dcee9dbbe54ab66788f9): all 38 sklearn tests pass.
  • The style/type checks, Reviewdog, Sphinx, and Read the Docs builds passed. Rerunning a cancelled job through the API requires repository admin access, so the hosted test matrix still needs a maintainer rerun after the dependency mismatch is resolved.

    not522 not522 commented on Oct 19, 2026 07:53 UTC
    Contributor

    Could you merge the main branch to fix the CI fail?

    ska2704 ska2704 commented on Oct 19, 2026 08:06 UTC
    Author

    Merged the latest main (c2cc20b4) in 30f4726. The test matrix now passes on Python 3.10, 3.11, 3.12, and 3.13. The style/type checks and Sphinx build also passed.

    The full sklearn suite passed locally as well: 38 tests. The PR diff still contains only the error-handling fix and its regression tests.

    not522 not522 commented on code on Oct 19, 2026 10:43 UTC
    Code Review
    tests/sklearn/test_sklearn.py:1
    @@ -372,6 +373,34 @@ def test_objective_y_None() -> None:
             optuna_search.fit(X)
     
     
    +@pytest.mark.parametrize("enable_pruning", [True, False])
    +@pytest.mark.parametrize("catch", [(ValueError,), ()])
    +def test_objective_error_score_raise(
    +    enable_pruning: bool, catch: tuple[type[Exception], ...]
    +) -> None:
    +    X = np.arange(24).reshape(12, 2)
    +    y = np.arange(12) % 2
    +    with pytest.warns(ExperimentalWarning):
    +        optuna_search = OptunaSearchCV(
    +            SGDClassifier(alpha=-1.0),
    +            {},
    +            cv=2,
    +            enable_pruning=enable_pruning,
    +            error_score="raise",
    +            n_trials=2,
    +            refit=False,
    +            catch=catch,
    +        )
    +
    +    if catch:
    +        optuna_search.fit(X, y)
    +        assert len(optuna_search.trials_) == 2
    +        assert all(trial.state == TrialState.FAIL for trial in optuna_search.trials_)
    +    else:
    +        with pytest.raises(ValueError, match="alpha"):

    Since error messages tend to change, Optuna follows a policy of not testing them.

            with pytest.raises(ValueError):
    

    ska2704 ska2704 commented on code on Oct 20, 2026 03:24 UTC
    Code Review
    tests/sklearn/test_sklearn.py:1
    @@ -372,6 +373,34 @@ def test_objective_y_None() -> None:
             optuna_search.fit(X)
     
     
    +@pytest.mark.parametrize("enable_pruning", [True, False])
    +@pytest.mark.parametrize("catch", [(ValueError,), ()])
    +def test_objective_error_score_raise(
    +    enable_pruning: bool, catch: tuple[type[Exception], ...]
    +) -> None:
    +    X = np.arange(24).reshape(12, 2)
    +    y = np.arange(12) % 2
    +    with pytest.warns(ExperimentalWarning):
    +        optuna_search = OptunaSearchCV(
    +            SGDClassifier(alpha=-1.0),
    +            {},
    +            cv=2,
    +            enable_pruning=enable_pruning,
    +            error_score="raise",
    +            n_trials=2,
    +            refit=False,
    +            catch=catch,
    +        )
    +
    +    if catch:
    +        optuna_search.fit(X, y)
    +        assert len(optuna_search.trials_) == 2
    +        assert all(trial.state == TrialState.FAIL for trial in optuna_search.trials_)
    +    else:
    +        with pytest.raises(ValueError, match="alpha"):

    Removed the message match in b3708cf. All 38 sklearn tests pass locally.

    not522 not522 approved these changes on Oct 20, 2026 03:31 UTC
    Approved Reviewer

    Thank you! LGTM!

    Reviewers
    Assignees
    ska2704 ska2704
    Labels
    risk: low confidence: 89.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 25.4% (LOW) · Higher = larger blast radius
    25.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.1% · Lower = rushed or shallow review
    89.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.8% · Safe to merge
    2.8%