[ML] Fix compiler warnings across the codebase - #2985
Conversation
Reduce Clang warnings from ~2500 to 86 (all remaining are -Wunsafe-buffer-usage which require a std::span migration). Compiler flag suppressions (clang.cmake): - -Wno-switch-default: conflicts with the more useful -Wswitch-enum - -Wno-nrvo: purely informational C++23 diagnostic - -Wno-missing-noreturn: remaining cases are lambdas where [[noreturn]] cannot be applied pre-C++23 Code fixes across 59 files: - Remove 37 unused const variables (dead code from state serialisation refactors) - Remove 2 unused functions and 2 unused-but-set variables - Fix 9 shadow warnings by renaming inner variables - Fix 8 implicit int-to-float conversions with static_cast - Fix 2 tautological-compare logic bugs where the condition !(p >= 0.0 || p <= 1.0) was always false - Remove 2 redundant default cases in exhaustive enum switches - Fix 1 pessimizing-move, 1 range-loop-bind-reference, 1 sign-compare, 1 shorten-64-to-32, 1 CTAD issue - Remove unnecessary virtual from method in final class - Add [[noreturn]] to named function throws() - Add missing newline at EOF Made-with: Cursor
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
Made-with: Cursor
Made-with: Cursor # Conflicts: # bin/pytorch_inference/Main.cc
Change [=] to [this, f] in CConcurrentWrapper to silence -Wdeprecated on GCC 13 and Clang. Made-with: Cursor
There was a problem hiding this comment.
Pull request overview
This PR reduces Clang warning volume across the ML C++ codebase and associated tests, including a couple of small correctness fixes, by removing unused declarations, tightening types/casts, and adjusting warning configuration.
Changes:
- Add Clang warning suppressions in CMake and remove/adjust code patterns that trigger noisy diagnostics.
- Remove unused constants/functions/variables and resolve shadowing / conversion warnings in production and test code.
- Fix probability-range validation logic in
CCategoricalTools(tautological compare) and other small correctness/typing issues.
Reviewed changes
Copilot reviewed 58 out of 60 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| lib/model/unittest/ModelTestHelpers.h | Marks header-local helper functions as [[maybe_unused]] to silence unused-function warnings. |
| lib/model/unittest/CTokenListDataCategorizerTest.cc | Renames lambda parameter to avoid shadowing/warnings. |
| lib/model/unittest/CModelMemoryTest.cc | Removes unused string constant from test TU. |
| lib/model/FunctionTypes.cc | Removes unused EMPTY_FUNCTIONS declaration. |
| lib/model/CSearchKey.cc | Removes unused tag constant(s). |
| lib/model/CResourceMonitor.cc | Removes redundant default: in an exhaustive enum switch. |
| lib/model/CMetricBucketGatherer.cc | Removes unused EMPTY_DOUBLE_VEC constant. |
| lib/model/CEventRateModel.cc | Adds explicit cast for category id passed to concentration(...). |
| lib/model/CDetectorEqualizer.cc | Renames lambda parameters to avoid shadowing / improve clarity. |
| lib/model/CDataGatherer.cc | Removes unused EMPTY_STRING constant. |
| lib/model/CAnnotatedProbability.cc | Removes unused persistence tag constant. |
| lib/maths/time_series/unittest/CCalendarCyclicTestTest.cc | Fixes sign-compare warning by casting loop index in comparison. |
| lib/maths/time_series/CTimeSeriesDecompositionStateSerialiser.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CTimeSeriesDecompositionDetail.cc | Adds explicit cast to match expected floating-point parameter types. |
| lib/maths/time_series/CTimeSeriesDecomposition.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CSeasonalComponentAdaptiveBucketing.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CSeasonalComponent.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CDecompositionComponent.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CCalendarCyclicTest.cc | Makes integer→double conversions explicit to silence warnings. |
| lib/maths/time_series/CCalendarComponentAdaptiveBucketing.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CCalendarComponent.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/time_series/CAdaptiveBucketing.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/unittest/CToolsTest.cc | Makes mixed-type loop bound comparison explicit. |
| lib/maths/common/unittest/CMultivariateNormalConjugateTest.cc | Removes unused helper functions in tests. |
| lib/maths/common/CXMeansOnline1d.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CStatisticalTests.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CPriorStateSerialiser.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CPoissonMeanConjugate.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/COneOfNPrior.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CNormalMeanPrecConjugate.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CNaturalBreaksClassifier.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CMultivariateConstantPrior.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CMultinomialConjugate.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CMultimodalPrior.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CModel.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CLogNormalMeanPrecConjugate.cc | Removes unused EMPTY_STRING constant. |
| lib/maths/common/CGammaRateConjugate.cc | Removes unused UNKNOWN_VALUE_STRING constant. |
| lib/maths/common/CCategoricalTools.cc | Fixes tautological probability-range checks (` |
| lib/maths/analytics/unittest/CDataFrameUtilsTest.cc | Adds explicit cast for map key conversion in test assertions. |
| lib/maths/analytics/CBoostedTreeLoss.cc | Removes unused tag constant. |
| lib/maths/analytics/CBoostedTreeFactory.cc | Removes unused tag constant. |
| lib/core/unittest/CConcurrencyTest.cc | Marks a test helper as [[noreturn]] to address missing-noreturn warnings. |
| lib/core/CStateMachine.cc | Removes unused tag constants. |
| lib/core/CJsonStateRestoreTraverser.cc | Removes redundant default: in switch used for logging token types. |
| lib/api/unittest/CTestAnomalyJob.cc | Formatting-only newline/line-ending adjustment. |
| lib/api/unittest/CInferenceModelMetadataTest.cc | Makes mixed integer/floating arithmetic explicit. |
| lib/api/unittest/CDataFrameAnalyzerTrainingTest.cc | Removes pessimizing move into stringstream. |
| lib/api/unittest/CAnomalyJobTest.cc | Renames test constants and makes template argument explicit for uniform_int_distribution. |
| lib/api/CSingleFieldDataCategorizer.cc | Renames lambda captures to avoid shadowing warnings. |
| lib/api/CModelSizeStatsJsonWriter.cc | Removes unused JSON field name constant. |
| lib/api/CForecastRunner.cc | Makes integer→double conversion explicit before applying fractional limit. |
| lib/api/CFieldDataCategorizer.cc | Renames lambda captures to avoid shadowing warnings in background persistence. |
| lib/api/CDetectionRulesJsonParser.cc | Removes unused CONDITION constant (keeps CONDITIONS). |
| lib/api/CDataFrameAnalysisInstrumentation.cc | Removes unused JSON tag constants. |
| include/model/CMetricModelFactory.h | Removes redundant virtual on method in a final class. |
| include/maths/common/CBootstrapClusterer.h | Removes unused locals and updates trace logging to derive partition sizes from parity vector. |
| include/maths/common/CBasicStatistics.h | Makes coordinate conversion explicit in custom central-moments add. |
| include/core/CConcurrentWrapper.h | Makes lambda capture explicit to avoid deprecated implicit this capture warnings. |
| cmake/compiler/clang.cmake | Adds warning suppressions for missing-noreturn, nrvo, and switch-default. |
| bin/pytorch_inference/Main.cc | Adds explicit cast for Torch thread count API. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address Copilot review: if a new enum value is added to SBoostJsonHandler, the switch won't cover it and the log message would contain an empty string. Initialising to "unknown" keeps the error log informative. Made-with: Cursor
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 58 out of 60 changed files in this pull request and generated 1 comment.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address Copilot review: the loop assumed contiguous integer category IDs (0..N-1) and used operator[] which silently inserts missing keys. Iterate over actual map entries instead. Made-with: Cursor
31f4f21 to
76a6eb1
Compare
- CDataFrameTrainBoostedTreeRunner: add LOG_ABORT after 3 exhaustive switch statements that had no default — falling off the end of a non-void function is undefined behaviour (MSVC C4715, GCC -Wreturn-type) - CBoostedTreeHyperparameters: initialise hyperparameterValue to 0.0 — previously uninitialised if a new enum value was added without updating the switch (MSVC C4701) - CJsonLogLayout: remove dangling reference to temporary from boost::log::extract().get() — binding const auto& to the result of .get() on a temporary extractor leaves the reference dangling after the full expression ends (GCC -Wdangling-reference) Made-with: Cursor
Change [=] to [=, this] in 6 lambdas that capture this. Implicit this capture via [=] is deprecated in C++20. (GCC -Wdeprecated) Made-with: Cursor
Add static_cast<double> at 7 locations where size_t values are implicitly converted to double. (GCC -Wconversion, MSVC C4244/C4267) Made-with: Cursor
The test deliberately divides by zero to verify edge-case handling in CMathsFuncs. Suppress C4723 for this file only. Made-with: Cursor
BOOST_TEST_MODULE and BOOST_TEST_NO_MAIN are consumed by the subsequent #include <boost/test/unit_test.hpp> but Clang flags them as unused since they're not referenced directly in source. This is a known false positive with Boost.Test's macro-driven configuration pattern. Made-with: Cursor
BOOST_TEST_MODULE and BOOST_TEST_NO_MAIN are consumed by the subsequent #include <boost/test/unit_test.hpp> but Clang flags them as unused since they're not referenced directly in source. Suppress for test targets only via target_compile_options in ml_add_test_executable, rather than globally. Made-with: Cursor
7295264 to
4b7e9a5
Compare
Co-authored-by: Cursor <cursoragent@cursor.com>
std::is_pod is deprecated in C++20; a single instantiation in the widely included CMemoryFwd.h produced ~454 MSVC C4996 warnings. Introduce a project-level ml::core::is_pod_v alias defined as is_trivial_v && is_standard_layout_v (the standard's exact definition of POD), verified equivalent to std::is_pod across fundamentals, cv/pointer/array qualification, enums, unions, aggregates, standard-layout inheritance edge cases and library types. Adds a guarding unit test. Co-authored-by: Cursor <cursoragent@cursor.com>
C4250 is a purely informational MSVC-only diagnostic (92 warnings from CDataFrameAnalysisInstrumentation.h). The instrumentation hierarchy uses a deliberate virtual-inheritance mixin where CDataFrameAnalysisInstrumentation provides the shared implementation and the per-analysis interfaces add their own pure virtuals; the standard dominance rule resolves this correctly and GCC/Clang do not warn. Suppress rather than redesign a working hierarchy. Co-authored-by: Cursor <cursoragent@cursor.com>
Boost.Test fixture macros generate externally-linked test classes deriving from fixtures declared in anonymous namespaces (internal linkage), which GCC flags with -Wsubobject-linkage (23 warnings across 4 test files). The anonymous namespace is intentional - it keeps per-file fixtures ODR-distinct within the monolithic per-library test binary, so moving them to a shared named namespace would risk ODR violations. Scope the suppression to ml_test_* targets so production code retains the warning. Co-authored-by: Cursor <cursoragent@cursor.com>
Combining the two orthogonal CResultType flag enums (EInterimOrFinal, EConditionalOrUnconditional) with the built-in bitwise OR is deprecated in C++20 (GCC -Wdeprecated-enum-enum-conversion / MSVC C5054), producing 14 warnings across 3 model test files. Provide operator| overloads for the two cross-enum combinations returning CResultType; being exact matches they are selected ahead of the built-in operator, clearing the warnings with no call-site changes. Same-enum ORs are unaffected. Co-authored-by: Cursor <cursoragent@cursor.com>
C4324 ("structure was padded due to alignment specifier") fires for types
that deliberately over-align members with alignas to avoid false sharing,
e.g. the std::atomic counters in CCompressedLfuCache. The padding is the
intended effect of the alignment, so the diagnostic is pure noise (~12
occurrences). GCC/Clang do not warn. Suppress it alongside the other
MSVC-only informational diagnostics.
Co-authored-by: Cursor <cursoragent@cursor.com>
SCentralMomentsCustomAdd::add cast the count n to double before forwarding to SSampleCentralMoments::add, whose parameter is const TCoordinate&. For float coordinates that introduced a TCoordinate -> double -> TCoordinate narrowing (clang -Wimplicit-float-conversion, GCC -Wfloat-conversion). n is already SCoordinate<T>::Type (== TCoordinate), so forward it unchanged, and make the value's U -> T conversion explicit to document the intended narrowing (GCC -Wconversion / MSVC C4244). Behaviour is unchanged. Co-authored-by: Cursor <cursoragent@cursor.com>
…rror_code boost::json::error_code is a deprecated typedef alias for boost::system::error_code (Boost 1.86 marks it BOOST_JSON_DEPRECATED and removes it entirely in 1.87.0). Using it triggered ~1264 MSVC C4996 deprecation warnings. The two are the same type and boost::system::error_code is always transitively included wherever boost::json is used, so this is a type-identical swap that removes the warnings and future-proofs the code. Co-authored-by: Cursor <cursoragent@cursor.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 101 out of 104 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (2)
lib/model/CResourceMonitor.cc:419
applyMemoryStrategynow has nodefaultcase (good for-Wswitch-enum), but it will silently return0ifCProcessMemoryUsage::MEMORY_STRATEGYever has an unexpected value (e.g. enum extended and not handled on one platform). That would under-report usage and could cascade into incorrect limit decisions. Prefer the established pattern used elsewhere in this PR: keep the switch exhaustive and add aLOG_ABORTon the unreachable path so a missing case can’t slip through at runtime.
include/maths/common/CBootstrapClusterer.h:739- This
LOG_TRACErecomputesstd::count(parities.begin(), parities.end(), true)twice. When trace logging is compiled in but filtered out at runtime (common), those counts are still evaluated, adding extra O(V) work on a hot path. Compute the count once and derive |B| from it, while keeping the computation inside a#ifndef EXCLUDE_TRACE_LOGGINGguard so it’s not evaluated when trace logging is compiled out.
LOG_TRACE(<< "Best cut |A| = "
<< static_cast<std::size_t>(
std::count(parities.begin(), parities.end(), true))
<< ", |B| = "
<< V - static_cast<std::size_t>(
std::count(parities.begin(), parities.end(), true))
<< ", cost = " << cost << ", threshold = " << threshold);
The best-cut LOG_TRACE recomputed std::count over the parities vector twice (once for |A|, once for |B|), doubling the O(V) work on a hot path when trace logging is compiled in. Compute |A| once and derive |B| from it, inside an EXCLUDE_TRACE_LOGGING guard so the local doesn't become an unused variable when trace logging is compiled out. Addresses a Copilot review note on elastic#2985. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Pinging @elastic/ml-core (Team:ML) |
Summary
Cleans up compiler warnings across all four platforms/compilers (Clang, MSVC, GCC x86_64/aarch64), fixing several genuine bugs along the way and suppressing only diagnostics that are provably noise. No behavioural changes other than the two tautological-compare bug fixes noted below.
Clang sweep
The Clang build (
-Weverythingwith a curated-Wno-list) is warning-clean in CI — a full compile (631 TUs) emits 0 warnings. Getting there took a substantial sweep:clang.cmake, each for a diagnostic that's noise rather than signal:-Wno-switch-default(174) — conflicts with the more useful-Wswitch-enum; addingdefault:to exhaustive enum switches would hide missing-case detection when new enum values are added.-Wno-nrvo(19) — purely informational C++23 diagnostic about NRVO eligibility.-Wno-missing-noreturn(5) — remaining cases are lambdas where[[noreturn]]can't be applied pre-C++23.constvariables (dead code from state-serialisation refactors), 2 unused functions (calibrationExperiment,dataGeneratorin tests) and 2 unused-but-set variables.!(p >= 0.0 || p <= 1.0)(always false) was corrected to!(p >= 0.0 && p <= 1.0).default:cases, an unnecessaryvirtualin afinalclass, and adds[[noreturn]]tothrows().MSVC / GCC cross-platform items
std::is_poddeprecated (454,CMemoryFwd.h)ml::core::is_pod_v(=is_trivial_v && is_standard_layout_v, the standard's POD definition); verified equivalent across 36 type categories +testIsPodVguardc29ff6a/wd4250— deliberate virtual-inheritance mixin, dominance resolves correctly, GCC/Clang don't warn47bc55f-Wsubobject-linkage(23, test files)-Wno-subobject-linkagetoml_test_*targets only; anonymous-namespace fixtures are intentional (ODR-distinct per file)b7a79e5CResultType operator|overloads for the cross-enum combinations; chosen ahead of the deprecated built-in, no call-site changesf1ff6d3boost::json::error_codedeprecated (~1264)boost::system::error_code(a type-identical alias that Boost removes entirely in 1.87.0 — also future-proofing)63113d7balignaspadding (~12)/wd4324— padding is the intended effect of deliberate cache-line alignment (CCompressedLfuCacheatomics); GCC/Clang don't warna93378d1SCentralMomentsCustomAdd::addcast the count todouble, causing aTCoordinate→double→TCoordinatenarrowing forfloatcoords;nis alreadyTCoordinateso it's forwarded unchanged and the value'sU→Tconversion made explicitb6536f65Verified reduction (CI build compiler output, before → after)
-Wimplicit-float-conversioncleared-Wconversion3→0,-Wfloat-conversion1→0All four cross-platform items verified absent as active warnings (C4996
is_pod, C4250,-Wsubobject-linkage, enum-enum/C5054 → 0 each).Deliberately out of scope (the remaining ~55 MSVC / ~131 GCC)
-Warray-bounds/-Wmaybe-uninitialized/-Wuninitialized(~131) — Eigen/SIMD optimizer false positives; all vanish in the Debug build (now 0).-Wunsafe-buffer-usage(~86) — opt-in only; needs astd::spanmigration.Test plan
clang-format(pinned 5.0.1) check passesMade with Cursor