Repository navigation
fix(SimpleSVM): correct constant-predictor handling in predict() and setup() (#9661) - #9670
Conversation
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
|
Warning Review limit reached
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthrough
ChangesSimpleSVM constant-predictor alignment
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/tests/class_tests/openms/source/SimpleSVM_test.cpp (1)
394-394: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
TEST_TRUEfor 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)andTEST_FALSE(expr)overTEST_EQUAL(expr, true)andTEST_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 winPrefer
std::vector<svm_node>over rawnew[]/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. Astd::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 | 🔵 TrivialReplace raw
svm_nodearray withstd::vectorto adhere to "Avoid raw pointers" guidelines.Verification confirms the feature indexing logic is correct:
convertData_()populatespredictor_names_and assigns 1-based indices in the same iteration order, whichpredict()faithfully reconstructs usingk + 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 manualdelete[]at lines 607 and 626. This violates the guideline to avoid raw pointers. Replacing it withstd::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
📒 Files selected for processing (2)
src/openms/source/ML/SVM/SimpleSVM.cppsrc/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
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/openms/source/ML/SVM/SimpleSVM.cppsrc/tests/class_tests/openms/source/SimpleSVM_test.cpp
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
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]>
Fixes #9661, plus a closely-related setup-side crash found (and independently confirmed) while fixing it. Both are about
SimpleSVMmishandling 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 withvmin == vmax, andconvertData_assigns LIBSVM indices only to the remaining informative predictors (recorded in order inpredictor_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, inconvertData_'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 firstscaleData_(called beforeconvertData_insetup()) empties the value vector of every constant predictor.convertData_then took the observation count frompredictors.begin()->second.size()— so if the alphabetically-first predictor was constant (hence emptied),n_obsbecame 0, the node arrays were sized to 0, andsetup()crashed dereferencingnodes_[training_index][0].Fix: derive
n_obsfrom the first non-empty predictor; throwMissingInformationwhen every predictor is constant rather than building a degenerate/empty model.Both affect any
SimpleSVMcaller 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)b(mid-sort), one without — then predict identical data withbpresent-and-varying; the fix makes them agree and recover the known classes. Verified it fails without the fix (outcome got '1', expected '0').MissingInformation. Verified it crashessetup()without the fix.🤖 Generated with Claude Code
https://claude.ai/code/session_016rawZsiVUCJjzyXTqkkrWK
Summary by CodeRabbit