Skip to content

fix(SimpleSVM): correct constant-predictor handling in predict() and setup() (#9661) - #9670

Merged
timosachsenberg merged 5 commits into
developfrom
fix/simplesvm-predict-feature-index
Jun 26, 2026
Merged

timosachsenberg merged 5 commits into
developfrom
fix/simplesvm-predict-feature-index

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9661, plus a closely-related setup-side crash found (and independently confirmed) while fixing it. Both are about SimpleSVM mishandling a predictor that is constant during training.

Bug 1 — predict() misaligns feature indices (#9661)

predict(PredictorMap&) built the LIBSVM nodes by iterating the prediction map by position (index = position + 1). But training drops constant predictors: scaleData_ skips a predictor with vmin == vmax, and convertData_ assigns LIBSVM indices only to the remaining informative predictors (recorded in order in predictor_names_). So a predictor that was constant during training (absent from the model) but present at prediction shifted every later feature's index — silently wrong predictions, and crashes once the shift ran past the model's feature count.

Fix: build the prediction nodes over predictor_names_ (the trained feature set, in convertData_'s order), looking each up by name. Present-but-untrained predictors are ignored; a trained predictor missing at prediction now throws instead of misaligning.

Bug 2 — setup() crashes when a constant predictor sorts first

scaleData_ (called before convertData_ in setup()) empties the value vector of every constant predictor. convertData_ then took the observation count from predictors.begin()->second.size() — so if the alphabetically-first predictor was constant (hence emptied), n_obs became 0, the node arrays were sized to 0, and setup() crashed dereferencing nodes_[training_index][0].

Fix: derive n_obs from the first non-empty predictor; throw MissingInformation when every predictor is constant rather than building a degenerate/empty model.

Both affect any SimpleSVM caller whose features can be constant within a training fold — e.g. PIP-ECHO's cross-validated transfer-FDR SVM (surfaced during the #9647 review).

Tests (SimpleSVM_test, both verified to fail/crash without the fix)

  • predict() alignment: train two models — one with an extra constant predictor b (mid-sort), one without — then predict identical data with b present-and-varying; the fix makes them agree and recover the known classes. Verified it fails without the fix (outcome got '1', expected '0').
  • setup() robustness: a constant predictor sorting first must train and predict like a model that never saw it; an all-constant input must throw MissingInformation. Verified it crashes setup() without the fix.

🤖 Generated with Claude Code

https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK

Summary by CodeRabbit

  • Bug Fixes
    • Improved model setup by deriving usable observation counts from informative predictors and failing when none remain.
    • Strengthened prediction input handling to use exactly the trained feature set and ordering with consistent scaling.
    • Added clear error handling when required trained predictors are missing during prediction.
  • Tests
    • Added regression coverage for dropping constant predictors, including cases where such predictors sort first.
    • Added a negative test verifying failure when all predictors are constant, plus a check that prediction results remain consistent.

SimpleSVM::predict(PredictorMap&) built the LIBSVM nodes by iterating the
prediction map by position (index = position + 1). But setup()/convertData_
drops predictors that are constant during training (vmin == vmax) and assigns
LIBSVM indices only to the remaining informative predictors, recorded in order
in predictor_names_. So a predictor that was constant during training -- and
therefore absent from the model -- but present at prediction time shifted every
later feature's index by one, silently producing wrong predictions (and, once
the shift ran past the model's feature count, crashes). Fixes #9661.

Build the prediction nodes over predictor_names_ (the trained feature set, in
the exact order convertData_ used), looking each predictor up by name.
Predictors present at prediction but not in the model are ignored; a trained
predictor missing at prediction now throws instead of misaligning.

Affects any SimpleSVM caller whose features can be constant within a training
fold but present at prediction -- e.g. PIP-ECHO's cross-validated transfer-FDR
SVM (surfaced during the #9647 review).

Adds a SimpleSVM_test regression: a model trained with a constant predictor
present at prediction must match one trained without it. The constant predictor
is placed mid-sort so it exercises predict()'s indexing (and not convertData_'s
observation-count seeding from the first predictor).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@timosachsenberg, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 20 minutes and 57 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4cd287c4-4801-4b04-845b-3f7815cec0c9

📥 Commits

Reviewing files that changed from the base of the PR and between fd4afb6 and a419608.

📒 Files selected for processing (2)
  • src/openms/source/ML/SVM/SimpleSVM.cpp
  • src/tests/class_tests/openms/source/SimpleSVM_test.cpp
📝 Walkthrough

Walkthrough

SimpleSVM now derives training observation counts from informative predictors, rejects all-constant inputs, and maps prediction features by trained predictor order. Tests add coverage for constant predictors during setup and prediction.

Changes

SimpleSVM constant-predictor alignment

Layer / File(s) Summary
Setup constant predictors
src/openms/source/ML/SVM/SimpleSVM.cpp, src/tests/class_tests/openms/source/SimpleSVM_test.cpp
convertData_() now uses the first informative predictor to set observation count and throws MissingInformation when all predictors are constant; tests cover constant-predictor setup behavior and the all-constant failure case.
Prediction feature mapping
src/openms/source/ML/SVM/SimpleSVM.cpp, src/tests/class_tests/openms/source/SimpleSVM_test.cpp
predict() now builds LIBSVM nodes from trained predictor names and stored scaling ranges, and tests cover constant predictors present only at prediction time plus the missing-predictor error path.

Poem

A rabbit hopped through features neat,
With names in order, scale complete.
Constant carrots fade away,
Missing ones now cannot stray,
And SVM steps land on both feet. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main SimpleSVM constant-predictor fix.
Linked Issues check ✅ Passed The predict path now matches training feature order and the regression test covers the constant-predictor case described in #9661.
Out of Scope Changes check ✅ Passed All changes stay within SimpleSVM constant-predictor handling and regression coverage; no unrelated functionality was added.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/simplesvm-predict-feature-index

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
src/tests/class_tests/openms/source/SimpleSVM_test.cpp (1)

394-394: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use TEST_TRUE for this boolean assertion.

-  TEST_EQUAL(svm_with_b.getScaling().find("b") == svm_with_b.getScaling().end(), true)
+  TEST_TRUE(svm_with_b.getScaling().find("b") == svm_with_b.getScaling().end())

As per coding guidelines: "Prefer TEST_TRUE(expr) and TEST_FALSE(expr) over TEST_EQUAL(expr, true) and TEST_EQUAL(expr, false) for boolean assertions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/SimpleSVM_test.cpp` at line 394, The
boolean assertion in the SimpleSVM test uses TEST_EQUAL with true, which should
be replaced with the preferred boolean-specific assertion macro. Update the
check around svm_with_b.getScaling().find("b") and getScaling().end() to use
TEST_TRUE with the expression that verifies the key is absent, keeping the same
intent while aligning with the testing guidelines.

Source: Coding guidelines

src/openms/source/ML/SVM/SimpleSVM.cpp (2)

599-626: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer std::vector<svm_node> over raw new[]/delete[].

The throw path now requires a manual delete[] x; (Line 607) duplicating the cleanup at Line 626; any future early-exit risks a leak. A std::vector<svm_node> is exception-safe and removes both manual deletes.

♻️ Proposed refactor
-  svm_node *x = new svm_node[feature_dim + 1];
+  std::vector<svm_node> x(feature_dim + 1);
   for (Size i = 0; i != n_obs; ++i)
   {
     for (Size k = 0; k < feature_dim; ++k)
     {
       PredictorMap::const_iterator pred_it = predictors.find(names[k]);
       if (pred_it == predictors.end())
       {
-        delete[] x;
         throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
           "SimpleSVM::predict: predictor '" + names[k] + "' used during training "
           "is missing from the prediction data.");
       }
       x[k].index = static_cast<int>(k + 1); // LIBSVM feature indices are 1-based
       x[k].value = pred_it->second[i];       // feature value for observation i
     }
     x[feature_dim].index = -1;
     x[feature_dim].value = 0;

     Prediction pred;
-    pred.outcome = svm_predict_probability(pimpl_->model_, x, &(probabilities[0]));
+    pred.outcome = svm_predict_probability(pimpl_->model_, x.data(), &(probabilities[0]));
     for (Size c = 0; c < n_classes; ++c)
     {
       pred.probabilities[outcomes[c]] = probabilities[c];
     }
     predictions.push_back(pred);
   }
-  delete[] x;
 }

As per coding guidelines: "Avoid raw pointers; prefer references or smart pointers".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ML/SVM/SimpleSVM.cpp` around lines 599 - 626, The manual
ownership of the svm_node buffer in SimpleSVM::predict is error-prone because it
relies on paired delete[] calls in both the exception path and the normal exit
path. Replace the raw new[]/delete[] usage for x with an exception-safe
std::vector<svm_node> (or equivalent RAII container) in the predict logic, and
update the svm_predict_probability call and the feature assignment loop to use
the container’s storage so cleanup is automatic even if predictor lookup throws.

Source: Coding guidelines


589-613: 🎯 Functional Correctness | 🔵 Trivial

Replace raw svm_node array with std::vector to adhere to "Avoid raw pointers" guidelines.

Verification confirms the feature indexing logic is correct: convertData_() populates predictor_names_ and assigns 1-based indices in the same iteration order, which predict() faithfully reconstructs using k + 1. The existing comments (lines 584–588) accurately explain why relying on the input map’s iteration order would be unsafe.

However, line 599 uses a raw pointer (new svm_node[...]) with manual delete[] at lines 607 and 626. This violates the guideline to avoid raw pointers. Replacing it with std::vector<svm_node> simplifies memory management and aligns with C++ best practices.

Replace:

svm_node *x = new svm_node[feature_dim + 1];
// ...
delete[] x;

with:

std::vector<svm_node> x(feature_dim + 1);

Exception paths no longer require explicit deallocation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ML/SVM/SimpleSVM.cpp` around lines 589 - 613, The raw
svm_node buffer in SimpleSVM::predict violates the no-raw-pointers guideline
because it is allocated with new[] and manually freed on multiple paths. Replace
the allocation of x with a std::vector<svm_node> sized to feature_dim + 1, and
update the existing x[k] and termination-element usage in predict() to use the
vector storage directly so the manual delete[] cleanup can be removed from both
the normal and exception paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/openms/source/ML/SVM/SimpleSVM.cpp`:
- Around line 599-626: The manual ownership of the svm_node buffer in
SimpleSVM::predict is error-prone because it relies on paired delete[] calls in
both the exception path and the normal exit path. Replace the raw new[]/delete[]
usage for x with an exception-safe std::vector<svm_node> (or equivalent RAII
container) in the predict logic, and update the svm_predict_probability call and
the feature assignment loop to use the container’s storage so cleanup is
automatic even if predictor lookup throws.
- Around line 589-613: The raw svm_node buffer in SimpleSVM::predict violates
the no-raw-pointers guideline because it is allocated with new[] and manually
freed on multiple paths. Replace the allocation of x with a
std::vector<svm_node> sized to feature_dim + 1, and update the existing x[k] and
termination-element usage in predict() to use the vector storage directly so the
manual delete[] cleanup can be removed from both the normal and exception paths.

In `@src/tests/class_tests/openms/source/SimpleSVM_test.cpp`:
- Line 394: The boolean assertion in the SimpleSVM test uses TEST_EQUAL with
true, which should be replaced with the preferred boolean-specific assertion
macro. Update the check around svm_with_b.getScaling().find("b") and
getScaling().end() to use TEST_TRUE with the expression that verifies the key is
absent, keeping the same intent while aligning with the testing guidelines.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bcabb1a3-b679-45f8-b0f5-926a772e1339

📥 Commits

Reviewing files that changed from the base of the PR and between 1b23de1 and 12bac86.

📒 Files selected for processing (2)
  • src/openms/source/ML/SVM/SimpleSVM.cpp
  • src/tests/class_tests/openms/source/SimpleSVM_test.cpp

A second manifestation of the constant-predictor handling, on the setup side:
scaleData_ empties constant predictors, then convertData_ took the observation
count from predictors.begin()->second.size(). When the alphabetically-first
predictor was constant (hence emptied), n_obs became 0, the node arrays were
sized to 0, and setup() crashed dereferencing nodes_[training_index][0].

Derive n_obs from the first NON-empty (informative) predictor, and throw
MissingInformation when every predictor is constant rather than building a
degenerate/empty model.

Extends the SimpleSVM_test regression: a constant predictor sorting first must
train and predict like a model that never saw it, and an all-constant input must
throw. Mechanism independently confirmed by a second analysis pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK
@timosachsenberg timosachsenberg changed the title fix(SimpleSVM): align predict() feature indices with the trained model (#9661) fix(SimpleSVM): correct constant-predictor handling in predict() and setup() (#9661) Jun 26, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/tests/class_tests/openms/source/SimpleSVM_test.cpp`:
- Line 467: Replace the boolean assertion in SimpleSVM_test’s getScaling check
with TEST_TRUE instead of TEST_EQUAL(..., true). Update the assertion that uses
svm_a.getScaling().find("a") == svm_a.getScaling().end() so it directly uses
TEST_TRUE for clearer boolean failure output and to follow the coding guideline
for boolean assertions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6c5ad573-e9d3-4165-83b8-9ab174023d55

📥 Commits

Reviewing files that changed from the base of the PR and between 12bac86 and 4568a25.

📒 Files selected for processing (2)
  • src/openms/source/ML/SVM/SimpleSVM.cpp
  • src/tests/class_tests/openms/source/SimpleSVM_test.cpp

timosachsenberg and others added 3 commits June 26, 2026 11:05
Per the OpenMS coding guideline (and CodeRabbit review on #9670): prefer
TEST_TRUE(expr) over TEST_EQUAL(expr, true) for the iterator-equality checks in
the new constant-predictor regression sections.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK
…dictor

Codex review of #9670: predict(PredictorMap&) took n_obs from
predictors.begin(), which need not be a model feature -- the prediction map may
carry extra predictors (e.g. ones constant during training and dropped). With an
inconsistent-length first predictor that mis-sizes the loop and could read out of
bounds. Derive n_obs from the first TRAINED predictor (predictor_names_[0]) and
throw if it is missing or the model has no features.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK
Codex review follow-up (#9670): close the remaining length-consistency gap.
setup() now rejects predictor vectors of differing lengths up front (otherwise
its n_obs could desync from the node arrays convertData_ sizes from the first
informative predictor, letting the outcome-index guard pass an index past
nodes_). predict() resolves each trained predictor once (also removing a
per-observation map lookup) and verifies every column shares the observation
count so the node loop cannot read past a shorter column. Adds a SimpleSVM_test
case for both.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK
@timosachsenberg
timosachsenberg merged commit 711bd19 into develop Jun 26, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the fix/simplesvm-predict-feature-index branch June 26, 2026 11:22
timosachsenberg added a commit that referenced this pull request Jun 27, 2026
Documents four PRs that landed on 2026-06-26 after the last CHANGELOG
update (#9667):

- #9668: fix platform-dependent float formatting in scientific notation
- #9669: feat(PIPECHO) cap SVM training-set size (max_training_points)
- #9670: fix SimpleSVM constant-predictor crashes in predict()/setup()
- #9672: perf PeptideAndProteinQuant O(1) sample-ID lookup (fixes IsobaricWorkflow hang)

GitHub Actions version bump (#9673) carries no CHANGELOG entry per the
PR author's own checklist.


Claude-Session: https://claude.ai/code/session_01JxivySW6RCM1tKbU8H6bfj

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SimpleSVM::predict misaligns feature indices when a predictor is constant during training but present at prediction

1 participant